/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd sync recursive":
/*!*****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/ sync ***!
  \*****************************************************************************************/
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd sync recursive";
module.exports = webpackEmptyContext;

/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/create-date.js":
/*!***********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/create-date.js ***!
  \***********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const f = __webpack_require__(/*! ./format-num.js */ "../pyright-internal/node_modules/@iarna/toml/lib/format-num.js");
const DateTime = global.Date;
class Date extends DateTime {
  constructor(value) {
    super(value);
    this.isDate = true;
  }
  toISOString() {
    return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
  }
}
module.exports = (value) => {
  const date = new Date(value);
  if (isNaN(date)) {
    throw new TypeError("Invalid Datetime");
  } else {
    return date;
  }
};


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/create-datetime-float.js":
/*!*********************************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/create-datetime-float.js ***!
  \*********************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const f = __webpack_require__(/*! ./format-num.js */ "../pyright-internal/node_modules/@iarna/toml/lib/format-num.js");
class FloatingDateTime extends Date {
  constructor(value) {
    super(value + "Z");
    this.isFloating = true;
  }
  toISOString() {
    const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
    const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
    return `${date}T${time}`;
  }
}
module.exports = (value) => {
  const date = new FloatingDateTime(value);
  if (isNaN(date)) {
    throw new TypeError("Invalid Datetime");
  } else {
    return date;
  }
};


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/create-datetime.js":
/*!***************************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/create-datetime.js ***!
  \***************************************************************************/
/***/ ((module) => {

"use strict";

module.exports = (value) => {
  const date = new Date(value);
  if (isNaN(date)) {
    throw new TypeError("Invalid Datetime");
  } else {
    return date;
  }
};


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/create-time.js":
/*!***********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/create-time.js ***!
  \***********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const f = __webpack_require__(/*! ./format-num.js */ "../pyright-internal/node_modules/@iarna/toml/lib/format-num.js");
class Time extends Date {
  constructor(value) {
    super(`0000-01-01T${value}Z`);
    this.isTime = true;
  }
  toISOString() {
    return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
  }
}
module.exports = (value) => {
  const date = new Time(value);
  if (isNaN(date)) {
    throw new TypeError("Invalid Datetime");
  } else {
    return date;
  }
};


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/format-num.js":
/*!**********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/format-num.js ***!
  \**********************************************************************/
/***/ ((module) => {

"use strict";

module.exports = (d, num) => {
  num = String(num);
  while (num.length < d)
    num = "0" + num;
  return num;
};


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/parser.js":
/*!******************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/parser.js ***!
  \******************************************************************/
/***/ ((module) => {

"use strict";

const ParserEND = 1114112;
class ParserError extends Error {
  /* istanbul ignore next */
  constructor(msg, filename, linenumber) {
    super("[ParserError] " + msg, filename, linenumber);
    this.name = "ParserError";
    this.code = "ParserError";
    if (Error.captureStackTrace)
      Error.captureStackTrace(this, ParserError);
  }
}
class State {
  constructor(parser) {
    this.parser = parser;
    this.buf = "";
    this.returned = null;
    this.result = null;
    this.resultTable = null;
    this.resultArr = null;
  }
}
class Parser {
  constructor() {
    this.pos = 0;
    this.col = 0;
    this.line = 0;
    this.obj = {};
    this.ctx = this.obj;
    this.stack = [];
    this._buf = "";
    this.char = null;
    this.ii = 0;
    this.state = new State(this.parseStart);
  }
  parse(str) {
    if (str.length === 0 || str.length == null)
      return;
    this._buf = String(str);
    this.ii = -1;
    this.char = -1;
    let getNext;
    while (getNext === false || this.nextChar()) {
      getNext = this.runOne();
    }
    this._buf = null;
  }
  nextChar() {
    if (this.char === 10) {
      ++this.line;
      this.col = -1;
    }
    ++this.ii;
    this.char = this._buf.codePointAt(this.ii);
    ++this.pos;
    ++this.col;
    return this.haveBuffer();
  }
  haveBuffer() {
    return this.ii < this._buf.length;
  }
  runOne() {
    return this.state.parser.call(this, this.state.returned);
  }
  finish() {
    this.char = ParserEND;
    let last;
    do {
      last = this.state.parser;
      this.runOne();
    } while (this.state.parser !== last);
    this.ctx = null;
    this.state = null;
    this._buf = null;
    return this.obj;
  }
  next(fn) {
    if (typeof fn !== "function")
      throw new ParserError("Tried to set state to non-existent state: " + JSON.stringify(fn));
    this.state.parser = fn;
  }
  goto(fn) {
    this.next(fn);
    return this.runOne();
  }
  call(fn, returnWith) {
    if (returnWith)
      this.next(returnWith);
    this.stack.push(this.state);
    this.state = new State(fn);
  }
  callNow(fn, returnWith) {
    this.call(fn, returnWith);
    return this.runOne();
  }
  return(value) {
    if (this.stack.length === 0)
      throw this.error(new ParserError("Stack underflow"));
    if (value === void 0)
      value = this.state.buf;
    this.state = this.stack.pop();
    this.state.returned = value;
  }
  returnNow(value) {
    this.return(value);
    return this.runOne();
  }
  consume() {
    if (this.char === ParserEND)
      throw this.error(new ParserError("Unexpected end-of-buffer"));
    this.state.buf += this._buf[this.ii];
  }
  error(err) {
    err.line = this.line;
    err.col = this.col;
    err.pos = this.pos;
    return err;
  }
  /* istanbul ignore next */
  parseStart() {
    throw new ParserError("Must declare a parseStart method");
  }
}
Parser.END = ParserEND;
Parser.Error = ParserError;
module.exports = Parser;


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/lib/toml-parser.js":
/*!***********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/lib/toml-parser.js ***!
  \***********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = makeParserClass(__webpack_require__(/*! ./parser.js */ "../pyright-internal/node_modules/@iarna/toml/lib/parser.js"));
module.exports.makeParserClass = makeParserClass;
class TomlError extends Error {
  constructor(msg) {
    super(msg);
    this.name = "TomlError";
    if (Error.captureStackTrace)
      Error.captureStackTrace(this, TomlError);
    this.fromTOML = true;
    this.wrapped = null;
  }
}
TomlError.wrap = (err) => {
  const terr = new TomlError(err.message);
  terr.code = err.code;
  terr.wrapped = err;
  return terr;
};
module.exports.TomlError = TomlError;
const createDateTime = __webpack_require__(/*! ./create-datetime.js */ "../pyright-internal/node_modules/@iarna/toml/lib/create-datetime.js");
const createDateTimeFloat = __webpack_require__(/*! ./create-datetime-float.js */ "../pyright-internal/node_modules/@iarna/toml/lib/create-datetime-float.js");
const createDate = __webpack_require__(/*! ./create-date.js */ "../pyright-internal/node_modules/@iarna/toml/lib/create-date.js");
const createTime = __webpack_require__(/*! ./create-time.js */ "../pyright-internal/node_modules/@iarna/toml/lib/create-time.js");
const CTRL_I = 9;
const CTRL_J = 10;
const CTRL_M = 13;
const CTRL_CHAR_BOUNDARY = 31;
const CHAR_SP = 32;
const CHAR_QUOT = 34;
const CHAR_NUM = 35;
const CHAR_APOS = 39;
const CHAR_PLUS = 43;
const CHAR_COMMA = 44;
const CHAR_HYPHEN = 45;
const CHAR_PERIOD = 46;
const CHAR_0 = 48;
const CHAR_1 = 49;
const CHAR_7 = 55;
const CHAR_9 = 57;
const CHAR_COLON = 58;
const CHAR_EQUALS = 61;
const CHAR_A = 65;
const CHAR_E = 69;
const CHAR_F = 70;
const CHAR_T = 84;
const CHAR_U = 85;
const CHAR_Z = 90;
const CHAR_LOWBAR = 95;
const CHAR_a = 97;
const CHAR_b = 98;
const CHAR_e = 101;
const CHAR_f = 102;
const CHAR_i = 105;
const CHAR_l = 108;
const CHAR_n = 110;
const CHAR_o = 111;
const CHAR_r = 114;
const CHAR_s = 115;
const CHAR_t = 116;
const CHAR_u = 117;
const CHAR_x = 120;
const CHAR_z = 122;
const CHAR_LCUB = 123;
const CHAR_RCUB = 125;
const CHAR_LSQB = 91;
const CHAR_BSOL = 92;
const CHAR_RSQB = 93;
const CHAR_DEL = 127;
const SURROGATE_FIRST = 55296;
const SURROGATE_LAST = 57343;
const escapes = {
  [CHAR_b]: "\b",
  [CHAR_t]: "	",
  [CHAR_n]: "\n",
  [CHAR_f]: "\f",
  [CHAR_r]: "\r",
  [CHAR_QUOT]: '"',
  [CHAR_BSOL]: "\\"
};
function isDigit(cp) {
  return cp >= CHAR_0 && cp <= CHAR_9;
}
function isHexit(cp) {
  return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
}
function isBit(cp) {
  return cp === CHAR_1 || cp === CHAR_0;
}
function isOctit(cp) {
  return cp >= CHAR_0 && cp <= CHAR_7;
}
function isAlphaNumQuoteHyphen(cp) {
  return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
}
function isAlphaNumHyphen(cp) {
  return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
}
const _type = Symbol("type");
const _declared = Symbol("declared");
const hasOwnProperty = Object.prototype.hasOwnProperty;
const defineProperty = Object.defineProperty;
const descriptor = { configurable: true, enumerable: true, writable: true, value: void 0 };
function hasKey(obj, key) {
  if (hasOwnProperty.call(obj, key))
    return true;
  if (key === "__proto__")
    defineProperty(obj, "__proto__", descriptor);
  return false;
}
const INLINE_TABLE = Symbol("inline-table");
function InlineTable() {
  return Object.defineProperties({}, {
    [_type]: { value: INLINE_TABLE }
  });
}
function isInlineTable(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === INLINE_TABLE;
}
const TABLE = Symbol("table");
function Table() {
  return Object.defineProperties({}, {
    [_type]: { value: TABLE },
    [_declared]: { value: false, writable: true }
  });
}
function isTable(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === TABLE;
}
const _contentType = Symbol("content-type");
const INLINE_LIST = Symbol("inline-list");
function InlineList(type) {
  return Object.defineProperties([], {
    [_type]: { value: INLINE_LIST },
    [_contentType]: { value: type }
  });
}
function isInlineList(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === INLINE_LIST;
}
const LIST = Symbol("list");
function List() {
  return Object.defineProperties([], {
    [_type]: { value: LIST }
  });
}
function isList(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === LIST;
}
let _custom;
try {
  const utilInspect = eval("require('util').inspect");
  _custom = utilInspect.custom;
} catch (_) {
}
const _inspect = _custom || "inspect";
class BoxedBigInt {
  constructor(value) {
    try {
      this.value = global.BigInt.asIntN(64, value);
    } catch (_) {
      this.value = null;
    }
    Object.defineProperty(this, _type, { value: INTEGER });
  }
  isNaN() {
    return this.value === null;
  }
  /* istanbul ignore next */
  toString() {
    return String(this.value);
  }
  /* istanbul ignore next */
  [_inspect]() {
    return `[BigInt: ${this.toString()}]}`;
  }
  valueOf() {
    return this.value;
  }
}
const INTEGER = Symbol("integer");
function Integer(value) {
  let num = Number(value);
  if (Object.is(num, -0))
    num = 0;
  if (global.BigInt && !Number.isSafeInteger(num)) {
    return new BoxedBigInt(value);
  } else {
    return Object.defineProperties(new Number(num), {
      isNaN: { value: function() {
        return isNaN(this);
      } },
      [_type]: { value: INTEGER },
      [_inspect]: { value: () => `[Integer: ${value}]` }
    });
  }
}
function isInteger(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === INTEGER;
}
const FLOAT = Symbol("float");
function Float(value) {
  return Object.defineProperties(new Number(value), {
    [_type]: { value: FLOAT },
    [_inspect]: { value: () => `[Float: ${value}]` }
  });
}
function isFloat(obj) {
  if (obj === null || typeof obj !== "object")
    return false;
  return obj[_type] === FLOAT;
}
function tomlType(value) {
  const type = typeof value;
  if (type === "object") {
    if (value === null)
      return "null";
    if (value instanceof Date)
      return "datetime";
    if (_type in value) {
      switch (value[_type]) {
        case INLINE_TABLE:
          return "inline-table";
        case INLINE_LIST:
          return "inline-list";
        case TABLE:
          return "table";
        case LIST:
          return "list";
        case FLOAT:
          return "float";
        case INTEGER:
          return "integer";
      }
    }
  }
  return type;
}
function makeParserClass(Parser) {
  class TOMLParser extends Parser {
    constructor() {
      super();
      this.ctx = this.obj = Table();
    }
    /* MATCH HELPER */
    atEndOfWord() {
      return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
    }
    atEndOfLine() {
      return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
    }
    parseStart() {
      if (this.char === Parser.END) {
        return null;
      } else if (this.char === CHAR_LSQB) {
        return this.call(this.parseTableOrList);
      } else if (this.char === CHAR_NUM) {
        return this.call(this.parseComment);
      } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
        return null;
      } else if (isAlphaNumQuoteHyphen(this.char)) {
        return this.callNow(this.parseAssignStatement);
      } else {
        throw this.error(new TomlError(`Unknown character "${this.char}"`));
      }
    }
    // HELPER, this strips any whitespace and comments to the end of the line
    // then RETURNS. Last state in a production.
    parseWhitespaceToEOL() {
      if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
        return null;
      } else if (this.char === CHAR_NUM) {
        return this.goto(this.parseComment);
      } else if (this.char === Parser.END || this.char === CTRL_J) {
        return this.return();
      } else {
        throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"));
      }
    }
    /* ASSIGNMENT: key = value */
    parseAssignStatement() {
      return this.callNow(this.parseAssign, this.recordAssignStatement);
    }
    recordAssignStatement(kv) {
      let target = this.ctx;
      let finalKey = kv.key.pop();
      for (let kw of kv.key) {
        if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
          throw this.error(new TomlError("Can't redefine existing key"));
        }
        target = target[kw] = target[kw] || Table();
      }
      if (hasKey(target, finalKey)) {
        throw this.error(new TomlError("Can't redefine existing key"));
      }
      if (isInteger(kv.value) || isFloat(kv.value)) {
        target[finalKey] = kv.value.valueOf();
      } else {
        target[finalKey] = kv.value;
      }
      return this.goto(this.parseWhitespaceToEOL);
    }
    /* ASSSIGNMENT expression, key = value possibly inside an inline table */
    parseAssign() {
      return this.callNow(this.parseKeyword, this.recordAssignKeyword);
    }
    recordAssignKeyword(key) {
      if (this.state.resultTable) {
        this.state.resultTable.push(key);
      } else {
        this.state.resultTable = [key];
      }
      return this.goto(this.parseAssignKeywordPreDot);
    }
    parseAssignKeywordPreDot() {
      if (this.char === CHAR_PERIOD) {
        return this.next(this.parseAssignKeywordPostDot);
      } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
        return this.goto(this.parseAssignEqual);
      }
    }
    parseAssignKeywordPostDot() {
      if (this.char !== CHAR_SP && this.char !== CTRL_I) {
        return this.callNow(this.parseKeyword, this.recordAssignKeyword);
      }
    }
    parseAssignEqual() {
      if (this.char === CHAR_EQUALS) {
        return this.next(this.parseAssignPreValue);
      } else {
        throw this.error(new TomlError('Invalid character, expected "="'));
      }
    }
    parseAssignPreValue() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else {
        return this.callNow(this.parseValue, this.recordAssignValue);
      }
    }
    recordAssignValue(value) {
      return this.returnNow({ key: this.state.resultTable, value });
    }
    /* COMMENTS: #...eol */
    parseComment() {
      do {
        if (this.char === Parser.END || this.char === CTRL_J) {
          return this.return();
        }
      } while (this.nextChar());
    }
    /* TABLES AND LISTS, [foo] and [[foo]] */
    parseTableOrList() {
      if (this.char === CHAR_LSQB) {
        this.next(this.parseList);
      } else {
        return this.goto(this.parseTable);
      }
    }
    /* TABLE [foo.bar.baz] */
    parseTable() {
      this.ctx = this.obj;
      return this.goto(this.parseTableNext);
    }
    parseTableNext() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else {
        return this.callNow(this.parseKeyword, this.parseTableMore);
      }
    }
    parseTableMore(keyword) {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else if (this.char === CHAR_RSQB) {
        if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
          throw this.error(new TomlError("Can't redefine existing key"));
        } else {
          this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
          this.ctx[_declared] = true;
        }
        return this.next(this.parseWhitespaceToEOL);
      } else if (this.char === CHAR_PERIOD) {
        if (!hasKey(this.ctx, keyword)) {
          this.ctx = this.ctx[keyword] = Table();
        } else if (isTable(this.ctx[keyword])) {
          this.ctx = this.ctx[keyword];
        } else if (isList(this.ctx[keyword])) {
          this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
        } else {
          throw this.error(new TomlError("Can't redefine existing key"));
        }
        return this.next(this.parseTableNext);
      } else {
        throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
      }
    }
    /* LIST [[a.b.c]] */
    parseList() {
      this.ctx = this.obj;
      return this.goto(this.parseListNext);
    }
    parseListNext() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else {
        return this.callNow(this.parseKeyword, this.parseListMore);
      }
    }
    parseListMore(keyword) {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else if (this.char === CHAR_RSQB) {
        if (!hasKey(this.ctx, keyword)) {
          this.ctx[keyword] = List();
        }
        if (isInlineList(this.ctx[keyword])) {
          throw this.error(new TomlError("Can't extend an inline array"));
        } else if (isList(this.ctx[keyword])) {
          const next = Table();
          this.ctx[keyword].push(next);
          this.ctx = next;
        } else {
          throw this.error(new TomlError("Can't redefine an existing key"));
        }
        return this.next(this.parseListEnd);
      } else if (this.char === CHAR_PERIOD) {
        if (!hasKey(this.ctx, keyword)) {
          this.ctx = this.ctx[keyword] = Table();
        } else if (isInlineList(this.ctx[keyword])) {
          throw this.error(new TomlError("Can't extend an inline array"));
        } else if (isInlineTable(this.ctx[keyword])) {
          throw this.error(new TomlError("Can't extend an inline table"));
        } else if (isList(this.ctx[keyword])) {
          this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
        } else if (isTable(this.ctx[keyword])) {
          this.ctx = this.ctx[keyword];
        } else {
          throw this.error(new TomlError("Can't redefine an existing key"));
        }
        return this.next(this.parseListNext);
      } else {
        throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
      }
    }
    parseListEnd(keyword) {
      if (this.char === CHAR_RSQB) {
        return this.next(this.parseWhitespaceToEOL);
      } else {
        throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
      }
    }
    /* VALUE string, number, boolean, inline list, inline object */
    parseValue() {
      if (this.char === Parser.END) {
        throw this.error(new TomlError("Key without value"));
      } else if (this.char === CHAR_QUOT) {
        return this.next(this.parseDoubleString);
      }
      if (this.char === CHAR_APOS) {
        return this.next(this.parseSingleString);
      } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
        return this.goto(this.parseNumberSign);
      } else if (this.char === CHAR_i) {
        return this.next(this.parseInf);
      } else if (this.char === CHAR_n) {
        return this.next(this.parseNan);
      } else if (isDigit(this.char)) {
        return this.goto(this.parseNumberOrDateTime);
      } else if (this.char === CHAR_t || this.char === CHAR_f) {
        return this.goto(this.parseBoolean);
      } else if (this.char === CHAR_LSQB) {
        return this.call(this.parseInlineList, this.recordValue);
      } else if (this.char === CHAR_LCUB) {
        return this.call(this.parseInlineTable, this.recordValue);
      } else {
        throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"));
      }
    }
    recordValue(value) {
      return this.returnNow(value);
    }
    parseInf() {
      if (this.char === CHAR_n) {
        return this.next(this.parseInf2);
      } else {
        throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
      }
    }
    parseInf2() {
      if (this.char === CHAR_f) {
        if (this.state.buf === "-") {
          return this.return(-Infinity);
        } else {
          return this.return(Infinity);
        }
      } else {
        throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
      }
    }
    parseNan() {
      if (this.char === CHAR_a) {
        return this.next(this.parseNan2);
      } else {
        throw this.error(new TomlError('Unexpected character, expected "nan"'));
      }
    }
    parseNan2() {
      if (this.char === CHAR_n) {
        return this.return(NaN);
      } else {
        throw this.error(new TomlError('Unexpected character, expected "nan"'));
      }
    }
    /* KEYS, barewords or basic, literal, or dotted */
    parseKeyword() {
      if (this.char === CHAR_QUOT) {
        return this.next(this.parseBasicString);
      } else if (this.char === CHAR_APOS) {
        return this.next(this.parseLiteralString);
      } else {
        return this.goto(this.parseBareKey);
      }
    }
    /* KEYS: barewords */
    parseBareKey() {
      do {
        if (this.char === Parser.END) {
          throw this.error(new TomlError("Key ended without value"));
        } else if (isAlphaNumHyphen(this.char)) {
          this.consume();
        } else if (this.state.buf.length === 0) {
          throw this.error(new TomlError("Empty bare keys are not allowed"));
        } else {
          return this.returnNow();
        }
      } while (this.nextChar());
    }
    /* STRINGS, single quoted (literal) */
    parseSingleString() {
      if (this.char === CHAR_APOS) {
        return this.next(this.parseLiteralMultiStringMaybe);
      } else {
        return this.goto(this.parseLiteralString);
      }
    }
    parseLiteralString() {
      do {
        if (this.char === CHAR_APOS) {
          return this.return();
        } else if (this.atEndOfLine()) {
          throw this.error(new TomlError("Unterminated string"));
        } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
          throw this.errorControlCharInString();
        } else {
          this.consume();
        }
      } while (this.nextChar());
    }
    parseLiteralMultiStringMaybe() {
      if (this.char === CHAR_APOS) {
        return this.next(this.parseLiteralMultiString);
      } else {
        return this.returnNow();
      }
    }
    parseLiteralMultiString() {
      if (this.char === CTRL_M) {
        return null;
      } else if (this.char === CTRL_J) {
        return this.next(this.parseLiteralMultiStringContent);
      } else {
        return this.goto(this.parseLiteralMultiStringContent);
      }
    }
    parseLiteralMultiStringContent() {
      do {
        if (this.char === CHAR_APOS) {
          return this.next(this.parseLiteralMultiEnd);
        } else if (this.char === Parser.END) {
          throw this.error(new TomlError("Unterminated multi-line string"));
        } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
          throw this.errorControlCharInString();
        } else {
          this.consume();
        }
      } while (this.nextChar());
    }
    parseLiteralMultiEnd() {
      if (this.char === CHAR_APOS) {
        return this.next(this.parseLiteralMultiEnd2);
      } else {
        this.state.buf += "'";
        return this.goto(this.parseLiteralMultiStringContent);
      }
    }
    parseLiteralMultiEnd2() {
      if (this.char === CHAR_APOS) {
        return this.return();
      } else {
        this.state.buf += "''";
        return this.goto(this.parseLiteralMultiStringContent);
      }
    }
    /* STRINGS double quoted */
    parseDoubleString() {
      if (this.char === CHAR_QUOT) {
        return this.next(this.parseMultiStringMaybe);
      } else {
        return this.goto(this.parseBasicString);
      }
    }
    parseBasicString() {
      do {
        if (this.char === CHAR_BSOL) {
          return this.call(this.parseEscape, this.recordEscapeReplacement);
        } else if (this.char === CHAR_QUOT) {
          return this.return();
        } else if (this.atEndOfLine()) {
          throw this.error(new TomlError("Unterminated string"));
        } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
          throw this.errorControlCharInString();
        } else {
          this.consume();
        }
      } while (this.nextChar());
    }
    recordEscapeReplacement(replacement) {
      this.state.buf += replacement;
      return this.goto(this.parseBasicString);
    }
    parseMultiStringMaybe() {
      if (this.char === CHAR_QUOT) {
        return this.next(this.parseMultiString);
      } else {
        return this.returnNow();
      }
    }
    parseMultiString() {
      if (this.char === CTRL_M) {
        return null;
      } else if (this.char === CTRL_J) {
        return this.next(this.parseMultiStringContent);
      } else {
        return this.goto(this.parseMultiStringContent);
      }
    }
    parseMultiStringContent() {
      do {
        if (this.char === CHAR_BSOL) {
          return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
        } else if (this.char === CHAR_QUOT) {
          return this.next(this.parseMultiEnd);
        } else if (this.char === Parser.END) {
          throw this.error(new TomlError("Unterminated multi-line string"));
        } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
          throw this.errorControlCharInString();
        } else {
          this.consume();
        }
      } while (this.nextChar());
    }
    errorControlCharInString() {
      let displayCode = "\\u00";
      if (this.char < 16) {
        displayCode += "0";
      }
      displayCode += this.char.toString(16);
      return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
    }
    recordMultiEscapeReplacement(replacement) {
      this.state.buf += replacement;
      return this.goto(this.parseMultiStringContent);
    }
    parseMultiEnd() {
      if (this.char === CHAR_QUOT) {
        return this.next(this.parseMultiEnd2);
      } else {
        this.state.buf += '"';
        return this.goto(this.parseMultiStringContent);
      }
    }
    parseMultiEnd2() {
      if (this.char === CHAR_QUOT) {
        return this.return();
      } else {
        this.state.buf += '""';
        return this.goto(this.parseMultiStringContent);
      }
    }
    parseMultiEscape() {
      if (this.char === CTRL_M || this.char === CTRL_J) {
        return this.next(this.parseMultiTrim);
      } else if (this.char === CHAR_SP || this.char === CTRL_I) {
        return this.next(this.parsePreMultiTrim);
      } else {
        return this.goto(this.parseEscape);
      }
    }
    parsePreMultiTrim() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else if (this.char === CTRL_M || this.char === CTRL_J) {
        return this.next(this.parseMultiTrim);
      } else {
        throw this.error(new TomlError("Can't escape whitespace"));
      }
    }
    parseMultiTrim() {
      if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
        return null;
      } else {
        return this.returnNow();
      }
    }
    parseEscape() {
      if (this.char in escapes) {
        return this.return(escapes[this.char]);
      } else if (this.char === CHAR_u) {
        return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
      } else if (this.char === CHAR_U) {
        return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
      } else {
        throw this.error(new TomlError("Unknown escape character: " + this.char));
      }
    }
    parseUnicodeReturn(char) {
      try {
        const codePoint = parseInt(char, 16);
        if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
          throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));
        }
        return this.returnNow(String.fromCodePoint(codePoint));
      } catch (err) {
        throw this.error(TomlError.wrap(err));
      }
    }
    parseSmallUnicode() {
      if (!isHexit(this.char)) {
        throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
      } else {
        this.consume();
        if (this.state.buf.length >= 4)
          return this.return();
      }
    }
    parseLargeUnicode() {
      if (!isHexit(this.char)) {
        throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
      } else {
        this.consume();
        if (this.state.buf.length >= 8)
          return this.return();
      }
    }
    /* NUMBERS */
    parseNumberSign() {
      this.consume();
      return this.next(this.parseMaybeSignedInfOrNan);
    }
    parseMaybeSignedInfOrNan() {
      if (this.char === CHAR_i) {
        return this.next(this.parseInf);
      } else if (this.char === CHAR_n) {
        return this.next(this.parseNan);
      } else {
        return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
      }
    }
    parseNumberIntegerStart() {
      if (this.char === CHAR_0) {
        this.consume();
        return this.next(this.parseNumberIntegerExponentOrDecimal);
      } else {
        return this.goto(this.parseNumberInteger);
      }
    }
    parseNumberIntegerExponentOrDecimal() {
      if (this.char === CHAR_PERIOD) {
        this.consume();
        return this.call(this.parseNoUnder, this.parseNumberFloat);
      } else if (this.char === CHAR_E || this.char === CHAR_e) {
        this.consume();
        return this.next(this.parseNumberExponentSign);
      } else {
        return this.returnNow(Integer(this.state.buf));
      }
    }
    parseNumberInteger() {
      if (isDigit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnder);
      } else if (this.char === CHAR_E || this.char === CHAR_e) {
        this.consume();
        return this.next(this.parseNumberExponentSign);
      } else if (this.char === CHAR_PERIOD) {
        this.consume();
        return this.call(this.parseNoUnder, this.parseNumberFloat);
      } else {
        const result = Integer(this.state.buf);
        if (result.isNaN()) {
          throw this.error(new TomlError("Invalid number"));
        } else {
          return this.returnNow(result);
        }
      }
    }
    parseNoUnder() {
      if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
        throw this.error(new TomlError("Unexpected character, expected digit"));
      } else if (this.atEndOfWord()) {
        throw this.error(new TomlError("Incomplete number"));
      }
      return this.returnNow();
    }
    parseNoUnderHexOctBinLiteral() {
      if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
        throw this.error(new TomlError("Unexpected character, expected digit"));
      } else if (this.atEndOfWord()) {
        throw this.error(new TomlError("Incomplete number"));
      }
      return this.returnNow();
    }
    parseNumberFloat() {
      if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnder, this.parseNumberFloat);
      } else if (isDigit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_E || this.char === CHAR_e) {
        this.consume();
        return this.next(this.parseNumberExponentSign);
      } else {
        return this.returnNow(Float(this.state.buf));
      }
    }
    parseNumberExponentSign() {
      if (isDigit(this.char)) {
        return this.goto(this.parseNumberExponent);
      } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
        this.consume();
        this.call(this.parseNoUnder, this.parseNumberExponent);
      } else {
        throw this.error(new TomlError("Unexpected character, expected -, + or digit"));
      }
    }
    parseNumberExponent() {
      if (isDigit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnder);
      } else {
        return this.returnNow(Float(this.state.buf));
      }
    }
    /* NUMBERS or DATETIMES  */
    parseNumberOrDateTime() {
      if (this.char === CHAR_0) {
        this.consume();
        return this.next(this.parseNumberBaseOrDateTime);
      } else {
        return this.goto(this.parseNumberOrDateTimeOnly);
      }
    }
    parseNumberOrDateTimeOnly() {
      if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnder, this.parseNumberInteger);
      } else if (isDigit(this.char)) {
        this.consume();
        if (this.state.buf.length > 4)
          this.next(this.parseNumberInteger);
      } else if (this.char === CHAR_E || this.char === CHAR_e) {
        this.consume();
        return this.next(this.parseNumberExponentSign);
      } else if (this.char === CHAR_PERIOD) {
        this.consume();
        return this.call(this.parseNoUnder, this.parseNumberFloat);
      } else if (this.char === CHAR_HYPHEN) {
        return this.goto(this.parseDateTime);
      } else if (this.char === CHAR_COLON) {
        return this.goto(this.parseOnlyTimeHour);
      } else {
        return this.returnNow(Integer(this.state.buf));
      }
    }
    parseDateTimeOnly() {
      if (this.state.buf.length < 4) {
        if (isDigit(this.char)) {
          return this.consume();
        } else if (this.char === CHAR_COLON) {
          return this.goto(this.parseOnlyTimeHour);
        } else {
          throw this.error(new TomlError("Expected digit while parsing year part of a date"));
        }
      } else {
        if (this.char === CHAR_HYPHEN) {
          return this.goto(this.parseDateTime);
        } else {
          throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"));
        }
      }
    }
    parseNumberBaseOrDateTime() {
      if (this.char === CHAR_b) {
        this.consume();
        return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
      } else if (this.char === CHAR_o) {
        this.consume();
        return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
      } else if (this.char === CHAR_x) {
        this.consume();
        return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
      } else if (this.char === CHAR_PERIOD) {
        return this.goto(this.parseNumberInteger);
      } else if (isDigit(this.char)) {
        return this.goto(this.parseDateTimeOnly);
      } else {
        return this.returnNow(Integer(this.state.buf));
      }
    }
    parseIntegerHex() {
      if (isHexit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnderHexOctBinLiteral);
      } else {
        const result = Integer(this.state.buf);
        if (result.isNaN()) {
          throw this.error(new TomlError("Invalid number"));
        } else {
          return this.returnNow(result);
        }
      }
    }
    parseIntegerOct() {
      if (isOctit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnderHexOctBinLiteral);
      } else {
        const result = Integer(this.state.buf);
        if (result.isNaN()) {
          throw this.error(new TomlError("Invalid number"));
        } else {
          return this.returnNow(result);
        }
      }
    }
    parseIntegerBin() {
      if (isBit(this.char)) {
        this.consume();
      } else if (this.char === CHAR_LOWBAR) {
        return this.call(this.parseNoUnderHexOctBinLiteral);
      } else {
        const result = Integer(this.state.buf);
        if (result.isNaN()) {
          throw this.error(new TomlError("Invalid number"));
        } else {
          return this.returnNow(result);
        }
      }
    }
    /* DATETIME */
    parseDateTime() {
      if (this.state.buf.length < 4) {
        throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));
      }
      this.state.result = this.state.buf;
      this.state.buf = "";
      return this.next(this.parseDateMonth);
    }
    parseDateMonth() {
      if (this.char === CHAR_HYPHEN) {
        if (this.state.buf.length < 2) {
          throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));
        }
        this.state.result += "-" + this.state.buf;
        this.state.buf = "";
        return this.next(this.parseDateDay);
      } else if (isDigit(this.char)) {
        this.consume();
      } else {
        throw this.error(new TomlError("Incomplete datetime"));
      }
    }
    parseDateDay() {
      if (this.char === CHAR_T || this.char === CHAR_SP) {
        if (this.state.buf.length < 2) {
          throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));
        }
        this.state.result += "-" + this.state.buf;
        this.state.buf = "";
        return this.next(this.parseStartTimeHour);
      } else if (this.atEndOfWord()) {
        return this.returnNow(createDate(this.state.result + "-" + this.state.buf));
      } else if (isDigit(this.char)) {
        this.consume();
      } else {
        throw this.error(new TomlError("Incomplete datetime"));
      }
    }
    parseStartTimeHour() {
      if (this.atEndOfWord()) {
        return this.returnNow(createDate(this.state.result));
      } else {
        return this.goto(this.parseTimeHour);
      }
    }
    parseTimeHour() {
      if (this.char === CHAR_COLON) {
        if (this.state.buf.length < 2) {
          throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
        }
        this.state.result += "T" + this.state.buf;
        this.state.buf = "";
        return this.next(this.parseTimeMin);
      } else if (isDigit(this.char)) {
        this.consume();
      } else {
        throw this.error(new TomlError("Incomplete datetime"));
      }
    }
    parseTimeMin() {
      if (this.state.buf.length < 2 && isDigit(this.char)) {
        this.consume();
      } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
        this.state.result += ":" + this.state.buf;
        this.state.buf = "";
        return this.next(this.parseTimeSec);
      } else {
        throw this.error(new TomlError("Incomplete datetime"));
      }
    }
    parseTimeSec() {
      if (isDigit(this.char)) {
        this.consume();
        if (this.state.buf.length === 2) {
          this.state.result += ":" + this.state.buf;
          this.state.buf = "";
          return this.next(this.parseTimeZoneOrFraction);
        }
      } else {
        throw this.error(new TomlError("Incomplete datetime"));
      }
    }
    parseOnlyTimeHour() {
      if (this.char === CHAR_COLON) {
        if (this.state.buf.length < 2) {
          throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
        }
        this.state.result = this.state.buf;
        this.state.buf = "";
        return this.next(this.parseOnlyTimeMin);
      } else {
        throw this.error(new TomlError("Incomplete time"));
      }
    }
    parseOnlyTimeMin() {
      if (this.state.buf.length < 2 && isDigit(this.char)) {
        this.consume();
      } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
        this.state.result += ":" + this.state.buf;
        this.state.buf = "";
        return this.next(this.parseOnlyTimeSec);
      } else {
        throw this.error(new TomlError("Incomplete time"));
      }
    }
    parseOnlyTimeSec() {
      if (isDigit(this.char)) {
        this.consume();
        if (this.state.buf.length === 2) {
          return this.next(this.parseOnlyTimeFractionMaybe);
        }
      } else {
        throw this.error(new TomlError("Incomplete time"));
      }
    }
    parseOnlyTimeFractionMaybe() {
      this.state.result += ":" + this.state.buf;
      if (this.char === CHAR_PERIOD) {
        this.state.buf = "";
        this.next(this.parseOnlyTimeFraction);
      } else {
        return this.return(createTime(this.state.result));
      }
    }
    parseOnlyTimeFraction() {
      if (isDigit(this.char)) {
        this.consume();
      } else if (this.atEndOfWord()) {
        if (this.state.buf.length === 0)
          throw this.error(new TomlError("Expected digit in milliseconds"));
        return this.returnNow(createTime(this.state.result + "." + this.state.buf));
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
      }
    }
    parseTimeZoneOrFraction() {
      if (this.char === CHAR_PERIOD) {
        this.consume();
        this.next(this.parseDateTimeFraction);
      } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
        this.consume();
        this.next(this.parseTimeZoneHour);
      } else if (this.char === CHAR_Z) {
        this.consume();
        return this.return(createDateTime(this.state.result + this.state.buf));
      } else if (this.atEndOfWord()) {
        return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
      }
    }
    parseDateTimeFraction() {
      if (isDigit(this.char)) {
        this.consume();
      } else if (this.state.buf.length === 1) {
        throw this.error(new TomlError("Expected digit in milliseconds"));
      } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
        this.consume();
        this.next(this.parseTimeZoneHour);
      } else if (this.char === CHAR_Z) {
        this.consume();
        return this.return(createDateTime(this.state.result + this.state.buf));
      } else if (this.atEndOfWord()) {
        return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
      }
    }
    parseTimeZoneHour() {
      if (isDigit(this.char)) {
        this.consume();
        if (/\d\d$/.test(this.state.buf))
          return this.next(this.parseTimeZoneSep);
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
      }
    }
    parseTimeZoneSep() {
      if (this.char === CHAR_COLON) {
        this.consume();
        this.next(this.parseTimeZoneMin);
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected colon"));
      }
    }
    parseTimeZoneMin() {
      if (isDigit(this.char)) {
        this.consume();
        if (/\d\d$/.test(this.state.buf))
          return this.return(createDateTime(this.state.result + this.state.buf));
      } else {
        throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
      }
    }
    /* BOOLEAN */
    parseBoolean() {
      if (this.char === CHAR_t) {
        this.consume();
        return this.next(this.parseTrue_r);
      } else if (this.char === CHAR_f) {
        this.consume();
        return this.next(this.parseFalse_a);
      }
    }
    parseTrue_r() {
      if (this.char === CHAR_r) {
        this.consume();
        return this.next(this.parseTrue_u);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseTrue_u() {
      if (this.char === CHAR_u) {
        this.consume();
        return this.next(this.parseTrue_e);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseTrue_e() {
      if (this.char === CHAR_e) {
        return this.return(true);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseFalse_a() {
      if (this.char === CHAR_a) {
        this.consume();
        return this.next(this.parseFalse_l);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseFalse_l() {
      if (this.char === CHAR_l) {
        this.consume();
        return this.next(this.parseFalse_s);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseFalse_s() {
      if (this.char === CHAR_s) {
        this.consume();
        return this.next(this.parseFalse_e);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    parseFalse_e() {
      if (this.char === CHAR_e) {
        return this.return(false);
      } else {
        throw this.error(new TomlError("Invalid boolean, expected true or false"));
      }
    }
    /* INLINE LISTS */
    parseInlineList() {
      if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
        return null;
      } else if (this.char === Parser.END) {
        throw this.error(new TomlError("Unterminated inline array"));
      } else if (this.char === CHAR_NUM) {
        return this.call(this.parseComment);
      } else if (this.char === CHAR_RSQB) {
        return this.return(this.state.resultArr || InlineList());
      } else {
        return this.callNow(this.parseValue, this.recordInlineListValue);
      }
    }
    recordInlineListValue(value) {
      if (this.state.resultArr) {
        const listType = this.state.resultArr[_contentType];
        const valueType = tomlType(value);
        if (listType !== valueType) {
          throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
        }
      } else {
        this.state.resultArr = InlineList(tomlType(value));
      }
      if (isFloat(value) || isInteger(value)) {
        this.state.resultArr.push(value.valueOf());
      } else {
        this.state.resultArr.push(value);
      }
      return this.goto(this.parseInlineListNext);
    }
    parseInlineListNext() {
      if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
        return null;
      } else if (this.char === CHAR_NUM) {
        return this.call(this.parseComment);
      } else if (this.char === CHAR_COMMA) {
        return this.next(this.parseInlineList);
      } else if (this.char === CHAR_RSQB) {
        return this.goto(this.parseInlineList);
      } else {
        throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
      }
    }
    /* INLINE TABLE */
    parseInlineTable() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
        throw this.error(new TomlError("Unterminated inline array"));
      } else if (this.char === CHAR_RCUB) {
        return this.return(this.state.resultTable || InlineTable());
      } else {
        if (!this.state.resultTable)
          this.state.resultTable = InlineTable();
        return this.callNow(this.parseAssign, this.recordInlineTableValue);
      }
    }
    recordInlineTableValue(kv) {
      let target = this.state.resultTable;
      let finalKey = kv.key.pop();
      for (let kw of kv.key) {
        if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
          throw this.error(new TomlError("Can't redefine existing key"));
        }
        target = target[kw] = target[kw] || Table();
      }
      if (hasKey(target, finalKey)) {
        throw this.error(new TomlError("Can't redefine existing key"));
      }
      if (isInteger(kv.value) || isFloat(kv.value)) {
        target[finalKey] = kv.value.valueOf();
      } else {
        target[finalKey] = kv.value;
      }
      return this.goto(this.parseInlineTableNext);
    }
    parseInlineTableNext() {
      if (this.char === CHAR_SP || this.char === CTRL_I) {
        return null;
      } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
        throw this.error(new TomlError("Unterminated inline array"));
      } else if (this.char === CHAR_COMMA) {
        return this.next(this.parseInlineTable);
      } else if (this.char === CHAR_RCUB) {
        return this.goto(this.parseInlineTable);
      } else {
        throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
      }
    }
  }
  return TOMLParser;
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/parse-async.js":
/*!*******************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/parse-async.js ***!
  \*******************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = parseAsync;
const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "../pyright-internal/node_modules/@iarna/toml/lib/toml-parser.js");
const prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "../pyright-internal/node_modules/@iarna/toml/parse-pretty-error.js");
function parseAsync(str, opts) {
  if (!opts)
    opts = {};
  const index = 0;
  const blocksize = opts.blocksize || 40960;
  const parser = new TOMLParser();
  return new Promise((resolve, reject) => {
    setImmediate(parseAsyncNext, index, blocksize, resolve, reject);
  });
  function parseAsyncNext(index2, blocksize2, resolve, reject) {
    if (index2 >= str.length) {
      try {
        return resolve(parser.finish());
      } catch (err) {
        return reject(prettyError(err, str));
      }
    }
    try {
      parser.parse(str.slice(index2, index2 + blocksize2));
      setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve, reject);
    } catch (err) {
      reject(prettyError(err, str));
    }
  }
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/parse-pretty-error.js":
/*!**************************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/parse-pretty-error.js ***!
  \**************************************************************************/
/***/ ((module) => {

"use strict";

module.exports = prettyError;
function prettyError(err, buf) {
  if (err.pos == null || err.line == null)
    return err;
  let msg = err.message;
  msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:
`;
  if (buf && buf.split) {
    const lines = buf.split(/\n/);
    const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
    let linePadding = " ";
    while (linePadding.length < lineNumWidth)
      linePadding += " ";
    for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
      let lineNum = String(ii + 1);
      if (lineNum.length < lineNumWidth)
        lineNum = " " + lineNum;
      if (err.line === ii) {
        msg += lineNum + "> " + lines[ii] + "\n";
        msg += linePadding + "  ";
        for (let hh = 0; hh < err.col; ++hh) {
          msg += " ";
        }
        msg += "^\n";
      } else {
        msg += lineNum + ": " + lines[ii] + "\n";
      }
    }
  }
  err.message = msg + "\n";
  return err;
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/parse-stream.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/parse-stream.js ***!
  \********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = parseStream;
const stream = __webpack_require__(/*! stream */ "stream");
const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "../pyright-internal/node_modules/@iarna/toml/lib/toml-parser.js");
function parseStream(stm) {
  if (stm) {
    return parseReadable(stm);
  } else {
    return parseTransform(stm);
  }
}
function parseReadable(stm) {
  const parser = new TOMLParser();
  stm.setEncoding("utf8");
  return new Promise((resolve, reject) => {
    let readable;
    let ended = false;
    let errored = false;
    function finish() {
      ended = true;
      if (readable)
        return;
      try {
        resolve(parser.finish());
      } catch (err) {
        reject(err);
      }
    }
    function error(err) {
      errored = true;
      reject(err);
    }
    stm.once("end", finish);
    stm.once("error", error);
    readNext();
    function readNext() {
      readable = true;
      let data;
      while ((data = stm.read()) !== null) {
        try {
          parser.parse(data);
        } catch (err) {
          return error(err);
        }
      }
      readable = false;
      if (ended)
        return finish();
      if (errored)
        return;
      stm.once("readable", readNext);
    }
  });
}
function parseTransform() {
  const parser = new TOMLParser();
  return new stream.Transform({
    objectMode: true,
    transform(chunk, encoding, cb) {
      try {
        parser.parse(chunk.toString(encoding));
      } catch (err) {
        this.emit("error", err);
      }
      cb();
    },
    flush(cb) {
      try {
        this.push(parser.finish());
      } catch (err) {
        this.emit("error", err);
      }
      cb();
    }
  });
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/parse-string.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/parse-string.js ***!
  \********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = parseString;
const TOMLParser = __webpack_require__(/*! ./lib/toml-parser.js */ "../pyright-internal/node_modules/@iarna/toml/lib/toml-parser.js");
const prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "../pyright-internal/node_modules/@iarna/toml/parse-pretty-error.js");
function parseString(str) {
  if (global.Buffer && global.Buffer.isBuffer(str)) {
    str = str.toString("utf8");
  }
  const parser = new TOMLParser();
  try {
    parser.parse(str);
    return parser.finish();
  } catch (err) {
    throw prettyError(err, str);
  }
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/parse.js":
/*!*************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/parse.js ***!
  \*************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = __webpack_require__(/*! ./parse-string.js */ "../pyright-internal/node_modules/@iarna/toml/parse-string.js");
module.exports.async = __webpack_require__(/*! ./parse-async.js */ "../pyright-internal/node_modules/@iarna/toml/parse-async.js");
module.exports.stream = __webpack_require__(/*! ./parse-stream.js */ "../pyright-internal/node_modules/@iarna/toml/parse-stream.js");
module.exports.prettyError = __webpack_require__(/*! ./parse-pretty-error.js */ "../pyright-internal/node_modules/@iarna/toml/parse-pretty-error.js");


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/stringify.js":
/*!*****************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/stringify.js ***!
  \*****************************************************************/
/***/ ((module) => {

"use strict";

module.exports = stringify;
module.exports.value = stringifyInline;
function stringify(obj) {
  if (obj === null)
    throw typeError("null");
  if (obj === void 0)
    throw typeError("undefined");
  if (typeof obj !== "object")
    throw typeError(typeof obj);
  if (typeof obj.toJSON === "function")
    obj = obj.toJSON();
  if (obj == null)
    return null;
  const type = tomlType(obj);
  if (type !== "table")
    throw typeError(type);
  return stringifyObject("", "", obj);
}
function typeError(type) {
  return new Error("Can only stringify objects, not " + type);
}
function arrayOneTypeError() {
  return new Error("Array values can't have mixed types");
}
function getInlineKeys(obj) {
  return Object.keys(obj).filter((key) => isInline(obj[key]));
}
function getComplexKeys(obj) {
  return Object.keys(obj).filter((key) => !isInline(obj[key]));
}
function toJSON(obj) {
  let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, "__proto__") ? { ["__proto__"]: void 0 } : {};
  for (let prop of Object.keys(obj)) {
    if (obj[prop] && typeof obj[prop].toJSON === "function" && !("toISOString" in obj[prop])) {
      nobj[prop] = obj[prop].toJSON();
    } else {
      nobj[prop] = obj[prop];
    }
  }
  return nobj;
}
function stringifyObject(prefix, indent, obj) {
  obj = toJSON(obj);
  var inlineKeys;
  var complexKeys;
  inlineKeys = getInlineKeys(obj);
  complexKeys = getComplexKeys(obj);
  var result = [];
  var inlineIndent = indent || "";
  inlineKeys.forEach((key) => {
    var type = tomlType(obj[key]);
    if (type !== "undefined" && type !== "null") {
      result.push(inlineIndent + stringifyKey(key) + " = " + stringifyAnyInline(obj[key], true));
    }
  });
  if (result.length > 0)
    result.push("");
  var complexIndent = prefix && inlineKeys.length > 0 ? indent + "  " : "";
  complexKeys.forEach((key) => {
    result.push(stringifyComplex(prefix, complexIndent, key, obj[key]));
  });
  return result.join("\n");
}
function isInline(value) {
  switch (tomlType(value)) {
    case "undefined":
    case "null":
    case "integer":
    case "nan":
    case "float":
    case "boolean":
    case "string":
    case "datetime":
      return true;
    case "array":
      return value.length === 0 || tomlType(value[0]) !== "table";
    case "table":
      return Object.keys(value).length === 0;
    default:
      return false;
  }
}
function tomlType(value) {
  if (value === void 0) {
    return "undefined";
  } else if (value === null) {
    return "null";
  } else if (typeof value === "bigint" || Number.isInteger(value) && !Object.is(value, -0)) {
    return "integer";
  } else if (typeof value === "number") {
    return "float";
  } else if (typeof value === "boolean") {
    return "boolean";
  } else if (typeof value === "string") {
    return "string";
  } else if ("toISOString" in value) {
    return isNaN(value) ? "undefined" : "datetime";
  } else if (Array.isArray(value)) {
    return "array";
  } else {
    return "table";
  }
}
function stringifyKey(key) {
  var keyStr = String(key);
  if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {
    return keyStr;
  } else {
    return stringifyBasicString(keyStr);
  }
}
function stringifyBasicString(str) {
  return '"' + escapeString(str).replace(/"/g, '\\"') + '"';
}
function stringifyLiteralString(str) {
  return "'" + str + "'";
}
function numpad(num, str) {
  while (str.length < num)
    str = "0" + str;
  return str;
}
function escapeString(str) {
  return str.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
}
function stringifyMultilineString(str) {
  let escaped = str.split(/\n/).map((str2) => {
    return escapeString(str2).replace(/"(?="")/g, '\\"');
  }).join("\n");
  if (escaped.slice(-1) === '"')
    escaped += "\\\n";
  return '"""\n' + escaped + '"""';
}
function stringifyAnyInline(value, multilineOk) {
  let type = tomlType(value);
  if (type === "string") {
    if (multilineOk && /\n/.test(value)) {
      type = "string-multiline";
    } else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) {
      type = "string-literal";
    }
  }
  return stringifyInline(value, type);
}
function stringifyInline(value, type) {
  if (!type)
    type = tomlType(value);
  switch (type) {
    case "string-multiline":
      return stringifyMultilineString(value);
    case "string":
      return stringifyBasicString(value);
    case "string-literal":
      return stringifyLiteralString(value);
    case "integer":
      return stringifyInteger(value);
    case "float":
      return stringifyFloat(value);
    case "boolean":
      return stringifyBoolean(value);
    case "datetime":
      return stringifyDatetime(value);
    case "array":
      return stringifyInlineArray(value.filter((_) => tomlType(_) !== "null" && tomlType(_) !== "undefined" && tomlType(_) !== "nan"));
    case "table":
      return stringifyInlineTable(value);
    default:
      throw typeError(type);
  }
}
function stringifyInteger(value) {
  return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, "_");
}
function stringifyFloat(value) {
  if (value === Infinity) {
    return "inf";
  } else if (value === -Infinity) {
    return "-inf";
  } else if (Object.is(value, NaN)) {
    return "nan";
  } else if (Object.is(value, -0)) {
    return "-0.0";
  }
  var chunks = String(value).split(".");
  var int = chunks[0];
  var dec = chunks[1] || 0;
  return stringifyInteger(int) + "." + dec;
}
function stringifyBoolean(value) {
  return String(value);
}
function stringifyDatetime(value) {
  return value.toISOString();
}
function isNumber(type) {
  return type === "float" || type === "integer";
}
function arrayType(values) {
  var contentType = tomlType(values[0]);
  if (values.every((_) => tomlType(_) === contentType))
    return contentType;
  if (values.every((_) => isNumber(tomlType(_))))
    return "float";
  return "mixed";
}
function validateArray(values) {
  const type = arrayType(values);
  if (type === "mixed") {
    throw arrayOneTypeError();
  }
  return type;
}
function stringifyInlineArray(values) {
  values = toJSON(values);
  const type = validateArray(values);
  var result = "[";
  var stringified = values.map((_) => stringifyInline(_, type));
  if (stringified.join(", ").length > 60 || /\n/.test(stringified)) {
    result += "\n  " + stringified.join(",\n  ") + "\n";
  } else {
    result += " " + stringified.join(", ") + (stringified.length > 0 ? " " : "");
  }
  return result + "]";
}
function stringifyInlineTable(value) {
  value = toJSON(value);
  var result = [];
  Object.keys(value).forEach((key) => {
    result.push(stringifyKey(key) + " = " + stringifyAnyInline(value[key], false));
  });
  return "{ " + result.join(", ") + (result.length > 0 ? " " : "") + "}";
}
function stringifyComplex(prefix, indent, key, value) {
  var valueType = tomlType(value);
  if (valueType === "array") {
    return stringifyArrayOfTables(prefix, indent, key, value);
  } else if (valueType === "table") {
    return stringifyComplexTable(prefix, indent, key, value);
  } else {
    throw typeError(valueType);
  }
}
function stringifyArrayOfTables(prefix, indent, key, values) {
  values = toJSON(values);
  validateArray(values);
  var firstValueType = tomlType(values[0]);
  if (firstValueType !== "table")
    throw typeError(firstValueType);
  var fullKey = prefix + stringifyKey(key);
  var result = "";
  values.forEach((table) => {
    if (result.length > 0)
      result += "\n";
    result += indent + "[[" + fullKey + "]]\n";
    result += stringifyObject(fullKey + ".", indent, table);
  });
  return result;
}
function stringifyComplexTable(prefix, indent, key, value) {
  var fullKey = prefix + stringifyKey(key);
  var result = "";
  if (getInlineKeys(value).length > 0) {
    result += indent + "[" + fullKey + "]\n";
  }
  return result + stringifyObject(fullKey + ".", indent, value);
}


/***/ }),

/***/ "../pyright-internal/node_modules/@iarna/toml/toml.js":
/*!************************************************************!*\
  !*** ../pyright-internal/node_modules/@iarna/toml/toml.js ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

exports.parse = __webpack_require__(/*! ./parse.js */ "../pyright-internal/node_modules/@iarna/toml/parse.js");
exports.stringify = __webpack_require__(/*! ./stringify.js */ "../pyright-internal/node_modules/@iarna/toml/stringify.js");


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/AliasFS.js":
/*!**********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/AliasFS.js ***!
  \**********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AliasFS = void 0;
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
class AliasFS extends ProxiedFS_1.ProxiedFS {
  constructor(target, { baseFs, pathUtils }) {
    super(pathUtils);
    this.target = target;
    this.baseFs = baseFs;
  }
  getRealPath() {
    return this.target;
  }
  getBaseFs() {
    return this.baseFs;
  }
  mapFromBase(p) {
    return p;
  }
  mapToBase(p) {
    return p;
  }
}
exports.AliasFS = AliasFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/CwdFS.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/CwdFS.js ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CwdFS = void 0;
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
class CwdFS extends ProxiedFS_1.ProxiedFS {
  constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) {
    super(path_1.ppath);
    this.target = this.pathUtils.normalize(target);
    this.baseFs = baseFs;
  }
  getRealPath() {
    return this.pathUtils.resolve(this.baseFs.getRealPath(), this.target);
  }
  resolve(p) {
    if (this.pathUtils.isAbsolute(p)) {
      return path_1.ppath.normalize(p);
    } else {
      return this.baseFs.resolve(path_1.ppath.join(this.target, p));
    }
  }
  mapFromBase(path) {
    return path;
  }
  mapToBase(path) {
    if (this.pathUtils.isAbsolute(path)) {
      return path;
    } else {
      return this.pathUtils.join(this.target, path);
    }
  }
}
exports.CwdFS = CwdFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.normalizeLineEndings = exports.BasePortableFakeFS = exports.FakeFS = void 0;
const os_1 = __webpack_require__(/*! os */ "os");
const copyPromise_1 = __webpack_require__(/*! ./algorithms/copyPromise */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/copyPromise.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
class FakeFS {
  constructor(pathUtils) {
    this.pathUtils = pathUtils;
  }
  async *genTraversePromise(init, { stableSort = false } = {}) {
    const stack = [init];
    while (stack.length > 0) {
      const p = stack.shift();
      const entry = await this.lstatPromise(p);
      if (entry.isDirectory()) {
        const entries = await this.readdirPromise(p);
        if (stableSort) {
          for (const entry2 of entries.sort()) {
            stack.push(this.pathUtils.join(p, entry2));
          }
        } else {
          throw new Error(`Not supported`);
        }
      } else {
        yield p;
      }
    }
  }
  async removePromise(p, { recursive = true, maxRetries = 5 } = {}) {
    let stat;
    try {
      stat = await this.lstatPromise(p);
    } catch (error) {
      if (error.code === `ENOENT`) {
        return;
      } else {
        throw error;
      }
    }
    if (stat.isDirectory()) {
      if (recursive) {
        const entries = await this.readdirPromise(p);
        await Promise.all(entries.map((entry) => {
          return this.removePromise(this.pathUtils.resolve(p, entry));
        }));
      }
      for (let t = 0; t <= maxRetries; t++) {
        try {
          await this.rmdirPromise(p);
          break;
        } catch (error) {
          if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) {
            throw error;
          } else if (t < maxRetries) {
            await new Promise((resolve) => setTimeout(resolve, t * 100));
          }
        }
      }
    } else {
      await this.unlinkPromise(p);
    }
  }
  removeSync(p, { recursive = true } = {}) {
    let stat;
    try {
      stat = this.lstatSync(p);
    } catch (error) {
      if (error.code === `ENOENT`) {
        return;
      } else {
        throw error;
      }
    }
    if (stat.isDirectory()) {
      if (recursive)
        for (const entry of this.readdirSync(p))
          this.removeSync(this.pathUtils.resolve(p, entry));
      this.rmdirSync(p);
    } else {
      this.unlinkSync(p);
    }
  }
  async mkdirpPromise(p, { chmod, utimes } = {}) {
    p = this.resolve(p);
    if (p === this.pathUtils.dirname(p))
      return void 0;
    const parts = p.split(this.pathUtils.sep);
    let createdDirectory;
    for (let u = 2; u <= parts.length; ++u) {
      const subPath = parts.slice(0, u).join(this.pathUtils.sep);
      if (!this.existsSync(subPath)) {
        try {
          await this.mkdirPromise(subPath);
        } catch (error) {
          if (error.code === `EEXIST`) {
            continue;
          } else {
            throw error;
          }
        }
        createdDirectory !== null && createdDirectory !== void 0 ? createdDirectory : createdDirectory = subPath;
        if (chmod != null)
          await this.chmodPromise(subPath, chmod);
        if (utimes != null) {
          await this.utimesPromise(subPath, utimes[0], utimes[1]);
        } else {
          const parentStat = await this.statPromise(this.pathUtils.dirname(subPath));
          await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime);
        }
      }
    }
    return createdDirectory;
  }
  mkdirpSync(p, { chmod, utimes } = {}) {
    p = this.resolve(p);
    if (p === this.pathUtils.dirname(p))
      return void 0;
    const parts = p.split(this.pathUtils.sep);
    let createdDirectory;
    for (let u = 2; u <= parts.length; ++u) {
      const subPath = parts.slice(0, u).join(this.pathUtils.sep);
      if (!this.existsSync(subPath)) {
        try {
          this.mkdirSync(subPath);
        } catch (error) {
          if (error.code === `EEXIST`) {
            continue;
          } else {
            throw error;
          }
        }
        createdDirectory !== null && createdDirectory !== void 0 ? createdDirectory : createdDirectory = subPath;
        if (chmod != null)
          this.chmodSync(subPath, chmod);
        if (utimes != null) {
          this.utimesSync(subPath, utimes[0], utimes[1]);
        } else {
          const parentStat = this.statSync(this.pathUtils.dirname(subPath));
          this.utimesSync(subPath, parentStat.atime, parentStat.mtime);
        }
      }
    }
    return createdDirectory;
  }
  async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) {
    return await (0, copyPromise_1.copyPromise)(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy });
  }
  copySync(destination, source, { baseFs = this, overwrite = true } = {}) {
    const stat = baseFs.lstatSync(source);
    const exists = this.existsSync(destination);
    if (stat.isDirectory()) {
      this.mkdirpSync(destination);
      const directoryListing = baseFs.readdirSync(source);
      for (const entry of directoryListing) {
        this.copySync(this.pathUtils.join(destination, entry), baseFs.pathUtils.join(source, entry), { baseFs, overwrite });
      }
    } else if (stat.isFile()) {
      if (!exists || overwrite) {
        if (exists)
          this.removeSync(destination);
        const content = baseFs.readFileSync(source);
        this.writeFileSync(destination, content);
      }
    } else if (stat.isSymbolicLink()) {
      if (!exists || overwrite) {
        if (exists)
          this.removeSync(destination);
        const target = baseFs.readlinkSync(source);
        this.symlinkSync((0, path_1.convertPath)(this.pathUtils, target), destination);
      }
    } else {
      throw new Error(`Unsupported file type (file: ${source}, mode: 0o${stat.mode.toString(8).padStart(6, `0`)})`);
    }
    const mode = stat.mode & 511;
    this.chmodSync(destination, mode);
  }
  async changeFilePromise(p, content, opts = {}) {
    if (Buffer.isBuffer(content)) {
      return this.changeFileBufferPromise(p, content, opts);
    } else {
      return this.changeFileTextPromise(p, content, opts);
    }
  }
  async changeFileBufferPromise(p, content, { mode } = {}) {
    let current = Buffer.alloc(0);
    try {
      current = await this.readFilePromise(p);
    } catch (error) {
    }
    if (Buffer.compare(current, content) === 0)
      return;
    await this.writeFilePromise(p, content, { mode });
  }
  async changeFileTextPromise(p, content, { automaticNewlines, mode } = {}) {
    let current = ``;
    try {
      current = await this.readFilePromise(p, `utf8`);
    } catch (error) {
    }
    const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;
    if (current === normalizedContent)
      return;
    await this.writeFilePromise(p, normalizedContent, { mode });
  }
  changeFileSync(p, content, opts = {}) {
    if (Buffer.isBuffer(content)) {
      return this.changeFileBufferSync(p, content, opts);
    } else {
      return this.changeFileTextSync(p, content, opts);
    }
  }
  changeFileBufferSync(p, content, { mode } = {}) {
    let current = Buffer.alloc(0);
    try {
      current = this.readFileSync(p);
    } catch (error) {
    }
    if (Buffer.compare(current, content) === 0)
      return;
    this.writeFileSync(p, content, { mode });
  }
  changeFileTextSync(p, content, { automaticNewlines = false, mode } = {}) {
    let current = ``;
    try {
      current = this.readFileSync(p, `utf8`);
    } catch (error) {
    }
    const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;
    if (current === normalizedContent)
      return;
    this.writeFileSync(p, normalizedContent, { mode });
  }
  async movePromise(fromP, toP) {
    try {
      await this.renamePromise(fromP, toP);
    } catch (error) {
      if (error.code === `EXDEV`) {
        await this.copyPromise(toP, fromP);
        await this.removePromise(fromP);
      } else {
        throw error;
      }
    }
  }
  moveSync(fromP, toP) {
    try {
      this.renameSync(fromP, toP);
    } catch (error) {
      if (error.code === `EXDEV`) {
        this.copySync(toP, fromP);
        this.removeSync(fromP);
      } else {
        throw error;
      }
    }
  }
  async lockPromise(affectedPath, callback) {
    const lockPath = `${affectedPath}.flock`;
    const interval = 1e3 / 60;
    const startTime = Date.now();
    let fd = null;
    const isAlive = async () => {
      let pid;
      try {
        [pid] = await this.readJsonPromise(lockPath);
      } catch (error) {
        return Date.now() - startTime < 500;
      }
      try {
        process.kill(pid, 0);
        return true;
      } catch (error) {
        return false;
      }
    };
    while (fd === null) {
      try {
        fd = await this.openPromise(lockPath, `wx`);
      } catch (error) {
        if (error.code === `EEXIST`) {
          if (!await isAlive()) {
            try {
              await this.unlinkPromise(lockPath);
              continue;
            } catch (error2) {
            }
          }
          if (Date.now() - startTime < 60 * 1e3) {
            await new Promise((resolve) => setTimeout(resolve, interval));
          } else {
            throw new Error(`Couldn't acquire a lock in a reasonable time (via ${lockPath})`);
          }
        } else {
          throw error;
        }
      }
    }
    await this.writePromise(fd, JSON.stringify([process.pid]));
    try {
      return await callback();
    } finally {
      try {
        await this.closePromise(fd);
        await this.unlinkPromise(lockPath);
      } catch (error) {
      }
    }
  }
  async readJsonPromise(p) {
    const content = await this.readFilePromise(p, `utf8`);
    try {
      return JSON.parse(content);
    } catch (error) {
      error.message += ` (in ${p})`;
      throw error;
    }
  }
  readJsonSync(p) {
    const content = this.readFileSync(p, `utf8`);
    try {
      return JSON.parse(content);
    } catch (error) {
      error.message += ` (in ${p})`;
      throw error;
    }
  }
  async writeJsonPromise(p, data) {
    return await this.writeFilePromise(p, `${JSON.stringify(data, null, 2)}
`);
  }
  writeJsonSync(p, data) {
    return this.writeFileSync(p, `${JSON.stringify(data, null, 2)}
`);
  }
  async preserveTimePromise(p, cb) {
    const stat = await this.lstatPromise(p);
    const result = await cb();
    if (typeof result !== `undefined`)
      p = result;
    if (this.lutimesPromise) {
      await this.lutimesPromise(p, stat.atime, stat.mtime);
    } else if (!stat.isSymbolicLink()) {
      await this.utimesPromise(p, stat.atime, stat.mtime);
    }
  }
  async preserveTimeSync(p, cb) {
    const stat = this.lstatSync(p);
    const result = cb();
    if (typeof result !== `undefined`)
      p = result;
    if (this.lutimesSync) {
      this.lutimesSync(p, stat.atime, stat.mtime);
    } else if (!stat.isSymbolicLink()) {
      this.utimesSync(p, stat.atime, stat.mtime);
    }
  }
}
exports.FakeFS = FakeFS;
class BasePortableFakeFS extends FakeFS {
  constructor() {
    super(path_1.ppath);
  }
}
exports.BasePortableFakeFS = BasePortableFakeFS;
function getEndOfLine(content) {
  const matches = content.match(/\r?\n/g);
  if (matches === null)
    return os_1.EOL;
  const crlf = matches.filter((nl) => nl === `\r
`).length;
  const lf = matches.length - crlf;
  return crlf > lf ? `\r
` : `
`;
}
function normalizeLineEndings(originalContent, newContent) {
  return newContent.replace(/\r?\n/g, getEndOfLine(originalContent));
}
exports.normalizeLineEndings = normalizeLineEndings;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/JailFS.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/JailFS.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.JailFS = void 0;
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const JAIL_ROOT = path_1.PortablePath.root;
class JailFS extends ProxiedFS_1.ProxiedFS {
  constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) {
    super(path_1.ppath);
    this.target = this.pathUtils.resolve(path_1.PortablePath.root, target);
    this.baseFs = baseFs;
  }
  getRealPath() {
    return this.pathUtils.resolve(this.baseFs.getRealPath(), this.pathUtils.relative(path_1.PortablePath.root, this.target));
  }
  getTarget() {
    return this.target;
  }
  getBaseFs() {
    return this.baseFs;
  }
  mapToBase(p) {
    const normalized = this.pathUtils.normalize(p);
    if (this.pathUtils.isAbsolute(p))
      return this.pathUtils.resolve(this.target, this.pathUtils.relative(JAIL_ROOT, p));
    if (normalized.match(/^\.\.\/?/))
      throw new Error(`Resolving this path (${p}) would escape the jail`);
    return this.pathUtils.resolve(this.target, p);
  }
  mapFromBase(p) {
    return this.pathUtils.resolve(JAIL_ROOT, this.pathUtils.relative(this.target, p));
  }
}
exports.JailFS = JailFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/LazyFS.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/LazyFS.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LazyFS = void 0;
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
class LazyFS extends ProxiedFS_1.ProxiedFS {
  constructor(factory, pathUtils) {
    super(pathUtils);
    this.instance = null;
    this.factory = factory;
  }
  get baseFs() {
    if (!this.instance)
      this.instance = this.factory();
    return this.instance;
  }
  set baseFs(value) {
    this.instance = value;
  }
  mapFromBase(p) {
    return p;
  }
  mapToBase(p) {
    return p;
  }
}
exports.LazyFS = LazyFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NoFS.js":
/*!*******************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/NoFS.js ***!
  \*******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoFS = void 0;
const FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const makeError = () => Object.assign(new Error(`ENOSYS: unsupported filesystem access`), { code: `ENOSYS` });
class NoFS extends FakeFS_1.FakeFS {
  constructor() {
    super(path_1.ppath);
  }
  getExtractHint() {
    throw makeError();
  }
  getRealPath() {
    throw makeError();
  }
  resolve() {
    throw makeError();
  }
  async openPromise() {
    throw makeError();
  }
  openSync() {
    throw makeError();
  }
  async opendirPromise() {
    throw makeError();
  }
  opendirSync() {
    throw makeError();
  }
  async readPromise() {
    throw makeError();
  }
  readSync() {
    throw makeError();
  }
  async writePromise() {
    throw makeError();
  }
  writeSync() {
    throw makeError();
  }
  async closePromise() {
    throw makeError();
  }
  closeSync() {
    throw makeError();
  }
  createWriteStream() {
    throw makeError();
  }
  createReadStream() {
    throw makeError();
  }
  async realpathPromise() {
    throw makeError();
  }
  realpathSync() {
    throw makeError();
  }
  async readdirPromise() {
    throw makeError();
  }
  readdirSync() {
    throw makeError();
  }
  async existsPromise(p) {
    throw makeError();
  }
  existsSync(p) {
    throw makeError();
  }
  async accessPromise() {
    throw makeError();
  }
  accessSync() {
    throw makeError();
  }
  async statPromise() {
    throw makeError();
  }
  statSync() {
    throw makeError();
  }
  async fstatPromise(fd) {
    throw makeError();
  }
  fstatSync(fd) {
    throw makeError();
  }
  async lstatPromise(p) {
    throw makeError();
  }
  lstatSync(p) {
    throw makeError();
  }
  async fchmodPromise() {
    throw makeError();
  }
  fchmodSync() {
    throw makeError();
  }
  async chmodPromise() {
    throw makeError();
  }
  chmodSync() {
    throw makeError();
  }
  async fchownPromise() {
    throw makeError();
  }
  fchownSync() {
    throw makeError();
  }
  async chownPromise() {
    throw makeError();
  }
  chownSync() {
    throw makeError();
  }
  async mkdirPromise() {
    throw makeError();
  }
  mkdirSync() {
    throw makeError();
  }
  async rmdirPromise() {
    throw makeError();
  }
  rmdirSync() {
    throw makeError();
  }
  async linkPromise() {
    throw makeError();
  }
  linkSync() {
    throw makeError();
  }
  async symlinkPromise() {
    throw makeError();
  }
  symlinkSync() {
    throw makeError();
  }
  async renamePromise() {
    throw makeError();
  }
  renameSync() {
    throw makeError();
  }
  async copyFilePromise() {
    throw makeError();
  }
  copyFileSync() {
    throw makeError();
  }
  async appendFilePromise() {
    throw makeError();
  }
  appendFileSync() {
    throw makeError();
  }
  async writeFilePromise() {
    throw makeError();
  }
  writeFileSync() {
    throw makeError();
  }
  async unlinkPromise() {
    throw makeError();
  }
  unlinkSync() {
    throw makeError();
  }
  async utimesPromise() {
    throw makeError();
  }
  utimesSync() {
    throw makeError();
  }
  async readFilePromise() {
    throw makeError();
  }
  readFileSync() {
    throw makeError();
  }
  async readlinkPromise() {
    throw makeError();
  }
  readlinkSync() {
    throw makeError();
  }
  async truncatePromise() {
    throw makeError();
  }
  truncateSync() {
    throw makeError();
  }
  async ftruncatePromise(fd, len) {
    throw makeError();
  }
  ftruncateSync(fd, len) {
    throw makeError();
  }
  watch() {
    throw makeError();
  }
  watchFile() {
    throw makeError();
  }
  unwatchFile() {
    throw makeError();
  }
}
exports.NoFS = NoFS;
NoFS.instance = new NoFS();


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NodeFS = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const fs_1 = tslib_1.__importDefault(__webpack_require__(/*! fs */ "fs"));
const FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
const errors_1 = __webpack_require__(/*! ./errors */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
class NodeFS extends FakeFS_1.BasePortableFakeFS {
  constructor(realFs = fs_1.default) {
    super();
    this.realFs = realFs;
    if (typeof this.realFs.lutimes !== `undefined`) {
      this.lutimesPromise = this.lutimesPromiseImpl;
      this.lutimesSync = this.lutimesSyncImpl;
    }
  }
  getExtractHint() {
    return false;
  }
  getRealPath() {
    return path_1.PortablePath.root;
  }
  resolve(p) {
    return path_1.ppath.resolve(p);
  }
  async openPromise(p, flags, mode) {
    return await new Promise((resolve, reject) => {
      this.realFs.open(path_1.npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject));
    });
  }
  openSync(p, flags, mode) {
    return this.realFs.openSync(path_1.npath.fromPortablePath(p), flags, mode);
  }
  async opendirPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      if (typeof opts !== `undefined`) {
        this.realFs.opendir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.opendir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
      }
    }).then((dir) => {
      return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true });
    });
  }
  opendirSync(p, opts) {
    const dir = typeof opts !== `undefined` ? this.realFs.opendirSync(path_1.npath.fromPortablePath(p), opts) : this.realFs.opendirSync(path_1.npath.fromPortablePath(p));
    return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true });
  }
  async readPromise(fd, buffer, offset = 0, length = 0, position = -1) {
    return await new Promise((resolve, reject) => {
      this.realFs.read(fd, buffer, offset, length, position, (error, bytesRead) => {
        if (error) {
          reject(error);
        } else {
          resolve(bytesRead);
        }
      });
    });
  }
  readSync(fd, buffer, offset, length, position) {
    return this.realFs.readSync(fd, buffer, offset, length, position);
  }
  async writePromise(fd, buffer, offset, length, position) {
    return await new Promise((resolve, reject) => {
      if (typeof buffer === `string`) {
        return this.realFs.write(fd, buffer, offset, this.makeCallback(resolve, reject));
      } else {
        return this.realFs.write(fd, buffer, offset, length, position, this.makeCallback(resolve, reject));
      }
    });
  }
  writeSync(fd, buffer, offset, length, position) {
    if (typeof buffer === `string`) {
      return this.realFs.writeSync(fd, buffer, offset);
    } else {
      return this.realFs.writeSync(fd, buffer, offset, length, position);
    }
  }
  async closePromise(fd) {
    await new Promise((resolve, reject) => {
      this.realFs.close(fd, this.makeCallback(resolve, reject));
    });
  }
  closeSync(fd) {
    this.realFs.closeSync(fd);
  }
  createReadStream(p, opts) {
    const realPath = p !== null ? path_1.npath.fromPortablePath(p) : p;
    return this.realFs.createReadStream(realPath, opts);
  }
  createWriteStream(p, opts) {
    const realPath = p !== null ? path_1.npath.fromPortablePath(p) : p;
    return this.realFs.createWriteStream(realPath, opts);
  }
  async realpathPromise(p) {
    return await new Promise((resolve, reject) => {
      this.realFs.realpath(path_1.npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject));
    }).then((path) => {
      return path_1.npath.toPortablePath(path);
    });
  }
  realpathSync(p) {
    return path_1.npath.toPortablePath(this.realFs.realpathSync(path_1.npath.fromPortablePath(p), {}));
  }
  async existsPromise(p) {
    return await new Promise((resolve) => {
      this.realFs.exists(path_1.npath.fromPortablePath(p), resolve);
    });
  }
  accessSync(p, mode) {
    return this.realFs.accessSync(path_1.npath.fromPortablePath(p), mode);
  }
  async accessPromise(p, mode) {
    return await new Promise((resolve, reject) => {
      this.realFs.access(path_1.npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject));
    });
  }
  existsSync(p) {
    return this.realFs.existsSync(path_1.npath.fromPortablePath(p));
  }
  async statPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      if (opts) {
        this.realFs.stat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.stat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
      }
    });
  }
  statSync(p, opts) {
    if (opts) {
      return this.realFs.statSync(path_1.npath.fromPortablePath(p), opts);
    } else {
      return this.realFs.statSync(path_1.npath.fromPortablePath(p));
    }
  }
  async fstatPromise(fd, opts) {
    return await new Promise((resolve, reject) => {
      if (opts) {
        this.realFs.fstat(fd, opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.fstat(fd, this.makeCallback(resolve, reject));
      }
    });
  }
  fstatSync(fd, opts) {
    if (opts) {
      return this.realFs.fstatSync(fd, opts);
    } else {
      return this.realFs.fstatSync(fd);
    }
  }
  async lstatPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      if (opts) {
        this.realFs.lstat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.lstat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
      }
    });
  }
  lstatSync(p, opts) {
    if (opts) {
      return this.realFs.lstatSync(path_1.npath.fromPortablePath(p), opts);
    } else {
      return this.realFs.lstatSync(path_1.npath.fromPortablePath(p));
    }
  }
  async fchmodPromise(fd, mask) {
    return await new Promise((resolve, reject) => {
      this.realFs.fchmod(fd, mask, this.makeCallback(resolve, reject));
    });
  }
  fchmodSync(fd, mask) {
    return this.realFs.fchmodSync(fd, mask);
  }
  async chmodPromise(p, mask) {
    return await new Promise((resolve, reject) => {
      this.realFs.chmod(path_1.npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject));
    });
  }
  chmodSync(p, mask) {
    return this.realFs.chmodSync(path_1.npath.fromPortablePath(p), mask);
  }
  async fchownPromise(fd, uid, gid) {
    return await new Promise((resolve, reject) => {
      this.realFs.fchown(fd, uid, gid, this.makeCallback(resolve, reject));
    });
  }
  fchownSync(fd, uid, gid) {
    return this.realFs.fchownSync(fd, uid, gid);
  }
  async chownPromise(p, uid, gid) {
    return await new Promise((resolve, reject) => {
      this.realFs.chown(path_1.npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject));
    });
  }
  chownSync(p, uid, gid) {
    return this.realFs.chownSync(path_1.npath.fromPortablePath(p), uid, gid);
  }
  async renamePromise(oldP, newP) {
    return await new Promise((resolve, reject) => {
      this.realFs.rename(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
    });
  }
  renameSync(oldP, newP) {
    return this.realFs.renameSync(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP));
  }
  async copyFilePromise(sourceP, destP, flags = 0) {
    return await new Promise((resolve, reject) => {
      this.realFs.copyFile(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject));
    });
  }
  copyFileSync(sourceP, destP, flags = 0) {
    return this.realFs.copyFileSync(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags);
  }
  async appendFilePromise(p, content, opts) {
    return await new Promise((resolve, reject) => {
      const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
      if (opts) {
        this.realFs.appendFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.appendFile(fsNativePath, content, this.makeCallback(resolve, reject));
      }
    });
  }
  appendFileSync(p, content, opts) {
    const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
    if (opts) {
      this.realFs.appendFileSync(fsNativePath, content, opts);
    } else {
      this.realFs.appendFileSync(fsNativePath, content);
    }
  }
  async writeFilePromise(p, content, opts) {
    return await new Promise((resolve, reject) => {
      const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
      if (opts) {
        this.realFs.writeFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.writeFile(fsNativePath, content, this.makeCallback(resolve, reject));
      }
    });
  }
  writeFileSync(p, content, opts) {
    const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
    if (opts) {
      this.realFs.writeFileSync(fsNativePath, content, opts);
    } else {
      this.realFs.writeFileSync(fsNativePath, content);
    }
  }
  async unlinkPromise(p) {
    return await new Promise((resolve, reject) => {
      this.realFs.unlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
    });
  }
  unlinkSync(p) {
    return this.realFs.unlinkSync(path_1.npath.fromPortablePath(p));
  }
  async utimesPromise(p, atime, mtime) {
    return await new Promise((resolve, reject) => {
      this.realFs.utimes(path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
    });
  }
  utimesSync(p, atime, mtime) {
    this.realFs.utimesSync(path_1.npath.fromPortablePath(p), atime, mtime);
  }
  async lutimesPromiseImpl(p, atime, mtime) {
    const lutimes = this.realFs.lutimes;
    if (typeof lutimes === `undefined`)
      throw (0, errors_1.ENOSYS)(`unavailable Node binding`, `lutimes '${p}'`);
    return await new Promise((resolve, reject) => {
      lutimes.call(this.realFs, path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
    });
  }
  lutimesSyncImpl(p, atime, mtime) {
    const lutimesSync = this.realFs.lutimesSync;
    if (typeof lutimesSync === `undefined`)
      throw (0, errors_1.ENOSYS)(`unavailable Node binding`, `lutimes '${p}'`);
    lutimesSync.call(this.realFs, path_1.npath.fromPortablePath(p), atime, mtime);
  }
  async mkdirPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      this.realFs.mkdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
    });
  }
  mkdirSync(p, opts) {
    return this.realFs.mkdirSync(path_1.npath.fromPortablePath(p), opts);
  }
  async rmdirPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      if (opts) {
        this.realFs.rmdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
      } else {
        this.realFs.rmdir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
      }
    });
  }
  rmdirSync(p, opts) {
    return this.realFs.rmdirSync(path_1.npath.fromPortablePath(p), opts);
  }
  async linkPromise(existingP, newP) {
    return await new Promise((resolve, reject) => {
      this.realFs.link(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
    });
  }
  linkSync(existingP, newP) {
    return this.realFs.linkSync(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP));
  }
  async symlinkPromise(target, p, type) {
    return await new Promise((resolve, reject) => {
      this.realFs.symlink(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type, this.makeCallback(resolve, reject));
    });
  }
  symlinkSync(target, p, type) {
    return this.realFs.symlinkSync(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type);
  }
  async readFilePromise(p, encoding) {
    return await new Promise((resolve, reject) => {
      const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
      this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject));
    });
  }
  readFileSync(p, encoding) {
    const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
    return this.realFs.readFileSync(fsNativePath, encoding);
  }
  async readdirPromise(p, opts) {
    return await new Promise((resolve, reject) => {
      if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) {
        this.realFs.readdir(path_1.npath.fromPortablePath(p), { withFileTypes: true }, this.makeCallback(resolve, reject));
      } else {
        this.realFs.readdir(path_1.npath.fromPortablePath(p), this.makeCallback((value) => resolve(value), reject));
      }
    });
  }
  readdirSync(p, opts) {
    if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) {
      return this.realFs.readdirSync(path_1.npath.fromPortablePath(p), { withFileTypes: true });
    } else {
      return this.realFs.readdirSync(path_1.npath.fromPortablePath(p));
    }
  }
  async readlinkPromise(p) {
    return await new Promise((resolve, reject) => {
      this.realFs.readlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
    }).then((path) => {
      return path_1.npath.toPortablePath(path);
    });
  }
  readlinkSync(p) {
    return path_1.npath.toPortablePath(this.realFs.readlinkSync(path_1.npath.fromPortablePath(p)));
  }
  async truncatePromise(p, len) {
    return await new Promise((resolve, reject) => {
      this.realFs.truncate(path_1.npath.fromPortablePath(p), len, this.makeCallback(resolve, reject));
    });
  }
  truncateSync(p, len) {
    return this.realFs.truncateSync(path_1.npath.fromPortablePath(p), len);
  }
  async ftruncatePromise(fd, len) {
    return await new Promise((resolve, reject) => {
      this.realFs.ftruncate(fd, len, this.makeCallback(resolve, reject));
    });
  }
  ftruncateSync(fd, len) {
    return this.realFs.ftruncateSync(fd, len);
  }
  watch(p, a, b) {
    return this.realFs.watch(
      path_1.npath.fromPortablePath(p),
      // @ts-expect-error
      a,
      b
    );
  }
  watchFile(p, a, b) {
    return this.realFs.watchFile(
      path_1.npath.fromPortablePath(p),
      // @ts-expect-error
      a,
      b
    );
  }
  unwatchFile(p, cb) {
    return this.realFs.unwatchFile(path_1.npath.fromPortablePath(p), cb);
  }
  makeCallback(resolve, reject) {
    return (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    };
  }
}
exports.NodeFS = NodeFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodePathFS.js":
/*!*************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodePathFS.js ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NodePathFS = void 0;
const url_1 = __webpack_require__(/*! url */ "url");
const util_1 = __webpack_require__(/*! util */ "util");
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
class NodePathFS extends ProxiedFS_1.ProxiedFS {
  constructor(baseFs) {
    super(path_1.npath);
    this.baseFs = baseFs;
  }
  mapFromBase(path) {
    return path;
  }
  mapToBase(path) {
    if (typeof path === `string`)
      return path;
    if (path instanceof url_1.URL)
      return (0, url_1.fileURLToPath)(path);
    if (Buffer.isBuffer(path)) {
      const str = path.toString();
      if (Buffer.byteLength(str) !== path.byteLength)
        throw new Error(`Non-utf8 buffers are not supported at the moment. Please upvote the following issue if you encounter this error: https://github.com/yarnpkg/berry/issues/4942`);
      return str;
    }
    throw new Error(`Unsupported path type: ${(0, util_1.inspect)(path)}`);
  }
}
exports.NodePathFS = NodePathFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/PosixFS.js":
/*!**********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/PosixFS.js ***!
  \**********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PosixFS = void 0;
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
class PosixFS extends ProxiedFS_1.ProxiedFS {
  constructor(baseFs) {
    super(path_1.npath);
    this.baseFs = baseFs;
  }
  mapFromBase(path) {
    return path_1.npath.fromPortablePath(path);
  }
  mapToBase(path) {
    return path_1.npath.toPortablePath(path);
  }
}
exports.PosixFS = PosixFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProxiedFS = void 0;
const FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
class ProxiedFS extends FakeFS_1.FakeFS {
  getExtractHint(hints) {
    return this.baseFs.getExtractHint(hints);
  }
  resolve(path) {
    return this.mapFromBase(this.baseFs.resolve(this.mapToBase(path)));
  }
  getRealPath() {
    return this.mapFromBase(this.baseFs.getRealPath());
  }
  async openPromise(p, flags, mode) {
    return this.baseFs.openPromise(this.mapToBase(p), flags, mode);
  }
  openSync(p, flags, mode) {
    return this.baseFs.openSync(this.mapToBase(p), flags, mode);
  }
  async opendirPromise(p, opts) {
    return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(p), opts), { path: p });
  }
  opendirSync(p, opts) {
    return Object.assign(this.baseFs.opendirSync(this.mapToBase(p), opts), { path: p });
  }
  async readPromise(fd, buffer, offset, length, position) {
    return await this.baseFs.readPromise(fd, buffer, offset, length, position);
  }
  readSync(fd, buffer, offset, length, position) {
    return this.baseFs.readSync(fd, buffer, offset, length, position);
  }
  async writePromise(fd, buffer, offset, length, position) {
    if (typeof buffer === `string`) {
      return await this.baseFs.writePromise(fd, buffer, offset);
    } else {
      return await this.baseFs.writePromise(fd, buffer, offset, length, position);
    }
  }
  writeSync(fd, buffer, offset, length, position) {
    if (typeof buffer === `string`) {
      return this.baseFs.writeSync(fd, buffer, offset);
    } else {
      return this.baseFs.writeSync(fd, buffer, offset, length, position);
    }
  }
  async closePromise(fd) {
    return this.baseFs.closePromise(fd);
  }
  closeSync(fd) {
    this.baseFs.closeSync(fd);
  }
  createReadStream(p, opts) {
    return this.baseFs.createReadStream(p !== null ? this.mapToBase(p) : p, opts);
  }
  createWriteStream(p, opts) {
    return this.baseFs.createWriteStream(p !== null ? this.mapToBase(p) : p, opts);
  }
  async realpathPromise(p) {
    return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(p)));
  }
  realpathSync(p) {
    return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(p)));
  }
  async existsPromise(p) {
    return this.baseFs.existsPromise(this.mapToBase(p));
  }
  existsSync(p) {
    return this.baseFs.existsSync(this.mapToBase(p));
  }
  accessSync(p, mode) {
    return this.baseFs.accessSync(this.mapToBase(p), mode);
  }
  async accessPromise(p, mode) {
    return this.baseFs.accessPromise(this.mapToBase(p), mode);
  }
  async statPromise(p, opts) {
    return this.baseFs.statPromise(this.mapToBase(p), opts);
  }
  statSync(p, opts) {
    return this.baseFs.statSync(this.mapToBase(p), opts);
  }
  async fstatPromise(fd, opts) {
    return this.baseFs.fstatPromise(fd, opts);
  }
  fstatSync(fd, opts) {
    return this.baseFs.fstatSync(fd, opts);
  }
  lstatPromise(p, opts) {
    return this.baseFs.lstatPromise(this.mapToBase(p), opts);
  }
  lstatSync(p, opts) {
    return this.baseFs.lstatSync(this.mapToBase(p), opts);
  }
  async fchmodPromise(fd, mask) {
    return this.baseFs.fchmodPromise(fd, mask);
  }
  fchmodSync(fd, mask) {
    return this.baseFs.fchmodSync(fd, mask);
  }
  async chmodPromise(p, mask) {
    return this.baseFs.chmodPromise(this.mapToBase(p), mask);
  }
  chmodSync(p, mask) {
    return this.baseFs.chmodSync(this.mapToBase(p), mask);
  }
  async fchownPromise(fd, uid, gid) {
    return this.baseFs.fchownPromise(fd, uid, gid);
  }
  fchownSync(fd, uid, gid) {
    return this.baseFs.fchownSync(fd, uid, gid);
  }
  async chownPromise(p, uid, gid) {
    return this.baseFs.chownPromise(this.mapToBase(p), uid, gid);
  }
  chownSync(p, uid, gid) {
    return this.baseFs.chownSync(this.mapToBase(p), uid, gid);
  }
  async renamePromise(oldP, newP) {
    return this.baseFs.renamePromise(this.mapToBase(oldP), this.mapToBase(newP));
  }
  renameSync(oldP, newP) {
    return this.baseFs.renameSync(this.mapToBase(oldP), this.mapToBase(newP));
  }
  async copyFilePromise(sourceP, destP, flags = 0) {
    return this.baseFs.copyFilePromise(this.mapToBase(sourceP), this.mapToBase(destP), flags);
  }
  copyFileSync(sourceP, destP, flags = 0) {
    return this.baseFs.copyFileSync(this.mapToBase(sourceP), this.mapToBase(destP), flags);
  }
  async appendFilePromise(p, content, opts) {
    return this.baseFs.appendFilePromise(this.fsMapToBase(p), content, opts);
  }
  appendFileSync(p, content, opts) {
    return this.baseFs.appendFileSync(this.fsMapToBase(p), content, opts);
  }
  async writeFilePromise(p, content, opts) {
    return this.baseFs.writeFilePromise(this.fsMapToBase(p), content, opts);
  }
  writeFileSync(p, content, opts) {
    return this.baseFs.writeFileSync(this.fsMapToBase(p), content, opts);
  }
  async unlinkPromise(p) {
    return this.baseFs.unlinkPromise(this.mapToBase(p));
  }
  unlinkSync(p) {
    return this.baseFs.unlinkSync(this.mapToBase(p));
  }
  async utimesPromise(p, atime, mtime) {
    return this.baseFs.utimesPromise(this.mapToBase(p), atime, mtime);
  }
  utimesSync(p, atime, mtime) {
    return this.baseFs.utimesSync(this.mapToBase(p), atime, mtime);
  }
  async mkdirPromise(p, opts) {
    return this.baseFs.mkdirPromise(this.mapToBase(p), opts);
  }
  mkdirSync(p, opts) {
    return this.baseFs.mkdirSync(this.mapToBase(p), opts);
  }
  async rmdirPromise(p, opts) {
    return this.baseFs.rmdirPromise(this.mapToBase(p), opts);
  }
  rmdirSync(p, opts) {
    return this.baseFs.rmdirSync(this.mapToBase(p), opts);
  }
  async linkPromise(existingP, newP) {
    return this.baseFs.linkPromise(this.mapToBase(existingP), this.mapToBase(newP));
  }
  linkSync(existingP, newP) {
    return this.baseFs.linkSync(this.mapToBase(existingP), this.mapToBase(newP));
  }
  async symlinkPromise(target, p, type) {
    const mappedP = this.mapToBase(p);
    if (this.pathUtils.isAbsolute(target))
      return this.baseFs.symlinkPromise(this.mapToBase(target), mappedP, type);
    const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
    const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
    return this.baseFs.symlinkPromise(mappedTarget, mappedP, type);
  }
  symlinkSync(target, p, type) {
    const mappedP = this.mapToBase(p);
    if (this.pathUtils.isAbsolute(target))
      return this.baseFs.symlinkSync(this.mapToBase(target), mappedP, type);
    const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
    const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
    return this.baseFs.symlinkSync(mappedTarget, mappedP, type);
  }
  async readFilePromise(p, encoding) {
    return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding);
  }
  readFileSync(p, encoding) {
    return this.baseFs.readFileSync(this.fsMapToBase(p), encoding);
  }
  async readdirPromise(p, opts) {
    return this.baseFs.readdirPromise(this.mapToBase(p), opts);
  }
  readdirSync(p, opts) {
    return this.baseFs.readdirSync(this.mapToBase(p), opts);
  }
  async readlinkPromise(p) {
    return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(p)));
  }
  readlinkSync(p) {
    return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(p)));
  }
  async truncatePromise(p, len) {
    return this.baseFs.truncatePromise(this.mapToBase(p), len);
  }
  truncateSync(p, len) {
    return this.baseFs.truncateSync(this.mapToBase(p), len);
  }
  async ftruncatePromise(fd, len) {
    return this.baseFs.ftruncatePromise(fd, len);
  }
  ftruncateSync(fd, len) {
    return this.baseFs.ftruncateSync(fd, len);
  }
  watch(p, a, b) {
    return this.baseFs.watch(
      this.mapToBase(p),
      // @ts-expect-error
      a,
      b
    );
  }
  watchFile(p, a, b) {
    return this.baseFs.watchFile(
      this.mapToBase(p),
      // @ts-expect-error
      a,
      b
    );
  }
  unwatchFile(p, cb) {
    return this.baseFs.unwatchFile(this.mapToBase(p), cb);
  }
  fsMapToBase(p) {
    if (typeof p === `number`) {
      return p;
    } else {
      return this.mapToBase(p);
    }
  }
}
exports.ProxiedFS = ProxiedFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/VirtualFS.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/VirtualFS.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VirtualFS = void 0;
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const NUMBER_REGEXP = /^[0-9]+$/;
const VIRTUAL_REGEXP = /^(\/(?:[^/]+\/)*?(?:\$\$virtual|__virtual__))((?:\/((?:[^/]+-)?[a-f0-9]+)(?:\/([^/]+))?)?((?:\/.*)?))$/;
const VALID_COMPONENT = /^([^/]+-)?[a-f0-9]+$/;
class VirtualFS extends ProxiedFS_1.ProxiedFS {
  static makeVirtualPath(base, component, to) {
    if (path_1.ppath.basename(base) !== `__virtual__`)
      throw new Error(`Assertion failed: Virtual folders must be named "__virtual__"`);
    if (!path_1.ppath.basename(component).match(VALID_COMPONENT))
      throw new Error(`Assertion failed: Virtual components must be ended by an hexadecimal hash`);
    const target = path_1.ppath.relative(path_1.ppath.dirname(base), to);
    const segments = target.split(`/`);
    let depth = 0;
    while (depth < segments.length && segments[depth] === `..`)
      depth += 1;
    const finalSegments = segments.slice(depth);
    const fullVirtualPath = path_1.ppath.join(base, component, String(depth), ...finalSegments);
    return fullVirtualPath;
  }
  static resolveVirtual(p) {
    const match = p.match(VIRTUAL_REGEXP);
    if (!match || !match[3] && match[5])
      return p;
    const target = path_1.ppath.dirname(match[1]);
    if (!match[3] || !match[4])
      return target;
    const isnum = NUMBER_REGEXP.test(match[4]);
    if (!isnum)
      return p;
    const depth = Number(match[4]);
    const backstep = `../`.repeat(depth);
    const subpath = match[5] || `.`;
    return VirtualFS.resolveVirtual(path_1.ppath.join(target, backstep, subpath));
  }
  constructor({ baseFs = new NodeFS_1.NodeFS() } = {}) {
    super(path_1.ppath);
    this.baseFs = baseFs;
  }
  getExtractHint(hints) {
    return this.baseFs.getExtractHint(hints);
  }
  getRealPath() {
    return this.baseFs.getRealPath();
  }
  realpathSync(p) {
    const match = p.match(VIRTUAL_REGEXP);
    if (!match)
      return this.baseFs.realpathSync(p);
    if (!match[5])
      return p;
    const realpath = this.baseFs.realpathSync(this.mapToBase(p));
    return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
  }
  async realpathPromise(p) {
    const match = p.match(VIRTUAL_REGEXP);
    if (!match)
      return await this.baseFs.realpathPromise(p);
    if (!match[5])
      return p;
    const realpath = await this.baseFs.realpathPromise(this.mapToBase(p));
    return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
  }
  mapToBase(p) {
    if (p === ``)
      return p;
    if (this.pathUtils.isAbsolute(p))
      return VirtualFS.resolveVirtual(p);
    const resolvedRoot = VirtualFS.resolveVirtual(this.baseFs.resolve(path_1.PortablePath.dot));
    const resolvedP = VirtualFS.resolveVirtual(this.baseFs.resolve(p));
    return path_1.ppath.relative(resolvedRoot, resolvedP) || path_1.PortablePath.dot;
  }
  mapFromBase(p) {
    return p;
  }
}
exports.VirtualFS = VirtualFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipFS.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipFS.js ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ZipFS = exports.makeEmptyArchive = exports.DEFAULT_COMPRESSION_LEVEL = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const fs_1 = __webpack_require__(/*! fs */ "fs");
const stream_1 = __webpack_require__(/*! stream */ "stream");
const util_1 = __webpack_require__(/*! util */ "util");
const zlib_1 = tslib_1.__importDefault(__webpack_require__(/*! zlib */ "zlib"));
const FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const opendir_1 = __webpack_require__(/*! ./algorithms/opendir */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/opendir.js");
const watchFile_1 = __webpack_require__(/*! ./algorithms/watchFile */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile.js");
const constants_1 = __webpack_require__(/*! ./constants */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js");
const errors = tslib_1.__importStar(__webpack_require__(/*! ./errors */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js"));
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const statUtils = tslib_1.__importStar(__webpack_require__(/*! ./statUtils */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/statUtils.js"));
exports.DEFAULT_COMPRESSION_LEVEL = `mixed`;
function toUnixTimestamp(time) {
  if (typeof time === `string` && String(+time) === time)
    return +time;
  if (typeof time === `number` && Number.isFinite(time)) {
    if (time < 0) {
      return Date.now() / 1e3;
    } else {
      return time;
    }
  }
  if (util_1.types.isDate(time))
    return time.getTime() / 1e3;
  throw new Error(`Invalid time`);
}
function makeEmptyArchive() {
  return Buffer.from([
    80,
    75,
    5,
    6,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0
  ]);
}
exports.makeEmptyArchive = makeEmptyArchive;
class ZipFS extends FakeFS_1.BasePortableFakeFS {
  constructor(source, opts) {
    super();
    this.lzSource = null;
    this.listings = /* @__PURE__ */ new Map();
    this.entries = /* @__PURE__ */ new Map();
    this.fileSources = /* @__PURE__ */ new Map();
    this.fds = /* @__PURE__ */ new Map();
    this.nextFd = 0;
    this.ready = false;
    this.readOnly = false;
    this.libzip = opts.libzip;
    const pathOptions = opts;
    this.level = typeof pathOptions.level !== `undefined` ? pathOptions.level : exports.DEFAULT_COMPRESSION_LEVEL;
    source !== null && source !== void 0 ? source : source = makeEmptyArchive();
    if (typeof source === `string`) {
      const { baseFs = new NodeFS_1.NodeFS() } = pathOptions;
      this.baseFs = baseFs;
      this.path = source;
    } else {
      this.path = null;
      this.baseFs = null;
    }
    if (opts.stats) {
      this.stats = opts.stats;
    } else {
      if (typeof source === `string`) {
        try {
          this.stats = this.baseFs.statSync(source);
        } catch (error) {
          if (error.code === `ENOENT` && pathOptions.create) {
            this.stats = statUtils.makeDefaultStats();
          } else {
            throw error;
          }
        }
      } else {
        this.stats = statUtils.makeDefaultStats();
      }
    }
    const errPtr = this.libzip.malloc(4);
    try {
      let flags = 0;
      if (typeof source === `string` && pathOptions.create)
        flags |= this.libzip.ZIP_CREATE | this.libzip.ZIP_TRUNCATE;
      if (opts.readOnly) {
        flags |= this.libzip.ZIP_RDONLY;
        this.readOnly = true;
      }
      if (typeof source === `string`) {
        this.zip = this.libzip.open(path_1.npath.fromPortablePath(source), flags, errPtr);
      } else {
        const lzSource = this.allocateUnattachedSource(source);
        try {
          this.zip = this.libzip.openFromSource(lzSource, flags, errPtr);
          this.lzSource = lzSource;
        } catch (error) {
          this.libzip.source.free(lzSource);
          throw error;
        }
      }
      if (this.zip === 0) {
        const error = this.libzip.struct.errorS();
        this.libzip.error.initWithCode(error, this.libzip.getValue(errPtr, `i32`));
        throw this.makeLibzipError(error);
      }
    } finally {
      this.libzip.free(errPtr);
    }
    this.listings.set(path_1.PortablePath.root, /* @__PURE__ */ new Set());
    const entryCount = this.libzip.getNumEntries(this.zip, 0);
    for (let t = 0; t < entryCount; ++t) {
      const raw = this.libzip.getName(this.zip, t, 0);
      if (path_1.ppath.isAbsolute(raw))
        continue;
      const p = path_1.ppath.resolve(path_1.PortablePath.root, raw);
      this.registerEntry(p, t);
      if (raw.endsWith(`/`)) {
        this.registerListing(p);
      }
    }
    this.symlinkCount = this.libzip.ext.countSymlinks(this.zip);
    if (this.symlinkCount === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    this.ready = true;
  }
  makeLibzipError(error) {
    const errorCode = this.libzip.struct.errorCodeZip(error);
    const strerror = this.libzip.error.strerror(error);
    const libzipError = new errors.LibzipError(strerror, this.libzip.errors[errorCode]);
    if (errorCode === this.libzip.errors.ZIP_ER_CHANGED)
      throw new Error(`Assertion failed: Unexpected libzip error: ${libzipError.message}`);
    return libzipError;
  }
  getExtractHint(hints) {
    for (const fileName of this.entries.keys()) {
      const ext = this.pathUtils.extname(fileName);
      if (hints.relevantExtensions.has(ext)) {
        return true;
      }
    }
    return false;
  }
  getAllFiles() {
    return Array.from(this.entries.keys());
  }
  getRealPath() {
    if (!this.path)
      throw new Error(`ZipFS don't have real paths when loaded from a buffer`);
    return this.path;
  }
  getBufferAndClose() {
    this.prepareClose();
    if (!this.lzSource)
      throw new Error(`ZipFS was not created from a Buffer`);
    if (this.entries.size === 0) {
      this.discardAndClose();
      return makeEmptyArchive();
    }
    try {
      this.libzip.source.keep(this.lzSource);
      if (this.libzip.close(this.zip) === -1)
        throw this.makeLibzipError(this.libzip.getError(this.zip));
      if (this.libzip.source.open(this.lzSource) === -1)
        throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
      if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_END) === -1)
        throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
      const size = this.libzip.source.tell(this.lzSource);
      if (size === -1)
        throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
      if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_SET) === -1)
        throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
      const buffer = this.libzip.malloc(size);
      if (!buffer)
        throw new Error(`Couldn't allocate enough memory`);
      try {
        const rc = this.libzip.source.read(this.lzSource, buffer, size);
        if (rc === -1)
          throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
        else if (rc < size)
          throw new Error(`Incomplete read`);
        else if (rc > size)
          throw new Error(`Overread`);
        const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
        return Buffer.from(memory);
      } finally {
        this.libzip.free(buffer);
      }
    } finally {
      this.libzip.source.close(this.lzSource);
      this.libzip.source.free(this.lzSource);
      this.ready = false;
    }
  }
  prepareClose() {
    if (!this.ready)
      throw errors.EBUSY(`archive closed, close`);
    (0, watchFile_1.unwatchAllFiles)(this);
  }
  saveAndClose() {
    if (!this.path || !this.baseFs)
      throw new Error(`ZipFS cannot be saved and must be discarded when loaded from a buffer`);
    this.prepareClose();
    if (this.readOnly) {
      this.discardAndClose();
      return;
    }
    const newMode = this.baseFs.existsSync(this.path) || this.stats.mode === statUtils.DEFAULT_MODE ? void 0 : this.stats.mode;
    if (this.entries.size === 0) {
      this.discardAndClose();
      this.baseFs.writeFileSync(this.path, makeEmptyArchive(), { mode: newMode });
    } else {
      const rc = this.libzip.close(this.zip);
      if (rc === -1)
        throw this.makeLibzipError(this.libzip.getError(this.zip));
      if (typeof newMode !== `undefined`) {
        this.baseFs.chmodSync(this.path, newMode);
      }
    }
    this.ready = false;
  }
  discardAndClose() {
    this.prepareClose();
    this.libzip.discard(this.zip);
    this.ready = false;
  }
  resolve(p) {
    return path_1.ppath.resolve(path_1.PortablePath.root, p);
  }
  async openPromise(p, flags, mode) {
    return this.openSync(p, flags, mode);
  }
  openSync(p, flags, mode) {
    const fd = this.nextFd++;
    this.fds.set(fd, { cursor: 0, p });
    return fd;
  }
  hasOpenFileHandles() {
    return !!this.fds.size;
  }
  async opendirPromise(p, opts) {
    return this.opendirSync(p, opts);
  }
  opendirSync(p, opts = {}) {
    const resolvedP = this.resolveFilename(`opendir '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`opendir '${p}'`);
    const directoryListing = this.listings.get(resolvedP);
    if (!directoryListing)
      throw errors.ENOTDIR(`opendir '${p}'`);
    const entries = [...directoryListing];
    const fd = this.openSync(resolvedP, `r`);
    const onClose = () => {
      this.closeSync(fd);
    };
    return (0, opendir_1.opendir)(this, resolvedP, entries, { onClose });
  }
  async readPromise(fd, buffer, offset, length, position) {
    return this.readSync(fd, buffer, offset, length, position);
  }
  readSync(fd, buffer, offset = 0, length = buffer.byteLength, position = -1) {
    const entry = this.fds.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`read`);
    const realPosition = position === -1 || position === null ? entry.cursor : position;
    const source = this.readFileSync(entry.p);
    source.copy(buffer, offset, realPosition, realPosition + length);
    const bytesRead = Math.max(0, Math.min(source.length - realPosition, length));
    if (position === -1 || position === null)
      entry.cursor += bytesRead;
    return bytesRead;
  }
  async writePromise(fd, buffer, offset, length, position) {
    if (typeof buffer === `string`) {
      return this.writeSync(fd, buffer, position);
    } else {
      return this.writeSync(fd, buffer, offset, length, position);
    }
  }
  writeSync(fd, buffer, offset, length, position) {
    const entry = this.fds.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`read`);
    throw new Error(`Unimplemented`);
  }
  async closePromise(fd) {
    return this.closeSync(fd);
  }
  closeSync(fd) {
    const entry = this.fds.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`read`);
    this.fds.delete(fd);
  }
  createReadStream(p, { encoding } = {}) {
    if (p === null)
      throw new Error(`Unimplemented`);
    const fd = this.openSync(p, `r`);
    const stream = Object.assign(new stream_1.PassThrough({
      emitClose: true,
      autoDestroy: true,
      destroy: (error, callback) => {
        clearImmediate(immediate);
        this.closeSync(fd);
        callback(error);
      }
    }), {
      close() {
        stream.destroy();
      },
      bytesRead: 0,
      path: p,
      // "This property is `true` if the underlying file has not been opened yet"
      pending: false
    });
    const immediate = setImmediate(async () => {
      try {
        const data = await this.readFilePromise(p, encoding);
        stream.bytesRead = data.length;
        stream.end(data);
      } catch (error) {
        stream.destroy(error);
      }
    });
    return stream;
  }
  createWriteStream(p, { encoding } = {}) {
    if (this.readOnly)
      throw errors.EROFS(`open '${p}'`);
    if (p === null)
      throw new Error(`Unimplemented`);
    const chunks = [];
    const fd = this.openSync(p, `w`);
    const stream = Object.assign(new stream_1.PassThrough({
      autoDestroy: true,
      emitClose: true,
      destroy: (error, callback) => {
        try {
          if (error) {
            callback(error);
          } else {
            this.writeFileSync(p, Buffer.concat(chunks), encoding);
            callback(null);
          }
        } catch (err) {
          callback(err);
        } finally {
          this.closeSync(fd);
        }
      }
    }), {
      close() {
        stream.destroy();
      },
      bytesWritten: 0,
      path: p,
      // "This property is `true` if the underlying file has not been opened yet"
      pending: false
    });
    stream.on(`data`, (chunk) => {
      const chunkBuffer = Buffer.from(chunk);
      stream.bytesWritten += chunkBuffer.length;
      chunks.push(chunkBuffer);
    });
    return stream;
  }
  async realpathPromise(p) {
    return this.realpathSync(p);
  }
  realpathSync(p) {
    const resolvedP = this.resolveFilename(`lstat '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`lstat '${p}'`);
    return resolvedP;
  }
  async existsPromise(p) {
    return this.existsSync(p);
  }
  existsSync(p) {
    if (!this.ready)
      throw errors.EBUSY(`archive closed, existsSync '${p}'`);
    if (this.symlinkCount === 0) {
      const resolvedP2 = path_1.ppath.resolve(path_1.PortablePath.root, p);
      return this.entries.has(resolvedP2) || this.listings.has(resolvedP2);
    }
    let resolvedP;
    try {
      resolvedP = this.resolveFilename(`stat '${p}'`, p, void 0, false);
    } catch (error) {
      return false;
    }
    if (resolvedP === void 0)
      return false;
    return this.entries.has(resolvedP) || this.listings.has(resolvedP);
  }
  async accessPromise(p, mode) {
    return this.accessSync(p, mode);
  }
  accessSync(p, mode = fs_1.constants.F_OK) {
    const resolvedP = this.resolveFilename(`access '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`access '${p}'`);
    if (this.readOnly && mode & fs_1.constants.W_OK) {
      throw errors.EROFS(`access '${p}'`);
    }
  }
  async statPromise(p, opts = { bigint: false }) {
    if (opts.bigint)
      return this.statSync(p, { bigint: true });
    return this.statSync(p);
  }
  statSync(p, opts = { bigint: false, throwIfNoEntry: true }) {
    const resolvedP = this.resolveFilename(`stat '${p}'`, p, void 0, opts.throwIfNoEntry);
    if (resolvedP === void 0)
      return void 0;
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) {
      if (opts.throwIfNoEntry === false)
        return void 0;
      throw errors.ENOENT(`stat '${p}'`);
    }
    if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
      throw errors.ENOTDIR(`stat '${p}'`);
    return this.statImpl(`stat '${p}'`, resolvedP, opts);
  }
  async fstatPromise(fd, opts) {
    return this.fstatSync(fd, opts);
  }
  fstatSync(fd, opts) {
    const entry = this.fds.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fstatSync`);
    const { p } = entry;
    const resolvedP = this.resolveFilename(`stat '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`stat '${p}'`);
    if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
      throw errors.ENOTDIR(`stat '${p}'`);
    return this.statImpl(`fstat '${p}'`, resolvedP, opts);
  }
  async lstatPromise(p, opts = { bigint: false }) {
    if (opts.bigint)
      return this.lstatSync(p, { bigint: true });
    return this.lstatSync(p);
  }
  lstatSync(p, opts = { bigint: false, throwIfNoEntry: true }) {
    const resolvedP = this.resolveFilename(`lstat '${p}'`, p, false, opts.throwIfNoEntry);
    if (resolvedP === void 0)
      return void 0;
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) {
      if (opts.throwIfNoEntry === false)
        return void 0;
      throw errors.ENOENT(`lstat '${p}'`);
    }
    if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
      throw errors.ENOTDIR(`lstat '${p}'`);
    return this.statImpl(`lstat '${p}'`, resolvedP, opts);
  }
  statImpl(reason, p, opts = {}) {
    const entry = this.entries.get(p);
    if (typeof entry !== `undefined`) {
      const stat = this.libzip.struct.statS();
      const rc = this.libzip.statIndex(this.zip, entry, 0, 0, stat);
      if (rc === -1)
        throw this.makeLibzipError(this.libzip.getError(this.zip));
      const uid = this.stats.uid;
      const gid = this.stats.gid;
      const size = this.libzip.struct.statSize(stat) >>> 0;
      const blksize = 512;
      const blocks = Math.ceil(size / blksize);
      const mtimeMs = (this.libzip.struct.statMtime(stat) >>> 0) * 1e3;
      const atimeMs = mtimeMs;
      const birthtimeMs = mtimeMs;
      const ctimeMs = mtimeMs;
      const atime = new Date(atimeMs);
      const birthtime = new Date(birthtimeMs);
      const ctime = new Date(ctimeMs);
      const mtime = new Date(mtimeMs);
      const type = this.listings.has(p) ? constants_1.S_IFDIR : this.isSymbolicLink(entry) ? constants_1.S_IFLNK : constants_1.S_IFREG;
      const defaultMode = type === constants_1.S_IFDIR ? 493 : 420;
      const mode = type | this.getUnixMode(entry, defaultMode) & 511;
      const crc = this.libzip.struct.statCrc(stat);
      const statInstance = Object.assign(new statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc });
      return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance;
    }
    if (this.listings.has(p)) {
      const uid = this.stats.uid;
      const gid = this.stats.gid;
      const size = 0;
      const blksize = 512;
      const blocks = 0;
      const atimeMs = this.stats.mtimeMs;
      const birthtimeMs = this.stats.mtimeMs;
      const ctimeMs = this.stats.mtimeMs;
      const mtimeMs = this.stats.mtimeMs;
      const atime = new Date(atimeMs);
      const birthtime = new Date(birthtimeMs);
      const ctime = new Date(ctimeMs);
      const mtime = new Date(mtimeMs);
      const mode = constants_1.S_IFDIR | 493;
      const crc = 0;
      const statInstance = Object.assign(new statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc });
      return opts.bigint === true ? statUtils.convertToBigIntStats(statInstance) : statInstance;
    }
    throw new Error(`Unreachable`);
  }
  getUnixMode(index, defaultMode) {
    const rc = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
    if (rc === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
    if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
      return defaultMode;
    return this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
  }
  registerListing(p) {
    const existingListing = this.listings.get(p);
    if (existingListing)
      return existingListing;
    const parentListing = this.registerListing(path_1.ppath.dirname(p));
    parentListing.add(path_1.ppath.basename(p));
    const newListing = /* @__PURE__ */ new Set();
    this.listings.set(p, newListing);
    return newListing;
  }
  registerEntry(p, index) {
    const parentListing = this.registerListing(path_1.ppath.dirname(p));
    parentListing.add(path_1.ppath.basename(p));
    this.entries.set(p, index);
  }
  unregisterListing(p) {
    this.listings.delete(p);
    const parentListing = this.listings.get(path_1.ppath.dirname(p));
    parentListing === null || parentListing === void 0 ? void 0 : parentListing.delete(path_1.ppath.basename(p));
  }
  unregisterEntry(p) {
    this.unregisterListing(p);
    const entry = this.entries.get(p);
    this.entries.delete(p);
    if (typeof entry === `undefined`)
      return;
    this.fileSources.delete(entry);
    if (this.isSymbolicLink(entry)) {
      this.symlinkCount--;
    }
  }
  deleteEntry(p, index) {
    this.unregisterEntry(p);
    const rc = this.libzip.delete(this.zip, index);
    if (rc === -1) {
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    }
  }
  resolveFilename(reason, p, resolveLastComponent = true, throwIfNoEntry = true) {
    if (!this.ready)
      throw errors.EBUSY(`archive closed, ${reason}`);
    let resolvedP = path_1.ppath.resolve(path_1.PortablePath.root, p);
    if (resolvedP === `/`)
      return path_1.PortablePath.root;
    const fileIndex = this.entries.get(resolvedP);
    if (resolveLastComponent && fileIndex !== void 0) {
      if (this.symlinkCount !== 0 && this.isSymbolicLink(fileIndex)) {
        const target = this.getFileSource(fileIndex).toString();
        return this.resolveFilename(reason, path_1.ppath.resolve(path_1.ppath.dirname(resolvedP), target), true, throwIfNoEntry);
      } else {
        return resolvedP;
      }
    }
    while (true) {
      const parentP = this.resolveFilename(reason, path_1.ppath.dirname(resolvedP), true, throwIfNoEntry);
      if (parentP === void 0)
        return parentP;
      const isDir = this.listings.has(parentP);
      const doesExist = this.entries.has(parentP);
      if (!isDir && !doesExist) {
        if (throwIfNoEntry === false)
          return void 0;
        throw errors.ENOENT(reason);
      }
      if (!isDir)
        throw errors.ENOTDIR(reason);
      resolvedP = path_1.ppath.resolve(parentP, path_1.ppath.basename(resolvedP));
      if (!resolveLastComponent || this.symlinkCount === 0)
        break;
      const index = this.libzip.name.locate(this.zip, resolvedP.slice(1), 0);
      if (index === -1)
        break;
      if (this.isSymbolicLink(index)) {
        const target = this.getFileSource(index).toString();
        resolvedP = path_1.ppath.resolve(path_1.ppath.dirname(resolvedP), target);
      } else {
        break;
      }
    }
    return resolvedP;
  }
  allocateBuffer(content) {
    if (!Buffer.isBuffer(content))
      content = Buffer.from(content);
    const buffer = this.libzip.malloc(content.byteLength);
    if (!buffer)
      throw new Error(`Couldn't allocate enough memory`);
    const heap = new Uint8Array(this.libzip.HEAPU8.buffer, buffer, content.byteLength);
    heap.set(content);
    return { buffer, byteLength: content.byteLength };
  }
  allocateUnattachedSource(content) {
    const error = this.libzip.struct.errorS();
    const { buffer, byteLength } = this.allocateBuffer(content);
    const source = this.libzip.source.fromUnattachedBuffer(buffer, byteLength, 0, 1, error);
    if (source === 0) {
      this.libzip.free(error);
      throw this.makeLibzipError(error);
    }
    return source;
  }
  allocateSource(content) {
    const { buffer, byteLength } = this.allocateBuffer(content);
    const source = this.libzip.source.fromBuffer(this.zip, buffer, byteLength, 0, 1);
    if (source === 0) {
      this.libzip.free(buffer);
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    }
    return source;
  }
  setFileSource(p, content) {
    const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
    const target = path_1.ppath.relative(path_1.PortablePath.root, p);
    const lzSource = this.allocateSource(content);
    try {
      const newIndex = this.libzip.file.add(this.zip, target, lzSource, this.libzip.ZIP_FL_OVERWRITE);
      if (newIndex === -1)
        throw this.makeLibzipError(this.libzip.getError(this.zip));
      if (this.level !== `mixed`) {
        const method = this.level === 0 ? this.libzip.ZIP_CM_STORE : this.libzip.ZIP_CM_DEFLATE;
        const rc = this.libzip.file.setCompression(this.zip, newIndex, 0, method, this.level);
        if (rc === -1) {
          throw this.makeLibzipError(this.libzip.getError(this.zip));
        }
      }
      this.fileSources.set(newIndex, buffer);
      return newIndex;
    } catch (error) {
      this.libzip.source.free(lzSource);
      throw error;
    }
  }
  isSymbolicLink(index) {
    if (this.symlinkCount === 0)
      return false;
    const attrs = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
    if (attrs === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
    if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
      return false;
    const attributes = this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
    return (attributes & constants_1.S_IFMT) === constants_1.S_IFLNK;
  }
  getFileSource(index, opts = { asyncDecompress: false }) {
    const cachedFileSource = this.fileSources.get(index);
    if (typeof cachedFileSource !== `undefined`)
      return cachedFileSource;
    const stat = this.libzip.struct.statS();
    const rc = this.libzip.statIndex(this.zip, index, 0, 0, stat);
    if (rc === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    const size = this.libzip.struct.statCompSize(stat);
    const compressionMethod = this.libzip.struct.statCompMethod(stat);
    const buffer = this.libzip.malloc(size);
    try {
      const file = this.libzip.fopenIndex(this.zip, index, 0, this.libzip.ZIP_FL_COMPRESSED);
      if (file === 0)
        throw this.makeLibzipError(this.libzip.getError(this.zip));
      try {
        const rc2 = this.libzip.fread(file, buffer, size, 0);
        if (rc2 === -1)
          throw this.makeLibzipError(this.libzip.file.getError(file));
        else if (rc2 < size)
          throw new Error(`Incomplete read`);
        else if (rc2 > size)
          throw new Error(`Overread`);
        const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
        const data = Buffer.from(memory);
        if (compressionMethod === 0) {
          this.fileSources.set(index, data);
          return data;
        } else if (opts.asyncDecompress) {
          return new Promise((resolve, reject) => {
            zlib_1.default.inflateRaw(data, (error, result) => {
              if (error) {
                reject(error);
              } else {
                this.fileSources.set(index, result);
                resolve(result);
              }
            });
          });
        } else {
          const decompressedData = zlib_1.default.inflateRawSync(data);
          this.fileSources.set(index, decompressedData);
          return decompressedData;
        }
      } finally {
        this.libzip.fclose(file);
      }
    } finally {
      this.libzip.free(buffer);
    }
  }
  async fchmodPromise(fd, mask) {
    return this.chmodPromise(this.fdToPath(fd, `fchmod`), mask);
  }
  fchmodSync(fd, mask) {
    return this.chmodSync(this.fdToPath(fd, `fchmodSync`), mask);
  }
  async chmodPromise(p, mask) {
    return this.chmodSync(p, mask);
  }
  chmodSync(p, mask) {
    if (this.readOnly)
      throw errors.EROFS(`chmod '${p}'`);
    mask &= 493;
    const resolvedP = this.resolveFilename(`chmod '${p}'`, p, false);
    const entry = this.entries.get(resolvedP);
    if (typeof entry === `undefined`)
      throw new Error(`Assertion failed: The entry should have been registered (${resolvedP})`);
    const oldMod = this.getUnixMode(entry, constants_1.S_IFREG | 0);
    const newMod = oldMod & ~511 | mask;
    const rc = this.libzip.file.setExternalAttributes(this.zip, entry, 0, 0, this.libzip.ZIP_OPSYS_UNIX, newMod << 16);
    if (rc === -1) {
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    }
  }
  async fchownPromise(fd, uid, gid) {
    return this.chownPromise(this.fdToPath(fd, `fchown`), uid, gid);
  }
  fchownSync(fd, uid, gid) {
    return this.chownSync(this.fdToPath(fd, `fchownSync`), uid, gid);
  }
  async chownPromise(p, uid, gid) {
    return this.chownSync(p, uid, gid);
  }
  chownSync(p, uid, gid) {
    throw new Error(`Unimplemented`);
  }
  async renamePromise(oldP, newP) {
    return this.renameSync(oldP, newP);
  }
  renameSync(oldP, newP) {
    throw new Error(`Unimplemented`);
  }
  async copyFilePromise(sourceP, destP, flags) {
    const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags);
    const source = await this.getFileSource(indexSource, { asyncDecompress: true });
    const newIndex = this.setFileSource(resolvedDestP, source);
    if (newIndex !== indexDest) {
      this.registerEntry(resolvedDestP, newIndex);
    }
  }
  copyFileSync(sourceP, destP, flags = 0) {
    const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags);
    const source = this.getFileSource(indexSource);
    const newIndex = this.setFileSource(resolvedDestP, source);
    if (newIndex !== indexDest) {
      this.registerEntry(resolvedDestP, newIndex);
    }
  }
  prepareCopyFile(sourceP, destP, flags = 0) {
    if (this.readOnly)
      throw errors.EROFS(`copyfile '${sourceP} -> '${destP}'`);
    if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
      throw errors.ENOSYS(`unsupported clone operation`, `copyfile '${sourceP}' -> ${destP}'`);
    const resolvedSourceP = this.resolveFilename(`copyfile '${sourceP} -> ${destP}'`, sourceP);
    const indexSource = this.entries.get(resolvedSourceP);
    if (typeof indexSource === `undefined`)
      throw errors.EINVAL(`copyfile '${sourceP}' -> '${destP}'`);
    const resolvedDestP = this.resolveFilename(`copyfile '${sourceP}' -> ${destP}'`, destP);
    const indexDest = this.entries.get(resolvedDestP);
    if ((flags & (fs_1.constants.COPYFILE_EXCL | fs_1.constants.COPYFILE_FICLONE_FORCE)) !== 0 && typeof indexDest !== `undefined`)
      throw errors.EEXIST(`copyfile '${sourceP}' -> '${destP}'`);
    return {
      indexSource,
      resolvedDestP,
      indexDest
    };
  }
  async appendFilePromise(p, content, opts) {
    if (this.readOnly)
      throw errors.EROFS(`open '${p}'`);
    if (typeof opts === `undefined`)
      opts = { flag: `a` };
    else if (typeof opts === `string`)
      opts = { flag: `a`, encoding: opts };
    else if (typeof opts.flag === `undefined`)
      opts = { flag: `a`, ...opts };
    return this.writeFilePromise(p, content, opts);
  }
  appendFileSync(p, content, opts = {}) {
    if (this.readOnly)
      throw errors.EROFS(`open '${p}'`);
    if (typeof opts === `undefined`)
      opts = { flag: `a` };
    else if (typeof opts === `string`)
      opts = { flag: `a`, encoding: opts };
    else if (typeof opts.flag === `undefined`)
      opts = { flag: `a`, ...opts };
    return this.writeFileSync(p, content, opts);
  }
  fdToPath(fd, reason) {
    var _a;
    const path = (_a = this.fds.get(fd)) === null || _a === void 0 ? void 0 : _a.p;
    if (typeof path === `undefined`)
      throw errors.EBADF(reason);
    return path;
  }
  async writeFilePromise(p, content, opts) {
    const { encoding, mode, index, resolvedP } = this.prepareWriteFile(p, opts);
    if (index !== void 0 && typeof opts === `object` && opts.flag && opts.flag.includes(`a`))
      content = Buffer.concat([await this.getFileSource(index, { asyncDecompress: true }), Buffer.from(content)]);
    if (encoding !== null)
      content = content.toString(encoding);
    const newIndex = this.setFileSource(resolvedP, content);
    if (newIndex !== index)
      this.registerEntry(resolvedP, newIndex);
    if (mode !== null) {
      await this.chmodPromise(resolvedP, mode);
    }
  }
  writeFileSync(p, content, opts) {
    const { encoding, mode, index, resolvedP } = this.prepareWriteFile(p, opts);
    if (index !== void 0 && typeof opts === `object` && opts.flag && opts.flag.includes(`a`))
      content = Buffer.concat([this.getFileSource(index), Buffer.from(content)]);
    if (encoding !== null)
      content = content.toString(encoding);
    const newIndex = this.setFileSource(resolvedP, content);
    if (newIndex !== index)
      this.registerEntry(resolvedP, newIndex);
    if (mode !== null) {
      this.chmodSync(resolvedP, mode);
    }
  }
  prepareWriteFile(p, opts) {
    if (typeof p === `number`)
      p = this.fdToPath(p, `read`);
    if (this.readOnly)
      throw errors.EROFS(`open '${p}'`);
    const resolvedP = this.resolveFilename(`open '${p}'`, p);
    if (this.listings.has(resolvedP))
      throw errors.EISDIR(`open '${p}'`);
    let encoding = null, mode = null;
    if (typeof opts === `string`) {
      encoding = opts;
    } else if (typeof opts === `object`) {
      ({
        encoding = null,
        mode = null
      } = opts);
    }
    const index = this.entries.get(resolvedP);
    return {
      encoding,
      mode,
      resolvedP,
      index
    };
  }
  async unlinkPromise(p) {
    return this.unlinkSync(p);
  }
  unlinkSync(p) {
    if (this.readOnly)
      throw errors.EROFS(`unlink '${p}'`);
    const resolvedP = this.resolveFilename(`unlink '${p}'`, p);
    if (this.listings.has(resolvedP))
      throw errors.EISDIR(`unlink '${p}'`);
    const index = this.entries.get(resolvedP);
    if (typeof index === `undefined`)
      throw errors.EINVAL(`unlink '${p}'`);
    this.deleteEntry(resolvedP, index);
  }
  async utimesPromise(p, atime, mtime) {
    return this.utimesSync(p, atime, mtime);
  }
  utimesSync(p, atime, mtime) {
    if (this.readOnly)
      throw errors.EROFS(`utimes '${p}'`);
    const resolvedP = this.resolveFilename(`utimes '${p}'`, p);
    this.utimesImpl(resolvedP, mtime);
  }
  async lutimesPromise(p, atime, mtime) {
    return this.lutimesSync(p, atime, mtime);
  }
  lutimesSync(p, atime, mtime) {
    if (this.readOnly)
      throw errors.EROFS(`lutimes '${p}'`);
    const resolvedP = this.resolveFilename(`utimes '${p}'`, p, false);
    this.utimesImpl(resolvedP, mtime);
  }
  utimesImpl(resolvedP, mtime) {
    if (this.listings.has(resolvedP)) {
      if (!this.entries.has(resolvedP))
        this.hydrateDirectory(resolvedP);
    }
    const entry = this.entries.get(resolvedP);
    if (entry === void 0)
      throw new Error(`Unreachable`);
    const rc = this.libzip.file.setMtime(this.zip, entry, 0, toUnixTimestamp(mtime), 0);
    if (rc === -1) {
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    }
  }
  async mkdirPromise(p, opts) {
    return this.mkdirSync(p, opts);
  }
  mkdirSync(p, { mode = 493, recursive = false } = {}) {
    if (recursive)
      return this.mkdirpSync(p, { chmod: mode });
    if (this.readOnly)
      throw errors.EROFS(`mkdir '${p}'`);
    const resolvedP = this.resolveFilename(`mkdir '${p}'`, p);
    if (this.entries.has(resolvedP) || this.listings.has(resolvedP))
      throw errors.EEXIST(`mkdir '${p}'`);
    this.hydrateDirectory(resolvedP);
    this.chmodSync(resolvedP, mode);
    return void 0;
  }
  async rmdirPromise(p, opts) {
    return this.rmdirSync(p, opts);
  }
  rmdirSync(p, { recursive = false } = {}) {
    if (this.readOnly)
      throw errors.EROFS(`rmdir '${p}'`);
    if (recursive) {
      this.removeSync(p);
      return;
    }
    const resolvedP = this.resolveFilename(`rmdir '${p}'`, p);
    const directoryListing = this.listings.get(resolvedP);
    if (!directoryListing)
      throw errors.ENOTDIR(`rmdir '${p}'`);
    if (directoryListing.size > 0)
      throw errors.ENOTEMPTY(`rmdir '${p}'`);
    const index = this.entries.get(resolvedP);
    if (typeof index === `undefined`)
      throw errors.EINVAL(`rmdir '${p}'`);
    this.deleteEntry(p, index);
  }
  hydrateDirectory(resolvedP) {
    const index = this.libzip.dir.add(this.zip, path_1.ppath.relative(path_1.PortablePath.root, resolvedP));
    if (index === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    this.registerListing(resolvedP);
    this.registerEntry(resolvedP, index);
    return index;
  }
  async linkPromise(existingP, newP) {
    return this.linkSync(existingP, newP);
  }
  linkSync(existingP, newP) {
    throw errors.EOPNOTSUPP(`link '${existingP}' -> '${newP}'`);
  }
  async symlinkPromise(target, p) {
    return this.symlinkSync(target, p);
  }
  symlinkSync(target, p) {
    if (this.readOnly)
      throw errors.EROFS(`symlink '${target}' -> '${p}'`);
    const resolvedP = this.resolveFilename(`symlink '${target}' -> '${p}'`, p);
    if (this.listings.has(resolvedP))
      throw errors.EISDIR(`symlink '${target}' -> '${p}'`);
    if (this.entries.has(resolvedP))
      throw errors.EEXIST(`symlink '${target}' -> '${p}'`);
    const index = this.setFileSource(resolvedP, target);
    this.registerEntry(resolvedP, index);
    const rc = this.libzip.file.setExternalAttributes(this.zip, index, 0, 0, this.libzip.ZIP_OPSYS_UNIX, (constants_1.S_IFLNK | 511) << 16);
    if (rc === -1)
      throw this.makeLibzipError(this.libzip.getError(this.zip));
    this.symlinkCount += 1;
  }
  async readFilePromise(p, encoding) {
    if (typeof encoding === `object`)
      encoding = encoding ? encoding.encoding : void 0;
    const data = await this.readFileBuffer(p, { asyncDecompress: true });
    return encoding ? data.toString(encoding) : data;
  }
  readFileSync(p, encoding) {
    if (typeof encoding === `object`)
      encoding = encoding ? encoding.encoding : void 0;
    const data = this.readFileBuffer(p);
    return encoding ? data.toString(encoding) : data;
  }
  readFileBuffer(p, opts = { asyncDecompress: false }) {
    if (typeof p === `number`)
      p = this.fdToPath(p, `read`);
    const resolvedP = this.resolveFilename(`open '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`open '${p}'`);
    if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
      throw errors.ENOTDIR(`open '${p}'`);
    if (this.listings.has(resolvedP))
      throw errors.EISDIR(`read`);
    const entry = this.entries.get(resolvedP);
    if (entry === void 0)
      throw new Error(`Unreachable`);
    return this.getFileSource(entry, opts);
  }
  async readdirPromise(p, opts) {
    return this.readdirSync(p, opts);
  }
  readdirSync(p, opts) {
    const resolvedP = this.resolveFilename(`scandir '${p}'`, p);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`scandir '${p}'`);
    const directoryListing = this.listings.get(resolvedP);
    if (!directoryListing)
      throw errors.ENOTDIR(`scandir '${p}'`);
    const entries = [...directoryListing];
    if (!(opts === null || opts === void 0 ? void 0 : opts.withFileTypes))
      return entries;
    return entries.map((name) => {
      return Object.assign(this.statImpl(`lstat`, path_1.ppath.join(p, name)), {
        name
      });
    });
  }
  async readlinkPromise(p) {
    const entry = this.prepareReadlink(p);
    return (await this.getFileSource(entry, { asyncDecompress: true })).toString();
  }
  readlinkSync(p) {
    const entry = this.prepareReadlink(p);
    return this.getFileSource(entry).toString();
  }
  prepareReadlink(p) {
    const resolvedP = this.resolveFilename(`readlink '${p}'`, p, false);
    if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
      throw errors.ENOENT(`readlink '${p}'`);
    if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
      throw errors.ENOTDIR(`open '${p}'`);
    if (this.listings.has(resolvedP))
      throw errors.EINVAL(`readlink '${p}'`);
    const entry = this.entries.get(resolvedP);
    if (entry === void 0)
      throw new Error(`Unreachable`);
    if (!this.isSymbolicLink(entry))
      throw errors.EINVAL(`readlink '${p}'`);
    return entry;
  }
  async truncatePromise(p, len = 0) {
    const resolvedP = this.resolveFilename(`open '${p}'`, p);
    const index = this.entries.get(resolvedP);
    if (typeof index === `undefined`)
      throw errors.EINVAL(`open '${p}'`);
    const source = await this.getFileSource(index, { asyncDecompress: true });
    const truncated = Buffer.alloc(len, 0);
    source.copy(truncated);
    return await this.writeFilePromise(p, truncated);
  }
  truncateSync(p, len = 0) {
    const resolvedP = this.resolveFilename(`open '${p}'`, p);
    const index = this.entries.get(resolvedP);
    if (typeof index === `undefined`)
      throw errors.EINVAL(`open '${p}'`);
    const source = this.getFileSource(index);
    const truncated = Buffer.alloc(len, 0);
    source.copy(truncated);
    return this.writeFileSync(p, truncated);
  }
  async ftruncatePromise(fd, len) {
    return this.truncatePromise(this.fdToPath(fd, `ftruncate`), len);
  }
  ftruncateSync(fd, len) {
    return this.truncateSync(this.fdToPath(fd, `ftruncateSync`), len);
  }
  watch(p, a, b) {
    let persistent;
    switch (typeof a) {
      case `function`:
      case `string`:
      case `undefined`:
        {
          persistent = true;
        }
        break;
      default:
        {
          ({ persistent = true } = a);
        }
        break;
    }
    if (!persistent)
      return { on: () => {
      }, close: () => {
      } };
    const interval = setInterval(() => {
    }, 24 * 60 * 60 * 1e3);
    return { on: () => {
    }, close: () => {
      clearInterval(interval);
    } };
  }
  watchFile(p, a, b) {
    const resolvedP = path_1.ppath.resolve(path_1.PortablePath.root, p);
    return (0, watchFile_1.watchFile)(this, resolvedP, a, b);
  }
  unwatchFile(p, cb) {
    const resolvedP = path_1.ppath.resolve(path_1.PortablePath.root, p);
    return (0, watchFile_1.unwatchFile)(this, resolvedP, cb);
  }
}
exports.ZipFS = ZipFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipOpenFS.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipOpenFS.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ZipOpenFS = exports.getArchivePart = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const fs_1 = __webpack_require__(/*! fs */ "fs");
const FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const ZipFS_1 = __webpack_require__(/*! ./ZipFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipFS.js");
const watchFile_1 = __webpack_require__(/*! ./algorithms/watchFile */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile.js");
const errors = tslib_1.__importStar(__webpack_require__(/*! ./errors */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js"));
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const ZIP_MASK = 4278190080;
const ZIP_MAGIC = 704643072;
const getArchivePart = (path, extension) => {
  let idx = path.indexOf(extension);
  if (idx <= 0)
    return null;
  let nextCharIdx = idx;
  while (idx >= 0) {
    nextCharIdx = idx + extension.length;
    if (path[nextCharIdx] === path_1.ppath.sep)
      break;
    if (path[idx - 1] === path_1.ppath.sep)
      return null;
    idx = path.indexOf(extension, nextCharIdx);
  }
  if (path.length > nextCharIdx && path[nextCharIdx] !== path_1.ppath.sep)
    return null;
  return path.slice(0, nextCharIdx);
};
exports.getArchivePart = getArchivePart;
class ZipOpenFS extends FakeFS_1.BasePortableFakeFS {
  static async openPromise(fn, opts) {
    const zipOpenFs = new ZipOpenFS(opts);
    try {
      return await fn(zipOpenFs);
    } finally {
      zipOpenFs.saveAndClose();
    }
  }
  get libzip() {
    if (typeof this.libzipInstance === `undefined`)
      this.libzipInstance = this.libzipFactory();
    return this.libzipInstance;
  }
  constructor({ libzip, baseFs = new NodeFS_1.NodeFS(), filter = null, maxOpenFiles = Infinity, readOnlyArchives = false, useCache = true, maxAge = 5e3, fileExtensions = null }) {
    super();
    this.fdMap = /* @__PURE__ */ new Map();
    this.nextFd = 3;
    this.isZip = /* @__PURE__ */ new Set();
    this.notZip = /* @__PURE__ */ new Set();
    this.realPaths = /* @__PURE__ */ new Map();
    this.limitOpenFilesTimeout = null;
    this.libzipFactory = typeof libzip !== `function` ? () => libzip : libzip;
    this.baseFs = baseFs;
    this.zipInstances = useCache ? /* @__PURE__ */ new Map() : null;
    this.filter = filter;
    this.maxOpenFiles = maxOpenFiles;
    this.readOnlyArchives = readOnlyArchives;
    this.maxAge = maxAge;
    this.fileExtensions = fileExtensions;
  }
  getExtractHint(hints) {
    return this.baseFs.getExtractHint(hints);
  }
  getRealPath() {
    return this.baseFs.getRealPath();
  }
  saveAndClose() {
    (0, watchFile_1.unwatchAllFiles)(this);
    if (this.zipInstances) {
      for (const [path, { zipFs }] of this.zipInstances.entries()) {
        zipFs.saveAndClose();
        this.zipInstances.delete(path);
      }
    }
  }
  discardAndClose() {
    (0, watchFile_1.unwatchAllFiles)(this);
    if (this.zipInstances) {
      for (const [path, { zipFs }] of this.zipInstances.entries()) {
        zipFs.discardAndClose();
        this.zipInstances.delete(path);
      }
    }
  }
  resolve(p) {
    return this.baseFs.resolve(p);
  }
  remapFd(zipFs, fd) {
    const remappedFd = this.nextFd++ | ZIP_MAGIC;
    this.fdMap.set(remappedFd, [zipFs, fd]);
    return remappedFd;
  }
  async openPromise(p, flags, mode) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.openPromise(p, flags, mode);
    }, async (zipFs, { subPath }) => {
      return this.remapFd(zipFs, await zipFs.openPromise(subPath, flags, mode));
    });
  }
  openSync(p, flags, mode) {
    return this.makeCallSync(p, () => {
      return this.baseFs.openSync(p, flags, mode);
    }, (zipFs, { subPath }) => {
      return this.remapFd(zipFs, zipFs.openSync(subPath, flags, mode));
    });
  }
  async opendirPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.opendirPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.opendirPromise(subPath, opts);
    }, {
      requireSubpath: false
    });
  }
  opendirSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.opendirSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.opendirSync(subPath, opts);
    }, {
      requireSubpath: false
    });
  }
  async readPromise(fd, buffer, offset, length, position) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return await this.baseFs.readPromise(fd, buffer, offset, length, position);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`read`);
    const [zipFs, realFd] = entry;
    return await zipFs.readPromise(realFd, buffer, offset, length, position);
  }
  readSync(fd, buffer, offset, length, position) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.readSync(fd, buffer, offset, length, position);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`readSync`);
    const [zipFs, realFd] = entry;
    return zipFs.readSync(realFd, buffer, offset, length, position);
  }
  async writePromise(fd, buffer, offset, length, position) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC) {
      if (typeof buffer === `string`) {
        return await this.baseFs.writePromise(fd, buffer, offset);
      } else {
        return await this.baseFs.writePromise(fd, buffer, offset, length, position);
      }
    }
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`write`);
    const [zipFs, realFd] = entry;
    if (typeof buffer === `string`) {
      return await zipFs.writePromise(realFd, buffer, offset);
    } else {
      return await zipFs.writePromise(realFd, buffer, offset, length, position);
    }
  }
  writeSync(fd, buffer, offset, length, position) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC) {
      if (typeof buffer === `string`) {
        return this.baseFs.writeSync(fd, buffer, offset);
      } else {
        return this.baseFs.writeSync(fd, buffer, offset, length, position);
      }
    }
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`writeSync`);
    const [zipFs, realFd] = entry;
    if (typeof buffer === `string`) {
      return zipFs.writeSync(realFd, buffer, offset);
    } else {
      return zipFs.writeSync(realFd, buffer, offset, length, position);
    }
  }
  async closePromise(fd) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return await this.baseFs.closePromise(fd);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`close`);
    this.fdMap.delete(fd);
    const [zipFs, realFd] = entry;
    return await zipFs.closePromise(realFd);
  }
  closeSync(fd) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.closeSync(fd);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`closeSync`);
    this.fdMap.delete(fd);
    const [zipFs, realFd] = entry;
    return zipFs.closeSync(realFd);
  }
  createReadStream(p, opts) {
    if (p === null)
      return this.baseFs.createReadStream(p, opts);
    return this.makeCallSync(p, () => {
      return this.baseFs.createReadStream(p, opts);
    }, (zipFs, { archivePath, subPath }) => {
      const stream = zipFs.createReadStream(subPath, opts);
      stream.path = path_1.npath.fromPortablePath(this.pathUtils.join(archivePath, subPath));
      return stream;
    });
  }
  createWriteStream(p, opts) {
    if (p === null)
      return this.baseFs.createWriteStream(p, opts);
    return this.makeCallSync(p, () => {
      return this.baseFs.createWriteStream(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.createWriteStream(subPath, opts);
    });
  }
  async realpathPromise(p) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.realpathPromise(p);
    }, async (zipFs, { archivePath, subPath }) => {
      let realArchivePath = this.realPaths.get(archivePath);
      if (typeof realArchivePath === `undefined`) {
        realArchivePath = await this.baseFs.realpathPromise(archivePath);
        this.realPaths.set(archivePath, realArchivePath);
      }
      return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, await zipFs.realpathPromise(subPath)));
    });
  }
  realpathSync(p) {
    return this.makeCallSync(p, () => {
      return this.baseFs.realpathSync(p);
    }, (zipFs, { archivePath, subPath }) => {
      let realArchivePath = this.realPaths.get(archivePath);
      if (typeof realArchivePath === `undefined`) {
        realArchivePath = this.baseFs.realpathSync(archivePath);
        this.realPaths.set(archivePath, realArchivePath);
      }
      return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, zipFs.realpathSync(subPath)));
    });
  }
  async existsPromise(p) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.existsPromise(p);
    }, async (zipFs, { subPath }) => {
      return await zipFs.existsPromise(subPath);
    });
  }
  existsSync(p) {
    return this.makeCallSync(p, () => {
      return this.baseFs.existsSync(p);
    }, (zipFs, { subPath }) => {
      return zipFs.existsSync(subPath);
    });
  }
  async accessPromise(p, mode) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.accessPromise(p, mode);
    }, async (zipFs, { subPath }) => {
      return await zipFs.accessPromise(subPath, mode);
    });
  }
  accessSync(p, mode) {
    return this.makeCallSync(p, () => {
      return this.baseFs.accessSync(p, mode);
    }, (zipFs, { subPath }) => {
      return zipFs.accessSync(subPath, mode);
    });
  }
  async statPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.statPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.statPromise(subPath, opts);
    });
  }
  statSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.statSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.statSync(subPath, opts);
    });
  }
  async fstatPromise(fd, opts) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fstatPromise(fd, opts);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fstat`);
    const [zipFs, realFd] = entry;
    return zipFs.fstatPromise(realFd, opts);
  }
  fstatSync(fd, opts) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fstatSync(fd, opts);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fstatSync`);
    const [zipFs, realFd] = entry;
    return zipFs.fstatSync(realFd, opts);
  }
  async lstatPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.lstatPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.lstatPromise(subPath, opts);
    });
  }
  lstatSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.lstatSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.lstatSync(subPath, opts);
    });
  }
  async fchmodPromise(fd, mask) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fchmodPromise(fd, mask);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fchmod`);
    const [zipFs, realFd] = entry;
    return zipFs.fchmodPromise(realFd, mask);
  }
  fchmodSync(fd, mask) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fchmodSync(fd, mask);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fchmodSync`);
    const [zipFs, realFd] = entry;
    return zipFs.fchmodSync(realFd, mask);
  }
  async chmodPromise(p, mask) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.chmodPromise(p, mask);
    }, async (zipFs, { subPath }) => {
      return await zipFs.chmodPromise(subPath, mask);
    });
  }
  chmodSync(p, mask) {
    return this.makeCallSync(p, () => {
      return this.baseFs.chmodSync(p, mask);
    }, (zipFs, { subPath }) => {
      return zipFs.chmodSync(subPath, mask);
    });
  }
  async fchownPromise(fd, uid, gid) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fchownPromise(fd, uid, gid);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fchown`);
    const [zipFs, realFd] = entry;
    return zipFs.fchownPromise(realFd, uid, gid);
  }
  fchownSync(fd, uid, gid) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.fchownSync(fd, uid, gid);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`fchownSync`);
    const [zipFs, realFd] = entry;
    return zipFs.fchownSync(realFd, uid, gid);
  }
  async chownPromise(p, uid, gid) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.chownPromise(p, uid, gid);
    }, async (zipFs, { subPath }) => {
      return await zipFs.chownPromise(subPath, uid, gid);
    });
  }
  chownSync(p, uid, gid) {
    return this.makeCallSync(p, () => {
      return this.baseFs.chownSync(p, uid, gid);
    }, (zipFs, { subPath }) => {
      return zipFs.chownSync(subPath, uid, gid);
    });
  }
  async renamePromise(oldP, newP) {
    return await this.makeCallPromise(oldP, async () => {
      return await this.makeCallPromise(newP, async () => {
        return await this.baseFs.renamePromise(oldP, newP);
      }, async () => {
        throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
      });
    }, async (zipFsO, { subPath: subPathO }) => {
      return await this.makeCallPromise(newP, async () => {
        throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
      }, async (zipFsN, { subPath: subPathN }) => {
        if (zipFsO !== zipFsN) {
          throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
        } else {
          return await zipFsO.renamePromise(subPathO, subPathN);
        }
      });
    });
  }
  renameSync(oldP, newP) {
    return this.makeCallSync(oldP, () => {
      return this.makeCallSync(newP, () => {
        return this.baseFs.renameSync(oldP, newP);
      }, () => {
        throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
      });
    }, (zipFsO, { subPath: subPathO }) => {
      return this.makeCallSync(newP, () => {
        throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
      }, (zipFsN, { subPath: subPathN }) => {
        if (zipFsO !== zipFsN) {
          throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
        } else {
          return zipFsO.renameSync(subPathO, subPathN);
        }
      });
    });
  }
  async copyFilePromise(sourceP, destP, flags = 0) {
    const fallback = async (sourceFs, sourceP2, destFs, destP2) => {
      if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
        throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP2}' -> ${destP2}'`), { code: `EXDEV` });
      if (flags & fs_1.constants.COPYFILE_EXCL && await this.existsPromise(sourceP2))
        throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP2}' -> '${destP2}'`), { code: `EEXIST` });
      let content;
      try {
        content = await sourceFs.readFilePromise(sourceP2);
      } catch (error) {
        throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP2}' -> '${destP2}'`), { code: `EINVAL` });
      }
      await destFs.writeFilePromise(destP2, content);
    };
    return await this.makeCallPromise(sourceP, async () => {
      return await this.makeCallPromise(destP, async () => {
        return await this.baseFs.copyFilePromise(sourceP, destP, flags);
      }, async (zipFsD, { subPath: subPathD }) => {
        return await fallback(this.baseFs, sourceP, zipFsD, subPathD);
      });
    }, async (zipFsS, { subPath: subPathS }) => {
      return await this.makeCallPromise(destP, async () => {
        return await fallback(zipFsS, subPathS, this.baseFs, destP);
      }, async (zipFsD, { subPath: subPathD }) => {
        if (zipFsS !== zipFsD) {
          return await fallback(zipFsS, subPathS, zipFsD, subPathD);
        } else {
          return await zipFsS.copyFilePromise(subPathS, subPathD, flags);
        }
      });
    });
  }
  copyFileSync(sourceP, destP, flags = 0) {
    const fallback = (sourceFs, sourceP2, destFs, destP2) => {
      if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
        throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP2}' -> ${destP2}'`), { code: `EXDEV` });
      if (flags & fs_1.constants.COPYFILE_EXCL && this.existsSync(sourceP2))
        throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP2}' -> '${destP2}'`), { code: `EEXIST` });
      let content;
      try {
        content = sourceFs.readFileSync(sourceP2);
      } catch (error) {
        throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP2}' -> '${destP2}'`), { code: `EINVAL` });
      }
      destFs.writeFileSync(destP2, content);
    };
    return this.makeCallSync(sourceP, () => {
      return this.makeCallSync(destP, () => {
        return this.baseFs.copyFileSync(sourceP, destP, flags);
      }, (zipFsD, { subPath: subPathD }) => {
        return fallback(this.baseFs, sourceP, zipFsD, subPathD);
      });
    }, (zipFsS, { subPath: subPathS }) => {
      return this.makeCallSync(destP, () => {
        return fallback(zipFsS, subPathS, this.baseFs, destP);
      }, (zipFsD, { subPath: subPathD }) => {
        if (zipFsS !== zipFsD) {
          return fallback(zipFsS, subPathS, zipFsD, subPathD);
        } else {
          return zipFsS.copyFileSync(subPathS, subPathD, flags);
        }
      });
    });
  }
  async appendFilePromise(p, content, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.appendFilePromise(p, content, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.appendFilePromise(subPath, content, opts);
    });
  }
  appendFileSync(p, content, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.appendFileSync(p, content, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.appendFileSync(subPath, content, opts);
    });
  }
  async writeFilePromise(p, content, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.writeFilePromise(p, content, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.writeFilePromise(subPath, content, opts);
    });
  }
  writeFileSync(p, content, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.writeFileSync(p, content, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.writeFileSync(subPath, content, opts);
    });
  }
  async unlinkPromise(p) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.unlinkPromise(p);
    }, async (zipFs, { subPath }) => {
      return await zipFs.unlinkPromise(subPath);
    });
  }
  unlinkSync(p) {
    return this.makeCallSync(p, () => {
      return this.baseFs.unlinkSync(p);
    }, (zipFs, { subPath }) => {
      return zipFs.unlinkSync(subPath);
    });
  }
  async utimesPromise(p, atime, mtime) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.utimesPromise(p, atime, mtime);
    }, async (zipFs, { subPath }) => {
      return await zipFs.utimesPromise(subPath, atime, mtime);
    });
  }
  utimesSync(p, atime, mtime) {
    return this.makeCallSync(p, () => {
      return this.baseFs.utimesSync(p, atime, mtime);
    }, (zipFs, { subPath }) => {
      return zipFs.utimesSync(subPath, atime, mtime);
    });
  }
  async mkdirPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.mkdirPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.mkdirPromise(subPath, opts);
    });
  }
  mkdirSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.mkdirSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.mkdirSync(subPath, opts);
    });
  }
  async rmdirPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.rmdirPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.rmdirPromise(subPath, opts);
    });
  }
  rmdirSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.rmdirSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.rmdirSync(subPath, opts);
    });
  }
  async linkPromise(existingP, newP) {
    return await this.makeCallPromise(newP, async () => {
      return await this.baseFs.linkPromise(existingP, newP);
    }, async (zipFs, { subPath }) => {
      return await zipFs.linkPromise(existingP, subPath);
    });
  }
  linkSync(existingP, newP) {
    return this.makeCallSync(newP, () => {
      return this.baseFs.linkSync(existingP, newP);
    }, (zipFs, { subPath }) => {
      return zipFs.linkSync(existingP, subPath);
    });
  }
  async symlinkPromise(target, p, type) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.symlinkPromise(target, p, type);
    }, async (zipFs, { subPath }) => {
      return await zipFs.symlinkPromise(target, subPath);
    });
  }
  symlinkSync(target, p, type) {
    return this.makeCallSync(p, () => {
      return this.baseFs.symlinkSync(target, p, type);
    }, (zipFs, { subPath }) => {
      return zipFs.symlinkSync(target, subPath);
    });
  }
  async readFilePromise(p, encoding) {
    return this.makeCallPromise(p, async () => {
      return await this.baseFs.readFilePromise(p, encoding);
    }, async (zipFs, { subPath }) => {
      return await zipFs.readFilePromise(subPath, encoding);
    });
  }
  readFileSync(p, encoding) {
    return this.makeCallSync(p, () => {
      return this.baseFs.readFileSync(p, encoding);
    }, (zipFs, { subPath }) => {
      return zipFs.readFileSync(subPath, encoding);
    });
  }
  async readdirPromise(p, opts) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.readdirPromise(p, opts);
    }, async (zipFs, { subPath }) => {
      return await zipFs.readdirPromise(subPath, opts);
    }, {
      requireSubpath: false
    });
  }
  readdirSync(p, opts) {
    return this.makeCallSync(p, () => {
      return this.baseFs.readdirSync(p, opts);
    }, (zipFs, { subPath }) => {
      return zipFs.readdirSync(subPath, opts);
    }, {
      requireSubpath: false
    });
  }
  async readlinkPromise(p) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.readlinkPromise(p);
    }, async (zipFs, { subPath }) => {
      return await zipFs.readlinkPromise(subPath);
    });
  }
  readlinkSync(p) {
    return this.makeCallSync(p, () => {
      return this.baseFs.readlinkSync(p);
    }, (zipFs, { subPath }) => {
      return zipFs.readlinkSync(subPath);
    });
  }
  async truncatePromise(p, len) {
    return await this.makeCallPromise(p, async () => {
      return await this.baseFs.truncatePromise(p, len);
    }, async (zipFs, { subPath }) => {
      return await zipFs.truncatePromise(subPath, len);
    });
  }
  truncateSync(p, len) {
    return this.makeCallSync(p, () => {
      return this.baseFs.truncateSync(p, len);
    }, (zipFs, { subPath }) => {
      return zipFs.truncateSync(subPath, len);
    });
  }
  async ftruncatePromise(fd, len) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.ftruncatePromise(fd, len);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`ftruncate`);
    const [zipFs, realFd] = entry;
    return zipFs.ftruncatePromise(realFd, len);
  }
  ftruncateSync(fd, len) {
    if ((fd & ZIP_MASK) !== ZIP_MAGIC)
      return this.baseFs.ftruncateSync(fd, len);
    const entry = this.fdMap.get(fd);
    if (typeof entry === `undefined`)
      throw errors.EBADF(`ftruncateSync`);
    const [zipFs, realFd] = entry;
    return zipFs.ftruncateSync(realFd, len);
  }
  watch(p, a, b) {
    return this.makeCallSync(p, () => {
      return this.baseFs.watch(
        p,
        // @ts-expect-error
        a,
        b
      );
    }, (zipFs, { subPath }) => {
      return zipFs.watch(
        subPath,
        // @ts-expect-error
        a,
        b
      );
    });
  }
  watchFile(p, a, b) {
    return this.makeCallSync(p, () => {
      return this.baseFs.watchFile(
        p,
        // @ts-expect-error
        a,
        b
      );
    }, () => {
      return (0, watchFile_1.watchFile)(this, p, a, b);
    });
  }
  unwatchFile(p, cb) {
    return this.makeCallSync(p, () => {
      return this.baseFs.unwatchFile(p, cb);
    }, () => {
      return (0, watchFile_1.unwatchFile)(this, p, cb);
    });
  }
  async makeCallPromise(p, discard, accept, { requireSubpath = true } = {}) {
    if (typeof p !== `string`)
      return await discard();
    const normalizedP = this.resolve(p);
    const zipInfo = this.findZip(normalizedP);
    if (!zipInfo)
      return await discard();
    if (requireSubpath && zipInfo.subPath === `/`)
      return await discard();
    return await this.getZipPromise(zipInfo.archivePath, async (zipFs) => await accept(zipFs, zipInfo));
  }
  makeCallSync(p, discard, accept, { requireSubpath = true } = {}) {
    if (typeof p !== `string`)
      return discard();
    const normalizedP = this.resolve(p);
    const zipInfo = this.findZip(normalizedP);
    if (!zipInfo)
      return discard();
    if (requireSubpath && zipInfo.subPath === `/`)
      return discard();
    return this.getZipSync(zipInfo.archivePath, (zipFs) => accept(zipFs, zipInfo));
  }
  findZip(p) {
    if (this.filter && !this.filter.test(p))
      return null;
    let filePath = ``;
    while (true) {
      const pathPartWithArchive = p.substring(filePath.length);
      let archivePart;
      if (!this.fileExtensions) {
        archivePart = (0, exports.getArchivePart)(pathPartWithArchive, `.zip`);
      } else {
        for (const ext of this.fileExtensions) {
          archivePart = (0, exports.getArchivePart)(pathPartWithArchive, ext);
          if (archivePart) {
            break;
          }
        }
      }
      if (!archivePart)
        return null;
      filePath = this.pathUtils.join(filePath, archivePart);
      if (this.isZip.has(filePath) === false) {
        if (this.notZip.has(filePath))
          continue;
        try {
          if (!this.baseFs.lstatSync(filePath).isFile()) {
            this.notZip.add(filePath);
            continue;
          }
        } catch {
          return null;
        }
        this.isZip.add(filePath);
      }
      return {
        archivePath: filePath,
        subPath: this.pathUtils.join(path_1.PortablePath.root, p.substring(filePath.length))
      };
    }
  }
  limitOpenFiles(max) {
    if (this.zipInstances === null)
      return;
    const now = Date.now();
    let nextExpiresAt = now + this.maxAge;
    let closeCount = max === null ? 0 : this.zipInstances.size - max;
    for (const [path, { zipFs, expiresAt, refCount }] of this.zipInstances.entries()) {
      if (refCount !== 0 || zipFs.hasOpenFileHandles()) {
        continue;
      } else if (now >= expiresAt) {
        zipFs.saveAndClose();
        this.zipInstances.delete(path);
        closeCount -= 1;
        continue;
      } else if (max === null || closeCount <= 0) {
        nextExpiresAt = expiresAt;
        break;
      }
      zipFs.saveAndClose();
      this.zipInstances.delete(path);
      closeCount -= 1;
    }
    if (this.limitOpenFilesTimeout === null && (max === null && this.zipInstances.size > 0 || max !== null)) {
      this.limitOpenFilesTimeout = setTimeout(() => {
        this.limitOpenFilesTimeout = null;
        this.limitOpenFiles(null);
      }, nextExpiresAt - now).unref();
    }
  }
  async getZipPromise(p, accept) {
    const getZipOptions = async () => ({
      baseFs: this.baseFs,
      libzip: this.libzip,
      readOnly: this.readOnlyArchives,
      stats: await this.baseFs.statPromise(p)
    });
    if (this.zipInstances) {
      let cachedZipFs = this.zipInstances.get(p);
      if (!cachedZipFs) {
        const zipOptions = await getZipOptions();
        cachedZipFs = this.zipInstances.get(p);
        if (!cachedZipFs) {
          cachedZipFs = {
            zipFs: new ZipFS_1.ZipFS(p, zipOptions),
            expiresAt: 0,
            refCount: 0
          };
        }
      }
      this.zipInstances.delete(p);
      this.limitOpenFiles(this.maxOpenFiles - 1);
      this.zipInstances.set(p, cachedZipFs);
      cachedZipFs.expiresAt = Date.now() + this.maxAge;
      cachedZipFs.refCount += 1;
      try {
        return await accept(cachedZipFs.zipFs);
      } finally {
        cachedZipFs.refCount -= 1;
      }
    } else {
      const zipFs = new ZipFS_1.ZipFS(p, await getZipOptions());
      try {
        return await accept(zipFs);
      } finally {
        zipFs.saveAndClose();
      }
    }
  }
  getZipSync(p, accept) {
    const getZipOptions = () => ({
      baseFs: this.baseFs,
      libzip: this.libzip,
      readOnly: this.readOnlyArchives,
      stats: this.baseFs.statSync(p)
    });
    if (this.zipInstances) {
      let cachedZipFs = this.zipInstances.get(p);
      if (!cachedZipFs) {
        cachedZipFs = {
          zipFs: new ZipFS_1.ZipFS(p, getZipOptions()),
          expiresAt: 0,
          refCount: 0
        };
      }
      this.zipInstances.delete(p);
      this.limitOpenFiles(this.maxOpenFiles - 1);
      this.zipInstances.set(p, cachedZipFs);
      cachedZipFs.expiresAt = Date.now() + this.maxAge;
      return accept(cachedZipFs.zipFs);
    } else {
      const zipFs = new ZipFS_1.ZipFS(p, getZipOptions());
      try {
        return accept(zipFs);
      } finally {
        zipFs.saveAndClose();
      }
    }
  }
}
exports.ZipOpenFS = ZipOpenFS;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/copyPromise.js":
/*!*************************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/copyPromise.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.copyPromise = exports.LinkStrategy = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const fs_1 = tslib_1.__importDefault(__webpack_require__(/*! fs */ "fs"));
const constants = tslib_1.__importStar(__webpack_require__(/*! ../constants */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js"));
const path_1 = __webpack_require__(/*! ../path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
const defaultTime = new Date(constants.SAFE_TIME * 1e3);
var LinkStrategy;
(function(LinkStrategy2) {
  LinkStrategy2["Allow"] = "allow";
  LinkStrategy2["ReadOnly"] = "readOnly";
})(LinkStrategy || (exports.LinkStrategy = LinkStrategy = {}));
async function copyPromise(destinationFs, destination, sourceFs, source, opts) {
  const normalizedDestination = destinationFs.pathUtils.normalize(destination);
  const normalizedSource = sourceFs.pathUtils.normalize(source);
  const prelayout = [];
  const postlayout = [];
  const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : await sourceFs.lstatPromise(normalizedSource);
  await destinationFs.mkdirpPromise(destinationFs.pathUtils.dirname(destination), { utimes: [atime, mtime] });
  const updateTime = typeof destinationFs.lutimesPromise === `function` ? destinationFs.lutimesPromise.bind(destinationFs) : destinationFs.utimesPromise.bind(destinationFs);
  await copyImpl(prelayout, postlayout, updateTime, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true });
  for (const operation of prelayout)
    await operation();
  await Promise.all(postlayout.map((operation) => {
    return operation();
  }));
}
exports.copyPromise = copyPromise;
async function copyImpl(prelayout, postlayout, updateTime, destinationFs, destination, sourceFs, source, opts) {
  var _a, _b;
  const destinationStat = opts.didParentExist ? await maybeLStat(destinationFs, destination) : null;
  const sourceStat = await sourceFs.lstatPromise(source);
  const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : sourceStat;
  let updated;
  switch (true) {
    case sourceStat.isDirectory():
      {
        updated = await copyFolder(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
      }
      break;
    case sourceStat.isFile():
      {
        updated = await copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
      }
      break;
    case sourceStat.isSymbolicLink():
      {
        updated = await copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
      }
      break;
    default:
      {
        throw new Error(`Unsupported file type (${sourceStat.mode})`);
      }
      break;
  }
  if (updated || ((_a = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.mtime) === null || _a === void 0 ? void 0 : _a.getTime()) !== mtime.getTime() || ((_b = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.atime) === null || _b === void 0 ? void 0 : _b.getTime()) !== atime.getTime()) {
    postlayout.push(() => updateTime(destination, atime, mtime));
    updated = true;
  }
  if (destinationStat === null || (destinationStat.mode & 511) !== (sourceStat.mode & 511)) {
    postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 511));
    updated = true;
  }
  return updated;
}
async function maybeLStat(baseFs, p) {
  try {
    return await baseFs.lstatPromise(p);
  } catch (e) {
    return null;
  }
}
async function copyFolder(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
  if (destinationStat !== null && !destinationStat.isDirectory()) {
    if (opts.overwrite) {
      prelayout.push(async () => destinationFs.removePromise(destination));
      destinationStat = null;
    } else {
      return false;
    }
  }
  let updated = false;
  if (destinationStat === null) {
    prelayout.push(async () => {
      try {
        await destinationFs.mkdirPromise(destination, { mode: sourceStat.mode });
      } catch (err) {
        if (err.code !== `EEXIST`) {
          throw err;
        }
      }
    });
    updated = true;
  }
  const entries = await sourceFs.readdirPromise(source);
  const nextOpts = opts.didParentExist && !destinationStat ? { ...opts, didParentExist: false } : opts;
  if (opts.stableSort) {
    for (const entry of entries.sort()) {
      if (await copyImpl(prelayout, postlayout, updateTime, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts)) {
        updated = true;
      }
    }
  } else {
    const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => {
      await copyImpl(prelayout, postlayout, updateTime, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts);
    }));
    if (entriesUpdateStatus.some((status) => status)) {
      updated = true;
    }
  }
  return updated;
}
const isCloneSupportedCache = /* @__PURE__ */ new WeakMap();
function makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy) {
  return async () => {
    await opFs.linkPromise(source, destination);
    if (linkStrategy === LinkStrategy.ReadOnly) {
      sourceStat.mode &= ~146;
      await opFs.chmodPromise(destination, sourceStat.mode);
    }
  };
}
function makeCloneLinkOperation(opFs, destination, source, sourceStat, linkStrategy) {
  const isCloneSupported = isCloneSupportedCache.get(opFs);
  if (typeof isCloneSupported === `undefined`) {
    return async () => {
      try {
        await opFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE_FORCE);
        isCloneSupportedCache.set(opFs, true);
      } catch (err) {
        if (err.code === `ENOSYS` || err.code === `ENOTSUP`) {
          isCloneSupportedCache.set(opFs, false);
          await makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy)();
        } else {
          throw err;
        }
      }
    };
  } else {
    if (isCloneSupported) {
      return async () => opFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE_FORCE);
    } else {
      return makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy);
    }
  }
}
async function copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
  var _a;
  if (destinationStat !== null) {
    if (opts.overwrite) {
      prelayout.push(async () => destinationFs.removePromise(destination));
      destinationStat = null;
    } else {
      return false;
    }
  }
  const linkStrategy = (_a = opts.linkStrategy) !== null && _a !== void 0 ? _a : null;
  const op = destinationFs === sourceFs ? linkStrategy !== null ? makeCloneLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.copyFilePromise(source, destination, fs_1.default.constants.COPYFILE_FICLONE) : linkStrategy !== null ? makeLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.writeFilePromise(destination, await sourceFs.readFilePromise(source));
  prelayout.push(async () => op());
  return true;
}
async function copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
  if (destinationStat !== null) {
    if (opts.overwrite) {
      prelayout.push(async () => destinationFs.removePromise(destination));
      destinationStat = null;
    } else {
      return false;
    }
  }
  prelayout.push(async () => {
    await destinationFs.symlinkPromise((0, path_1.convertPath)(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination);
  });
  return true;
}


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/opendir.js":
/*!*********************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/opendir.js ***!
  \*********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.opendir = exports.CustomDir = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const errors = tslib_1.__importStar(__webpack_require__(/*! ../errors */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js"));
class CustomDir {
  constructor(path, nextDirent, opts = {}) {
    this.path = path;
    this.nextDirent = nextDirent;
    this.opts = opts;
    this.closed = false;
  }
  throwIfClosed() {
    if (this.closed) {
      throw errors.ERR_DIR_CLOSED();
    }
  }
  async *[Symbol.asyncIterator]() {
    try {
      let dirent;
      while ((dirent = await this.read()) !== null) {
        yield dirent;
      }
    } finally {
      await this.close();
    }
  }
  read(cb) {
    const dirent = this.readSync();
    if (typeof cb !== `undefined`)
      return cb(null, dirent);
    return Promise.resolve(dirent);
  }
  readSync() {
    this.throwIfClosed();
    return this.nextDirent();
  }
  close(cb) {
    this.closeSync();
    if (typeof cb !== `undefined`)
      return cb(null);
    return Promise.resolve();
  }
  closeSync() {
    var _a, _b;
    this.throwIfClosed();
    (_b = (_a = this.opts).onClose) === null || _b === void 0 ? void 0 : _b.call(_a);
    this.closed = true;
  }
}
exports.CustomDir = CustomDir;
function opendir(fakeFs, path, entries, opts) {
  const nextDirent = () => {
    const filename = entries.shift();
    if (typeof filename === `undefined`)
      return null;
    return Object.assign(fakeFs.statSync(fakeFs.pathUtils.join(path, filename)), {
      name: filename
    });
  };
  return new CustomDir(path, nextDirent, opts);
}
exports.opendir = opendir;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unwatchAllFiles = exports.unwatchFile = exports.watchFile = void 0;
const CustomStatWatcher_1 = __webpack_require__(/*! ./watchFile/CustomStatWatcher */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile/CustomStatWatcher.js");
const statWatchersByFakeFS = /* @__PURE__ */ new WeakMap();
function watchFile(fakeFs, path, a, b) {
  let bigint;
  let persistent;
  let interval;
  let listener;
  switch (typeof a) {
    case `function`:
      {
        bigint = false;
        persistent = true;
        interval = 5007;
        listener = a;
      }
      break;
    default:
      {
        ({
          bigint = false,
          persistent = true,
          interval = 5007
        } = a);
        listener = b;
      }
      break;
  }
  let statWatchers = statWatchersByFakeFS.get(fakeFs);
  if (typeof statWatchers === `undefined`)
    statWatchersByFakeFS.set(fakeFs, statWatchers = /* @__PURE__ */ new Map());
  let statWatcher = statWatchers.get(path);
  if (typeof statWatcher === `undefined`) {
    statWatcher = CustomStatWatcher_1.CustomStatWatcher.create(fakeFs, path, { bigint });
    statWatchers.set(path, statWatcher);
  }
  statWatcher.registerChangeListener(listener, { persistent, interval });
  return statWatcher;
}
exports.watchFile = watchFile;
function unwatchFile(fakeFs, path, cb) {
  const statWatchers = statWatchersByFakeFS.get(fakeFs);
  if (typeof statWatchers === `undefined`)
    return;
  const statWatcher = statWatchers.get(path);
  if (typeof statWatcher === `undefined`)
    return;
  if (typeof cb === `undefined`)
    statWatcher.unregisterAllChangeListeners();
  else
    statWatcher.unregisterChangeListener(cb);
  if (!statWatcher.hasChangeListeners()) {
    statWatcher.stop();
    statWatchers.delete(path);
  }
}
exports.unwatchFile = unwatchFile;
function unwatchAllFiles(fakeFs) {
  const statWatchers = statWatchersByFakeFS.get(fakeFs);
  if (typeof statWatchers === `undefined`)
    return;
  for (const path of statWatchers.keys()) {
    unwatchFile(fakeFs, path);
  }
}
exports.unwatchAllFiles = unwatchAllFiles;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile/CustomStatWatcher.js":
/*!*****************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/watchFile/CustomStatWatcher.js ***!
  \*****************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CustomStatWatcher = exports.assertStatus = exports.Status = exports.Event = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const events_1 = __webpack_require__(/*! events */ "events");
const statUtils = tslib_1.__importStar(__webpack_require__(/*! ../../statUtils */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/statUtils.js"));
var Event;
(function(Event2) {
  Event2["Change"] = "change";
  Event2["Stop"] = "stop";
})(Event || (exports.Event = Event = {}));
var Status;
(function(Status2) {
  Status2["Ready"] = "ready";
  Status2["Running"] = "running";
  Status2["Stopped"] = "stopped";
})(Status || (exports.Status = Status = {}));
function assertStatus(current, expected) {
  if (current !== expected) {
    throw new Error(`Invalid StatWatcher status: expected '${expected}', got '${current}'`);
  }
}
exports.assertStatus = assertStatus;
class CustomStatWatcher extends events_1.EventEmitter {
  static create(fakeFs, path, opts) {
    const statWatcher = new CustomStatWatcher(fakeFs, path, opts);
    statWatcher.start();
    return statWatcher;
  }
  constructor(fakeFs, path, { bigint = false } = {}) {
    super();
    this.status = Status.Ready;
    this.changeListeners = /* @__PURE__ */ new Map();
    this.startTimeout = null;
    this.fakeFs = fakeFs;
    this.path = path;
    this.bigint = bigint;
    this.lastStats = this.stat();
  }
  start() {
    assertStatus(this.status, Status.Ready);
    this.status = Status.Running;
    this.startTimeout = setTimeout(() => {
      this.startTimeout = null;
      if (!this.fakeFs.existsSync(this.path)) {
        this.emit(Event.Change, this.lastStats, this.lastStats);
      }
    }, 3);
  }
  stop() {
    assertStatus(this.status, Status.Running);
    this.status = Status.Stopped;
    if (this.startTimeout !== null) {
      clearTimeout(this.startTimeout);
      this.startTimeout = null;
    }
    this.emit(Event.Stop);
  }
  stat() {
    try {
      return this.fakeFs.statSync(this.path, { bigint: this.bigint });
    } catch (error) {
      const statInstance = this.bigint ? new statUtils.BigIntStatsEntry() : new statUtils.StatEntry();
      return statUtils.clearStats(statInstance);
    }
  }
  /**
   * Creates an interval whose callback compares the current stats with the previous stats and notifies all listeners in case of changes.
   *
   * @param opts.persistent Decides whether the interval should be immediately unref-ed.
   */
  makeInterval(opts) {
    const interval = setInterval(() => {
      const currentStats = this.stat();
      const previousStats = this.lastStats;
      if (statUtils.areStatsEqual(currentStats, previousStats))
        return;
      this.lastStats = currentStats;
      this.emit(Event.Change, currentStats, previousStats);
    }, opts.interval);
    return opts.persistent ? interval : interval.unref();
  }
  /**
   * Registers a listener and assigns it an interval.
   */
  registerChangeListener(listener, opts) {
    this.addListener(Event.Change, listener);
    this.changeListeners.set(listener, this.makeInterval(opts));
  }
  /**
   * Unregisters the listener and clears the assigned interval.
   */
  unregisterChangeListener(listener) {
    this.removeListener(Event.Change, listener);
    const interval = this.changeListeners.get(listener);
    if (typeof interval !== `undefined`)
      clearInterval(interval);
    this.changeListeners.delete(listener);
  }
  /**
   * Unregisters all listeners and clears all assigned intervals.
   */
  unregisterAllChangeListeners() {
    for (const listener of this.changeListeners.keys()) {
      this.unregisterChangeListener(listener);
    }
  }
  hasChangeListeners() {
    return this.changeListeners.size > 0;
  }
  /**
   * Refs all stored intervals.
   */
  ref() {
    for (const interval of this.changeListeners.values())
      interval.ref();
    return this;
  }
  /**
   * Unrefs all stored intervals.
   */
  unref() {
    for (const interval of this.changeListeners.values())
      interval.unref();
    return this;
  }
}
exports.CustomStatWatcher = CustomStatWatcher;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SAFE_TIME = exports.S_IFLNK = exports.S_IFREG = exports.S_IFDIR = exports.S_IFMT = void 0;
exports.S_IFMT = 61440;
exports.S_IFDIR = 16384;
exports.S_IFREG = 32768;
exports.S_IFLNK = 40960;
exports.SAFE_TIME = 456789e3;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/errors.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LibzipError = exports.ERR_DIR_CLOSED = exports.EOPNOTSUPP = exports.ENOTEMPTY = exports.EROFS = exports.EEXIST = exports.EISDIR = exports.ENOTDIR = exports.ENOENT = exports.EBADF = exports.EINVAL = exports.ENOSYS = exports.EBUSY = void 0;
function makeError(code, message) {
  return Object.assign(new Error(`${code}: ${message}`), { code });
}
function EBUSY(message) {
  return makeError(`EBUSY`, message);
}
exports.EBUSY = EBUSY;
function ENOSYS(message, reason) {
  return makeError(`ENOSYS`, `${message}, ${reason}`);
}
exports.ENOSYS = ENOSYS;
function EINVAL(reason) {
  return makeError(`EINVAL`, `invalid argument, ${reason}`);
}
exports.EINVAL = EINVAL;
function EBADF(reason) {
  return makeError(`EBADF`, `bad file descriptor, ${reason}`);
}
exports.EBADF = EBADF;
function ENOENT(reason) {
  return makeError(`ENOENT`, `no such file or directory, ${reason}`);
}
exports.ENOENT = ENOENT;
function ENOTDIR(reason) {
  return makeError(`ENOTDIR`, `not a directory, ${reason}`);
}
exports.ENOTDIR = ENOTDIR;
function EISDIR(reason) {
  return makeError(`EISDIR`, `illegal operation on a directory, ${reason}`);
}
exports.EISDIR = EISDIR;
function EEXIST(reason) {
  return makeError(`EEXIST`, `file already exists, ${reason}`);
}
exports.EEXIST = EEXIST;
function EROFS(reason) {
  return makeError(`EROFS`, `read-only filesystem, ${reason}`);
}
exports.EROFS = EROFS;
function ENOTEMPTY(reason) {
  return makeError(`ENOTEMPTY`, `directory not empty, ${reason}`);
}
exports.ENOTEMPTY = ENOTEMPTY;
function EOPNOTSUPP(reason) {
  return makeError(`EOPNOTSUPP`, `operation not supported, ${reason}`);
}
exports.EOPNOTSUPP = EOPNOTSUPP;
function ERR_DIR_CLOSED() {
  return makeError(`ERR_DIR_CLOSED`, `Directory handle was closed`);
}
exports.ERR_DIR_CLOSED = ERR_DIR_CLOSED;
class LibzipError extends Error {
  constructor(message, code) {
    super(message);
    this.name = `Libzip Error`;
    this.code = code;
  }
}
exports.LibzipError = LibzipError;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/index.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/index.js ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.xfs = exports.extendFs = exports.patchFs = exports.ZipOpenFS = exports.ZipFS = exports.VirtualFS = exports.ProxiedFS = exports.PosixFS = exports.NodeFS = exports.NoFS = exports.LazyFS = exports.JailFS = exports.CwdFS = exports.FakeFS = exports.AliasFS = exports.toFilename = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = exports.DEFAULT_COMPRESSION_LEVEL = exports.normalizeLineEndings = exports.statUtils = exports.CustomDir = exports.opendir = exports.LinkStrategy = exports.constants = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const constants = tslib_1.__importStar(__webpack_require__(/*! ./constants */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js"));
exports.constants = constants;
const statUtils = tslib_1.__importStar(__webpack_require__(/*! ./statUtils */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/statUtils.js"));
exports.statUtils = statUtils;
var copyPromise_1 = __webpack_require__(/*! ./algorithms/copyPromise */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/copyPromise.js");
Object.defineProperty(exports, "LinkStrategy", ({ enumerable: true, get: function() {
  return copyPromise_1.LinkStrategy;
} }));
var opendir_1 = __webpack_require__(/*! ./algorithms/opendir */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/algorithms/opendir.js");
Object.defineProperty(exports, "opendir", ({ enumerable: true, get: function() {
  return opendir_1.opendir;
} }));
Object.defineProperty(exports, "CustomDir", ({ enumerable: true, get: function() {
  return opendir_1.CustomDir;
} }));
var FakeFS_1 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
Object.defineProperty(exports, "normalizeLineEndings", ({ enumerable: true, get: function() {
  return FakeFS_1.normalizeLineEndings;
} }));
var ZipFS_1 = __webpack_require__(/*! ./ZipFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipFS.js");
Object.defineProperty(exports, "DEFAULT_COMPRESSION_LEVEL", ({ enumerable: true, get: function() {
  return ZipFS_1.DEFAULT_COMPRESSION_LEVEL;
} }));
var path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
Object.defineProperty(exports, "PortablePath", ({ enumerable: true, get: function() {
  return path_1.PortablePath;
} }));
Object.defineProperty(exports, "Filename", ({ enumerable: true, get: function() {
  return path_1.Filename;
} }));
var path_2 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
Object.defineProperty(exports, "npath", ({ enumerable: true, get: function() {
  return path_2.npath;
} }));
Object.defineProperty(exports, "ppath", ({ enumerable: true, get: function() {
  return path_2.ppath;
} }));
Object.defineProperty(exports, "toFilename", ({ enumerable: true, get: function() {
  return path_2.toFilename;
} }));
var AliasFS_1 = __webpack_require__(/*! ./AliasFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/AliasFS.js");
Object.defineProperty(exports, "AliasFS", ({ enumerable: true, get: function() {
  return AliasFS_1.AliasFS;
} }));
var FakeFS_2 = __webpack_require__(/*! ./FakeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/FakeFS.js");
Object.defineProperty(exports, "FakeFS", ({ enumerable: true, get: function() {
  return FakeFS_2.FakeFS;
} }));
var CwdFS_1 = __webpack_require__(/*! ./CwdFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/CwdFS.js");
Object.defineProperty(exports, "CwdFS", ({ enumerable: true, get: function() {
  return CwdFS_1.CwdFS;
} }));
var JailFS_1 = __webpack_require__(/*! ./JailFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/JailFS.js");
Object.defineProperty(exports, "JailFS", ({ enumerable: true, get: function() {
  return JailFS_1.JailFS;
} }));
var LazyFS_1 = __webpack_require__(/*! ./LazyFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/LazyFS.js");
Object.defineProperty(exports, "LazyFS", ({ enumerable: true, get: function() {
  return LazyFS_1.LazyFS;
} }));
var NoFS_1 = __webpack_require__(/*! ./NoFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NoFS.js");
Object.defineProperty(exports, "NoFS", ({ enumerable: true, get: function() {
  return NoFS_1.NoFS;
} }));
var NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
Object.defineProperty(exports, "NodeFS", ({ enumerable: true, get: function() {
  return NodeFS_1.NodeFS;
} }));
var PosixFS_1 = __webpack_require__(/*! ./PosixFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/PosixFS.js");
Object.defineProperty(exports, "PosixFS", ({ enumerable: true, get: function() {
  return PosixFS_1.PosixFS;
} }));
var ProxiedFS_1 = __webpack_require__(/*! ./ProxiedFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ProxiedFS.js");
Object.defineProperty(exports, "ProxiedFS", ({ enumerable: true, get: function() {
  return ProxiedFS_1.ProxiedFS;
} }));
var VirtualFS_1 = __webpack_require__(/*! ./VirtualFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/VirtualFS.js");
Object.defineProperty(exports, "VirtualFS", ({ enumerable: true, get: function() {
  return VirtualFS_1.VirtualFS;
} }));
var ZipFS_2 = __webpack_require__(/*! ./ZipFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipFS.js");
Object.defineProperty(exports, "ZipFS", ({ enumerable: true, get: function() {
  return ZipFS_2.ZipFS;
} }));
var ZipOpenFS_1 = __webpack_require__(/*! ./ZipOpenFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/ZipOpenFS.js");
Object.defineProperty(exports, "ZipOpenFS", ({ enumerable: true, get: function() {
  return ZipOpenFS_1.ZipOpenFS;
} }));
var patchFs_1 = __webpack_require__(/*! ./patchFs/patchFs */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/patchFs.js");
Object.defineProperty(exports, "patchFs", ({ enumerable: true, get: function() {
  return patchFs_1.patchFs;
} }));
Object.defineProperty(exports, "extendFs", ({ enumerable: true, get: function() {
  return patchFs_1.extendFs;
} }));
var xfs_1 = __webpack_require__(/*! ./xfs */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/xfs.js");
Object.defineProperty(exports, "xfs", ({ enumerable: true, get: function() {
  return xfs_1.xfs;
} }));


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/FileHandle.js":
/*!*********************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/FileHandle.js ***!
  \*********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _a, _b, _c, _d;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FileHandle = void 0;
const readline_1 = __webpack_require__(/*! readline */ "readline");
const kBaseFs = Symbol(`kBaseFs`);
const kFd = Symbol(`kFd`);
const kClosePromise = Symbol(`kClosePromise`);
const kCloseResolve = Symbol(`kCloseResolve`);
const kCloseReject = Symbol(`kCloseReject`);
const kRefs = Symbol(`kRefs`);
const kRef = Symbol(`kRef`);
const kUnref = Symbol(`kUnref`);
class FileHandle {
  constructor(fd, baseFs) {
    this[_a] = 1;
    this[_b] = void 0;
    this[_c] = void 0;
    this[_d] = void 0;
    this[kBaseFs] = baseFs;
    this[kFd] = fd;
  }
  get fd() {
    return this[kFd];
  }
  async appendFile(data, options) {
    var _e;
    try {
      this[kRef](this.appendFile);
      const encoding = (_e = typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding) !== null && _e !== void 0 ? _e : void 0;
      return await this[kBaseFs].appendFilePromise(this.fd, data, encoding ? { encoding } : void 0);
    } finally {
      this[kUnref]();
    }
  }
  async chown(uid, gid) {
    try {
      this[kRef](this.chown);
      return await this[kBaseFs].fchownPromise(this.fd, uid, gid);
    } finally {
      this[kUnref]();
    }
  }
  async chmod(mode) {
    try {
      this[kRef](this.chmod);
      return await this[kBaseFs].fchmodPromise(this.fd, mode);
    } finally {
      this[kUnref]();
    }
  }
  createReadStream(options) {
    return this[kBaseFs].createReadStream(null, { ...options, fd: this.fd });
  }
  createWriteStream(options) {
    return this[kBaseFs].createWriteStream(null, { ...options, fd: this.fd });
  }
  // FIXME: Missing FakeFS version
  datasync() {
    throw new Error(`Method not implemented.`);
  }
  // FIXME: Missing FakeFS version
  sync() {
    throw new Error(`Method not implemented.`);
  }
  async read(bufferOrOptions, offset, length, position) {
    var _e, _f, _g;
    try {
      this[kRef](this.read);
      let buffer;
      if (!Buffer.isBuffer(bufferOrOptions)) {
        bufferOrOptions !== null && bufferOrOptions !== void 0 ? bufferOrOptions : bufferOrOptions = {};
        buffer = (_e = bufferOrOptions.buffer) !== null && _e !== void 0 ? _e : Buffer.alloc(16384);
        offset = bufferOrOptions.offset || 0;
        length = (_f = bufferOrOptions.length) !== null && _f !== void 0 ? _f : buffer.byteLength;
        position = (_g = bufferOrOptions.position) !== null && _g !== void 0 ? _g : null;
      } else {
        buffer = bufferOrOptions;
      }
      offset !== null && offset !== void 0 ? offset : offset = 0;
      length !== null && length !== void 0 ? length : length = 0;
      if (length === 0) {
        return {
          bytesRead: length,
          buffer
        };
      }
      const bytesRead = await this[kBaseFs].readPromise(this.fd, buffer, offset, length, position);
      return {
        bytesRead,
        buffer
      };
    } finally {
      this[kUnref]();
    }
  }
  async readFile(options) {
    var _e;
    try {
      this[kRef](this.readFile);
      const encoding = (_e = typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding) !== null && _e !== void 0 ? _e : void 0;
      return await this[kBaseFs].readFilePromise(this.fd, encoding);
    } finally {
      this[kUnref]();
    }
  }
  readLines(options) {
    return (0, readline_1.createInterface)({
      input: this.createReadStream(options),
      crlfDelay: Infinity
    });
  }
  async stat(opts) {
    try {
      this[kRef](this.stat);
      return await this[kBaseFs].fstatPromise(this.fd, opts);
    } finally {
      this[kUnref]();
    }
  }
  async truncate(len) {
    try {
      this[kRef](this.truncate);
      return await this[kBaseFs].ftruncatePromise(this.fd, len);
    } finally {
      this[kUnref]();
    }
  }
  // FIXME: Missing FakeFS version
  utimes(atime, mtime) {
    throw new Error(`Method not implemented.`);
  }
  async writeFile(data, options) {
    var _e;
    try {
      this[kRef](this.writeFile);
      const encoding = (_e = typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding) !== null && _e !== void 0 ? _e : void 0;
      await this[kBaseFs].writeFilePromise(this.fd, data, encoding);
    } finally {
      this[kUnref]();
    }
  }
  async write(...args) {
    try {
      this[kRef](this.write);
      if (ArrayBuffer.isView(args[0])) {
        const [buffer, offset, length, position] = args;
        const bytesWritten = await this[kBaseFs].writePromise(this.fd, buffer, offset !== null && offset !== void 0 ? offset : void 0, length !== null && length !== void 0 ? length : void 0, position !== null && position !== void 0 ? position : void 0);
        return { bytesWritten, buffer };
      } else {
        const [data, position, encoding] = args;
        const bytesWritten = await this[kBaseFs].writePromise(this.fd, data, position, encoding);
        return { bytesWritten, buffer: data };
      }
    } finally {
      this[kUnref]();
    }
  }
  // TODO: Use writev from FakeFS when that is implemented
  async writev(buffers, position) {
    try {
      this[kRef](this.writev);
      let bytesWritten = 0;
      if (typeof position !== `undefined`) {
        for (const buffer of buffers) {
          const writeResult = await this.write(buffer, void 0, void 0, position);
          bytesWritten += writeResult.bytesWritten;
          position += writeResult.bytesWritten;
        }
      } else {
        for (const buffer of buffers) {
          const writeResult = await this.write(buffer);
          bytesWritten += writeResult.bytesWritten;
        }
      }
      return {
        buffers,
        bytesWritten
      };
    } finally {
      this[kUnref]();
    }
  }
  // FIXME: Missing FakeFS version
  readv(buffers, position) {
    throw new Error(`Method not implemented.`);
  }
  close() {
    if (this[kFd] === -1)
      return Promise.resolve();
    if (this[kClosePromise])
      return this[kClosePromise];
    this[kRefs]--;
    if (this[kRefs] === 0) {
      const fd = this[kFd];
      this[kFd] = -1;
      this[kClosePromise] = this[kBaseFs].closePromise(fd).finally(() => {
        this[kClosePromise] = void 0;
      });
    } else {
      this[kClosePromise] = new Promise((resolve, reject) => {
        this[kCloseResolve] = resolve;
        this[kCloseReject] = reject;
      }).finally(() => {
        this[kClosePromise] = void 0;
        this[kCloseReject] = void 0;
        this[kCloseResolve] = void 0;
      });
    }
    return this[kClosePromise];
  }
  [(_a = kRefs, _b = kClosePromise, _c = kCloseResolve, _d = kCloseReject, kRef)](caller) {
    if (this[kFd] === -1) {
      const err = new Error(`file closed`);
      err.code = `EBADF`;
      err.syscall = caller.name;
      throw err;
    }
    this[kRefs]++;
  }
  [kUnref]() {
    this[kRefs]--;
    if (this[kRefs] === 0) {
      const fd = this[kFd];
      this[kFd] = -1;
      this[kBaseFs].closePromise(fd).then(this[kCloseResolve], this[kCloseReject]);
    }
  }
}
exports.FileHandle = FileHandle;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/patchFs.js":
/*!******************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/patchFs.js ***!
  \******************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendFs = exports.patchFs = void 0;
const util_1 = __webpack_require__(/*! util */ "util");
const NodePathFS_1 = __webpack_require__(/*! ../NodePathFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodePathFS.js");
const FileHandle_1 = __webpack_require__(/*! ./FileHandle */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/patchFs/FileHandle.js");
const SYNC_IMPLEMENTATIONS = /* @__PURE__ */ new Set([
  `accessSync`,
  `appendFileSync`,
  `createReadStream`,
  `createWriteStream`,
  `chmodSync`,
  `fchmodSync`,
  `chownSync`,
  `fchownSync`,
  `closeSync`,
  `copyFileSync`,
  `linkSync`,
  `lstatSync`,
  `fstatSync`,
  `lutimesSync`,
  `mkdirSync`,
  `openSync`,
  `opendirSync`,
  `readlinkSync`,
  `readFileSync`,
  `readdirSync`,
  `readlinkSync`,
  `realpathSync`,
  `renameSync`,
  `rmdirSync`,
  `statSync`,
  `symlinkSync`,
  `truncateSync`,
  `ftruncateSync`,
  `unlinkSync`,
  `unwatchFile`,
  `utimesSync`,
  `watch`,
  `watchFile`,
  `writeFileSync`,
  `writeSync`
]);
const ASYNC_IMPLEMENTATIONS = /* @__PURE__ */ new Set([
  `accessPromise`,
  `appendFilePromise`,
  `fchmodPromise`,
  `chmodPromise`,
  `fchownPromise`,
  `chownPromise`,
  `closePromise`,
  `copyFilePromise`,
  `linkPromise`,
  `fstatPromise`,
  `lstatPromise`,
  `lutimesPromise`,
  `mkdirPromise`,
  `openPromise`,
  `opendirPromise`,
  `readdirPromise`,
  `realpathPromise`,
  `readFilePromise`,
  `readdirPromise`,
  `readlinkPromise`,
  `renamePromise`,
  `rmdirPromise`,
  `statPromise`,
  `symlinkPromise`,
  `truncatePromise`,
  `ftruncatePromise`,
  `unlinkPromise`,
  `utimesPromise`,
  `writeFilePromise`,
  `writeSync`
]);
function patchFs(patchedFs, fakeFs) {
  fakeFs = new NodePathFS_1.NodePathFS(fakeFs);
  const setupFn = (target, name, replacement) => {
    const orig = target[name];
    target[name] = replacement;
    if (typeof (orig === null || orig === void 0 ? void 0 : orig[util_1.promisify.custom]) !== `undefined`) {
      replacement[util_1.promisify.custom] = orig[util_1.promisify.custom];
    }
  };
  {
    setupFn(patchedFs, `exists`, (p, ...args) => {
      const hasCallback = typeof args[args.length - 1] === `function`;
      const callback = hasCallback ? args.pop() : () => {
      };
      process.nextTick(() => {
        fakeFs.existsPromise(p).then((exists) => {
          callback(exists);
        }, () => {
          callback(false);
        });
      });
    });
    setupFn(patchedFs, `read`, (...args) => {
      let [fd, buffer, offset, length, position, callback] = args;
      if (args.length <= 3) {
        let options = {};
        if (args.length < 3) {
          callback = args[1];
        } else {
          options = args[1];
          callback = args[2];
        }
        ({
          buffer = Buffer.alloc(16384),
          offset = 0,
          length = buffer.byteLength,
          position
        } = options);
      }
      if (offset == null)
        offset = 0;
      length |= 0;
      if (length === 0) {
        process.nextTick(() => {
          callback(null, 0, buffer);
        });
        return;
      }
      if (position == null)
        position = -1;
      process.nextTick(() => {
        fakeFs.readPromise(fd, buffer, offset, length, position).then((bytesRead) => {
          callback(null, bytesRead, buffer);
        }, (error) => {
          callback(error, 0, buffer);
        });
      });
    });
    for (const fnName of ASYNC_IMPLEMENTATIONS) {
      const origName = fnName.replace(/Promise$/, ``);
      if (typeof patchedFs[origName] === `undefined`)
        continue;
      const fakeImpl = fakeFs[fnName];
      if (typeof fakeImpl === `undefined`)
        continue;
      const wrapper = (...args) => {
        const hasCallback = typeof args[args.length - 1] === `function`;
        const callback = hasCallback ? args.pop() : () => {
        };
        process.nextTick(() => {
          fakeImpl.apply(fakeFs, args).then((result) => {
            callback(null, result);
          }, (error) => {
            callback(error);
          });
        });
      };
      setupFn(patchedFs, origName, wrapper);
    }
    patchedFs.realpath.native = patchedFs.realpath;
  }
  {
    setupFn(patchedFs, `existsSync`, (p) => {
      try {
        return fakeFs.existsSync(p);
      } catch (error) {
        return false;
      }
    });
    setupFn(patchedFs, `readSync`, (...args) => {
      let [fd, buffer, offset, length, position] = args;
      if (args.length <= 3) {
        const options = args[2] || {};
        ({ offset = 0, length = buffer.byteLength, position } = options);
      }
      if (offset == null)
        offset = 0;
      length |= 0;
      if (length === 0)
        return 0;
      if (position == null)
        position = -1;
      return fakeFs.readSync(fd, buffer, offset, length, position);
    });
    for (const fnName of SYNC_IMPLEMENTATIONS) {
      const origName = fnName;
      if (typeof patchedFs[origName] === `undefined`)
        continue;
      const fakeImpl = fakeFs[fnName];
      if (typeof fakeImpl === `undefined`)
        continue;
      setupFn(patchedFs, origName, fakeImpl.bind(fakeFs));
    }
    patchedFs.realpathSync.native = patchedFs.realpathSync;
  }
  {
    const patchedFsPromises = patchedFs.promises;
    for (const fnName of ASYNC_IMPLEMENTATIONS) {
      const origName = fnName.replace(/Promise$/, ``);
      if (typeof patchedFsPromises[origName] === `undefined`)
        continue;
      const fakeImpl = fakeFs[fnName];
      if (typeof fakeImpl === `undefined`)
        continue;
      if (fnName === `open`)
        continue;
      setupFn(patchedFsPromises, origName, (pathLike, ...args) => {
        if (pathLike instanceof FileHandle_1.FileHandle) {
          return pathLike[origName].apply(pathLike, args);
        } else {
          return fakeImpl.call(fakeFs, pathLike, ...args);
        }
      });
    }
    setupFn(patchedFsPromises, `open`, async (...args) => {
      const fd = await fakeFs.openPromise(...args);
      return new FileHandle_1.FileHandle(fd, fakeFs);
    });
  }
  {
    patchedFs.read[util_1.promisify.custom] = async (fd, buffer, ...args) => {
      const res = fakeFs.readPromise(fd, buffer, ...args);
      return { bytesRead: await res, buffer };
    };
    patchedFs.write[util_1.promisify.custom] = async (fd, buffer, ...args) => {
      const res = fakeFs.writePromise(fd, buffer, ...args);
      return { bytesWritten: await res, buffer };
    };
  }
}
exports.patchFs = patchFs;
function extendFs(realFs, fakeFs) {
  const patchedFs = Object.create(realFs);
  patchFs(patchedFs, fakeFs);
  return patchedFs;
}
exports.extendFs = extendFs;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js":
/*!*******************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js ***!
  \*******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toFilename = exports.convertPath = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const path_1 = tslib_1.__importDefault(__webpack_require__(/*! path */ "path"));
var PathType;
(function(PathType2) {
  PathType2[PathType2["File"] = 0] = "File";
  PathType2[PathType2["Portable"] = 1] = "Portable";
  PathType2[PathType2["Native"] = 2] = "Native";
})(PathType || (PathType = {}));
exports.PortablePath = {
  root: `/`,
  dot: `.`,
  parent: `..`
};
exports.Filename = {
  nodeModules: `node_modules`,
  manifest: `package.json`,
  lockfile: `yarn.lock`,
  virtual: `__virtual__`,
  /**
   * @deprecated
   */
  pnpJs: `.pnp.js`,
  pnpCjs: `.pnp.cjs`,
  rc: `.yarnrc.yml`
};
exports.npath = Object.create(path_1.default);
exports.ppath = Object.create(path_1.default.posix);
exports.npath.cwd = () => process.cwd();
exports.ppath.cwd = () => toPortablePath(process.cwd());
exports.ppath.resolve = (...segments) => {
  if (segments.length > 0 && exports.ppath.isAbsolute(segments[0])) {
    return path_1.default.posix.resolve(...segments);
  } else {
    return path_1.default.posix.resolve(exports.ppath.cwd(), ...segments);
  }
};
const contains = function(pathUtils, from, to) {
  from = pathUtils.normalize(from);
  to = pathUtils.normalize(to);
  if (from === to)
    return `.`;
  if (!from.endsWith(pathUtils.sep))
    from = from + pathUtils.sep;
  if (to.startsWith(from)) {
    return to.slice(from.length);
  } else {
    return null;
  }
};
exports.npath.fromPortablePath = fromPortablePath;
exports.npath.toPortablePath = toPortablePath;
exports.npath.contains = (from, to) => contains(exports.npath, from, to);
exports.ppath.contains = (from, to) => contains(exports.ppath, from, to);
const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;
const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;
const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;
const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;
function fromPortablePath(p) {
  if (process.platform !== `win32`)
    return p;
  let portablePathMatch, uncPortablePathMatch;
  if (portablePathMatch = p.match(PORTABLE_PATH_REGEXP))
    p = portablePathMatch[1];
  else if (uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP))
    p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;
  else
    return p;
  return p.replace(/\//g, `\\`);
}
function toPortablePath(p) {
  if (process.platform !== `win32`)
    return p;
  p = p.replace(/\\/g, `/`);
  let windowsPathMatch, uncWindowsPathMatch;
  if (windowsPathMatch = p.match(WINDOWS_PATH_REGEXP))
    p = `/${windowsPathMatch[1]}`;
  else if (uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP))
    p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;
  return p;
}
function convertPath(targetPathUtils, sourcePath) {
  return targetPathUtils === exports.npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath);
}
exports.convertPath = convertPath;
function toFilename(filename) {
  if (exports.npath.parse(filename).dir !== `` || exports.ppath.parse(filename).dir !== ``)
    throw new Error(`Invalid filename: "${filename}"`);
  return filename;
}
exports.toFilename = toFilename;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/statUtils.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/statUtils.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.areStatsEqual = exports.convertToBigIntStats = exports.clearStats = exports.makeEmptyStats = exports.makeDefaultStats = exports.BigIntStatsEntry = exports.StatEntry = exports.DirEntry = exports.DEFAULT_MODE = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const nodeUtils = tslib_1.__importStar(__webpack_require__(/*! util */ "util"));
const constants_1 = __webpack_require__(/*! ./constants */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/constants.js");
exports.DEFAULT_MODE = constants_1.S_IFREG | 420;
class DirEntry {
  constructor() {
    this.name = ``;
    this.mode = 0;
  }
  isBlockDevice() {
    return false;
  }
  isCharacterDevice() {
    return false;
  }
  isDirectory() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR;
  }
  isFIFO() {
    return false;
  }
  isFile() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG;
  }
  isSocket() {
    return false;
  }
  isSymbolicLink() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK;
  }
}
exports.DirEntry = DirEntry;
class StatEntry {
  constructor() {
    this.uid = 0;
    this.gid = 0;
    this.size = 0;
    this.blksize = 0;
    this.atimeMs = 0;
    this.mtimeMs = 0;
    this.ctimeMs = 0;
    this.birthtimeMs = 0;
    this.atime = /* @__PURE__ */ new Date(0);
    this.mtime = /* @__PURE__ */ new Date(0);
    this.ctime = /* @__PURE__ */ new Date(0);
    this.birthtime = /* @__PURE__ */ new Date(0);
    this.dev = 0;
    this.ino = 0;
    this.mode = exports.DEFAULT_MODE;
    this.nlink = 1;
    this.rdev = 0;
    this.blocks = 1;
  }
  isBlockDevice() {
    return false;
  }
  isCharacterDevice() {
    return false;
  }
  isDirectory() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR;
  }
  isFIFO() {
    return false;
  }
  isFile() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG;
  }
  isSocket() {
    return false;
  }
  isSymbolicLink() {
    return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK;
  }
}
exports.StatEntry = StatEntry;
class BigIntStatsEntry {
  constructor() {
    this.uid = BigInt(0);
    this.gid = BigInt(0);
    this.size = BigInt(0);
    this.blksize = BigInt(0);
    this.atimeMs = BigInt(0);
    this.mtimeMs = BigInt(0);
    this.ctimeMs = BigInt(0);
    this.birthtimeMs = BigInt(0);
    this.atimeNs = BigInt(0);
    this.mtimeNs = BigInt(0);
    this.ctimeNs = BigInt(0);
    this.birthtimeNs = BigInt(0);
    this.atime = /* @__PURE__ */ new Date(0);
    this.mtime = /* @__PURE__ */ new Date(0);
    this.ctime = /* @__PURE__ */ new Date(0);
    this.birthtime = /* @__PURE__ */ new Date(0);
    this.dev = BigInt(0);
    this.ino = BigInt(0);
    this.mode = BigInt(exports.DEFAULT_MODE);
    this.nlink = BigInt(1);
    this.rdev = BigInt(0);
    this.blocks = BigInt(1);
  }
  isBlockDevice() {
    return false;
  }
  isCharacterDevice() {
    return false;
  }
  isDirectory() {
    return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFDIR);
  }
  isFIFO() {
    return false;
  }
  isFile() {
    return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFREG);
  }
  isSocket() {
    return false;
  }
  isSymbolicLink() {
    return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFLNK);
  }
}
exports.BigIntStatsEntry = BigIntStatsEntry;
function makeDefaultStats() {
  return new StatEntry();
}
exports.makeDefaultStats = makeDefaultStats;
function makeEmptyStats() {
  return clearStats(makeDefaultStats());
}
exports.makeEmptyStats = makeEmptyStats;
function clearStats(stats) {
  for (const key in stats) {
    if (Object.prototype.hasOwnProperty.call(stats, key)) {
      const element = stats[key];
      if (typeof element === `number`) {
        stats[key] = 0;
      } else if (typeof element === `bigint`) {
        stats[key] = BigInt(0);
      } else if (nodeUtils.types.isDate(element)) {
        stats[key] = /* @__PURE__ */ new Date(0);
      }
    }
  }
  return stats;
}
exports.clearStats = clearStats;
function convertToBigIntStats(stats) {
  const bigintStats = new BigIntStatsEntry();
  for (const key in stats) {
    if (Object.prototype.hasOwnProperty.call(stats, key)) {
      const element = stats[key];
      if (typeof element === `number`) {
        bigintStats[key] = BigInt(element);
      } else if (nodeUtils.types.isDate(element)) {
        bigintStats[key] = new Date(element);
      }
    }
  }
  bigintStats.atimeNs = bigintStats.atimeMs * BigInt(1e6);
  bigintStats.mtimeNs = bigintStats.mtimeMs * BigInt(1e6);
  bigintStats.ctimeNs = bigintStats.ctimeMs * BigInt(1e6);
  bigintStats.birthtimeNs = bigintStats.birthtimeMs * BigInt(1e6);
  return bigintStats;
}
exports.convertToBigIntStats = convertToBigIntStats;
function areStatsEqual(a, b) {
  if (a.atimeMs !== b.atimeMs)
    return false;
  if (a.birthtimeMs !== b.birthtimeMs)
    return false;
  if (a.blksize !== b.blksize)
    return false;
  if (a.blocks !== b.blocks)
    return false;
  if (a.ctimeMs !== b.ctimeMs)
    return false;
  if (a.dev !== b.dev)
    return false;
  if (a.gid !== b.gid)
    return false;
  if (a.ino !== b.ino)
    return false;
  if (a.isBlockDevice() !== b.isBlockDevice())
    return false;
  if (a.isCharacterDevice() !== b.isCharacterDevice())
    return false;
  if (a.isDirectory() !== b.isDirectory())
    return false;
  if (a.isFIFO() !== b.isFIFO())
    return false;
  if (a.isFile() !== b.isFile())
    return false;
  if (a.isSocket() !== b.isSocket())
    return false;
  if (a.isSymbolicLink() !== b.isSymbolicLink())
    return false;
  if (a.mode !== b.mode)
    return false;
  if (a.mtimeMs !== b.mtimeMs)
    return false;
  if (a.nlink !== b.nlink)
    return false;
  if (a.rdev !== b.rdev)
    return false;
  if (a.size !== b.size)
    return false;
  if (a.uid !== b.uid)
    return false;
  const aN = a;
  const bN = b;
  if (aN.atimeNs !== bN.atimeNs)
    return false;
  if (aN.mtimeNs !== bN.mtimeNs)
    return false;
  if (aN.ctimeNs !== bN.ctimeNs)
    return false;
  if (aN.birthtimeNs !== bN.birthtimeNs)
    return false;
  return true;
}
exports.areStatsEqual = areStatsEqual;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/xfs.js":
/*!******************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/lib/xfs.js ***!
  \******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.xfs = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js");
const os_1 = tslib_1.__importDefault(__webpack_require__(/*! os */ "os"));
const NodeFS_1 = __webpack_require__(/*! ./NodeFS */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/NodeFS.js");
const path_1 = __webpack_require__(/*! ./path */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/path.js");
function getTempName(prefix) {
  const hash = Math.ceil(Math.random() * 4294967296).toString(16).padStart(8, `0`);
  return `${prefix}${hash}`;
}
const tmpdirs = /* @__PURE__ */ new Set();
let tmpEnv = null;
function initTmpEnv() {
  if (tmpEnv)
    return tmpEnv;
  const tmpdir = path_1.npath.toPortablePath(os_1.default.tmpdir());
  const realTmpdir = exports.xfs.realpathSync(tmpdir);
  process.once(`exit`, () => {
    exports.xfs.rmtempSync();
  });
  return tmpEnv = {
    tmpdir,
    realTmpdir
  };
}
exports.xfs = Object.assign(new NodeFS_1.NodeFS(), {
  detachTemp(p) {
    tmpdirs.delete(p);
  },
  mktempSync(cb) {
    const { tmpdir, realTmpdir } = initTmpEnv();
    while (true) {
      const name = getTempName(`xfs-`);
      try {
        this.mkdirSync(path_1.ppath.join(tmpdir, name));
      } catch (error) {
        if (error.code === `EEXIST`) {
          continue;
        } else {
          throw error;
        }
      }
      const realP = path_1.ppath.join(realTmpdir, name);
      tmpdirs.add(realP);
      if (typeof cb === `undefined`)
        return realP;
      try {
        return cb(realP);
      } finally {
        if (tmpdirs.has(realP)) {
          tmpdirs.delete(realP);
          try {
            this.removeSync(realP);
          } catch {
          }
        }
      }
    }
  },
  async mktempPromise(cb) {
    const { tmpdir, realTmpdir } = initTmpEnv();
    while (true) {
      const name = getTempName(`xfs-`);
      try {
        await this.mkdirPromise(path_1.ppath.join(tmpdir, name));
      } catch (error) {
        if (error.code === `EEXIST`) {
          continue;
        } else {
          throw error;
        }
      }
      const realP = path_1.ppath.join(realTmpdir, name);
      tmpdirs.add(realP);
      if (typeof cb === `undefined`)
        return realP;
      try {
        return await cb(realP);
      } finally {
        if (tmpdirs.has(realP)) {
          tmpdirs.delete(realP);
          try {
            await this.removePromise(realP);
          } catch {
          }
        }
      }
    }
  },
  async rmtempPromise() {
    await Promise.all(Array.from(tmpdirs.values()).map(async (p) => {
      try {
        await exports.xfs.removePromise(p, { maxRetries: 0 });
        tmpdirs.delete(p);
      } catch {
      }
    }));
  },
  rmtempSync() {
    for (const p of tmpdirs) {
      try {
        exports.xfs.removeSync(p);
        tmpdirs.delete(p);
      } catch {
      }
    }
  }
});


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js":
/*!***************************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/fslib/node_modules/tslib/tslib.es6.js ***!
  \***************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   __assign: () => (/* binding */ __assign),
/* harmony export */   __asyncDelegator: () => (/* binding */ __asyncDelegator),
/* harmony export */   __asyncGenerator: () => (/* binding */ __asyncGenerator),
/* harmony export */   __asyncValues: () => (/* binding */ __asyncValues),
/* harmony export */   __await: () => (/* binding */ __await),
/* harmony export */   __awaiter: () => (/* binding */ __awaiter),
/* harmony export */   __classPrivateFieldGet: () => (/* binding */ __classPrivateFieldGet),
/* harmony export */   __classPrivateFieldSet: () => (/* binding */ __classPrivateFieldSet),
/* harmony export */   __createBinding: () => (/* binding */ __createBinding),
/* harmony export */   __decorate: () => (/* binding */ __decorate),
/* harmony export */   __exportStar: () => (/* binding */ __exportStar),
/* harmony export */   __extends: () => (/* binding */ __extends),
/* harmony export */   __generator: () => (/* binding */ __generator),
/* harmony export */   __importDefault: () => (/* binding */ __importDefault),
/* harmony export */   __importStar: () => (/* binding */ __importStar),
/* harmony export */   __makeTemplateObject: () => (/* binding */ __makeTemplateObject),
/* harmony export */   __metadata: () => (/* binding */ __metadata),
/* harmony export */   __param: () => (/* binding */ __param),
/* harmony export */   __read: () => (/* binding */ __read),
/* harmony export */   __rest: () => (/* binding */ __rest),
/* harmony export */   __spread: () => (/* binding */ __spread),
/* harmony export */   __spreadArrays: () => (/* binding */ __spreadArrays),
/* harmony export */   __values: () => (/* binding */ __values)
/* harmony export */ });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2)
      if (b2.hasOwnProperty(p))
        d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
function __rest(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1)
      throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f)
      throw new TypeError("Generator is already executing.");
    while (_)
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
          return t;
        if (y = 0, t)
          op = [op[0] & 2, t.value];
        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;
          case 4:
            _.label++;
            return { value: op[1], done: false };
          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            if (t[2])
              _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __createBinding(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
}
function __exportStar(m, exports) {
  for (var p in m)
    if (p !== "default" && !exports.hasOwnProperty(p))
      exports[p] = m[p];
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m)
    return m.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i >= o.length)
          o = void 0;
        return { value: o && o[i++], done: !o };
      }
    };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
    ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++)
    s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}
;
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function verb(n) {
    if (g[n])
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length)
      resume(q[0][0], q[0][1]);
  }
}
function __asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function(e) {
    throw e;
  }), verb("return"), i[Symbol.iterator] = function() {
    return this;
  }, i;
  function verb(n, f) {
    i[n] = o[n] ? function(v) {
      return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve, reject) {
        v = o[n](v), settle(resolve, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
;
function __importStar(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k in mod)
      if (Object.hasOwnProperty.call(mod, k))
        result[k] = mod[k];
  }
  result.default = mod;
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to get private field on non-instance");
  }
  return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to set private field on non-instance");
  }
  privateMap.set(receiver, value);
  return value;
}


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/libzipSync.js":
/*!**************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/libzip/lib/libzipSync.js ***!
  \**************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var frozenFs = Object.assign({}, __webpack_require__(/*! fs */ "fs"));
var createModule = function() {
  var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0;
  if (true)
    _scriptDir = _scriptDir || __filename;
  return function(createModule2) {
    createModule2 = createModule2 || {};
    var Module = typeof createModule2 !== "undefined" ? createModule2 : {};
    var readyPromiseResolve, readyPromiseReject;
    Module["ready"] = new Promise(function(resolve, reject) {
      readyPromiseResolve = resolve;
      readyPromiseReject = reject;
    });
    var moduleOverrides = {};
    var key;
    for (key in Module) {
      if (Module.hasOwnProperty(key)) {
        moduleOverrides[key] = Module[key];
      }
    }
    var arguments_ = [];
    var thisProgram = "./this.program";
    var quit_ = function(status, toThrow) {
      throw toThrow;
    };
    var ENVIRONMENT_IS_WORKER = false;
    var ENVIRONMENT_IS_NODE = true;
    var scriptDirectory = "";
    function locateFile(path) {
      if (Module["locateFile"]) {
        return Module["locateFile"](path, scriptDirectory);
      }
      return scriptDirectory + path;
    }
    var read_, readBinary;
    var nodeFS;
    var nodePath;
    if (ENVIRONMENT_IS_NODE) {
      if (ENVIRONMENT_IS_WORKER) {
        scriptDirectory = (__webpack_require__(/*! path */ "path").dirname)(scriptDirectory) + "/";
      } else {
        scriptDirectory = __dirname + "/";
      }
      read_ = function shell_read(filename, binary) {
        var ret = tryParseAsDataURI(filename);
        if (ret) {
          return binary ? ret : ret.toString();
        }
        if (!nodeFS)
          nodeFS = frozenFs;
        if (!nodePath)
          nodePath = __webpack_require__(/*! path */ "path");
        filename = nodePath["normalize"](filename);
        return nodeFS["readFileSync"](filename, binary ? null : "utf8");
      };
      readBinary = function readBinary2(filename) {
        var ret = read_(filename, true);
        if (!ret.buffer) {
          ret = new Uint8Array(ret);
        }
        assert(ret.buffer);
        return ret;
      };
      if (process["argv"].length > 1) {
        thisProgram = process["argv"][1].replace(/\\/g, "/");
      }
      arguments_ = process["argv"].slice(2);
      quit_ = function(status) {
        process["exit"](status);
      };
      Module["inspect"] = function() {
        return "[Emscripten Module object]";
      };
    } else {
    }
    var out = Module["print"] || console.log.bind(console);
    var err = Module["printErr"] || console.warn.bind(console);
    for (key in moduleOverrides) {
      if (moduleOverrides.hasOwnProperty(key)) {
        Module[key] = moduleOverrides[key];
      }
    }
    moduleOverrides = null;
    if (Module["arguments"])
      arguments_ = Module["arguments"];
    if (Module["thisProgram"])
      thisProgram = Module["thisProgram"];
    if (Module["quit"])
      quit_ = Module["quit"];
    var STACK_ALIGN = 16;
    function alignMemory(size, factor) {
      if (!factor)
        factor = STACK_ALIGN;
      return Math.ceil(size / factor) * factor;
    }
    var tempRet0 = 0;
    var setTempRet0 = function(value) {
      tempRet0 = value;
    };
    var wasmBinary;
    if (Module["wasmBinary"])
      wasmBinary = Module["wasmBinary"];
    var noExitRuntime = Module["noExitRuntime"] || true;
    if (typeof WebAssembly !== "object") {
      abort("no native wasm support detected");
    }
    function getValue(ptr, type, noSafe) {
      type = type || "i8";
      if (type.charAt(type.length - 1) === "*")
        type = "i32";
      switch (type) {
        case "i1":
          return HEAP8[ptr >> 0];
        case "i8":
          return HEAP8[ptr >> 0];
        case "i16":
          return HEAP16[ptr >> 1];
        case "i32":
          return HEAP32[ptr >> 2];
        case "i64":
          return HEAP32[ptr >> 2];
        case "float":
          return HEAPF32[ptr >> 2];
        case "double":
          return HEAPF64[ptr >> 3];
        default:
          abort("invalid type for getValue: " + type);
      }
      return null;
    }
    var wasmMemory;
    var ABORT = false;
    var EXITSTATUS;
    function assert(condition, text) {
      if (!condition) {
        abort("Assertion failed: " + text);
      }
    }
    function getCFunc(ident) {
      var func = Module["_" + ident];
      assert(
        func,
        "Cannot call unknown function " + ident + ", make sure it is exported"
      );
      return func;
    }
    function ccall(ident, returnType, argTypes, args, opts) {
      var toC = {
        string: function(str) {
          var ret2 = 0;
          if (str !== null && str !== void 0 && str !== 0) {
            var len = (str.length << 2) + 1;
            ret2 = stackAlloc(len);
            stringToUTF8(str, ret2, len);
          }
          return ret2;
        },
        array: function(arr) {
          var ret2 = stackAlloc(arr.length);
          writeArrayToMemory(arr, ret2);
          return ret2;
        }
      };
      function convertReturnValue(ret2) {
        if (returnType === "string")
          return UTF8ToString(ret2);
        if (returnType === "boolean")
          return Boolean(ret2);
        return ret2;
      }
      var func = getCFunc(ident);
      var cArgs = [];
      var stack = 0;
      if (args) {
        for (var i = 0; i < args.length; i++) {
          var converter = toC[argTypes[i]];
          if (converter) {
            if (stack === 0)
              stack = stackSave();
            cArgs[i] = converter(args[i]);
          } else {
            cArgs[i] = args[i];
          }
        }
      }
      var ret = func.apply(null, cArgs);
      ret = convertReturnValue(ret);
      if (stack !== 0)
        stackRestore(stack);
      return ret;
    }
    function cwrap(ident, returnType, argTypes, opts) {
      argTypes = argTypes || [];
      var numericArgs = argTypes.every(function(type) {
        return type === "number";
      });
      var numericRet = returnType !== "string";
      if (numericRet && numericArgs && !opts) {
        return getCFunc(ident);
      }
      return function() {
        return ccall(ident, returnType, argTypes, arguments, opts);
      };
    }
    var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : void 0;
    function UTF8ArrayToString(heap, idx, maxBytesToRead) {
      var endIdx = idx + maxBytesToRead;
      var endPtr = idx;
      while (heap[endPtr] && !(endPtr >= endIdx))
        ++endPtr;
      if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) {
        return UTF8Decoder.decode(heap.subarray(idx, endPtr));
      } else {
        var str = "";
        while (idx < endPtr) {
          var u0 = heap[idx++];
          if (!(u0 & 128)) {
            str += String.fromCharCode(u0);
            continue;
          }
          var u1 = heap[idx++] & 63;
          if ((u0 & 224) == 192) {
            str += String.fromCharCode((u0 & 31) << 6 | u1);
            continue;
          }
          var u2 = heap[idx++] & 63;
          if ((u0 & 240) == 224) {
            u0 = (u0 & 15) << 12 | u1 << 6 | u2;
          } else {
            u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63;
          }
          if (u0 < 65536) {
            str += String.fromCharCode(u0);
          } else {
            var ch = u0 - 65536;
            str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
          }
        }
      }
      return str;
    }
    function UTF8ToString(ptr, maxBytesToRead) {
      return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
    }
    function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
      if (!(maxBytesToWrite > 0))
        return 0;
      var startIdx = outIdx;
      var endIdx = outIdx + maxBytesToWrite - 1;
      for (var i = 0; i < str.length; ++i) {
        var u = str.charCodeAt(i);
        if (u >= 55296 && u <= 57343) {
          var u1 = str.charCodeAt(++i);
          u = 65536 + ((u & 1023) << 10) | u1 & 1023;
        }
        if (u <= 127) {
          if (outIdx >= endIdx)
            break;
          heap[outIdx++] = u;
        } else if (u <= 2047) {
          if (outIdx + 1 >= endIdx)
            break;
          heap[outIdx++] = 192 | u >> 6;
          heap[outIdx++] = 128 | u & 63;
        } else if (u <= 65535) {
          if (outIdx + 2 >= endIdx)
            break;
          heap[outIdx++] = 224 | u >> 12;
          heap[outIdx++] = 128 | u >> 6 & 63;
          heap[outIdx++] = 128 | u & 63;
        } else {
          if (outIdx + 3 >= endIdx)
            break;
          heap[outIdx++] = 240 | u >> 18;
          heap[outIdx++] = 128 | u >> 12 & 63;
          heap[outIdx++] = 128 | u >> 6 & 63;
          heap[outIdx++] = 128 | u & 63;
        }
      }
      heap[outIdx] = 0;
      return outIdx - startIdx;
    }
    function stringToUTF8(str, outPtr, maxBytesToWrite) {
      return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
    }
    function lengthBytesUTF8(str) {
      var len = 0;
      for (var i = 0; i < str.length; ++i) {
        var u = str.charCodeAt(i);
        if (u >= 55296 && u <= 57343)
          u = 65536 + ((u & 1023) << 10) | str.charCodeAt(++i) & 1023;
        if (u <= 127)
          ++len;
        else if (u <= 2047)
          len += 2;
        else if (u <= 65535)
          len += 3;
        else
          len += 4;
      }
      return len;
    }
    function allocateUTF8(str) {
      var size = lengthBytesUTF8(str) + 1;
      var ret = _malloc(size);
      if (ret)
        stringToUTF8Array(str, HEAP8, ret, size);
      return ret;
    }
    function writeArrayToMemory(array, buffer2) {
      HEAP8.set(array, buffer2);
    }
    function alignUp(x, multiple) {
      if (x % multiple > 0) {
        x += multiple - x % multiple;
      }
      return x;
    }
    var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
    function updateGlobalBufferAndViews(buf) {
      buffer = buf;
      Module["HEAP8"] = HEAP8 = new Int8Array(buf);
      Module["HEAP16"] = HEAP16 = new Int16Array(buf);
      Module["HEAP32"] = HEAP32 = new Int32Array(buf);
      Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf);
      Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf);
      Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf);
      Module["HEAPF32"] = HEAPF32 = new Float32Array(buf);
      Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
    }
    var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216;
    var wasmTable;
    var __ATPRERUN__ = [];
    var __ATINIT__ = [];
    var __ATPOSTRUN__ = [];
    var runtimeInitialized = false;
    function preRun() {
      if (Module["preRun"]) {
        if (typeof Module["preRun"] == "function")
          Module["preRun"] = [Module["preRun"]];
        while (Module["preRun"].length) {
          addOnPreRun(Module["preRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPRERUN__);
    }
    function initRuntime() {
      runtimeInitialized = true;
      if (!Module["noFSInit"] && !FS.init.initialized)
        FS.init();
      TTY.init();
      callRuntimeCallbacks(__ATINIT__);
    }
    function postRun() {
      if (Module["postRun"]) {
        if (typeof Module["postRun"] == "function")
          Module["postRun"] = [Module["postRun"]];
        while (Module["postRun"].length) {
          addOnPostRun(Module["postRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPOSTRUN__);
    }
    function addOnPreRun(cb) {
      __ATPRERUN__.unshift(cb);
    }
    function addOnInit(cb) {
      __ATINIT__.unshift(cb);
    }
    function addOnPostRun(cb) {
      __ATPOSTRUN__.unshift(cb);
    }
    var runDependencies = 0;
    var runDependencyWatcher = null;
    var dependenciesFulfilled = null;
    function getUniqueRunDependency(id) {
      return id;
    }
    function addRunDependency(id) {
      runDependencies++;
      if (Module["monitorRunDependencies"]) {
        Module["monitorRunDependencies"](runDependencies);
      }
    }
    function removeRunDependency(id) {
      runDependencies--;
      if (Module["monitorRunDependencies"]) {
        Module["monitorRunDependencies"](runDependencies);
      }
      if (runDependencies == 0) {
        if (runDependencyWatcher !== null) {
          clearInterval(runDependencyWatcher);
          runDependencyWatcher = null;
        }
        if (dependenciesFulfilled) {
          var callback = dependenciesFulfilled;
          dependenciesFulfilled = null;
          callback();
        }
      }
    }
    Module["preloadedImages"] = {};
    Module["preloadedAudios"] = {};
    function abort(what) {
      if (Module["onAbort"]) {
        Module["onAbort"](what);
      }
      what += "";
      err(what);
      ABORT = true;
      EXITSTATUS = 1;
      what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info.";
      var e = new WebAssembly.RuntimeError(what);
      readyPromiseReject(e);
      throw e;
    }
    var dataURIPrefix = "data:application/octet-stream;base64,";
    function isDataURI(filename) {
      return filename.startsWith(dataURIPrefix);
    }
    var wasmBinaryFile = "data:application/octet-stream;base64, ";
    if (!isDataURI(wasmBinaryFile)) {
      wasmBinaryFile = locateFile(wasmBinaryFile);
    }
    function getBinary(file) {
      try {
        if (file == wasmBinaryFile && wasmBinary) {
          return new Uint8Array(wasmBinary);
        }
        var binary = tryParseAsDataURI(file);
        if (binary) {
          return binary;
        }
        if (readBinary) {
          return readBinary(file);
        } else {
          throw "sync fetching of the wasm failed: you can preload it to Module['wasmBinary'] manually, or emcc.py will do that for you when generating HTML (but not JS)";
        }
      } catch (err2) {
        abort(err2);
      }
    }
    function instantiateSync(file, info) {
      var instance;
      var module2;
      var binary;
      try {
        binary = getBinary(file);
        module2 = new WebAssembly.Module(binary);
        instance = new WebAssembly.Instance(module2, info);
      } catch (e) {
        var str = e.toString();
        err("failed to compile wasm module: " + str);
        if (str.includes("imported Memory") || str.includes("memory import")) {
          err(
            "Memory size incompatibility issues may be due to changing INITIAL_MEMORY at runtime to something too large. Use ALLOW_MEMORY_GROWTH to allow any size memory (and also make sure not to set INITIAL_MEMORY at runtime to something smaller than it was at compile time)."
          );
        }
        throw e;
      }
      return [instance, module2];
    }
    function createWasm() {
      var info = { a: asmLibraryArg };
      function receiveInstance(instance, module2) {
        var exports3 = instance.exports;
        Module["asm"] = exports3;
        wasmMemory = Module["asm"]["u"];
        updateGlobalBufferAndViews(wasmMemory.buffer);
        wasmTable = Module["asm"]["pa"];
        addOnInit(Module["asm"]["v"]);
        removeRunDependency("wasm-instantiate");
      }
      addRunDependency("wasm-instantiate");
      if (Module["instantiateWasm"]) {
        try {
          var exports2 = Module["instantiateWasm"](info, receiveInstance);
          return exports2;
        } catch (e) {
          err("Module.instantiateWasm callback failed with error: " + e);
          return false;
        }
      }
      var result = instantiateSync(wasmBinaryFile, info);
      receiveInstance(result[0]);
      return Module["asm"];
    }
    var tempDouble;
    var tempI64;
    function callRuntimeCallbacks(callbacks) {
      while (callbacks.length > 0) {
        var callback = callbacks.shift();
        if (typeof callback == "function") {
          callback(Module);
          continue;
        }
        var func = callback.func;
        if (typeof func === "number") {
          if (callback.arg === void 0) {
            wasmTable.get(func)();
          } else {
            wasmTable.get(func)(callback.arg);
          }
        } else {
          func(callback.arg === void 0 ? null : callback.arg);
        }
      }
    }
    function _gmtime_r(time, tmPtr) {
      var date = new Date(HEAP32[time >> 2] * 1e3);
      HEAP32[tmPtr >> 2] = date.getUTCSeconds();
      HEAP32[tmPtr + 4 >> 2] = date.getUTCMinutes();
      HEAP32[tmPtr + 8 >> 2] = date.getUTCHours();
      HEAP32[tmPtr + 12 >> 2] = date.getUTCDate();
      HEAP32[tmPtr + 16 >> 2] = date.getUTCMonth();
      HEAP32[tmPtr + 20 >> 2] = date.getUTCFullYear() - 1900;
      HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();
      HEAP32[tmPtr + 36 >> 2] = 0;
      HEAP32[tmPtr + 32 >> 2] = 0;
      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
      var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;
      HEAP32[tmPtr + 28 >> 2] = yday;
      if (!_gmtime_r.GMTString)
        _gmtime_r.GMTString = allocateUTF8("GMT");
      HEAP32[tmPtr + 40 >> 2] = _gmtime_r.GMTString;
      return tmPtr;
    }
    function ___gmtime_r(a0, a1) {
      return _gmtime_r(a0, a1);
    }
    var PATH = {
      splitPath: function(filename) {
        var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
        return splitPathRe.exec(filename).slice(1);
      },
      normalizeArray: function(parts, allowAboveRoot) {
        var up = 0;
        for (var i = parts.length - 1; i >= 0; i--) {
          var last = parts[i];
          if (last === ".") {
            parts.splice(i, 1);
          } else if (last === "..") {
            parts.splice(i, 1);
            up++;
          } else if (up) {
            parts.splice(i, 1);
            up--;
          }
        }
        if (allowAboveRoot) {
          for (; up; up--) {
            parts.unshift("..");
          }
        }
        return parts;
      },
      normalize: function(path) {
        var isAbsolute = path.charAt(0) === "/", trailingSlash = path.substr(-1) === "/";
        path = PATH.normalizeArray(
          path.split("/").filter(function(p) {
            return !!p;
          }),
          !isAbsolute
        ).join("/");
        if (!path && !isAbsolute) {
          path = ".";
        }
        if (path && trailingSlash) {
          path += "/";
        }
        return (isAbsolute ? "/" : "") + path;
      },
      dirname: function(path) {
        var result = PATH.splitPath(path), root = result[0], dir = result[1];
        if (!root && !dir) {
          return ".";
        }
        if (dir) {
          dir = dir.substr(0, dir.length - 1);
        }
        return root + dir;
      },
      basename: function(path) {
        if (path === "/")
          return "/";
        path = PATH.normalize(path);
        path = path.replace(/\/$/, "");
        var lastSlash = path.lastIndexOf("/");
        if (lastSlash === -1)
          return path;
        return path.substr(lastSlash + 1);
      },
      extname: function(path) {
        return PATH.splitPath(path)[3];
      },
      join: function() {
        var paths = Array.prototype.slice.call(arguments, 0);
        return PATH.normalize(paths.join("/"));
      },
      join2: function(l, r) {
        return PATH.normalize(l + "/" + r);
      }
    };
    function getRandomDevice() {
      if (typeof crypto === "object" && typeof crypto["getRandomValues"] === "function") {
        var randomBuffer = new Uint8Array(1);
        return function() {
          crypto.getRandomValues(randomBuffer);
          return randomBuffer[0];
        };
      } else if (ENVIRONMENT_IS_NODE) {
        try {
          var crypto_module = __webpack_require__(/*! crypto */ "crypto");
          return function() {
            return crypto_module["randomBytes"](1)[0];
          };
        } catch (e) {
        }
      }
      return function() {
        abort("randomDevice");
      };
    }
    var PATH_FS = {
      resolve: function() {
        var resolvedPath = "", resolvedAbsolute = false;
        for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
          var path = i >= 0 ? arguments[i] : FS.cwd();
          if (typeof path !== "string") {
            throw new TypeError("Arguments to path.resolve must be strings");
          } else if (!path) {
            return "";
          }
          resolvedPath = path + "/" + resolvedPath;
          resolvedAbsolute = path.charAt(0) === "/";
        }
        resolvedPath = PATH.normalizeArray(
          resolvedPath.split("/").filter(function(p) {
            return !!p;
          }),
          !resolvedAbsolute
        ).join("/");
        return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
      },
      relative: function(from, to) {
        from = PATH_FS.resolve(from).substr(1);
        to = PATH_FS.resolve(to).substr(1);
        function trim(arr) {
          var start = 0;
          for (; start < arr.length; start++) {
            if (arr[start] !== "")
              break;
          }
          var end = arr.length - 1;
          for (; end >= 0; end--) {
            if (arr[end] !== "")
              break;
          }
          if (start > end)
            return [];
          return arr.slice(start, end - start + 1);
        }
        var fromParts = trim(from.split("/"));
        var toParts = trim(to.split("/"));
        var length = Math.min(fromParts.length, toParts.length);
        var samePartsLength = length;
        for (var i = 0; i < length; i++) {
          if (fromParts[i] !== toParts[i]) {
            samePartsLength = i;
            break;
          }
        }
        var outputParts = [];
        for (var i = samePartsLength; i < fromParts.length; i++) {
          outputParts.push("..");
        }
        outputParts = outputParts.concat(toParts.slice(samePartsLength));
        return outputParts.join("/");
      }
    };
    var TTY = {
      ttys: [],
      init: function() {
      },
      shutdown: function() {
      },
      register: function(dev, ops) {
        TTY.ttys[dev] = { input: [], output: [], ops };
        FS.registerDevice(dev, TTY.stream_ops);
      },
      stream_ops: {
        open: function(stream) {
          var tty = TTY.ttys[stream.node.rdev];
          if (!tty) {
            throw new FS.ErrnoError(43);
          }
          stream.tty = tty;
          stream.seekable = false;
        },
        close: function(stream) {
          stream.tty.ops.flush(stream.tty);
        },
        flush: function(stream) {
          stream.tty.ops.flush(stream.tty);
        },
        read: function(stream, buffer2, offset, length, pos) {
          if (!stream.tty || !stream.tty.ops.get_char) {
            throw new FS.ErrnoError(60);
          }
          var bytesRead = 0;
          for (var i = 0; i < length; i++) {
            var result;
            try {
              result = stream.tty.ops.get_char(stream.tty);
            } catch (e) {
              throw new FS.ErrnoError(29);
            }
            if (result === void 0 && bytesRead === 0) {
              throw new FS.ErrnoError(6);
            }
            if (result === null || result === void 0)
              break;
            bytesRead++;
            buffer2[offset + i] = result;
          }
          if (bytesRead) {
            stream.node.timestamp = Date.now();
          }
          return bytesRead;
        },
        write: function(stream, buffer2, offset, length, pos) {
          if (!stream.tty || !stream.tty.ops.put_char) {
            throw new FS.ErrnoError(60);
          }
          try {
            for (var i = 0; i < length; i++) {
              stream.tty.ops.put_char(stream.tty, buffer2[offset + i]);
            }
          } catch (e) {
            throw new FS.ErrnoError(29);
          }
          if (length) {
            stream.node.timestamp = Date.now();
          }
          return i;
        }
      },
      default_tty_ops: {
        get_char: function(tty) {
          if (!tty.input.length) {
            var result = null;
            if (ENVIRONMENT_IS_NODE) {
              var BUFSIZE = 256;
              var buf = Buffer.alloc ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE);
              var bytesRead = 0;
              try {
                bytesRead = nodeFS.readSync(
                  process.stdin.fd,
                  buf,
                  0,
                  BUFSIZE,
                  null
                );
              } catch (e) {
                if (e.toString().includes("EOF"))
                  bytesRead = 0;
                else
                  throw e;
              }
              if (bytesRead > 0) {
                result = buf.slice(0, bytesRead).toString("utf-8");
              } else {
                result = null;
              }
            } else if (typeof window != "undefined" && typeof window.prompt == "function") {
              result = window.prompt("Input: ");
              if (result !== null) {
                result += "\n";
              }
            } else if (typeof readline == "function") {
              result = readline();
              if (result !== null) {
                result += "\n";
              }
            }
            if (!result) {
              return null;
            }
            tty.input = intArrayFromString(result, true);
          }
          return tty.input.shift();
        },
        put_char: function(tty, val) {
          if (val === null || val === 10) {
            out(UTF8ArrayToString(tty.output, 0));
            tty.output = [];
          } else {
            if (val != 0)
              tty.output.push(val);
          }
        },
        flush: function(tty) {
          if (tty.output && tty.output.length > 0) {
            out(UTF8ArrayToString(tty.output, 0));
            tty.output = [];
          }
        }
      },
      default_tty1_ops: {
        put_char: function(tty, val) {
          if (val === null || val === 10) {
            err(UTF8ArrayToString(tty.output, 0));
            tty.output = [];
          } else {
            if (val != 0)
              tty.output.push(val);
          }
        },
        flush: function(tty) {
          if (tty.output && tty.output.length > 0) {
            err(UTF8ArrayToString(tty.output, 0));
            tty.output = [];
          }
        }
      }
    };
    function mmapAlloc(size) {
      var alignedSize = alignMemory(size, 65536);
      var ptr = _malloc(alignedSize);
      while (size < alignedSize)
        HEAP8[ptr + size++] = 0;
      return ptr;
    }
    var MEMFS = {
      ops_table: null,
      mount: function(mount) {
        return MEMFS.createNode(null, "/", 16384 | 511, 0);
      },
      createNode: function(parent, name, mode, dev) {
        if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
          throw new FS.ErrnoError(63);
        }
        if (!MEMFS.ops_table) {
          MEMFS.ops_table = {
            dir: {
              node: {
                getattr: MEMFS.node_ops.getattr,
                setattr: MEMFS.node_ops.setattr,
                lookup: MEMFS.node_ops.lookup,
                mknod: MEMFS.node_ops.mknod,
                rename: MEMFS.node_ops.rename,
                unlink: MEMFS.node_ops.unlink,
                rmdir: MEMFS.node_ops.rmdir,
                readdir: MEMFS.node_ops.readdir,
                symlink: MEMFS.node_ops.symlink
              },
              stream: { llseek: MEMFS.stream_ops.llseek }
            },
            file: {
              node: {
                getattr: MEMFS.node_ops.getattr,
                setattr: MEMFS.node_ops.setattr
              },
              stream: {
                llseek: MEMFS.stream_ops.llseek,
                read: MEMFS.stream_ops.read,
                write: MEMFS.stream_ops.write,
                allocate: MEMFS.stream_ops.allocate,
                mmap: MEMFS.stream_ops.mmap,
                msync: MEMFS.stream_ops.msync
              }
            },
            link: {
              node: {
                getattr: MEMFS.node_ops.getattr,
                setattr: MEMFS.node_ops.setattr,
                readlink: MEMFS.node_ops.readlink
              },
              stream: {}
            },
            chrdev: {
              node: {
                getattr: MEMFS.node_ops.getattr,
                setattr: MEMFS.node_ops.setattr
              },
              stream: FS.chrdev_stream_ops
            }
          };
        }
        var node = FS.createNode(parent, name, mode, dev);
        if (FS.isDir(node.mode)) {
          node.node_ops = MEMFS.ops_table.dir.node;
          node.stream_ops = MEMFS.ops_table.dir.stream;
          node.contents = {};
        } else if (FS.isFile(node.mode)) {
          node.node_ops = MEMFS.ops_table.file.node;
          node.stream_ops = MEMFS.ops_table.file.stream;
          node.usedBytes = 0;
          node.contents = null;
        } else if (FS.isLink(node.mode)) {
          node.node_ops = MEMFS.ops_table.link.node;
          node.stream_ops = MEMFS.ops_table.link.stream;
        } else if (FS.isChrdev(node.mode)) {
          node.node_ops = MEMFS.ops_table.chrdev.node;
          node.stream_ops = MEMFS.ops_table.chrdev.stream;
        }
        node.timestamp = Date.now();
        if (parent) {
          parent.contents[name] = node;
          parent.timestamp = node.timestamp;
        }
        return node;
      },
      getFileDataAsTypedArray: function(node) {
        if (!node.contents)
          return new Uint8Array(0);
        if (node.contents.subarray)
          return node.contents.subarray(0, node.usedBytes);
        return new Uint8Array(node.contents);
      },
      expandFileStorage: function(node, newCapacity) {
        var prevCapacity = node.contents ? node.contents.length : 0;
        if (prevCapacity >= newCapacity)
          return;
        var CAPACITY_DOUBLING_MAX = 1024 * 1024;
        newCapacity = Math.max(
          newCapacity,
          prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0
        );
        if (prevCapacity != 0)
          newCapacity = Math.max(newCapacity, 256);
        var oldContents = node.contents;
        node.contents = new Uint8Array(newCapacity);
        if (node.usedBytes > 0)
          node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
      },
      resizeFileStorage: function(node, newSize) {
        if (node.usedBytes == newSize)
          return;
        if (newSize == 0) {
          node.contents = null;
          node.usedBytes = 0;
        } else {
          var oldContents = node.contents;
          node.contents = new Uint8Array(newSize);
          if (oldContents) {
            node.contents.set(
              oldContents.subarray(0, Math.min(newSize, node.usedBytes))
            );
          }
          node.usedBytes = newSize;
        }
      },
      node_ops: {
        getattr: function(node) {
          var attr = {};
          attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
          attr.ino = node.id;
          attr.mode = node.mode;
          attr.nlink = 1;
          attr.uid = 0;
          attr.gid = 0;
          attr.rdev = node.rdev;
          if (FS.isDir(node.mode)) {
            attr.size = 4096;
          } else if (FS.isFile(node.mode)) {
            attr.size = node.usedBytes;
          } else if (FS.isLink(node.mode)) {
            attr.size = node.link.length;
          } else {
            attr.size = 0;
          }
          attr.atime = new Date(node.timestamp);
          attr.mtime = new Date(node.timestamp);
          attr.ctime = new Date(node.timestamp);
          attr.blksize = 4096;
          attr.blocks = Math.ceil(attr.size / attr.blksize);
          return attr;
        },
        setattr: function(node, attr) {
          if (attr.mode !== void 0) {
            node.mode = attr.mode;
          }
          if (attr.timestamp !== void 0) {
            node.timestamp = attr.timestamp;
          }
          if (attr.size !== void 0) {
            MEMFS.resizeFileStorage(node, attr.size);
          }
        },
        lookup: function(parent, name) {
          throw FS.genericErrors[44];
        },
        mknod: function(parent, name, mode, dev) {
          return MEMFS.createNode(parent, name, mode, dev);
        },
        rename: function(old_node, new_dir, new_name) {
          if (FS.isDir(old_node.mode)) {
            var new_node;
            try {
              new_node = FS.lookupNode(new_dir, new_name);
            } catch (e) {
            }
            if (new_node) {
              for (var i in new_node.contents) {
                throw new FS.ErrnoError(55);
              }
            }
          }
          delete old_node.parent.contents[old_node.name];
          old_node.parent.timestamp = Date.now();
          old_node.name = new_name;
          new_dir.contents[new_name] = old_node;
          new_dir.timestamp = old_node.parent.timestamp;
          old_node.parent = new_dir;
        },
        unlink: function(parent, name) {
          delete parent.contents[name];
          parent.timestamp = Date.now();
        },
        rmdir: function(parent, name) {
          var node = FS.lookupNode(parent, name);
          for (var i in node.contents) {
            throw new FS.ErrnoError(55);
          }
          delete parent.contents[name];
          parent.timestamp = Date.now();
        },
        readdir: function(node) {
          var entries = [".", ".."];
          for (var key2 in node.contents) {
            if (!node.contents.hasOwnProperty(key2)) {
              continue;
            }
            entries.push(key2);
          }
          return entries;
        },
        symlink: function(parent, newname, oldpath) {
          var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
          node.link = oldpath;
          return node;
        },
        readlink: function(node) {
          if (!FS.isLink(node.mode)) {
            throw new FS.ErrnoError(28);
          }
          return node.link;
        }
      },
      stream_ops: {
        read: function(stream, buffer2, offset, length, position) {
          var contents = stream.node.contents;
          if (position >= stream.node.usedBytes)
            return 0;
          var size = Math.min(stream.node.usedBytes - position, length);
          if (size > 8 && contents.subarray) {
            buffer2.set(contents.subarray(position, position + size), offset);
          } else {
            for (var i = 0; i < size; i++)
              buffer2[offset + i] = contents[position + i];
          }
          return size;
        },
        write: function(stream, buffer2, offset, length, position, canOwn) {
          if (buffer2.buffer === HEAP8.buffer) {
            canOwn = false;
          }
          if (!length)
            return 0;
          var node = stream.node;
          node.timestamp = Date.now();
          if (buffer2.subarray && (!node.contents || node.contents.subarray)) {
            if (canOwn) {
              node.contents = buffer2.subarray(offset, offset + length);
              node.usedBytes = length;
              return length;
            } else if (node.usedBytes === 0 && position === 0) {
              node.contents = buffer2.slice(offset, offset + length);
              node.usedBytes = length;
              return length;
            } else if (position + length <= node.usedBytes) {
              node.contents.set(
                buffer2.subarray(offset, offset + length),
                position
              );
              return length;
            }
          }
          MEMFS.expandFileStorage(node, position + length);
          if (node.contents.subarray && buffer2.subarray) {
            node.contents.set(
              buffer2.subarray(offset, offset + length),
              position
            );
          } else {
            for (var i = 0; i < length; i++) {
              node.contents[position + i] = buffer2[offset + i];
            }
          }
          node.usedBytes = Math.max(node.usedBytes, position + length);
          return length;
        },
        llseek: function(stream, offset, whence) {
          var position = offset;
          if (whence === 1) {
            position += stream.position;
          } else if (whence === 2) {
            if (FS.isFile(stream.node.mode)) {
              position += stream.node.usedBytes;
            }
          }
          if (position < 0) {
            throw new FS.ErrnoError(28);
          }
          return position;
        },
        allocate: function(stream, offset, length) {
          MEMFS.expandFileStorage(stream.node, offset + length);
          stream.node.usedBytes = Math.max(
            stream.node.usedBytes,
            offset + length
          );
        },
        mmap: function(stream, address, length, position, prot, flags) {
          if (address !== 0) {
            throw new FS.ErrnoError(28);
          }
          if (!FS.isFile(stream.node.mode)) {
            throw new FS.ErrnoError(43);
          }
          var ptr;
          var allocated;
          var contents = stream.node.contents;
          if (!(flags & 2) && contents.buffer === buffer) {
            allocated = false;
            ptr = contents.byteOffset;
          } else {
            if (position > 0 || position + length < contents.length) {
              if (contents.subarray) {
                contents = contents.subarray(position, position + length);
              } else {
                contents = Array.prototype.slice.call(
                  contents,
                  position,
                  position + length
                );
              }
            }
            allocated = true;
            ptr = mmapAlloc(length);
            if (!ptr) {
              throw new FS.ErrnoError(48);
            }
            HEAP8.set(contents, ptr);
          }
          return { ptr, allocated };
        },
        msync: function(stream, buffer2, offset, length, mmapFlags) {
          if (!FS.isFile(stream.node.mode)) {
            throw new FS.ErrnoError(43);
          }
          if (mmapFlags & 2) {
            return 0;
          }
          var bytesWritten = MEMFS.stream_ops.write(
            stream,
            buffer2,
            0,
            length,
            offset,
            false
          );
          return 0;
        }
      }
    };
    var ERRNO_CODES = {
      EPERM: 63,
      ENOENT: 44,
      ESRCH: 71,
      EINTR: 27,
      EIO: 29,
      ENXIO: 60,
      E2BIG: 1,
      ENOEXEC: 45,
      EBADF: 8,
      ECHILD: 12,
      EAGAIN: 6,
      EWOULDBLOCK: 6,
      ENOMEM: 48,
      EACCES: 2,
      EFAULT: 21,
      ENOTBLK: 105,
      EBUSY: 10,
      EEXIST: 20,
      EXDEV: 75,
      ENODEV: 43,
      ENOTDIR: 54,
      EISDIR: 31,
      EINVAL: 28,
      ENFILE: 41,
      EMFILE: 33,
      ENOTTY: 59,
      ETXTBSY: 74,
      EFBIG: 22,
      ENOSPC: 51,
      ESPIPE: 70,
      EROFS: 69,
      EMLINK: 34,
      EPIPE: 64,
      EDOM: 18,
      ERANGE: 68,
      ENOMSG: 49,
      EIDRM: 24,
      ECHRNG: 106,
      EL2NSYNC: 156,
      EL3HLT: 107,
      EL3RST: 108,
      ELNRNG: 109,
      EUNATCH: 110,
      ENOCSI: 111,
      EL2HLT: 112,
      EDEADLK: 16,
      ENOLCK: 46,
      EBADE: 113,
      EBADR: 114,
      EXFULL: 115,
      ENOANO: 104,
      EBADRQC: 103,
      EBADSLT: 102,
      EDEADLOCK: 16,
      EBFONT: 101,
      ENOSTR: 100,
      ENODATA: 116,
      ETIME: 117,
      ENOSR: 118,
      ENONET: 119,
      ENOPKG: 120,
      EREMOTE: 121,
      ENOLINK: 47,
      EADV: 122,
      ESRMNT: 123,
      ECOMM: 124,
      EPROTO: 65,
      EMULTIHOP: 36,
      EDOTDOT: 125,
      EBADMSG: 9,
      ENOTUNIQ: 126,
      EBADFD: 127,
      EREMCHG: 128,
      ELIBACC: 129,
      ELIBBAD: 130,
      ELIBSCN: 131,
      ELIBMAX: 132,
      ELIBEXEC: 133,
      ENOSYS: 52,
      ENOTEMPTY: 55,
      ENAMETOOLONG: 37,
      ELOOP: 32,
      EOPNOTSUPP: 138,
      EPFNOSUPPORT: 139,
      ECONNRESET: 15,
      ENOBUFS: 42,
      EAFNOSUPPORT: 5,
      EPROTOTYPE: 67,
      ENOTSOCK: 57,
      ENOPROTOOPT: 50,
      ESHUTDOWN: 140,
      ECONNREFUSED: 14,
      EADDRINUSE: 3,
      ECONNABORTED: 13,
      ENETUNREACH: 40,
      ENETDOWN: 38,
      ETIMEDOUT: 73,
      EHOSTDOWN: 142,
      EHOSTUNREACH: 23,
      EINPROGRESS: 26,
      EALREADY: 7,
      EDESTADDRREQ: 17,
      EMSGSIZE: 35,
      EPROTONOSUPPORT: 66,
      ESOCKTNOSUPPORT: 137,
      EADDRNOTAVAIL: 4,
      ENETRESET: 39,
      EISCONN: 30,
      ENOTCONN: 53,
      ETOOMANYREFS: 141,
      EUSERS: 136,
      EDQUOT: 19,
      ESTALE: 72,
      ENOTSUP: 138,
      ENOMEDIUM: 148,
      EILSEQ: 25,
      EOVERFLOW: 61,
      ECANCELED: 11,
      ENOTRECOVERABLE: 56,
      EOWNERDEAD: 62,
      ESTRPIPE: 135
    };
    var NODEFS = {
      isWindows: false,
      staticInit: function() {
        NODEFS.isWindows = !!process.platform.match(/^win/);
        var flags = { fs: fs.constants };
        if (flags["fs"]) {
          flags = flags["fs"];
        }
        NODEFS.flagsForNodeMap = {
          1024: flags["O_APPEND"],
          64: flags["O_CREAT"],
          128: flags["O_EXCL"],
          256: flags["O_NOCTTY"],
          0: flags["O_RDONLY"],
          2: flags["O_RDWR"],
          4096: flags["O_SYNC"],
          512: flags["O_TRUNC"],
          1: flags["O_WRONLY"]
        };
      },
      bufferFrom: function(arrayBuffer) {
        return Buffer["alloc"] ? Buffer.from(arrayBuffer) : new Buffer(arrayBuffer);
      },
      convertNodeCode: function(e) {
        var code = e.code;
        return ERRNO_CODES[code];
      },
      mount: function(mount) {
        return NODEFS.createNode(null, "/", NODEFS.getMode(mount.opts.root), 0);
      },
      createNode: function(parent, name, mode, dev) {
        if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) {
          throw new FS.ErrnoError(28);
        }
        var node = FS.createNode(parent, name, mode);
        node.node_ops = NODEFS.node_ops;
        node.stream_ops = NODEFS.stream_ops;
        return node;
      },
      getMode: function(path) {
        var stat;
        try {
          stat = fs.lstatSync(path);
          if (NODEFS.isWindows) {
            stat.mode = stat.mode | (stat.mode & 292) >> 2;
          }
        } catch (e) {
          if (!e.code)
            throw e;
          throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
        }
        return stat.mode;
      },
      realPath: function(node) {
        var parts = [];
        while (node.parent !== node) {
          parts.push(node.name);
          node = node.parent;
        }
        parts.push(node.mount.opts.root);
        parts.reverse();
        return PATH.join.apply(null, parts);
      },
      flagsForNode: function(flags) {
        flags &= ~2097152;
        flags &= ~2048;
        flags &= ~32768;
        flags &= ~524288;
        var newFlags = 0;
        for (var k in NODEFS.flagsForNodeMap) {
          if (flags & k) {
            newFlags |= NODEFS.flagsForNodeMap[k];
            flags ^= k;
          }
        }
        if (!flags) {
          return newFlags;
        } else {
          throw new FS.ErrnoError(28);
        }
      },
      node_ops: {
        getattr: function(node) {
          var path = NODEFS.realPath(node);
          var stat;
          try {
            stat = fs.lstatSync(path);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
          if (NODEFS.isWindows && !stat.blksize) {
            stat.blksize = 4096;
          }
          if (NODEFS.isWindows && !stat.blocks) {
            stat.blocks = (stat.size + stat.blksize - 1) / stat.blksize | 0;
          }
          return {
            dev: stat.dev,
            ino: stat.ino,
            mode: stat.mode,
            nlink: stat.nlink,
            uid: stat.uid,
            gid: stat.gid,
            rdev: stat.rdev,
            size: stat.size,
            atime: stat.atime,
            mtime: stat.mtime,
            ctime: stat.ctime,
            blksize: stat.blksize,
            blocks: stat.blocks
          };
        },
        setattr: function(node, attr) {
          var path = NODEFS.realPath(node);
          try {
            if (attr.mode !== void 0) {
              fs.chmodSync(path, attr.mode);
              node.mode = attr.mode;
            }
            if (attr.timestamp !== void 0) {
              var date = new Date(attr.timestamp);
              fs.utimesSync(path, date, date);
            }
            if (attr.size !== void 0) {
              fs.truncateSync(path, attr.size);
            }
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        lookup: function(parent, name) {
          var path = PATH.join2(NODEFS.realPath(parent), name);
          var mode = NODEFS.getMode(path);
          return NODEFS.createNode(parent, name, mode);
        },
        mknod: function(parent, name, mode, dev) {
          var node = NODEFS.createNode(parent, name, mode, dev);
          var path = NODEFS.realPath(node);
          try {
            if (FS.isDir(node.mode)) {
              fs.mkdirSync(path, node.mode);
            } else {
              fs.writeFileSync(path, "", { mode: node.mode });
            }
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
          return node;
        },
        rename: function(oldNode, newDir, newName) {
          var oldPath = NODEFS.realPath(oldNode);
          var newPath = PATH.join2(NODEFS.realPath(newDir), newName);
          try {
            fs.renameSync(oldPath, newPath);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
          oldNode.name = newName;
        },
        unlink: function(parent, name) {
          var path = PATH.join2(NODEFS.realPath(parent), name);
          try {
            fs.unlinkSync(path);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        rmdir: function(parent, name) {
          var path = PATH.join2(NODEFS.realPath(parent), name);
          try {
            fs.rmdirSync(path);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        readdir: function(node) {
          var path = NODEFS.realPath(node);
          try {
            return fs.readdirSync(path);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        symlink: function(parent, newName, oldPath) {
          var newPath = PATH.join2(NODEFS.realPath(parent), newName);
          try {
            fs.symlinkSync(oldPath, newPath);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        readlink: function(node) {
          var path = NODEFS.realPath(node);
          try {
            path = fs.readlinkSync(path);
            path = NODEJS_PATH.relative(
              NODEJS_PATH.resolve(node.mount.opts.root),
              path
            );
            return path;
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        }
      },
      stream_ops: {
        open: function(stream) {
          var path = NODEFS.realPath(stream.node);
          try {
            if (FS.isFile(stream.node.mode)) {
              stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags));
            }
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        close: function(stream) {
          try {
            if (FS.isFile(stream.node.mode) && stream.nfd) {
              fs.closeSync(stream.nfd);
            }
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        read: function(stream, buffer2, offset, length, position) {
          if (length === 0)
            return 0;
          try {
            return fs.readSync(
              stream.nfd,
              NODEFS.bufferFrom(buffer2.buffer),
              offset,
              length,
              position
            );
          } catch (e) {
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        write: function(stream, buffer2, offset, length, position) {
          try {
            return fs.writeSync(
              stream.nfd,
              NODEFS.bufferFrom(buffer2.buffer),
              offset,
              length,
              position
            );
          } catch (e) {
            throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
          }
        },
        llseek: function(stream, offset, whence) {
          var position = offset;
          if (whence === 1) {
            position += stream.position;
          } else if (whence === 2) {
            if (FS.isFile(stream.node.mode)) {
              try {
                var stat = fs.fstatSync(stream.nfd);
                position += stat.size;
              } catch (e) {
                throw new FS.ErrnoError(NODEFS.convertNodeCode(e));
              }
            }
          }
          if (position < 0) {
            throw new FS.ErrnoError(28);
          }
          return position;
        },
        mmap: function(stream, address, length, position, prot, flags) {
          if (address !== 0) {
            throw new FS.ErrnoError(28);
          }
          if (!FS.isFile(stream.node.mode)) {
            throw new FS.ErrnoError(43);
          }
          var ptr = mmapAlloc(length);
          NODEFS.stream_ops.read(stream, HEAP8, ptr, length, position);
          return { ptr, allocated: true };
        },
        msync: function(stream, buffer2, offset, length, mmapFlags) {
          if (!FS.isFile(stream.node.mode)) {
            throw new FS.ErrnoError(43);
          }
          if (mmapFlags & 2) {
            return 0;
          }
          var bytesWritten = NODEFS.stream_ops.write(
            stream,
            buffer2,
            0,
            length,
            offset,
            false
          );
          return 0;
        }
      }
    };
    var NODERAWFS = {
      lookupPath: function(path) {
        return { path, node: { mode: NODEFS.getMode(path) } };
      },
      createStandardStreams: function() {
        FS.streams[0] = {
          fd: 0,
          nfd: 0,
          position: 0,
          path: "",
          flags: 0,
          tty: true,
          seekable: false
        };
        for (var i = 1; i < 3; i++) {
          FS.streams[i] = {
            fd: i,
            nfd: i,
            position: 0,
            path: "",
            flags: 577,
            tty: true,
            seekable: false
          };
        }
      },
      cwd: function() {
        return process.cwd();
      },
      chdir: function() {
        process.chdir.apply(void 0, arguments);
      },
      mknod: function(path, mode) {
        if (FS.isDir(path)) {
          fs.mkdirSync(path, mode);
        } else {
          fs.writeFileSync(path, "", { mode });
        }
      },
      mkdir: function() {
        fs.mkdirSync.apply(void 0, arguments);
      },
      symlink: function() {
        fs.symlinkSync.apply(void 0, arguments);
      },
      rename: function() {
        fs.renameSync.apply(void 0, arguments);
      },
      rmdir: function() {
        fs.rmdirSync.apply(void 0, arguments);
      },
      readdir: function() {
        fs.readdirSync.apply(void 0, arguments);
      },
      unlink: function() {
        fs.unlinkSync.apply(void 0, arguments);
      },
      readlink: function() {
        return fs.readlinkSync.apply(void 0, arguments);
      },
      stat: function() {
        return fs.statSync.apply(void 0, arguments);
      },
      lstat: function() {
        return fs.lstatSync.apply(void 0, arguments);
      },
      chmod: function() {
        fs.chmodSync.apply(void 0, arguments);
      },
      fchmod: function() {
        fs.fchmodSync.apply(void 0, arguments);
      },
      chown: function() {
        fs.chownSync.apply(void 0, arguments);
      },
      fchown: function() {
        fs.fchownSync.apply(void 0, arguments);
      },
      truncate: function() {
        fs.truncateSync.apply(void 0, arguments);
      },
      ftruncate: function(fd, len) {
        if (len < 0) {
          throw new FS.ErrnoError(28);
        }
        fs.ftruncateSync.apply(void 0, arguments);
      },
      utime: function() {
        fs.utimesSync.apply(void 0, arguments);
      },
      open: function(path, flags, mode, suggestFD) {
        if (typeof flags === "string") {
          flags = VFS.modeStringToFlags(flags);
        }
        var nfd = fs.openSync(path, NODEFS.flagsForNode(flags), mode);
        var fd = suggestFD != null ? suggestFD : FS.nextfd(nfd);
        var stream = {
          fd,
          nfd,
          position: 0,
          path,
          flags,
          seekable: true
        };
        FS.streams[fd] = stream;
        return stream;
      },
      close: function(stream) {
        if (!stream.stream_ops) {
          fs.closeSync(stream.nfd);
        }
        FS.closeStream(stream.fd);
      },
      llseek: function(stream, offset, whence) {
        if (stream.stream_ops) {
          return VFS.llseek(stream, offset, whence);
        }
        var position = offset;
        if (whence === 1) {
          position += stream.position;
        } else if (whence === 2) {
          position += fs.fstatSync(stream.nfd).size;
        } else if (whence !== 0) {
          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
        }
        if (position < 0) {
          throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
        }
        stream.position = position;
        return position;
      },
      read: function(stream, buffer2, offset, length, position) {
        if (stream.stream_ops) {
          return VFS.read(stream, buffer2, offset, length, position);
        }
        var seeking = typeof position !== "undefined";
        if (!seeking && stream.seekable)
          position = stream.position;
        var bytesRead = fs.readSync(
          stream.nfd,
          NODEFS.bufferFrom(buffer2.buffer),
          offset,
          length,
          position
        );
        if (!seeking)
          stream.position += bytesRead;
        return bytesRead;
      },
      write: function(stream, buffer2, offset, length, position) {
        if (stream.stream_ops) {
          return VFS.write(stream, buffer2, offset, length, position);
        }
        if (stream.flags & 1024) {
          FS.llseek(stream, 0, 2);
        }
        var seeking = typeof position !== "undefined";
        if (!seeking && stream.seekable)
          position = stream.position;
        var bytesWritten = fs.writeSync(
          stream.nfd,
          NODEFS.bufferFrom(buffer2.buffer),
          offset,
          length,
          position
        );
        if (!seeking)
          stream.position += bytesWritten;
        return bytesWritten;
      },
      allocate: function() {
        throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP);
      },
      mmap: function(stream, address, length, position, prot, flags) {
        if (stream.stream_ops) {
          return VFS.mmap(stream, address, length, position, prot, flags);
        }
        if (address !== 0) {
          throw new FS.ErrnoError(28);
        }
        var ptr = mmapAlloc(length);
        FS.read(stream, HEAP8, ptr, length, position);
        return { ptr, allocated: true };
      },
      msync: function(stream, buffer2, offset, length, mmapFlags) {
        if (stream.stream_ops) {
          return VFS.msync(stream, buffer2, offset, length, mmapFlags);
        }
        if (mmapFlags & 2) {
          return 0;
        }
        FS.write(stream, buffer2, 0, length, offset);
        return 0;
      },
      munmap: function() {
        return 0;
      },
      ioctl: function() {
        throw new FS.ErrnoError(ERRNO_CODES.ENOTTY);
      }
    };
    var FS = {
      root: null,
      mounts: [],
      devices: {},
      streams: [],
      nextInode: 1,
      nameTable: null,
      currentPath: "/",
      initialized: false,
      ignorePermissions: true,
      trackingDelegate: {},
      tracking: { openFlags: { READ: 1, WRITE: 2 } },
      ErrnoError: null,
      genericErrors: {},
      filesystems: null,
      syncFSRequests: 0,
      lookupPath: function(path, opts) {
        path = PATH_FS.resolve(FS.cwd(), path);
        opts = opts || {};
        if (!path)
          return { path: "", node: null };
        var defaults = { follow_mount: true, recurse_count: 0 };
        for (var key2 in defaults) {
          if (opts[key2] === void 0) {
            opts[key2] = defaults[key2];
          }
        }
        if (opts.recurse_count > 8) {
          throw new FS.ErrnoError(32);
        }
        var parts = PATH.normalizeArray(
          path.split("/").filter(function(p) {
            return !!p;
          }),
          false
        );
        var current = FS.root;
        var current_path = "/";
        for (var i = 0; i < parts.length; i++) {
          var islast = i === parts.length - 1;
          if (islast && opts.parent) {
            break;
          }
          current = FS.lookupNode(current, parts[i]);
          current_path = PATH.join2(current_path, parts[i]);
          if (FS.isMountpoint(current)) {
            if (!islast || islast && opts.follow_mount) {
              current = current.mounted.root;
            }
          }
          if (!islast || opts.follow) {
            var count = 0;
            while (FS.isLink(current.mode)) {
              var link = FS.readlink(current_path);
              current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
              var lookup = FS.lookupPath(current_path, {
                recurse_count: opts.recurse_count
              });
              current = lookup.node;
              if (count++ > 40) {
                throw new FS.ErrnoError(32);
              }
            }
          }
        }
        return { path: current_path, node: current };
      },
      getPath: function(node) {
        var path;
        while (true) {
          if (FS.isRoot(node)) {
            var mount = node.mount.mountpoint;
            if (!path)
              return mount;
            return mount[mount.length - 1] !== "/" ? mount + "/" + path : mount + path;
          }
          path = path ? node.name + "/" + path : node.name;
          node = node.parent;
        }
      },
      hashName: function(parentid, name) {
        var hash = 0;
        for (var i = 0; i < name.length; i++) {
          hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
        }
        return (parentid + hash >>> 0) % FS.nameTable.length;
      },
      hashAddNode: function(node) {
        var hash = FS.hashName(node.parent.id, node.name);
        node.name_next = FS.nameTable[hash];
        FS.nameTable[hash] = node;
      },
      hashRemoveNode: function(node) {
        var hash = FS.hashName(node.parent.id, node.name);
        if (FS.nameTable[hash] === node) {
          FS.nameTable[hash] = node.name_next;
        } else {
          var current = FS.nameTable[hash];
          while (current) {
            if (current.name_next === node) {
              current.name_next = node.name_next;
              break;
            }
            current = current.name_next;
          }
        }
      },
      lookupNode: function(parent, name) {
        var errCode = FS.mayLookup(parent);
        if (errCode) {
          throw new FS.ErrnoError(errCode, parent);
        }
        var hash = FS.hashName(parent.id, name);
        for (var node = FS.nameTable[hash]; node; node = node.name_next) {
          var nodeName = node.name;
          if (node.parent.id === parent.id && nodeName === name) {
            return node;
          }
        }
        return FS.lookup(parent, name);
      },
      createNode: function(parent, name, mode, rdev) {
        var node = new FS.FSNode(parent, name, mode, rdev);
        FS.hashAddNode(node);
        return node;
      },
      destroyNode: function(node) {
        FS.hashRemoveNode(node);
      },
      isRoot: function(node) {
        return node === node.parent;
      },
      isMountpoint: function(node) {
        return !!node.mounted;
      },
      isFile: function(mode) {
        return (mode & 61440) === 32768;
      },
      isDir: function(mode) {
        return (mode & 61440) === 16384;
      },
      isLink: function(mode) {
        return (mode & 61440) === 40960;
      },
      isChrdev: function(mode) {
        return (mode & 61440) === 8192;
      },
      isBlkdev: function(mode) {
        return (mode & 61440) === 24576;
      },
      isFIFO: function(mode) {
        return (mode & 61440) === 4096;
      },
      isSocket: function(mode) {
        return (mode & 49152) === 49152;
      },
      flagModes: { r: 0, "r+": 2, w: 577, "w+": 578, a: 1089, "a+": 1090 },
      modeStringToFlags: function(str) {
        var flags = FS.flagModes[str];
        if (typeof flags === "undefined") {
          throw new Error("Unknown file open mode: " + str);
        }
        return flags;
      },
      flagsToPermissionString: function(flag) {
        var perms = ["r", "w", "rw"][flag & 3];
        if (flag & 512) {
          perms += "w";
        }
        return perms;
      },
      nodePermissions: function(node, perms) {
        if (FS.ignorePermissions) {
          return 0;
        }
        if (perms.includes("r") && !(node.mode & 292)) {
          return 2;
        } else if (perms.includes("w") && !(node.mode & 146)) {
          return 2;
        } else if (perms.includes("x") && !(node.mode & 73)) {
          return 2;
        }
        return 0;
      },
      mayLookup: function(dir) {
        var errCode = FS.nodePermissions(dir, "x");
        if (errCode)
          return errCode;
        if (!dir.node_ops.lookup)
          return 2;
        return 0;
      },
      mayCreate: function(dir, name) {
        try {
          var node = FS.lookupNode(dir, name);
          return 20;
        } catch (e) {
        }
        return FS.nodePermissions(dir, "wx");
      },
      mayDelete: function(dir, name, isdir) {
        var node;
        try {
          node = FS.lookupNode(dir, name);
        } catch (e) {
          return e.errno;
        }
        var errCode = FS.nodePermissions(dir, "wx");
        if (errCode) {
          return errCode;
        }
        if (isdir) {
          if (!FS.isDir(node.mode)) {
            return 54;
          }
          if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
            return 10;
          }
        } else {
          if (FS.isDir(node.mode)) {
            return 31;
          }
        }
        return 0;
      },
      mayOpen: function(node, flags) {
        if (!node) {
          return 44;
        }
        if (FS.isLink(node.mode)) {
          return 32;
        } else if (FS.isDir(node.mode)) {
          if (FS.flagsToPermissionString(flags) !== "r" || flags & 512) {
            return 31;
          }
        }
        return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
      },
      MAX_OPEN_FDS: 4096,
      nextfd: function(fd_start, fd_end) {
        fd_start = fd_start || 0;
        fd_end = fd_end || FS.MAX_OPEN_FDS;
        for (var fd = fd_start; fd <= fd_end; fd++) {
          if (!FS.streams[fd]) {
            return fd;
          }
        }
        throw new FS.ErrnoError(33);
      },
      getStream: function(fd) {
        return FS.streams[fd];
      },
      createStream: function(stream, fd_start, fd_end) {
        if (!FS.FSStream) {
          FS.FSStream = function() {
          };
          FS.FSStream.prototype = {
            object: {
              get: function() {
                return this.node;
              },
              set: function(val) {
                this.node = val;
              }
            },
            isRead: {
              get: function() {
                return (this.flags & 2097155) !== 1;
              }
            },
            isWrite: {
              get: function() {
                return (this.flags & 2097155) !== 0;
              }
            },
            isAppend: {
              get: function() {
                return this.flags & 1024;
              }
            }
          };
        }
        var newStream = new FS.FSStream();
        for (var p in stream) {
          newStream[p] = stream[p];
        }
        stream = newStream;
        var fd = FS.nextfd(fd_start, fd_end);
        stream.fd = fd;
        FS.streams[fd] = stream;
        return stream;
      },
      closeStream: function(fd) {
        FS.streams[fd] = null;
      },
      chrdev_stream_ops: {
        open: function(stream) {
          var device = FS.getDevice(stream.node.rdev);
          stream.stream_ops = device.stream_ops;
          if (stream.stream_ops.open) {
            stream.stream_ops.open(stream);
          }
        },
        llseek: function() {
          throw new FS.ErrnoError(70);
        }
      },
      major: function(dev) {
        return dev >> 8;
      },
      minor: function(dev) {
        return dev & 255;
      },
      makedev: function(ma, mi) {
        return ma << 8 | mi;
      },
      registerDevice: function(dev, ops) {
        FS.devices[dev] = { stream_ops: ops };
      },
      getDevice: function(dev) {
        return FS.devices[dev];
      },
      getMounts: function(mount) {
        var mounts = [];
        var check = [mount];
        while (check.length) {
          var m = check.pop();
          mounts.push(m);
          check.push.apply(check, m.mounts);
        }
        return mounts;
      },
      syncfs: function(populate, callback) {
        if (typeof populate === "function") {
          callback = populate;
          populate = false;
        }
        FS.syncFSRequests++;
        if (FS.syncFSRequests > 1) {
          err(
            "warning: " + FS.syncFSRequests + " FS.syncfs operations in flight at once, probably just doing extra work"
          );
        }
        var mounts = FS.getMounts(FS.root.mount);
        var completed = 0;
        function doCallback(errCode) {
          FS.syncFSRequests--;
          return callback(errCode);
        }
        function done(errCode) {
          if (errCode) {
            if (!done.errored) {
              done.errored = true;
              return doCallback(errCode);
            }
            return;
          }
          if (++completed >= mounts.length) {
            doCallback(null);
          }
        }
        mounts.forEach(function(mount) {
          if (!mount.type.syncfs) {
            return done(null);
          }
          mount.type.syncfs(mount, populate, done);
        });
      },
      mount: function(type, opts, mountpoint) {
        var root = mountpoint === "/";
        var pseudo = !mountpoint;
        var node;
        if (root && FS.root) {
          throw new FS.ErrnoError(10);
        } else if (!root && !pseudo) {
          var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
          mountpoint = lookup.path;
          node = lookup.node;
          if (FS.isMountpoint(node)) {
            throw new FS.ErrnoError(10);
          }
          if (!FS.isDir(node.mode)) {
            throw new FS.ErrnoError(54);
          }
        }
        var mount = {
          type,
          opts,
          mountpoint,
          mounts: []
        };
        var mountRoot = type.mount(mount);
        mountRoot.mount = mount;
        mount.root = mountRoot;
        if (root) {
          FS.root = mountRoot;
        } else if (node) {
          node.mounted = mount;
          if (node.mount) {
            node.mount.mounts.push(mount);
          }
        }
        return mountRoot;
      },
      unmount: function(mountpoint) {
        var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
        if (!FS.isMountpoint(lookup.node)) {
          throw new FS.ErrnoError(28);
        }
        var node = lookup.node;
        var mount = node.mounted;
        var mounts = FS.getMounts(mount);
        Object.keys(FS.nameTable).forEach(function(hash) {
          var current = FS.nameTable[hash];
          while (current) {
            var next = current.name_next;
            if (mounts.includes(current.mount)) {
              FS.destroyNode(current);
            }
            current = next;
          }
        });
        node.mounted = null;
        var idx = node.mount.mounts.indexOf(mount);
        node.mount.mounts.splice(idx, 1);
      },
      lookup: function(parent, name) {
        return parent.node_ops.lookup(parent, name);
      },
      mknod: function(path, mode, dev) {
        var lookup = FS.lookupPath(path, { parent: true });
        var parent = lookup.node;
        var name = PATH.basename(path);
        if (!name || name === "." || name === "..") {
          throw new FS.ErrnoError(28);
        }
        var errCode = FS.mayCreate(parent, name);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.mknod) {
          throw new FS.ErrnoError(63);
        }
        return parent.node_ops.mknod(parent, name, mode, dev);
      },
      create: function(path, mode) {
        mode = mode !== void 0 ? mode : 438;
        mode &= 4095;
        mode |= 32768;
        return FS.mknod(path, mode, 0);
      },
      mkdir: function(path, mode) {
        mode = mode !== void 0 ? mode : 511;
        mode &= 511 | 512;
        mode |= 16384;
        return FS.mknod(path, mode, 0);
      },
      mkdirTree: function(path, mode) {
        var dirs = path.split("/");
        var d = "";
        for (var i = 0; i < dirs.length; ++i) {
          if (!dirs[i])
            continue;
          d += "/" + dirs[i];
          try {
            FS.mkdir(d, mode);
          } catch (e) {
            if (e.errno != 20)
              throw e;
          }
        }
      },
      mkdev: function(path, mode, dev) {
        if (typeof dev === "undefined") {
          dev = mode;
          mode = 438;
        }
        mode |= 8192;
        return FS.mknod(path, mode, dev);
      },
      symlink: function(oldpath, newpath) {
        if (!PATH_FS.resolve(oldpath)) {
          throw new FS.ErrnoError(44);
        }
        var lookup = FS.lookupPath(newpath, { parent: true });
        var parent = lookup.node;
        if (!parent) {
          throw new FS.ErrnoError(44);
        }
        var newname = PATH.basename(newpath);
        var errCode = FS.mayCreate(parent, newname);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.symlink) {
          throw new FS.ErrnoError(63);
        }
        return parent.node_ops.symlink(parent, newname, oldpath);
      },
      rename: function(old_path, new_path) {
        var old_dirname = PATH.dirname(old_path);
        var new_dirname = PATH.dirname(new_path);
        var old_name = PATH.basename(old_path);
        var new_name = PATH.basename(new_path);
        var lookup, old_dir, new_dir;
        lookup = FS.lookupPath(old_path, { parent: true });
        old_dir = lookup.node;
        lookup = FS.lookupPath(new_path, { parent: true });
        new_dir = lookup.node;
        if (!old_dir || !new_dir)
          throw new FS.ErrnoError(44);
        if (old_dir.mount !== new_dir.mount) {
          throw new FS.ErrnoError(75);
        }
        var old_node = FS.lookupNode(old_dir, old_name);
        var relative = PATH_FS.relative(old_path, new_dirname);
        if (relative.charAt(0) !== ".") {
          throw new FS.ErrnoError(28);
        }
        relative = PATH_FS.relative(new_path, old_dirname);
        if (relative.charAt(0) !== ".") {
          throw new FS.ErrnoError(55);
        }
        var new_node;
        try {
          new_node = FS.lookupNode(new_dir, new_name);
        } catch (e) {
        }
        if (old_node === new_node) {
          return;
        }
        var isdir = FS.isDir(old_node.mode);
        var errCode = FS.mayDelete(old_dir, old_name, isdir);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!old_dir.node_ops.rename) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
          throw new FS.ErrnoError(10);
        }
        if (new_dir !== old_dir) {
          errCode = FS.nodePermissions(old_dir, "w");
          if (errCode) {
            throw new FS.ErrnoError(errCode);
          }
        }
        try {
          if (FS.trackingDelegate["willMovePath"]) {
            FS.trackingDelegate["willMovePath"](old_path, new_path);
          }
        } catch (e) {
          err(
            "FS.trackingDelegate['willMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message
          );
        }
        FS.hashRemoveNode(old_node);
        try {
          old_dir.node_ops.rename(old_node, new_dir, new_name);
        } catch (e) {
          throw e;
        } finally {
          FS.hashAddNode(old_node);
        }
        try {
          if (FS.trackingDelegate["onMovePath"])
            FS.trackingDelegate["onMovePath"](old_path, new_path);
        } catch (e) {
          err(
            "FS.trackingDelegate['onMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message
          );
        }
      },
      rmdir: function(path) {
        var lookup = FS.lookupPath(path, { parent: true });
        var parent = lookup.node;
        var name = PATH.basename(path);
        var node = FS.lookupNode(parent, name);
        var errCode = FS.mayDelete(parent, name, true);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.rmdir) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(node)) {
          throw new FS.ErrnoError(10);
        }
        try {
          if (FS.trackingDelegate["willDeletePath"]) {
            FS.trackingDelegate["willDeletePath"](path);
          }
        } catch (e) {
          err(
            "FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message
          );
        }
        parent.node_ops.rmdir(parent, name);
        FS.destroyNode(node);
        try {
          if (FS.trackingDelegate["onDeletePath"])
            FS.trackingDelegate["onDeletePath"](path);
        } catch (e) {
          err(
            "FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message
          );
        }
      },
      readdir: function(path) {
        var lookup = FS.lookupPath(path, { follow: true });
        var node = lookup.node;
        if (!node.node_ops.readdir) {
          throw new FS.ErrnoError(54);
        }
        return node.node_ops.readdir(node);
      },
      unlink: function(path) {
        var lookup = FS.lookupPath(path, { parent: true });
        var parent = lookup.node;
        var name = PATH.basename(path);
        var node = FS.lookupNode(parent, name);
        var errCode = FS.mayDelete(parent, name, false);
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        if (!parent.node_ops.unlink) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isMountpoint(node)) {
          throw new FS.ErrnoError(10);
        }
        try {
          if (FS.trackingDelegate["willDeletePath"]) {
            FS.trackingDelegate["willDeletePath"](path);
          }
        } catch (e) {
          err(
            "FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message
          );
        }
        parent.node_ops.unlink(parent, name);
        FS.destroyNode(node);
        try {
          if (FS.trackingDelegate["onDeletePath"])
            FS.trackingDelegate["onDeletePath"](path);
        } catch (e) {
          err(
            "FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message
          );
        }
      },
      readlink: function(path) {
        var lookup = FS.lookupPath(path);
        var link = lookup.node;
        if (!link) {
          throw new FS.ErrnoError(44);
        }
        if (!link.node_ops.readlink) {
          throw new FS.ErrnoError(28);
        }
        return PATH_FS.resolve(
          FS.getPath(link.parent),
          link.node_ops.readlink(link)
        );
      },
      stat: function(path, dontFollow) {
        var lookup = FS.lookupPath(path, { follow: !dontFollow });
        var node = lookup.node;
        if (!node) {
          throw new FS.ErrnoError(44);
        }
        if (!node.node_ops.getattr) {
          throw new FS.ErrnoError(63);
        }
        return node.node_ops.getattr(node);
      },
      lstat: function(path) {
        return FS.stat(path, true);
      },
      chmod: function(path, mode, dontFollow) {
        var node;
        if (typeof path === "string") {
          var lookup = FS.lookupPath(path, { follow: !dontFollow });
          node = lookup.node;
        } else {
          node = path;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        node.node_ops.setattr(node, {
          mode: mode & 4095 | node.mode & ~4095,
          timestamp: Date.now()
        });
      },
      lchmod: function(path, mode) {
        FS.chmod(path, mode, true);
      },
      fchmod: function(fd, mode) {
        var stream = FS.getStream(fd);
        if (!stream) {
          throw new FS.ErrnoError(8);
        }
        FS.chmod(stream.node, mode);
      },
      chown: function(path, uid, gid, dontFollow) {
        var node;
        if (typeof path === "string") {
          var lookup = FS.lookupPath(path, { follow: !dontFollow });
          node = lookup.node;
        } else {
          node = path;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        node.node_ops.setattr(node, { timestamp: Date.now() });
      },
      lchown: function(path, uid, gid) {
        FS.chown(path, uid, gid, true);
      },
      fchown: function(fd, uid, gid) {
        var stream = FS.getStream(fd);
        if (!stream) {
          throw new FS.ErrnoError(8);
        }
        FS.chown(stream.node, uid, gid);
      },
      truncate: function(path, len) {
        if (len < 0) {
          throw new FS.ErrnoError(28);
        }
        var node;
        if (typeof path === "string") {
          var lookup = FS.lookupPath(path, { follow: true });
          node = lookup.node;
        } else {
          node = path;
        }
        if (!node.node_ops.setattr) {
          throw new FS.ErrnoError(63);
        }
        if (FS.isDir(node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!FS.isFile(node.mode)) {
          throw new FS.ErrnoError(28);
        }
        var errCode = FS.nodePermissions(node, "w");
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        node.node_ops.setattr(node, { size: len, timestamp: Date.now() });
      },
      ftruncate: function(fd, len) {
        var stream = FS.getStream(fd);
        if (!stream) {
          throw new FS.ErrnoError(8);
        }
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(28);
        }
        FS.truncate(stream.node, len);
      },
      utime: function(path, atime, mtime) {
        var lookup = FS.lookupPath(path, { follow: true });
        var node = lookup.node;
        node.node_ops.setattr(node, { timestamp: Math.max(atime, mtime) });
      },
      open: function(path, flags, mode, fd_start, fd_end) {
        if (path === "") {
          throw new FS.ErrnoError(44);
        }
        flags = typeof flags === "string" ? FS.modeStringToFlags(flags) : flags;
        mode = typeof mode === "undefined" ? 438 : mode;
        if (flags & 64) {
          mode = mode & 4095 | 32768;
        } else {
          mode = 0;
        }
        var node;
        if (typeof path === "object") {
          node = path;
        } else {
          path = PATH.normalize(path);
          try {
            var lookup = FS.lookupPath(path, { follow: !(flags & 131072) });
            node = lookup.node;
          } catch (e) {
          }
        }
        var created = false;
        if (flags & 64) {
          if (node) {
            if (flags & 128) {
              throw new FS.ErrnoError(20);
            }
          } else {
            node = FS.mknod(path, mode, 0);
            created = true;
          }
        }
        if (!node) {
          throw new FS.ErrnoError(44);
        }
        if (FS.isChrdev(node.mode)) {
          flags &= ~512;
        }
        if (flags & 65536 && !FS.isDir(node.mode)) {
          throw new FS.ErrnoError(54);
        }
        if (!created) {
          var errCode = FS.mayOpen(node, flags);
          if (errCode) {
            throw new FS.ErrnoError(errCode);
          }
        }
        if (flags & 512) {
          FS.truncate(node, 0);
        }
        flags &= ~(128 | 512 | 131072);
        var stream = FS.createStream(
          {
            node,
            path: FS.getPath(node),
            flags,
            seekable: true,
            position: 0,
            stream_ops: node.stream_ops,
            ungotten: [],
            error: false
          },
          fd_start,
          fd_end
        );
        if (stream.stream_ops.open) {
          stream.stream_ops.open(stream);
        }
        if (Module["logReadFiles"] && !(flags & 1)) {
          if (!FS.readFiles)
            FS.readFiles = {};
          if (!(path in FS.readFiles)) {
            FS.readFiles[path] = 1;
            err("FS.trackingDelegate error on read file: " + path);
          }
        }
        try {
          if (FS.trackingDelegate["onOpenFile"]) {
            var trackingFlags = 0;
            if ((flags & 2097155) !== 1) {
              trackingFlags |= FS.tracking.openFlags.READ;
            }
            if ((flags & 2097155) !== 0) {
              trackingFlags |= FS.tracking.openFlags.WRITE;
            }
            FS.trackingDelegate["onOpenFile"](path, trackingFlags);
          }
        } catch (e) {
          err(
            "FS.trackingDelegate['onOpenFile']('" + path + "', flags) threw an exception: " + e.message
          );
        }
        return stream;
      },
      close: function(stream) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (stream.getdents)
          stream.getdents = null;
        try {
          if (stream.stream_ops.close) {
            stream.stream_ops.close(stream);
          }
        } catch (e) {
          throw e;
        } finally {
          FS.closeStream(stream.fd);
        }
        stream.fd = null;
      },
      isClosed: function(stream) {
        return stream.fd === null;
      },
      llseek: function(stream, offset, whence) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (!stream.seekable || !stream.stream_ops.llseek) {
          throw new FS.ErrnoError(70);
        }
        if (whence != 0 && whence != 1 && whence != 2) {
          throw new FS.ErrnoError(28);
        }
        stream.position = stream.stream_ops.llseek(stream, offset, whence);
        stream.ungotten = [];
        return stream.position;
      },
      read: function(stream, buffer2, offset, length, position) {
        if (length < 0 || position < 0) {
          throw new FS.ErrnoError(28);
        }
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if ((stream.flags & 2097155) === 1) {
          throw new FS.ErrnoError(8);
        }
        if (FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!stream.stream_ops.read) {
          throw new FS.ErrnoError(28);
        }
        var seeking = typeof position !== "undefined";
        if (!seeking) {
          position = stream.position;
        } else if (!stream.seekable) {
          throw new FS.ErrnoError(70);
        }
        var bytesRead = stream.stream_ops.read(
          stream,
          buffer2,
          offset,
          length,
          position
        );
        if (!seeking)
          stream.position += bytesRead;
        return bytesRead;
      },
      write: function(stream, buffer2, offset, length, position, canOwn) {
        if (length < 0 || position < 0) {
          throw new FS.ErrnoError(28);
        }
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(8);
        }
        if (FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(31);
        }
        if (!stream.stream_ops.write) {
          throw new FS.ErrnoError(28);
        }
        if (stream.seekable && stream.flags & 1024) {
          FS.llseek(stream, 0, 2);
        }
        var seeking = typeof position !== "undefined";
        if (!seeking) {
          position = stream.position;
        } else if (!stream.seekable) {
          throw new FS.ErrnoError(70);
        }
        var bytesWritten = stream.stream_ops.write(
          stream,
          buffer2,
          offset,
          length,
          position,
          canOwn
        );
        if (!seeking)
          stream.position += bytesWritten;
        try {
          if (stream.path && FS.trackingDelegate["onWriteToFile"])
            FS.trackingDelegate["onWriteToFile"](stream.path);
        } catch (e) {
          err(
            "FS.trackingDelegate['onWriteToFile']('" + stream.path + "') threw an exception: " + e.message
          );
        }
        return bytesWritten;
      },
      allocate: function(stream, offset, length) {
        if (FS.isClosed(stream)) {
          throw new FS.ErrnoError(8);
        }
        if (offset < 0 || length <= 0) {
          throw new FS.ErrnoError(28);
        }
        if ((stream.flags & 2097155) === 0) {
          throw new FS.ErrnoError(8);
        }
        if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
          throw new FS.ErrnoError(43);
        }
        if (!stream.stream_ops.allocate) {
          throw new FS.ErrnoError(138);
        }
        stream.stream_ops.allocate(stream, offset, length);
      },
      mmap: function(stream, address, length, position, prot, flags) {
        if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
          throw new FS.ErrnoError(2);
        }
        if ((stream.flags & 2097155) === 1) {
          throw new FS.ErrnoError(2);
        }
        if (!stream.stream_ops.mmap) {
          throw new FS.ErrnoError(43);
        }
        return stream.stream_ops.mmap(
          stream,
          address,
          length,
          position,
          prot,
          flags
        );
      },
      msync: function(stream, buffer2, offset, length, mmapFlags) {
        if (!stream || !stream.stream_ops.msync) {
          return 0;
        }
        return stream.stream_ops.msync(
          stream,
          buffer2,
          offset,
          length,
          mmapFlags
        );
      },
      munmap: function(stream) {
        return 0;
      },
      ioctl: function(stream, cmd, arg) {
        if (!stream.stream_ops.ioctl) {
          throw new FS.ErrnoError(59);
        }
        return stream.stream_ops.ioctl(stream, cmd, arg);
      },
      readFile: function(path, opts) {
        opts = opts || {};
        opts.flags = opts.flags || 0;
        opts.encoding = opts.encoding || "binary";
        if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
          throw new Error('Invalid encoding type "' + opts.encoding + '"');
        }
        var ret;
        var stream = FS.open(path, opts.flags);
        var stat = FS.stat(path);
        var length = stat.size;
        var buf = new Uint8Array(length);
        FS.read(stream, buf, 0, length, 0);
        if (opts.encoding === "utf8") {
          ret = UTF8ArrayToString(buf, 0);
        } else if (opts.encoding === "binary") {
          ret = buf;
        }
        FS.close(stream);
        return ret;
      },
      writeFile: function(path, data, opts) {
        opts = opts || {};
        opts.flags = opts.flags || 577;
        var stream = FS.open(path, opts.flags, opts.mode);
        if (typeof data === "string") {
          var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
          var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
          FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);
        } else if (ArrayBuffer.isView(data)) {
          FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);
        } else {
          throw new Error("Unsupported data type");
        }
        FS.close(stream);
      },
      cwd: function() {
        return FS.currentPath;
      },
      chdir: function(path) {
        var lookup = FS.lookupPath(path, { follow: true });
        if (lookup.node === null) {
          throw new FS.ErrnoError(44);
        }
        if (!FS.isDir(lookup.node.mode)) {
          throw new FS.ErrnoError(54);
        }
        var errCode = FS.nodePermissions(lookup.node, "x");
        if (errCode) {
          throw new FS.ErrnoError(errCode);
        }
        FS.currentPath = lookup.path;
      },
      createDefaultDirectories: function() {
        FS.mkdir("/tmp");
        FS.mkdir("/home");
        FS.mkdir("/home/web_user");
      },
      createDefaultDevices: function() {
        FS.mkdir("/dev");
        FS.registerDevice(FS.makedev(1, 3), {
          read: function() {
            return 0;
          },
          write: function(stream, buffer2, offset, length, pos) {
            return length;
          }
        });
        FS.mkdev("/dev/null", FS.makedev(1, 3));
        TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
        TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
        FS.mkdev("/dev/tty", FS.makedev(5, 0));
        FS.mkdev("/dev/tty1", FS.makedev(6, 0));
        var random_device = getRandomDevice();
        FS.createDevice("/dev", "random", random_device);
        FS.createDevice("/dev", "urandom", random_device);
        FS.mkdir("/dev/shm");
        FS.mkdir("/dev/shm/tmp");
      },
      createSpecialDirectories: function() {
        FS.mkdir("/proc");
        var proc_self = FS.mkdir("/proc/self");
        FS.mkdir("/proc/self/fd");
        FS.mount(
          {
            mount: function() {
              var node = FS.createNode(proc_self, "fd", 16384 | 511, 73);
              node.node_ops = {
                lookup: function(parent, name) {
                  var fd = +name;
                  var stream = FS.getStream(fd);
                  if (!stream)
                    throw new FS.ErrnoError(8);
                  var ret = {
                    parent: null,
                    mount: { mountpoint: "fake" },
                    node_ops: {
                      readlink: function() {
                        return stream.path;
                      }
                    }
                  };
                  ret.parent = ret;
                  return ret;
                }
              };
              return node;
            }
          },
          {},
          "/proc/self/fd"
        );
      },
      createStandardStreams: function() {
        if (Module["stdin"]) {
          FS.createDevice("/dev", "stdin", Module["stdin"]);
        } else {
          FS.symlink("/dev/tty", "/dev/stdin");
        }
        if (Module["stdout"]) {
          FS.createDevice("/dev", "stdout", null, Module["stdout"]);
        } else {
          FS.symlink("/dev/tty", "/dev/stdout");
        }
        if (Module["stderr"]) {
          FS.createDevice("/dev", "stderr", null, Module["stderr"]);
        } else {
          FS.symlink("/dev/tty1", "/dev/stderr");
        }
        var stdin = FS.open("/dev/stdin", 0);
        var stdout = FS.open("/dev/stdout", 1);
        var stderr = FS.open("/dev/stderr", 1);
      },
      ensureErrnoError: function() {
        if (FS.ErrnoError)
          return;
        FS.ErrnoError = function ErrnoError(errno, node) {
          this.node = node;
          this.setErrno = function(errno2) {
            this.errno = errno2;
          };
          this.setErrno(errno);
          this.message = "FS error";
        };
        FS.ErrnoError.prototype = new Error();
        FS.ErrnoError.prototype.constructor = FS.ErrnoError;
        [44].forEach(function(code) {
          FS.genericErrors[code] = new FS.ErrnoError(code);
          FS.genericErrors[code].stack = "<generic error, no stack>";
        });
      },
      staticInit: function() {
        FS.ensureErrnoError();
        FS.nameTable = new Array(4096);
        FS.mount(MEMFS, {}, "/");
        FS.createDefaultDirectories();
        FS.createDefaultDevices();
        FS.createSpecialDirectories();
        FS.filesystems = { MEMFS, NODEFS };
      },
      init: function(input, output, error) {
        FS.init.initialized = true;
        FS.ensureErrnoError();
        Module["stdin"] = input || Module["stdin"];
        Module["stdout"] = output || Module["stdout"];
        Module["stderr"] = error || Module["stderr"];
        FS.createStandardStreams();
      },
      quit: function() {
        FS.init.initialized = false;
        var fflush = Module["_fflush"];
        if (fflush)
          fflush(0);
        for (var i = 0; i < FS.streams.length; i++) {
          var stream = FS.streams[i];
          if (!stream) {
            continue;
          }
          FS.close(stream);
        }
      },
      getMode: function(canRead, canWrite) {
        var mode = 0;
        if (canRead)
          mode |= 292 | 73;
        if (canWrite)
          mode |= 146;
        return mode;
      },
      findObject: function(path, dontResolveLastLink) {
        var ret = FS.analyzePath(path, dontResolveLastLink);
        if (ret.exists) {
          return ret.object;
        } else {
          return null;
        }
      },
      analyzePath: function(path, dontResolveLastLink) {
        try {
          var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
          path = lookup.path;
        } catch (e) {
        }
        var ret = {
          isRoot: false,
          exists: false,
          error: 0,
          name: null,
          path: null,
          object: null,
          parentExists: false,
          parentPath: null,
          parentObject: null
        };
        try {
          var lookup = FS.lookupPath(path, { parent: true });
          ret.parentExists = true;
          ret.parentPath = lookup.path;
          ret.parentObject = lookup.node;
          ret.name = PATH.basename(path);
          lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
          ret.exists = true;
          ret.path = lookup.path;
          ret.object = lookup.node;
          ret.name = lookup.node.name;
          ret.isRoot = lookup.path === "/";
        } catch (e) {
          ret.error = e.errno;
        }
        return ret;
      },
      createPath: function(parent, path, canRead, canWrite) {
        parent = typeof parent === "string" ? parent : FS.getPath(parent);
        var parts = path.split("/").reverse();
        while (parts.length) {
          var part = parts.pop();
          if (!part)
            continue;
          var current = PATH.join2(parent, part);
          try {
            FS.mkdir(current);
          } catch (e) {
          }
          parent = current;
        }
        return current;
      },
      createFile: function(parent, name, properties, canRead, canWrite) {
        var path = PATH.join2(
          typeof parent === "string" ? parent : FS.getPath(parent),
          name
        );
        var mode = FS.getMode(canRead, canWrite);
        return FS.create(path, mode);
      },
      createDataFile: function(parent, name, data, canRead, canWrite, canOwn) {
        var path = name ? PATH.join2(
          typeof parent === "string" ? parent : FS.getPath(parent),
          name
        ) : parent;
        var mode = FS.getMode(canRead, canWrite);
        var node = FS.create(path, mode);
        if (data) {
          if (typeof data === "string") {
            var arr = new Array(data.length);
            for (var i = 0, len = data.length; i < len; ++i)
              arr[i] = data.charCodeAt(i);
            data = arr;
          }
          FS.chmod(node, mode | 146);
          var stream = FS.open(node, 577);
          FS.write(stream, data, 0, data.length, 0, canOwn);
          FS.close(stream);
          FS.chmod(node, mode);
        }
        return node;
      },
      createDevice: function(parent, name, input, output) {
        var path = PATH.join2(
          typeof parent === "string" ? parent : FS.getPath(parent),
          name
        );
        var mode = FS.getMode(!!input, !!output);
        if (!FS.createDevice.major)
          FS.createDevice.major = 64;
        var dev = FS.makedev(FS.createDevice.major++, 0);
        FS.registerDevice(dev, {
          open: function(stream) {
            stream.seekable = false;
          },
          close: function(stream) {
            if (output && output.buffer && output.buffer.length) {
              output(10);
            }
          },
          read: function(stream, buffer2, offset, length, pos) {
            var bytesRead = 0;
            for (var i = 0; i < length; i++) {
              var result;
              try {
                result = input();
              } catch (e) {
                throw new FS.ErrnoError(29);
              }
              if (result === void 0 && bytesRead === 0) {
                throw new FS.ErrnoError(6);
              }
              if (result === null || result === void 0)
                break;
              bytesRead++;
              buffer2[offset + i] = result;
            }
            if (bytesRead) {
              stream.node.timestamp = Date.now();
            }
            return bytesRead;
          },
          write: function(stream, buffer2, offset, length, pos) {
            for (var i = 0; i < length; i++) {
              try {
                output(buffer2[offset + i]);
              } catch (e) {
                throw new FS.ErrnoError(29);
              }
            }
            if (length) {
              stream.node.timestamp = Date.now();
            }
            return i;
          }
        });
        return FS.mkdev(path, mode, dev);
      },
      forceLoadFile: function(obj) {
        if (obj.isDevice || obj.isFolder || obj.link || obj.contents)
          return true;
        if (typeof XMLHttpRequest !== "undefined") {
          throw new Error(
            "Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."
          );
        } else if (read_) {
          try {
            obj.contents = intArrayFromString(read_(obj.url), true);
            obj.usedBytes = obj.contents.length;
          } catch (e) {
            throw new FS.ErrnoError(29);
          }
        } else {
          throw new Error("Cannot load without read() or XMLHttpRequest.");
        }
      },
      createLazyFile: function(parent, name, url, canRead, canWrite) {
        function LazyUint8Array() {
          this.lengthKnown = false;
          this.chunks = [];
        }
        LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) {
          if (idx > this.length - 1 || idx < 0) {
            return void 0;
          }
          var chunkOffset = idx % this.chunkSize;
          var chunkNum = idx / this.chunkSize | 0;
          return this.getter(chunkNum)[chunkOffset];
        };
        LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
          this.getter = getter;
        };
        LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
          var xhr = new XMLHttpRequest();
          xhr.open("HEAD", url, false);
          xhr.send(null);
          if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))
            throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
          var datalength = Number(xhr.getResponseHeader("Content-length"));
          var header;
          var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
          var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
          var chunkSize = 1024 * 1024;
          if (!hasByteServing)
            chunkSize = datalength;
          var doXHR = function(from, to) {
            if (from > to)
              throw new Error(
                "invalid range (" + from + ", " + to + ") or no bytes requested!"
              );
            if (to > datalength - 1)
              throw new Error(
                "only " + datalength + " bytes available! programmer error!"
              );
            var xhr2 = new XMLHttpRequest();
            xhr2.open("GET", url, false);
            if (datalength !== chunkSize)
              xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);
            if (typeof Uint8Array != "undefined")
              xhr2.responseType = "arraybuffer";
            if (xhr2.overrideMimeType) {
              xhr2.overrideMimeType("text/plain; charset=x-user-defined");
            }
            xhr2.send(null);
            if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))
              throw new Error(
                "Couldn't load " + url + ". Status: " + xhr2.status
              );
            if (xhr2.response !== void 0) {
              return new Uint8Array(xhr2.response || []);
            } else {
              return intArrayFromString(xhr2.responseText || "", true);
            }
          };
          var lazyArray2 = this;
          lazyArray2.setDataGetter(function(chunkNum) {
            var start = chunkNum * chunkSize;
            var end = (chunkNum + 1) * chunkSize - 1;
            end = Math.min(end, datalength - 1);
            if (typeof lazyArray2.chunks[chunkNum] === "undefined") {
              lazyArray2.chunks[chunkNum] = doXHR(start, end);
            }
            if (typeof lazyArray2.chunks[chunkNum] === "undefined")
              throw new Error("doXHR failed!");
            return lazyArray2.chunks[chunkNum];
          });
          if (usesGzip || !datalength) {
            chunkSize = datalength = 1;
            datalength = this.getter(0).length;
            chunkSize = datalength;
            out(
              "LazyFiles on gzip forces download of the whole file when length is accessed"
            );
          }
          this._length = datalength;
          this._chunkSize = chunkSize;
          this.lengthKnown = true;
        };
        if (typeof XMLHttpRequest !== "undefined") {
          if (!ENVIRONMENT_IS_WORKER)
            throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
          var lazyArray = new LazyUint8Array();
          Object.defineProperties(lazyArray, {
            length: {
              get: function() {
                if (!this.lengthKnown) {
                  this.cacheLength();
                }
                return this._length;
              }
            },
            chunkSize: {
              get: function() {
                if (!this.lengthKnown) {
                  this.cacheLength();
                }
                return this._chunkSize;
              }
            }
          });
          var properties = { isDevice: false, contents: lazyArray };
        } else {
          var properties = { isDevice: false, url };
        }
        var node = FS.createFile(parent, name, properties, canRead, canWrite);
        if (properties.contents) {
          node.contents = properties.contents;
        } else if (properties.url) {
          node.contents = null;
          node.url = properties.url;
        }
        Object.defineProperties(node, {
          usedBytes: {
            get: function() {
              return this.contents.length;
            }
          }
        });
        var stream_ops = {};
        var keys = Object.keys(node.stream_ops);
        keys.forEach(function(key2) {
          var fn = node.stream_ops[key2];
          stream_ops[key2] = function forceLoadLazyFile() {
            FS.forceLoadFile(node);
            return fn.apply(null, arguments);
          };
        });
        stream_ops.read = function stream_ops_read(stream, buffer2, offset, length, position) {
          FS.forceLoadFile(node);
          var contents = stream.node.contents;
          if (position >= contents.length)
            return 0;
          var size = Math.min(contents.length - position, length);
          if (contents.slice) {
            for (var i = 0; i < size; i++) {
              buffer2[offset + i] = contents[position + i];
            }
          } else {
            for (var i = 0; i < size; i++) {
              buffer2[offset + i] = contents.get(position + i);
            }
          }
          return size;
        };
        node.stream_ops = stream_ops;
        return node;
      },
      createPreloadedFile: function(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
        Browser.init();
        var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
        var dep = getUniqueRunDependency("cp " + fullname);
        function processData(byteArray) {
          function finish(byteArray2) {
            if (preFinish)
              preFinish();
            if (!dontCreateFile) {
              FS.createDataFile(
                parent,
                name,
                byteArray2,
                canRead,
                canWrite,
                canOwn
              );
            }
            if (onload)
              onload();
            removeRunDependency(dep);
          }
          var handled = false;
          Module["preloadPlugins"].forEach(function(plugin) {
            if (handled)
              return;
            if (plugin["canHandle"](fullname)) {
              plugin["handle"](byteArray, fullname, finish, function() {
                if (onerror)
                  onerror();
                removeRunDependency(dep);
              });
              handled = true;
            }
          });
          if (!handled)
            finish(byteArray);
        }
        addRunDependency(dep);
        if (typeof url == "string") {
          Browser.asyncLoad(
            url,
            function(byteArray) {
              processData(byteArray);
            },
            onerror
          );
        } else {
          processData(url);
        }
      },
      indexedDB: function() {
        return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
      },
      DB_NAME: function() {
        return "EM_FS_" + window.location.pathname;
      },
      DB_VERSION: 20,
      DB_STORE_NAME: "FILE_DATA",
      saveFilesToDB: function(paths, onload, onerror) {
        onload = onload || function() {
        };
        onerror = onerror || function() {
        };
        var indexedDB = FS.indexedDB();
        try {
          var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
        } catch (e) {
          return onerror(e);
        }
        openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
          out("creating db");
          var db = openRequest.result;
          db.createObjectStore(FS.DB_STORE_NAME);
        };
        openRequest.onsuccess = function openRequest_onsuccess() {
          var db = openRequest.result;
          var transaction = db.transaction([FS.DB_STORE_NAME], "readwrite");
          var files = transaction.objectStore(FS.DB_STORE_NAME);
          var ok = 0, fail = 0, total = paths.length;
          function finish() {
            if (fail == 0)
              onload();
            else
              onerror();
          }
          paths.forEach(function(path) {
            var putRequest = files.put(
              FS.analyzePath(path).object.contents,
              path
            );
            putRequest.onsuccess = function putRequest_onsuccess() {
              ok++;
              if (ok + fail == total)
                finish();
            };
            putRequest.onerror = function putRequest_onerror() {
              fail++;
              if (ok + fail == total)
                finish();
            };
          });
          transaction.onerror = onerror;
        };
        openRequest.onerror = onerror;
      },
      loadFilesFromDB: function(paths, onload, onerror) {
        onload = onload || function() {
        };
        onerror = onerror || function() {
        };
        var indexedDB = FS.indexedDB();
        try {
          var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
        } catch (e) {
          return onerror(e);
        }
        openRequest.onupgradeneeded = onerror;
        openRequest.onsuccess = function openRequest_onsuccess() {
          var db = openRequest.result;
          try {
            var transaction = db.transaction([FS.DB_STORE_NAME], "readonly");
          } catch (e) {
            onerror(e);
            return;
          }
          var files = transaction.objectStore(FS.DB_STORE_NAME);
          var ok = 0, fail = 0, total = paths.length;
          function finish() {
            if (fail == 0)
              onload();
            else
              onerror();
          }
          paths.forEach(function(path) {
            var getRequest = files.get(path);
            getRequest.onsuccess = function getRequest_onsuccess() {
              if (FS.analyzePath(path).exists) {
                FS.unlink(path);
              }
              FS.createDataFile(
                PATH.dirname(path),
                PATH.basename(path),
                getRequest.result,
                true,
                true,
                true
              );
              ok++;
              if (ok + fail == total)
                finish();
            };
            getRequest.onerror = function getRequest_onerror() {
              fail++;
              if (ok + fail == total)
                finish();
            };
          });
          transaction.onerror = onerror;
        };
        openRequest.onerror = onerror;
      }
    };
    var SYSCALLS = {
      mappings: {},
      DEFAULT_POLLMASK: 5,
      umask: 511,
      calculateAt: function(dirfd, path, allowEmpty) {
        if (path[0] === "/") {
          return path;
        }
        var dir;
        if (dirfd === -100) {
          dir = FS.cwd();
        } else {
          var dirstream = FS.getStream(dirfd);
          if (!dirstream)
            throw new FS.ErrnoError(8);
          dir = dirstream.path;
        }
        if (path.length == 0) {
          if (!allowEmpty) {
            throw new FS.ErrnoError(44);
          }
          return dir;
        }
        return PATH.join2(dir, path);
      },
      doStat: function(func, path, buf) {
        try {
          var stat = func(path);
        } catch (e) {
          if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
            return -54;
          }
          throw e;
        }
        HEAP32[buf >> 2] = stat.dev;
        HEAP32[buf + 4 >> 2] = 0;
        HEAP32[buf + 8 >> 2] = stat.ino;
        HEAP32[buf + 12 >> 2] = stat.mode;
        HEAP32[buf + 16 >> 2] = stat.nlink;
        HEAP32[buf + 20 >> 2] = stat.uid;
        HEAP32[buf + 24 >> 2] = stat.gid;
        HEAP32[buf + 28 >> 2] = stat.rdev;
        HEAP32[buf + 32 >> 2] = 0;
        tempI64 = [
          stat.size >>> 0,
          (tempDouble = stat.size, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil(
            (tempDouble - +(~~tempDouble >>> 0)) / 4294967296
          ) >>> 0 : 0)
        ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
        HEAP32[buf + 48 >> 2] = 4096;
        HEAP32[buf + 52 >> 2] = stat.blocks;
        HEAP32[buf + 56 >> 2] = stat.atime.getTime() / 1e3 | 0;
        HEAP32[buf + 60 >> 2] = 0;
        HEAP32[buf + 64 >> 2] = stat.mtime.getTime() / 1e3 | 0;
        HEAP32[buf + 68 >> 2] = 0;
        HEAP32[buf + 72 >> 2] = stat.ctime.getTime() / 1e3 | 0;
        HEAP32[buf + 76 >> 2] = 0;
        tempI64 = [
          stat.ino >>> 0,
          (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil(
            (tempDouble - +(~~tempDouble >>> 0)) / 4294967296
          ) >>> 0 : 0)
        ], HEAP32[buf + 80 >> 2] = tempI64[0], HEAP32[buf + 84 >> 2] = tempI64[1];
        return 0;
      },
      doMsync: function(addr, stream, len, flags, offset) {
        var buffer2 = HEAPU8.slice(addr, addr + len);
        FS.msync(stream, buffer2, offset, len, flags);
      },
      doMkdir: function(path, mode) {
        path = PATH.normalize(path);
        if (path[path.length - 1] === "/")
          path = path.substr(0, path.length - 1);
        FS.mkdir(path, mode, 0);
        return 0;
      },
      doMknod: function(path, mode, dev) {
        switch (mode & 61440) {
          case 32768:
          case 8192:
          case 24576:
          case 4096:
          case 49152:
            break;
          default:
            return -28;
        }
        FS.mknod(path, mode, dev);
        return 0;
      },
      doReadlink: function(path, buf, bufsize) {
        if (bufsize <= 0)
          return -28;
        var ret = FS.readlink(path);
        var len = Math.min(bufsize, lengthBytesUTF8(ret));
        var endChar = HEAP8[buf + len];
        stringToUTF8(ret, buf, bufsize + 1);
        HEAP8[buf + len] = endChar;
        return len;
      },
      doAccess: function(path, amode) {
        if (amode & ~7) {
          return -28;
        }
        var node;
        var lookup = FS.lookupPath(path, { follow: true });
        node = lookup.node;
        if (!node) {
          return -44;
        }
        var perms = "";
        if (amode & 4)
          perms += "r";
        if (amode & 2)
          perms += "w";
        if (amode & 1)
          perms += "x";
        if (perms && FS.nodePermissions(node, perms)) {
          return -2;
        }
        return 0;
      },
      doDup: function(path, flags, suggestFD) {
        var suggest = FS.getStream(suggestFD);
        if (suggest)
          FS.close(suggest);
        return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
      },
      doReadv: function(stream, iov, iovcnt, offset) {
        var ret = 0;
        for (var i = 0; i < iovcnt; i++) {
          var ptr = HEAP32[iov + i * 8 >> 2];
          var len = HEAP32[iov + (i * 8 + 4) >> 2];
          var curr = FS.read(stream, HEAP8, ptr, len, offset);
          if (curr < 0)
            return -1;
          ret += curr;
          if (curr < len)
            break;
        }
        return ret;
      },
      doWritev: function(stream, iov, iovcnt, offset) {
        var ret = 0;
        for (var i = 0; i < iovcnt; i++) {
          var ptr = HEAP32[iov + i * 8 >> 2];
          var len = HEAP32[iov + (i * 8 + 4) >> 2];
          var curr = FS.write(stream, HEAP8, ptr, len, offset);
          if (curr < 0)
            return -1;
          ret += curr;
        }
        return ret;
      },
      varargs: void 0,
      get: function() {
        SYSCALLS.varargs += 4;
        var ret = HEAP32[SYSCALLS.varargs - 4 >> 2];
        return ret;
      },
      getStr: function(ptr) {
        var ret = UTF8ToString(ptr);
        return ret;
      },
      getStreamFromFD: function(fd) {
        var stream = FS.getStream(fd);
        if (!stream)
          throw new FS.ErrnoError(8);
        return stream;
      },
      get64: function(low, high) {
        return low;
      }
    };
    function ___sys_chmod(path, mode) {
      try {
        path = SYSCALLS.getStr(path);
        FS.chmod(path, mode);
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function setErrNo(value) {
      HEAP32[___errno_location() >> 2] = value;
      return value;
    }
    function ___sys_fcntl64(fd, cmd, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        switch (cmd) {
          case 0: {
            var arg = SYSCALLS.get();
            if (arg < 0) {
              return -28;
            }
            var newStream;
            newStream = FS.open(stream.path, stream.flags, 0, arg);
            return newStream.fd;
          }
          case 1:
          case 2:
            return 0;
          case 3:
            return stream.flags;
          case 4: {
            var arg = SYSCALLS.get();
            stream.flags |= arg;
            return 0;
          }
          case 12: {
            var arg = SYSCALLS.get();
            var offset = 0;
            HEAP16[arg + offset >> 1] = 2;
            return 0;
          }
          case 13:
          case 14:
            return 0;
          case 16:
          case 8:
            return -28;
          case 9:
            setErrNo(28);
            return -1;
          default: {
            return -28;
          }
        }
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_fstat64(fd, buf) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        return SYSCALLS.doStat(FS.stat, stream.path, buf);
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_ioctl(fd, op, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        switch (op) {
          case 21509:
          case 21505: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21510:
          case 21511:
          case 21512:
          case 21506:
          case 21507:
          case 21508: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21519: {
            if (!stream.tty)
              return -59;
            var argp = SYSCALLS.get();
            HEAP32[argp >> 2] = 0;
            return 0;
          }
          case 21520: {
            if (!stream.tty)
              return -59;
            return -28;
          }
          case 21531: {
            var argp = SYSCALLS.get();
            return FS.ioctl(stream, op, argp);
          }
          case 21523: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          case 21524: {
            if (!stream.tty)
              return -59;
            return 0;
          }
          default:
            abort("bad ioctl syscall " + op);
        }
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_open(path, flags, varargs) {
      SYSCALLS.varargs = varargs;
      try {
        var pathname = SYSCALLS.getStr(path);
        var mode = varargs ? SYSCALLS.get() : 0;
        var stream = FS.open(pathname, flags, mode);
        return stream.fd;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_rename(old_path, new_path) {
      try {
        old_path = SYSCALLS.getStr(old_path);
        new_path = SYSCALLS.getStr(new_path);
        FS.rename(old_path, new_path);
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_rmdir(path) {
      try {
        path = SYSCALLS.getStr(path);
        FS.rmdir(path);
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_stat64(path, buf) {
      try {
        path = SYSCALLS.getStr(path);
        return SYSCALLS.doStat(FS.stat, path, buf);
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function ___sys_unlink(path) {
      try {
        path = SYSCALLS.getStr(path);
        FS.unlink(path);
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return -e.errno;
      }
    }
    function _emscripten_memcpy_big(dest, src, num) {
      HEAPU8.copyWithin(dest, src, src + num);
    }
    function emscripten_realloc_buffer(size) {
      try {
        wasmMemory.grow(size - buffer.byteLength + 65535 >>> 16);
        updateGlobalBufferAndViews(wasmMemory.buffer);
        return 1;
      } catch (e) {
      }
    }
    function _emscripten_resize_heap(requestedSize) {
      var oldSize = HEAPU8.length;
      requestedSize = requestedSize >>> 0;
      var maxHeapSize = 2147483648;
      if (requestedSize > maxHeapSize) {
        return false;
      }
      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
        overGrownHeapSize = Math.min(
          overGrownHeapSize,
          requestedSize + 100663296
        );
        var newSize = Math.min(
          maxHeapSize,
          alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
        );
        var replacement = emscripten_realloc_buffer(newSize);
        if (replacement) {
          return true;
        }
      }
      return false;
    }
    function _fd_close(fd) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        FS.close(stream);
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return e.errno;
      }
    }
    function _fd_fdstat_get(fd, pbuf) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var type = stream.tty ? 2 : FS.isDir(stream.mode) ? 3 : FS.isLink(stream.mode) ? 7 : 4;
        HEAP8[pbuf >> 0] = type;
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return e.errno;
      }
    }
    function _fd_read(fd, iov, iovcnt, pnum) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var num = SYSCALLS.doReadv(stream, iov, iovcnt);
        HEAP32[pnum >> 2] = num;
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return e.errno;
      }
    }
    function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var HIGH_OFFSET = 4294967296;
        var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0);
        var DOUBLE_LIMIT = 9007199254740992;
        if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) {
          return -61;
        }
        FS.llseek(stream, offset, whence);
        tempI64 = [
          stream.position >>> 0,
          (tempDouble = stream.position, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil(
            (tempDouble - +(~~tempDouble >>> 0)) / 4294967296
          ) >>> 0 : 0)
        ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
        if (stream.getdents && offset === 0 && whence === 0)
          stream.getdents = null;
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return e.errno;
      }
    }
    function _fd_write(fd, iov, iovcnt, pnum) {
      try {
        var stream = SYSCALLS.getStreamFromFD(fd);
        var num = SYSCALLS.doWritev(stream, iov, iovcnt);
        HEAP32[pnum >> 2] = num;
        return 0;
      } catch (e) {
        if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
          abort(e);
        return e.errno;
      }
    }
    function _setTempRet0(val) {
      setTempRet0(val);
    }
    function _time(ptr) {
      var ret = Date.now() / 1e3 | 0;
      if (ptr) {
        HEAP32[ptr >> 2] = ret;
      }
      return ret;
    }
    function _tzset() {
      if (_tzset.called)
        return;
      _tzset.called = true;
      var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
      var winter = new Date(currentYear, 0, 1);
      var summer = new Date(currentYear, 6, 1);
      var winterOffset = winter.getTimezoneOffset();
      var summerOffset = summer.getTimezoneOffset();
      var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
      HEAP32[__get_timezone() >> 2] = stdTimezoneOffset * 60;
      HEAP32[__get_daylight() >> 2] = Number(winterOffset != summerOffset);
      function extractZone(date) {
        var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
        return match ? match[1] : "GMT";
      }
      var winterName = extractZone(winter);
      var summerName = extractZone(summer);
      var winterNamePtr = allocateUTF8(winterName);
      var summerNamePtr = allocateUTF8(summerName);
      if (summerOffset < winterOffset) {
        HEAP32[__get_tzname() >> 2] = winterNamePtr;
        HEAP32[__get_tzname() + 4 >> 2] = summerNamePtr;
      } else {
        HEAP32[__get_tzname() >> 2] = summerNamePtr;
        HEAP32[__get_tzname() + 4 >> 2] = winterNamePtr;
      }
    }
    function _timegm(tmPtr) {
      _tzset();
      var time = Date.UTC(
        HEAP32[tmPtr + 20 >> 2] + 1900,
        HEAP32[tmPtr + 16 >> 2],
        HEAP32[tmPtr + 12 >> 2],
        HEAP32[tmPtr + 8 >> 2],
        HEAP32[tmPtr + 4 >> 2],
        HEAP32[tmPtr >> 2],
        0
      );
      var date = new Date(time);
      HEAP32[tmPtr + 24 >> 2] = date.getUTCDay();
      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
      var yday = (date.getTime() - start) / (1e3 * 60 * 60 * 24) | 0;
      HEAP32[tmPtr + 28 >> 2] = yday;
      return date.getTime() / 1e3 | 0;
    }
    var FSNode = function(parent, name, mode, rdev) {
      if (!parent) {
        parent = this;
      }
      this.parent = parent;
      this.mount = parent.mount;
      this.mounted = null;
      this.id = FS.nextInode++;
      this.name = name;
      this.mode = mode;
      this.node_ops = {};
      this.stream_ops = {};
      this.rdev = rdev;
    };
    var readMode = 292 | 73;
    var writeMode = 146;
    Object.defineProperties(FSNode.prototype, {
      read: {
        get: function() {
          return (this.mode & readMode) === readMode;
        },
        set: function(val) {
          val ? this.mode |= readMode : this.mode &= ~readMode;
        }
      },
      write: {
        get: function() {
          return (this.mode & writeMode) === writeMode;
        },
        set: function(val) {
          val ? this.mode |= writeMode : this.mode &= ~writeMode;
        }
      },
      isFolder: {
        get: function() {
          return FS.isDir(this.mode);
        }
      },
      isDevice: {
        get: function() {
          return FS.isChrdev(this.mode);
        }
      }
    });
    FS.FSNode = FSNode;
    FS.staticInit();
    if (ENVIRONMENT_IS_NODE) {
      var fs = frozenFs;
      var NODEJS_PATH = __webpack_require__(/*! path */ "path");
      NODEFS.staticInit();
    }
    if (ENVIRONMENT_IS_NODE) {
      var _wrapNodeError = function(func) {
        return function() {
          try {
            return func.apply(this, arguments);
          } catch (e) {
            if (!e.code)
              throw e;
            throw new FS.ErrnoError(ERRNO_CODES[e.code]);
          }
        };
      };
      var VFS = Object.assign({}, FS);
      for (var _key in NODERAWFS)
        FS[_key] = _wrapNodeError(NODERAWFS[_key]);
    } else {
      throw new Error(
        "NODERAWFS is currently only supported on Node.js environment."
      );
    }
    function intArrayFromString(stringy, dontAddNull, length) {
      var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1;
      var u8array = new Array(len);
      var numBytesWritten = stringToUTF8Array(
        stringy,
        u8array,
        0,
        u8array.length
      );
      if (dontAddNull)
        u8array.length = numBytesWritten;
      return u8array;
    }
    var decodeBase64 = typeof atob === "function" ? atob : function(input) {
      var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      var output = "";
      var chr1, chr2, chr3;
      var enc1, enc2, enc3, enc4;
      var i = 0;
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
      do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));
        chr1 = enc1 << 2 | enc2 >> 4;
        chr2 = (enc2 & 15) << 4 | enc3 >> 2;
        chr3 = (enc3 & 3) << 6 | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 !== 64) {
          output = output + String.fromCharCode(chr2);
        }
        if (enc4 !== 64) {
          output = output + String.fromCharCode(chr3);
        }
      } while (i < input.length);
      return output;
    };
    function intArrayFromBase64(s) {
      if (typeof ENVIRONMENT_IS_NODE === "boolean" && ENVIRONMENT_IS_NODE) {
        var buf;
        try {
          buf = Buffer.from(s, "base64");
        } catch (_) {
          buf = new Buffer(s, "base64");
        }
        return new Uint8Array(
          buf["buffer"],
          buf["byteOffset"],
          buf["byteLength"]
        );
      }
      try {
        var decoded = decodeBase64(s);
        var bytes = new Uint8Array(decoded.length);
        for (var i = 0; i < decoded.length; ++i) {
          bytes[i] = decoded.charCodeAt(i);
        }
        return bytes;
      } catch (_) {
        throw new Error("Converting base64 string to bytes failed.");
      }
    }
    function tryParseAsDataURI(filename) {
      if (!isDataURI(filename)) {
        return;
      }
      return intArrayFromBase64(filename.slice(dataURIPrefix.length));
    }
    var asmLibraryArg = {
      s: ___gmtime_r,
      p: ___sys_chmod,
      e: ___sys_fcntl64,
      k: ___sys_fstat64,
      o: ___sys_ioctl,
      q: ___sys_open,
      i: ___sys_rename,
      r: ___sys_rmdir,
      c: ___sys_stat64,
      h: ___sys_unlink,
      l: _emscripten_memcpy_big,
      m: _emscripten_resize_heap,
      f: _fd_close,
      j: _fd_fdstat_get,
      g: _fd_read,
      n: _fd_seek,
      d: _fd_write,
      a: _setTempRet0,
      b: _time,
      t: _timegm
    };
    var asm = createWasm();
    var ___wasm_call_ctors = Module["___wasm_call_ctors"] = asm["v"];
    var _zip_ext_count_symlinks = Module["_zip_ext_count_symlinks"] = asm["w"];
    var _zip_file_get_external_attributes = Module["_zip_file_get_external_attributes"] = asm["x"];
    var _zipstruct_stat = Module["_zipstruct_stat"] = asm["y"];
    var _zipstruct_statS = Module["_zipstruct_statS"] = asm["z"];
    var _zipstruct_stat_name = Module["_zipstruct_stat_name"] = asm["A"];
    var _zipstruct_stat_index = Module["_zipstruct_stat_index"] = asm["B"];
    var _zipstruct_stat_size = Module["_zipstruct_stat_size"] = asm["C"];
    var _zipstruct_stat_mtime = Module["_zipstruct_stat_mtime"] = asm["D"];
    var _zipstruct_stat_crc = Module["_zipstruct_stat_crc"] = asm["E"];
    var _zipstruct_error = Module["_zipstruct_error"] = asm["F"];
    var _zipstruct_errorS = Module["_zipstruct_errorS"] = asm["G"];
    var _zipstruct_error_code_zip = Module["_zipstruct_error_code_zip"] = asm["H"];
    var _zipstruct_stat_comp_size = Module["_zipstruct_stat_comp_size"] = asm["I"];
    var _zipstruct_stat_comp_method = Module["_zipstruct_stat_comp_method"] = asm["J"];
    var _zip_close = Module["_zip_close"] = asm["K"];
    var _zip_delete = Module["_zip_delete"] = asm["L"];
    var _zip_dir_add = Module["_zip_dir_add"] = asm["M"];
    var _zip_discard = Module["_zip_discard"] = asm["N"];
    var _zip_error_init_with_code = Module["_zip_error_init_with_code"] = asm["O"];
    var _zip_get_error = Module["_zip_get_error"] = asm["P"];
    var _zip_file_get_error = Module["_zip_file_get_error"] = asm["Q"];
    var _zip_error_strerror = Module["_zip_error_strerror"] = asm["R"];
    var _zip_fclose = Module["_zip_fclose"] = asm["S"];
    var _zip_file_add = Module["_zip_file_add"] = asm["T"];
    var _free = Module["_free"] = asm["U"];
    var _malloc = Module["_malloc"] = asm["V"];
    var ___errno_location = Module["___errno_location"] = asm["W"];
    var _zip_source_error = Module["_zip_source_error"] = asm["X"];
    var _zip_source_seek = Module["_zip_source_seek"] = asm["Y"];
    var _zip_file_set_external_attributes = Module["_zip_file_set_external_attributes"] = asm["Z"];
    var _zip_file_set_mtime = Module["_zip_file_set_mtime"] = asm["_"];
    var _zip_fopen = Module["_zip_fopen"] = asm["$"];
    var _zip_fopen_index = Module["_zip_fopen_index"] = asm["aa"];
    var _zip_fread = Module["_zip_fread"] = asm["ba"];
    var _zip_get_name = Module["_zip_get_name"] = asm["ca"];
    var _zip_get_num_entries = Module["_zip_get_num_entries"] = asm["da"];
    var _zip_source_read = Module["_zip_source_read"] = asm["ea"];
    var _zip_name_locate = Module["_zip_name_locate"] = asm["fa"];
    var _zip_open = Module["_zip_open"] = asm["ga"];
    var _zip_open_from_source = Module["_zip_open_from_source"] = asm["ha"];
    var _zip_set_file_compression = Module["_zip_set_file_compression"] = asm["ia"];
    var _zip_source_buffer = Module["_zip_source_buffer"] = asm["ja"];
    var _zip_source_buffer_create = Module["_zip_source_buffer_create"] = asm["ka"];
    var _zip_source_close = Module["_zip_source_close"] = asm["la"];
    var _zip_source_free = Module["_zip_source_free"] = asm["ma"];
    var _zip_source_keep = Module["_zip_source_keep"] = asm["na"];
    var _zip_source_open = Module["_zip_source_open"] = asm["oa"];
    var _zip_source_set_mtime = Module["_zip_source_set_mtime"] = asm["qa"];
    var _zip_source_tell = Module["_zip_source_tell"] = asm["ra"];
    var _zip_stat = Module["_zip_stat"] = asm["sa"];
    var _zip_stat_index = Module["_zip_stat_index"] = asm["ta"];
    var __get_tzname = Module["__get_tzname"] = asm["ua"];
    var __get_daylight = Module["__get_daylight"] = asm["va"];
    var __get_timezone = Module["__get_timezone"] = asm["wa"];
    var stackSave = Module["stackSave"] = asm["xa"];
    var stackRestore = Module["stackRestore"] = asm["ya"];
    var stackAlloc = Module["stackAlloc"] = asm["za"];
    Module["cwrap"] = cwrap;
    Module["getValue"] = getValue;
    var calledRun;
    dependenciesFulfilled = function runCaller() {
      if (!calledRun)
        run();
      if (!calledRun)
        dependenciesFulfilled = runCaller;
    };
    function run(args) {
      args = args || arguments_;
      if (runDependencies > 0) {
        return;
      }
      preRun();
      if (runDependencies > 0) {
        return;
      }
      function doRun() {
        if (calledRun)
          return;
        calledRun = true;
        Module["calledRun"] = true;
        if (ABORT)
          return;
        initRuntime();
        readyPromiseResolve(Module);
        if (Module["onRuntimeInitialized"])
          Module["onRuntimeInitialized"]();
        postRun();
      }
      if (Module["setStatus"]) {
        Module["setStatus"]("Running...");
        setTimeout(function() {
          setTimeout(function() {
            Module["setStatus"]("");
          }, 1);
          doRun();
        }, 1);
      } else {
        doRun();
      }
    }
    Module["run"] = run;
    if (Module["preInit"]) {
      if (typeof Module["preInit"] == "function")
        Module["preInit"] = [Module["preInit"]];
      while (Module["preInit"].length > 0) {
        Module["preInit"].pop()();
      }
    }
    run();
    return createModule2;
  };
}();
if (true)
  module.exports = createModule;
else {}


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/makeInterface.js":
/*!*****************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/libzip/lib/makeInterface.js ***!
  \*****************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.makeInterface = exports.Errors = void 0;
const number64 = [
  `number`,
  `number`
  // high
];
var Errors;
(function(Errors2) {
  Errors2[Errors2["ZIP_ER_OK"] = 0] = "ZIP_ER_OK";
  Errors2[Errors2["ZIP_ER_MULTIDISK"] = 1] = "ZIP_ER_MULTIDISK";
  Errors2[Errors2["ZIP_ER_RENAME"] = 2] = "ZIP_ER_RENAME";
  Errors2[Errors2["ZIP_ER_CLOSE"] = 3] = "ZIP_ER_CLOSE";
  Errors2[Errors2["ZIP_ER_SEEK"] = 4] = "ZIP_ER_SEEK";
  Errors2[Errors2["ZIP_ER_READ"] = 5] = "ZIP_ER_READ";
  Errors2[Errors2["ZIP_ER_WRITE"] = 6] = "ZIP_ER_WRITE";
  Errors2[Errors2["ZIP_ER_CRC"] = 7] = "ZIP_ER_CRC";
  Errors2[Errors2["ZIP_ER_ZIPCLOSED"] = 8] = "ZIP_ER_ZIPCLOSED";
  Errors2[Errors2["ZIP_ER_NOENT"] = 9] = "ZIP_ER_NOENT";
  Errors2[Errors2["ZIP_ER_EXISTS"] = 10] = "ZIP_ER_EXISTS";
  Errors2[Errors2["ZIP_ER_OPEN"] = 11] = "ZIP_ER_OPEN";
  Errors2[Errors2["ZIP_ER_TMPOPEN"] = 12] = "ZIP_ER_TMPOPEN";
  Errors2[Errors2["ZIP_ER_ZLIB"] = 13] = "ZIP_ER_ZLIB";
  Errors2[Errors2["ZIP_ER_MEMORY"] = 14] = "ZIP_ER_MEMORY";
  Errors2[Errors2["ZIP_ER_CHANGED"] = 15] = "ZIP_ER_CHANGED";
  Errors2[Errors2["ZIP_ER_COMPNOTSUPP"] = 16] = "ZIP_ER_COMPNOTSUPP";
  Errors2[Errors2["ZIP_ER_EOF"] = 17] = "ZIP_ER_EOF";
  Errors2[Errors2["ZIP_ER_INVAL"] = 18] = "ZIP_ER_INVAL";
  Errors2[Errors2["ZIP_ER_NOZIP"] = 19] = "ZIP_ER_NOZIP";
  Errors2[Errors2["ZIP_ER_INTERNAL"] = 20] = "ZIP_ER_INTERNAL";
  Errors2[Errors2["ZIP_ER_INCONS"] = 21] = "ZIP_ER_INCONS";
  Errors2[Errors2["ZIP_ER_REMOVE"] = 22] = "ZIP_ER_REMOVE";
  Errors2[Errors2["ZIP_ER_DELETED"] = 23] = "ZIP_ER_DELETED";
  Errors2[Errors2["ZIP_ER_ENCRNOTSUPP"] = 24] = "ZIP_ER_ENCRNOTSUPP";
  Errors2[Errors2["ZIP_ER_RDONLY"] = 25] = "ZIP_ER_RDONLY";
  Errors2[Errors2["ZIP_ER_NOPASSWD"] = 26] = "ZIP_ER_NOPASSWD";
  Errors2[Errors2["ZIP_ER_WRONGPASSWD"] = 27] = "ZIP_ER_WRONGPASSWD";
  Errors2[Errors2["ZIP_ER_OPNOTSUPP"] = 28] = "ZIP_ER_OPNOTSUPP";
  Errors2[Errors2["ZIP_ER_INUSE"] = 29] = "ZIP_ER_INUSE";
  Errors2[Errors2["ZIP_ER_TELL"] = 30] = "ZIP_ER_TELL";
  Errors2[Errors2["ZIP_ER_COMPRESSED_DATA"] = 31] = "ZIP_ER_COMPRESSED_DATA";
})(Errors = exports.Errors || (exports.Errors = {}));
const makeInterface = (libzip) => ({
  // Those are getters because they can change after memory growth
  get HEAP8() {
    return libzip.HEAP8;
  },
  get HEAPU8() {
    return libzip.HEAPU8;
  },
  errors: Errors,
  SEEK_SET: 0,
  SEEK_CUR: 1,
  SEEK_END: 2,
  ZIP_CHECKCONS: 4,
  ZIP_CREATE: 1,
  ZIP_EXCL: 2,
  ZIP_TRUNCATE: 8,
  ZIP_RDONLY: 16,
  ZIP_FL_OVERWRITE: 8192,
  ZIP_FL_COMPRESSED: 4,
  ZIP_OPSYS_DOS: 0,
  ZIP_OPSYS_AMIGA: 1,
  ZIP_OPSYS_OPENVMS: 2,
  ZIP_OPSYS_UNIX: 3,
  ZIP_OPSYS_VM_CMS: 4,
  ZIP_OPSYS_ATARI_ST: 5,
  ZIP_OPSYS_OS_2: 6,
  ZIP_OPSYS_MACINTOSH: 7,
  ZIP_OPSYS_Z_SYSTEM: 8,
  ZIP_OPSYS_CPM: 9,
  ZIP_OPSYS_WINDOWS_NTFS: 10,
  ZIP_OPSYS_MVS: 11,
  ZIP_OPSYS_VSE: 12,
  ZIP_OPSYS_ACORN_RISC: 13,
  ZIP_OPSYS_VFAT: 14,
  ZIP_OPSYS_ALTERNATE_MVS: 15,
  ZIP_OPSYS_BEOS: 16,
  ZIP_OPSYS_TANDEM: 17,
  ZIP_OPSYS_OS_400: 18,
  ZIP_OPSYS_OS_X: 19,
  ZIP_CM_DEFAULT: -1,
  ZIP_CM_STORE: 0,
  ZIP_CM_DEFLATE: 8,
  uint08S: libzip._malloc(1),
  uint16S: libzip._malloc(2),
  uint32S: libzip._malloc(4),
  uint64S: libzip._malloc(8),
  malloc: libzip._malloc,
  free: libzip._free,
  getValue: libzip.getValue,
  open: libzip.cwrap(`zip_open`, `number`, [`string`, `number`, `number`]),
  openFromSource: libzip.cwrap(`zip_open_from_source`, `number`, [`number`, `number`, `number`]),
  close: libzip.cwrap(`zip_close`, `number`, [`number`]),
  discard: libzip.cwrap(`zip_discard`, null, [`number`]),
  getError: libzip.cwrap(`zip_get_error`, `number`, [`number`]),
  getName: libzip.cwrap(`zip_get_name`, `string`, [`number`, `number`, `number`]),
  getNumEntries: libzip.cwrap(`zip_get_num_entries`, `number`, [`number`, `number`]),
  delete: libzip.cwrap(`zip_delete`, `number`, [`number`, `number`]),
  stat: libzip.cwrap(`zip_stat`, `number`, [`number`, `string`, `number`, `number`]),
  statIndex: libzip.cwrap(`zip_stat_index`, `number`, [`number`, ...number64, `number`, `number`]),
  fopen: libzip.cwrap(`zip_fopen`, `number`, [`number`, `string`, `number`]),
  fopenIndex: libzip.cwrap(`zip_fopen_index`, `number`, [`number`, ...number64, `number`]),
  fread: libzip.cwrap(`zip_fread`, `number`, [`number`, `number`, `number`, `number`]),
  fclose: libzip.cwrap(`zip_fclose`, `number`, [`number`]),
  dir: {
    add: libzip.cwrap(`zip_dir_add`, `number`, [`number`, `string`])
  },
  file: {
    add: libzip.cwrap(`zip_file_add`, `number`, [`number`, `string`, `number`, `number`]),
    getError: libzip.cwrap(`zip_file_get_error`, `number`, [`number`]),
    getExternalAttributes: libzip.cwrap(`zip_file_get_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]),
    setExternalAttributes: libzip.cwrap(`zip_file_set_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]),
    setMtime: libzip.cwrap(`zip_file_set_mtime`, `number`, [`number`, ...number64, `number`, `number`]),
    setCompression: libzip.cwrap(`zip_set_file_compression`, `number`, [`number`, ...number64, `number`, `number`])
  },
  ext: {
    countSymlinks: libzip.cwrap(`zip_ext_count_symlinks`, `number`, [`number`])
  },
  error: {
    initWithCode: libzip.cwrap(`zip_error_init_with_code`, null, [`number`, `number`]),
    strerror: libzip.cwrap(`zip_error_strerror`, `string`, [`number`])
  },
  name: {
    locate: libzip.cwrap(`zip_name_locate`, `number`, [`number`, `string`, `number`])
  },
  source: {
    fromUnattachedBuffer: libzip.cwrap(`zip_source_buffer_create`, `number`, [`number`, ...number64, `number`, `number`]),
    fromBuffer: libzip.cwrap(`zip_source_buffer`, `number`, [`number`, `number`, ...number64, `number`]),
    free: libzip.cwrap(`zip_source_free`, null, [`number`]),
    keep: libzip.cwrap(`zip_source_keep`, null, [`number`]),
    open: libzip.cwrap(`zip_source_open`, `number`, [`number`]),
    close: libzip.cwrap(`zip_source_close`, `number`, [`number`]),
    seek: libzip.cwrap(`zip_source_seek`, `number`, [`number`, ...number64, `number`]),
    tell: libzip.cwrap(`zip_source_tell`, `number`, [`number`]),
    read: libzip.cwrap(`zip_source_read`, `number`, [`number`, `number`, `number`]),
    error: libzip.cwrap(`zip_source_error`, `number`, [`number`]),
    setMtime: libzip.cwrap(`zip_source_set_mtime`, `number`, [`number`, `number`])
  },
  struct: {
    stat: libzip.cwrap(`zipstruct_stat`, `number`, []),
    statS: libzip.cwrap(`zipstruct_statS`, `number`, []),
    statName: libzip.cwrap(`zipstruct_stat_name`, `string`, [`number`]),
    statIndex: libzip.cwrap(`zipstruct_stat_index`, `number`, [`number`]),
    statSize: libzip.cwrap(`zipstruct_stat_size`, `number`, [`number`]),
    statCompSize: libzip.cwrap(`zipstruct_stat_comp_size`, `number`, [`number`]),
    statCompMethod: libzip.cwrap(`zipstruct_stat_comp_method`, `number`, [`number`]),
    statMtime: libzip.cwrap(`zipstruct_stat_mtime`, `number`, [`number`]),
    statCrc: libzip.cwrap(`zipstruct_stat_crc`, `number`, [`number`]),
    error: libzip.cwrap(`zipstruct_error`, `number`, []),
    errorS: libzip.cwrap(`zipstruct_errorS`, `number`, []),
    errorCodeZip: libzip.cwrap(`zipstruct_error_code_zip`, `number`, [`number`])
  }
});
exports.makeInterface = makeInterface;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/sync.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/libzip/lib/sync.js ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getLibzipPromise = exports.getLibzipSync = void 0;
const tslib_1 = __webpack_require__(/*! tslib */ "../pyright-internal/node_modules/@yarnpkg/libzip/node_modules/tslib/tslib.es6.js");
const libzipSync_1 = tslib_1.__importDefault(__webpack_require__(/*! ./libzipSync */ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/libzipSync.js"));
const makeInterface_1 = __webpack_require__(/*! ./makeInterface */ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/makeInterface.js");
let mod = null;
function getLibzipSync() {
  if (mod === null)
    mod = (0, makeInterface_1.makeInterface)((0, libzipSync_1.default)());
  return mod;
}
exports.getLibzipSync = getLibzipSync;
async function getLibzipPromise() {
  return getLibzipSync();
}
exports.getLibzipPromise = getLibzipPromise;


/***/ }),

/***/ "../pyright-internal/node_modules/@yarnpkg/libzip/node_modules/tslib/tslib.es6.js":
/*!****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/@yarnpkg/libzip/node_modules/tslib/tslib.es6.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   __assign: () => (/* binding */ __assign),
/* harmony export */   __asyncDelegator: () => (/* binding */ __asyncDelegator),
/* harmony export */   __asyncGenerator: () => (/* binding */ __asyncGenerator),
/* harmony export */   __asyncValues: () => (/* binding */ __asyncValues),
/* harmony export */   __await: () => (/* binding */ __await),
/* harmony export */   __awaiter: () => (/* binding */ __awaiter),
/* harmony export */   __classPrivateFieldGet: () => (/* binding */ __classPrivateFieldGet),
/* harmony export */   __classPrivateFieldSet: () => (/* binding */ __classPrivateFieldSet),
/* harmony export */   __createBinding: () => (/* binding */ __createBinding),
/* harmony export */   __decorate: () => (/* binding */ __decorate),
/* harmony export */   __exportStar: () => (/* binding */ __exportStar),
/* harmony export */   __extends: () => (/* binding */ __extends),
/* harmony export */   __generator: () => (/* binding */ __generator),
/* harmony export */   __importDefault: () => (/* binding */ __importDefault),
/* harmony export */   __importStar: () => (/* binding */ __importStar),
/* harmony export */   __makeTemplateObject: () => (/* binding */ __makeTemplateObject),
/* harmony export */   __metadata: () => (/* binding */ __metadata),
/* harmony export */   __param: () => (/* binding */ __param),
/* harmony export */   __read: () => (/* binding */ __read),
/* harmony export */   __rest: () => (/* binding */ __rest),
/* harmony export */   __spread: () => (/* binding */ __spread),
/* harmony export */   __spreadArrays: () => (/* binding */ __spreadArrays),
/* harmony export */   __values: () => (/* binding */ __values)
/* harmony export */ });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2)
      if (b2.hasOwnProperty(p))
        d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
function __rest(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1)
      throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f)
      throw new TypeError("Generator is already executing.");
    while (_)
      try {
        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
          return t;
        if (y = 0, t)
          op = [op[0] & 2, t.value];
        switch (op[0]) {
          case 0:
          case 1:
            t = op;
            break;
          case 4:
            _.label++;
            return { value: op[1], done: false };
          case 5:
            _.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            if (t[2])
              _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e) {
        op = [6, e];
        y = 0;
      } finally {
        f = t = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __createBinding(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
}
function __exportStar(m, exports) {
  for (var p in m)
    if (p !== "default" && !exports.hasOwnProperty(p))
      exports[p] = m[p];
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m)
    return m.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i >= o.length)
          o = void 0;
        return { value: o && o[i++], done: !o };
      }
    };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
    ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++)
    s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}
;
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function verb(n) {
    if (g[n])
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length)
      resume(q[0][0], q[0][1]);
  }
}
function __asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function(e) {
    throw e;
  }), verb("return"), i[Symbol.iterator] = function() {
    return this;
  }, i;
  function verb(n, f) {
    i[n] = o[n] ? function(v) {
      return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve, reject) {
        v = o[n](v), settle(resolve, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
;
function __importStar(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k in mod)
      if (Object.hasOwnProperty.call(mod, k))
        result[k] = mod[k];
  }
  result.default = mod;
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to get private field on non-instance");
  }
  return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to set private field on non-instance");
  }
  privateMap.set(receiver, value);
  return value;
}


/***/ }),

/***/ "../pyright-internal/node_modules/balanced-match/index.js":
/*!****************************************************************!*\
  !*** ../pyright-internal/node_modules/balanced-match/index.js ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";

module.exports = balanced;
function balanced(a, b, str) {
  if (a instanceof RegExp)
    a = maybeMatch(a, str);
  if (b instanceof RegExp)
    b = maybeMatch(b, str);
  var r = range(a, b, str);
  return r && {
    start: r[0],
    end: r[1],
    pre: str.slice(0, r[0]),
    body: str.slice(r[0] + a.length, r[1]),
    post: str.slice(r[1] + b.length)
  };
}
function maybeMatch(reg, str) {
  var m = str.match(reg);
  return m ? m[0] : null;
}
balanced.range = range;
function range(a, b, str) {
  var begs, beg, left, right, result;
  var ai = str.indexOf(a);
  var bi = str.indexOf(b, ai + 1);
  var i = ai;
  if (ai >= 0 && bi > 0) {
    if (a === b) {
      return [ai, bi];
    }
    begs = [];
    left = str.length;
    while (i >= 0 && !result) {
      if (i == ai) {
        begs.push(i);
        ai = str.indexOf(a, i + 1);
      } else if (begs.length == 1) {
        result = [begs.pop(), bi];
      } else {
        beg = begs.pop();
        if (beg < left) {
          left = beg;
          right = bi;
        }
        bi = str.indexOf(b, i + 1);
      }
      i = ai < bi && ai >= 0 ? ai : bi;
    }
    if (begs.length) {
      result = [left, right];
    }
  }
  return result;
}


/***/ }),

/***/ "../pyright-internal/node_modules/brace-expansion/index.js":
/*!*****************************************************************!*\
  !*** ../pyright-internal/node_modules/brace-expansion/index.js ***!
  \*****************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var concatMap = __webpack_require__(/*! concat-map */ "../pyright-internal/node_modules/concat-map/index.js");
var balanced = __webpack_require__(/*! balanced-match */ "../pyright-internal/node_modules/balanced-match/index.js");
module.exports = expandTop;
var escSlash = "\0SLASH" + Math.random() + "\0";
var escOpen = "\0OPEN" + Math.random() + "\0";
var escClose = "\0CLOSE" + Math.random() + "\0";
var escComma = "\0COMMA" + Math.random() + "\0";
var escPeriod = "\0PERIOD" + Math.random() + "\0";
function numeric(str) {
  return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
}
function escapeBraces(str) {
  return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
}
function unescapeBraces(str) {
  return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
}
function parseCommaParts(str) {
  if (!str)
    return [""];
  var parts = [];
  var m = balanced("{", "}", str);
  if (!m)
    return str.split(",");
  var pre = m.pre;
  var body = m.body;
  var post = m.post;
  var p = pre.split(",");
  p[p.length - 1] += "{" + body + "}";
  var postParts = parseCommaParts(post);
  if (post.length) {
    p[p.length - 1] += postParts.shift();
    p.push.apply(p, postParts);
  }
  parts.push.apply(parts, p);
  return parts;
}
function expandTop(str) {
  if (!str)
    return [];
  if (str.substr(0, 2) === "{}") {
    str = "\\{\\}" + str.substr(2);
  }
  return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
  return e;
}
function embrace(str) {
  return "{" + str + "}";
}
function isPadded(el) {
  return /^-?0\d/.test(el);
}
function lte(i, y) {
  return i <= y;
}
function gte(i, y) {
  return i >= y;
}
function expand(str, isTop) {
  var expansions = [];
  var m = balanced("{", "}", str);
  if (!m || /\$$/.test(m.pre))
    return [str];
  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  var isSequence = isNumericSequence || isAlphaSequence;
  var isOptions = m.body.indexOf(",") >= 0;
  if (!isSequence && !isOptions) {
    if (m.post.match(/,.*\}/)) {
      str = m.pre + "{" + m.body + escClose + m.post;
      return expand(str);
    }
    return [str];
  }
  var n;
  if (isSequence) {
    n = m.body.split(/\.\./);
  } else {
    n = parseCommaParts(m.body);
    if (n.length === 1) {
      n = expand(n[0], false).map(embrace);
      if (n.length === 1) {
        var post = m.post.length ? expand(m.post, false) : [""];
        return post.map(function(p) {
          return m.pre + n[0] + p;
        });
      }
    }
  }
  var pre = m.pre;
  var post = m.post.length ? expand(m.post, false) : [""];
  var N;
  if (isSequence) {
    var x = numeric(n[0]);
    var y = numeric(n[1]);
    var width = Math.max(n[0].length, n[1].length);
    var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
    var test = lte;
    var reverse = y < x;
    if (reverse) {
      incr *= -1;
      test = gte;
    }
    var pad = n.some(isPadded);
    N = [];
    for (var i = x; test(i, y); i += incr) {
      var c;
      if (isAlphaSequence) {
        c = String.fromCharCode(i);
        if (c === "\\")
          c = "";
      } else {
        c = String(i);
        if (pad) {
          var need = width - c.length;
          if (need > 0) {
            var z = new Array(need + 1).join("0");
            if (i < 0)
              c = "-" + z + c.slice(1);
            else
              c = z + c;
          }
        }
      }
      N.push(c);
    }
  } else {
    N = concatMap(n, function(el) {
      return expand(el, false);
    });
  }
  for (var j = 0; j < N.length; j++) {
    for (var k = 0; k < post.length; k++) {
      var expansion = pre + N[j] + post[k];
      if (!isTop || isSequence || expansion)
        expansions.push(expansion);
    }
  }
  return expansions;
}


/***/ }),

/***/ "../pyright-internal/node_modules/concat-map/index.js":
/*!************************************************************!*\
  !*** ../pyright-internal/node_modules/concat-map/index.js ***!
  \************************************************************/
/***/ ((module) => {

module.exports = function(xs, fn) {
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    var x = fn(xs[i], i);
    if (isArray(x))
      res.push.apply(res, x);
    else
      res.push(x);
  }
  return res;
};
var isArray = Array.isArray || function(xs) {
  return Object.prototype.toString.call(xs) === "[object Array]";
};


/***/ }),

/***/ "../pyright-internal/node_modules/fs.realpath/index.js":
/*!*************************************************************!*\
  !*** ../pyright-internal/node_modules/fs.realpath/index.js ***!
  \*************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = realpath;
realpath.realpath = realpath;
realpath.sync = realpathSync;
realpath.realpathSync = realpathSync;
realpath.monkeypatch = monkeypatch;
realpath.unmonkeypatch = unmonkeypatch;
var fs = __webpack_require__(/*! fs */ "fs");
var origRealpath = fs.realpath;
var origRealpathSync = fs.realpathSync;
var version = process.version;
var ok = /^v[0-5]\./.test(version);
var old = __webpack_require__(/*! ./old.js */ "../pyright-internal/node_modules/fs.realpath/old.js");
function newError(er) {
  return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
}
function realpath(p, cache, cb) {
  if (ok) {
    return origRealpath(p, cache, cb);
  }
  if (typeof cache === "function") {
    cb = cache;
    cache = null;
  }
  origRealpath(p, cache, function(er, result) {
    if (newError(er)) {
      old.realpath(p, cache, cb);
    } else {
      cb(er, result);
    }
  });
}
function realpathSync(p, cache) {
  if (ok) {
    return origRealpathSync(p, cache);
  }
  try {
    return origRealpathSync(p, cache);
  } catch (er) {
    if (newError(er)) {
      return old.realpathSync(p, cache);
    } else {
      throw er;
    }
  }
}
function monkeypatch() {
  fs.realpath = realpath;
  fs.realpathSync = realpathSync;
}
function unmonkeypatch() {
  fs.realpath = origRealpath;
  fs.realpathSync = origRealpathSync;
}


/***/ }),

/***/ "../pyright-internal/node_modules/fs.realpath/old.js":
/*!***********************************************************!*\
  !*** ../pyright-internal/node_modules/fs.realpath/old.js ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var pathModule = __webpack_require__(/*! path */ "path");
var isWindows = process.platform === "win32";
var fs = __webpack_require__(/*! fs */ "fs");
var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
function rethrow() {
  var callback;
  if (DEBUG) {
    var backtrace = new Error();
    callback = debugCallback;
  } else
    callback = missingCallback;
  return callback;
  function debugCallback(err) {
    if (err) {
      backtrace.message = err.message;
      err = backtrace;
      missingCallback(err);
    }
  }
  function missingCallback(err) {
    if (err) {
      if (process.throwDeprecation)
        throw err;
      else if (!process.noDeprecation) {
        var msg = "fs: missing callback " + (err.stack || err.message);
        if (process.traceDeprecation)
          console.trace(msg);
        else
          console.error(msg);
      }
    }
  }
}
function maybeCallback(cb) {
  return typeof cb === "function" ? cb : rethrow();
}
var normalize = pathModule.normalize;
if (isWindows) {
  var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
} else {
  var nextPartRe = /(.*?)(?:[\/]+|$)/g;
}
if (isWindows) {
  var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
} else {
  var splitRootRe = /^[\/]*/;
}
exports.realpathSync = function realpathSync(p, cache) {
  p = pathModule.resolve(p);
  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
    return cache[p];
  }
  var original = p, seenLinks = {}, knownHard = {};
  var pos;
  var current;
  var base;
  var previous;
  start();
  function start() {
    var m = splitRootRe.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = "";
    if (isWindows && !knownHard[base]) {
      fs.lstatSync(base);
      knownHard[base] = true;
    }
  }
  while (pos < p.length) {
    nextPartRe.lastIndex = pos;
    var result = nextPartRe.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextPartRe.lastIndex;
    if (knownHard[base] || cache && cache[base] === base) {
      continue;
    }
    var resolvedLink;
    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
      resolvedLink = cache[base];
    } else {
      var stat = fs.lstatSync(base);
      if (!stat.isSymbolicLink()) {
        knownHard[base] = true;
        if (cache)
          cache[base] = base;
        continue;
      }
      var linkTarget = null;
      if (!isWindows) {
        var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
        if (seenLinks.hasOwnProperty(id)) {
          linkTarget = seenLinks[id];
        }
      }
      if (linkTarget === null) {
        fs.statSync(base);
        linkTarget = fs.readlinkSync(base);
      }
      resolvedLink = pathModule.resolve(previous, linkTarget);
      if (cache)
        cache[base] = resolvedLink;
      if (!isWindows)
        seenLinks[id] = linkTarget;
    }
    p = pathModule.resolve(resolvedLink, p.slice(pos));
    start();
  }
  if (cache)
    cache[original] = p;
  return p;
};
exports.realpath = function realpath(p, cache, cb) {
  if (typeof cb !== "function") {
    cb = maybeCallback(cache);
    cache = null;
  }
  p = pathModule.resolve(p);
  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
    return process.nextTick(cb.bind(null, null, cache[p]));
  }
  var original = p, seenLinks = {}, knownHard = {};
  var pos;
  var current;
  var base;
  var previous;
  start();
  function start() {
    var m = splitRootRe.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = "";
    if (isWindows && !knownHard[base]) {
      fs.lstat(base, function(err) {
        if (err)
          return cb(err);
        knownHard[base] = true;
        LOOP();
      });
    } else {
      process.nextTick(LOOP);
    }
  }
  function LOOP() {
    if (pos >= p.length) {
      if (cache)
        cache[original] = p;
      return cb(null, p);
    }
    nextPartRe.lastIndex = pos;
    var result = nextPartRe.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextPartRe.lastIndex;
    if (knownHard[base] || cache && cache[base] === base) {
      return process.nextTick(LOOP);
    }
    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
      return gotResolvedLink(cache[base]);
    }
    return fs.lstat(base, gotStat);
  }
  function gotStat(err, stat) {
    if (err)
      return cb(err);
    if (!stat.isSymbolicLink()) {
      knownHard[base] = true;
      if (cache)
        cache[base] = base;
      return process.nextTick(LOOP);
    }
    if (!isWindows) {
      var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
      if (seenLinks.hasOwnProperty(id)) {
        return gotTarget(null, seenLinks[id], base);
      }
    }
    fs.stat(base, function(err2) {
      if (err2)
        return cb(err2);
      fs.readlink(base, function(err3, target) {
        if (!isWindows)
          seenLinks[id] = target;
        gotTarget(err3, target);
      });
    });
  }
  function gotTarget(err, target, base2) {
    if (err)
      return cb(err);
    var resolvedLink = pathModule.resolve(previous, target);
    if (cache)
      cache[base2] = resolvedLink;
    gotResolvedLink(resolvedLink);
  }
  function gotResolvedLink(resolvedLink) {
    p = pathModule.resolve(resolvedLink, p.slice(pos));
    start();
  }
};


/***/ }),

/***/ "../pyright-internal/node_modules/glob/common.js":
/*!*******************************************************!*\
  !*** ../pyright-internal/node_modules/glob/common.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

exports.setopts = setopts;
exports.ownProp = ownProp;
exports.makeAbs = makeAbs;
exports.finish = finish;
exports.mark = mark;
exports.isIgnored = isIgnored;
exports.childrenIgnored = childrenIgnored;
function ownProp(obj, field) {
  return Object.prototype.hasOwnProperty.call(obj, field);
}
var fs = __webpack_require__(/*! fs */ "fs");
var path = __webpack_require__(/*! path */ "path");
var minimatch = __webpack_require__(/*! minimatch */ "../pyright-internal/node_modules/minimatch/minimatch.js");
var isAbsolute = __webpack_require__(/*! path-is-absolute */ "../pyright-internal/node_modules/path-is-absolute/index.js");
var Minimatch = minimatch.Minimatch;
function alphasort(a, b) {
  return a.localeCompare(b, "en");
}
function setupIgnores(self, options) {
  self.ignore = options.ignore || [];
  if (!Array.isArray(self.ignore))
    self.ignore = [self.ignore];
  if (self.ignore.length) {
    self.ignore = self.ignore.map(ignoreMap);
  }
}
function ignoreMap(pattern) {
  var gmatcher = null;
  if (pattern.slice(-3) === "/**") {
    var gpattern = pattern.replace(/(\/\*\*)+$/, "");
    gmatcher = new Minimatch(gpattern, { dot: true });
  }
  return {
    matcher: new Minimatch(pattern, { dot: true }),
    gmatcher
  };
}
function setopts(self, pattern, options) {
  if (!options)
    options = {};
  if (options.matchBase && -1 === pattern.indexOf("/")) {
    if (options.noglobstar) {
      throw new Error("base matching requires globstar");
    }
    pattern = "**/" + pattern;
  }
  self.silent = !!options.silent;
  self.pattern = pattern;
  self.strict = options.strict !== false;
  self.realpath = !!options.realpath;
  self.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
  self.follow = !!options.follow;
  self.dot = !!options.dot;
  self.mark = !!options.mark;
  self.nodir = !!options.nodir;
  if (self.nodir)
    self.mark = true;
  self.sync = !!options.sync;
  self.nounique = !!options.nounique;
  self.nonull = !!options.nonull;
  self.nosort = !!options.nosort;
  self.nocase = !!options.nocase;
  self.stat = !!options.stat;
  self.noprocess = !!options.noprocess;
  self.absolute = !!options.absolute;
  self.fs = options.fs || fs;
  self.maxLength = options.maxLength || Infinity;
  self.cache = options.cache || /* @__PURE__ */ Object.create(null);
  self.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
  self.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
  setupIgnores(self, options);
  self.changedCwd = false;
  var cwd = process.cwd();
  if (!ownProp(options, "cwd"))
    self.cwd = cwd;
  else {
    self.cwd = path.resolve(options.cwd);
    self.changedCwd = self.cwd !== cwd;
  }
  self.root = options.root || path.resolve(self.cwd, "/");
  self.root = path.resolve(self.root);
  if (process.platform === "win32")
    self.root = self.root.replace(/\\/g, "/");
  self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  if (process.platform === "win32")
    self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  self.nomount = !!options.nomount;
  options.nonegate = true;
  options.nocomment = true;
  options.allowWindowsEscape = false;
  self.minimatch = new Minimatch(pattern, options);
  self.options = self.minimatch.options;
}
function finish(self) {
  var nou = self.nounique;
  var all = nou ? [] : /* @__PURE__ */ Object.create(null);
  for (var i = 0, l = self.matches.length; i < l; i++) {
    var matches = self.matches[i];
    if (!matches || Object.keys(matches).length === 0) {
      if (self.nonull) {
        var literal = self.minimatch.globSet[i];
        if (nou)
          all.push(literal);
        else
          all[literal] = true;
      }
    } else {
      var m = Object.keys(matches);
      if (nou)
        all.push.apply(all, m);
      else
        m.forEach(function(m2) {
          all[m2] = true;
        });
    }
  }
  if (!nou)
    all = Object.keys(all);
  if (!self.nosort)
    all = all.sort(alphasort);
  if (self.mark) {
    for (var i = 0; i < all.length; i++) {
      all[i] = self._mark(all[i]);
    }
    if (self.nodir) {
      all = all.filter(function(e) {
        var notDir = !/\/$/.test(e);
        var c = self.cache[e] || self.cache[makeAbs(self, e)];
        if (notDir && c)
          notDir = c !== "DIR" && !Array.isArray(c);
        return notDir;
      });
    }
  }
  if (self.ignore.length)
    all = all.filter(function(m2) {
      return !isIgnored(self, m2);
    });
  self.found = all;
}
function mark(self, p) {
  var abs = makeAbs(self, p);
  var c = self.cache[abs];
  var m = p;
  if (c) {
    var isDir = c === "DIR" || Array.isArray(c);
    var slash = p.slice(-1) === "/";
    if (isDir && !slash)
      m += "/";
    else if (!isDir && slash)
      m = m.slice(0, -1);
    if (m !== p) {
      var mabs = makeAbs(self, m);
      self.statCache[mabs] = self.statCache[abs];
      self.cache[mabs] = self.cache[abs];
    }
  }
  return m;
}
function makeAbs(self, f) {
  var abs = f;
  if (f.charAt(0) === "/") {
    abs = path.join(self.root, f);
  } else if (isAbsolute(f) || f === "") {
    abs = f;
  } else if (self.changedCwd) {
    abs = path.resolve(self.cwd, f);
  } else {
    abs = path.resolve(f);
  }
  if (process.platform === "win32")
    abs = abs.replace(/\\/g, "/");
  return abs;
}
function isIgnored(self, path2) {
  if (!self.ignore.length)
    return false;
  return self.ignore.some(function(item) {
    return item.matcher.match(path2) || !!(item.gmatcher && item.gmatcher.match(path2));
  });
}
function childrenIgnored(self, path2) {
  if (!self.ignore.length)
    return false;
  return self.ignore.some(function(item) {
    return !!(item.gmatcher && item.gmatcher.match(path2));
  });
}


/***/ }),

/***/ "../pyright-internal/node_modules/glob/glob.js":
/*!*****************************************************!*\
  !*** ../pyright-internal/node_modules/glob/glob.js ***!
  \*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = glob;
var rp = __webpack_require__(/*! fs.realpath */ "../pyright-internal/node_modules/fs.realpath/index.js");
var minimatch = __webpack_require__(/*! minimatch */ "../pyright-internal/node_modules/minimatch/minimatch.js");
var Minimatch = minimatch.Minimatch;
var inherits = __webpack_require__(/*! inherits */ "../pyright-internal/node_modules/inherits/inherits.js");
var EE = (__webpack_require__(/*! events */ "events").EventEmitter);
var path = __webpack_require__(/*! path */ "path");
var assert = __webpack_require__(/*! assert */ "assert");
var isAbsolute = __webpack_require__(/*! path-is-absolute */ "../pyright-internal/node_modules/path-is-absolute/index.js");
var globSync = __webpack_require__(/*! ./sync.js */ "../pyright-internal/node_modules/glob/sync.js");
var common = __webpack_require__(/*! ./common.js */ "../pyright-internal/node_modules/glob/common.js");
var setopts = common.setopts;
var ownProp = common.ownProp;
var inflight = __webpack_require__(/*! inflight */ "../pyright-internal/node_modules/inflight/inflight.js");
var util = __webpack_require__(/*! util */ "util");
var childrenIgnored = common.childrenIgnored;
var isIgnored = common.isIgnored;
var once = __webpack_require__(/*! once */ "../pyright-internal/node_modules/once/once.js");
function glob(pattern, options, cb) {
  if (typeof options === "function")
    cb = options, options = {};
  if (!options)
    options = {};
  if (options.sync) {
    if (cb)
      throw new TypeError("callback provided to sync glob");
    return globSync(pattern, options);
  }
  return new Glob(pattern, options, cb);
}
glob.sync = globSync;
var GlobSync = glob.GlobSync = globSync.GlobSync;
glob.glob = glob;
function extend(origin, add) {
  if (add === null || typeof add !== "object") {
    return origin;
  }
  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
}
glob.hasMagic = function(pattern, options_) {
  var options = extend({}, options_);
  options.noprocess = true;
  var g = new Glob(pattern, options);
  var set = g.minimatch.set;
  if (!pattern)
    return false;
  if (set.length > 1)
    return true;
  for (var j = 0; j < set[0].length; j++) {
    if (typeof set[0][j] !== "string")
      return true;
  }
  return false;
};
glob.Glob = Glob;
inherits(Glob, EE);
function Glob(pattern, options, cb) {
  if (typeof options === "function") {
    cb = options;
    options = null;
  }
  if (options && options.sync) {
    if (cb)
      throw new TypeError("callback provided to sync glob");
    return new GlobSync(pattern, options);
  }
  if (!(this instanceof Glob))
    return new Glob(pattern, options, cb);
  setopts(this, pattern, options);
  this._didRealPath = false;
  var n = this.minimatch.set.length;
  this.matches = new Array(n);
  if (typeof cb === "function") {
    cb = once(cb);
    this.on("error", cb);
    this.on("end", function(matches) {
      cb(null, matches);
    });
  }
  var self = this;
  this._processing = 0;
  this._emitQueue = [];
  this._processQueue = [];
  this.paused = false;
  if (this.noprocess)
    return this;
  if (n === 0)
    return done();
  var sync = true;
  for (var i = 0; i < n; i++) {
    this._process(this.minimatch.set[i], i, false, done);
  }
  sync = false;
  function done() {
    --self._processing;
    if (self._processing <= 0) {
      if (sync) {
        process.nextTick(function() {
          self._finish();
        });
      } else {
        self._finish();
      }
    }
  }
}
Glob.prototype._finish = function() {
  assert(this instanceof Glob);
  if (this.aborted)
    return;
  if (this.realpath && !this._didRealpath)
    return this._realpath();
  common.finish(this);
  this.emit("end", this.found);
};
Glob.prototype._realpath = function() {
  if (this._didRealpath)
    return;
  this._didRealpath = true;
  var n = this.matches.length;
  if (n === 0)
    return this._finish();
  var self = this;
  for (var i = 0; i < this.matches.length; i++)
    this._realpathSet(i, next);
  function next() {
    if (--n === 0)
      self._finish();
  }
};
Glob.prototype._realpathSet = function(index, cb) {
  var matchset = this.matches[index];
  if (!matchset)
    return cb();
  var found = Object.keys(matchset);
  var self = this;
  var n = found.length;
  if (n === 0)
    return cb();
  var set = this.matches[index] = /* @__PURE__ */ Object.create(null);
  found.forEach(function(p, i) {
    p = self._makeAbs(p);
    rp.realpath(p, self.realpathCache, function(er, real) {
      if (!er)
        set[real] = true;
      else if (er.syscall === "stat")
        set[p] = true;
      else
        self.emit("error", er);
      if (--n === 0) {
        self.matches[index] = set;
        cb();
      }
    });
  });
};
Glob.prototype._mark = function(p) {
  return common.mark(this, p);
};
Glob.prototype._makeAbs = function(f) {
  return common.makeAbs(this, f);
};
Glob.prototype.abort = function() {
  this.aborted = true;
  this.emit("abort");
};
Glob.prototype.pause = function() {
  if (!this.paused) {
    this.paused = true;
    this.emit("pause");
  }
};
Glob.prototype.resume = function() {
  if (this.paused) {
    this.emit("resume");
    this.paused = false;
    if (this._emitQueue.length) {
      var eq = this._emitQueue.slice(0);
      this._emitQueue.length = 0;
      for (var i = 0; i < eq.length; i++) {
        var e = eq[i];
        this._emitMatch(e[0], e[1]);
      }
    }
    if (this._processQueue.length) {
      var pq = this._processQueue.slice(0);
      this._processQueue.length = 0;
      for (var i = 0; i < pq.length; i++) {
        var p = pq[i];
        this._processing--;
        this._process(p[0], p[1], p[2], p[3]);
      }
    }
  }
};
Glob.prototype._process = function(pattern, index, inGlobStar, cb) {
  assert(this instanceof Glob);
  assert(typeof cb === "function");
  if (this.aborted)
    return;
  this._processing++;
  if (this.paused) {
    this._processQueue.push([pattern, index, inGlobStar, cb]);
    return;
  }
  var n = 0;
  while (typeof pattern[n] === "string") {
    n++;
  }
  var prefix;
  switch (n) {
    case pattern.length:
      this._processSimple(pattern.join("/"), index, cb);
      return;
    case 0:
      prefix = null;
      break;
    default:
      prefix = pattern.slice(0, n).join("/");
      break;
  }
  var remain = pattern.slice(n);
  var read;
  if (prefix === null)
    read = ".";
  else if (isAbsolute(prefix) || isAbsolute(pattern.map(function(p) {
    return typeof p === "string" ? p : "[*]";
  }).join("/"))) {
    if (!prefix || !isAbsolute(prefix))
      prefix = "/" + prefix;
    read = prefix;
  } else
    read = prefix;
  var abs = this._makeAbs(read);
  if (childrenIgnored(this, read))
    return cb();
  var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  if (isGlobStar)
    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  else
    this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
};
Glob.prototype._processReaddir = function(prefix, read, abs, remain, index, inGlobStar, cb) {
  var self = this;
  this._readdir(abs, inGlobStar, function(er, entries) {
    return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  });
};
Glob.prototype._processReaddir2 = function(prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  if (!entries)
    return cb();
  var pn = remain[0];
  var negate = !!this.minimatch.negate;
  var rawGlob = pn._glob;
  var dotOk = this.dot || rawGlob.charAt(0) === ".";
  var matchedEntries = [];
  for (var i = 0; i < entries.length; i++) {
    var e = entries[i];
    if (e.charAt(0) !== "." || dotOk) {
      var m;
      if (negate && !prefix) {
        m = !e.match(pn);
      } else {
        m = e.match(pn);
      }
      if (m)
        matchedEntries.push(e);
    }
  }
  var len = matchedEntries.length;
  if (len === 0)
    return cb();
  if (remain.length === 1 && !this.mark && !this.stat) {
    if (!this.matches[index])
      this.matches[index] = /* @__PURE__ */ Object.create(null);
    for (var i = 0; i < len; i++) {
      var e = matchedEntries[i];
      if (prefix) {
        if (prefix !== "/")
          e = prefix + "/" + e;
        else
          e = prefix + e;
      }
      if (e.charAt(0) === "/" && !this.nomount) {
        e = path.join(this.root, e);
      }
      this._emitMatch(index, e);
    }
    return cb();
  }
  remain.shift();
  for (var i = 0; i < len; i++) {
    var e = matchedEntries[i];
    var newPattern;
    if (prefix) {
      if (prefix !== "/")
        e = prefix + "/" + e;
      else
        e = prefix + e;
    }
    this._process([e].concat(remain), index, inGlobStar, cb);
  }
  cb();
};
Glob.prototype._emitMatch = function(index, e) {
  if (this.aborted)
    return;
  if (isIgnored(this, e))
    return;
  if (this.paused) {
    this._emitQueue.push([index, e]);
    return;
  }
  var abs = isAbsolute(e) ? e : this._makeAbs(e);
  if (this.mark)
    e = this._mark(e);
  if (this.absolute)
    e = abs;
  if (this.matches[index][e])
    return;
  if (this.nodir) {
    var c = this.cache[abs];
    if (c === "DIR" || Array.isArray(c))
      return;
  }
  this.matches[index][e] = true;
  var st = this.statCache[abs];
  if (st)
    this.emit("stat", e, st);
  this.emit("match", e);
};
Glob.prototype._readdirInGlobStar = function(abs, cb) {
  if (this.aborted)
    return;
  if (this.follow)
    return this._readdir(abs, false, cb);
  var lstatkey = "lstat\0" + abs;
  var self = this;
  var lstatcb = inflight(lstatkey, lstatcb_);
  if (lstatcb)
    self.fs.lstat(abs, lstatcb);
  function lstatcb_(er, lstat) {
    if (er && er.code === "ENOENT")
      return cb();
    var isSym = lstat && lstat.isSymbolicLink();
    self.symlinks[abs] = isSym;
    if (!isSym && lstat && !lstat.isDirectory()) {
      self.cache[abs] = "FILE";
      cb();
    } else
      self._readdir(abs, false, cb);
  }
};
Glob.prototype._readdir = function(abs, inGlobStar, cb) {
  if (this.aborted)
    return;
  cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
  if (!cb)
    return;
  if (inGlobStar && !ownProp(this.symlinks, abs))
    return this._readdirInGlobStar(abs, cb);
  if (ownProp(this.cache, abs)) {
    var c = this.cache[abs];
    if (!c || c === "FILE")
      return cb();
    if (Array.isArray(c))
      return cb(null, c);
  }
  var self = this;
  self.fs.readdir(abs, readdirCb(this, abs, cb));
};
function readdirCb(self, abs, cb) {
  return function(er, entries) {
    if (er)
      self._readdirError(abs, er, cb);
    else
      self._readdirEntries(abs, entries, cb);
  };
}
Glob.prototype._readdirEntries = function(abs, entries, cb) {
  if (this.aborted)
    return;
  if (!this.mark && !this.stat) {
    for (var i = 0; i < entries.length; i++) {
      var e = entries[i];
      if (abs === "/")
        e = abs + e;
      else
        e = abs + "/" + e;
      this.cache[e] = true;
    }
  }
  this.cache[abs] = entries;
  return cb(null, entries);
};
Glob.prototype._readdirError = function(f, er, cb) {
  if (this.aborted)
    return;
  switch (er.code) {
    case "ENOTSUP":
    case "ENOTDIR":
      var abs = this._makeAbs(f);
      this.cache[abs] = "FILE";
      if (abs === this.cwdAbs) {
        var error = new Error(er.code + " invalid cwd " + this.cwd);
        error.path = this.cwd;
        error.code = er.code;
        this.emit("error", error);
        this.abort();
      }
      break;
    case "ENOENT":
    case "ELOOP":
    case "ENAMETOOLONG":
    case "UNKNOWN":
      this.cache[this._makeAbs(f)] = false;
      break;
    default:
      this.cache[this._makeAbs(f)] = false;
      if (this.strict) {
        this.emit("error", er);
        this.abort();
      }
      if (!this.silent)
        console.error("glob error", er);
      break;
  }
  return cb();
};
Glob.prototype._processGlobStar = function(prefix, read, abs, remain, index, inGlobStar, cb) {
  var self = this;
  this._readdir(abs, inGlobStar, function(er, entries) {
    self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  });
};
Glob.prototype._processGlobStar2 = function(prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  if (!entries)
    return cb();
  var remainWithoutGlobStar = remain.slice(1);
  var gspref = prefix ? [prefix] : [];
  var noGlobStar = gspref.concat(remainWithoutGlobStar);
  this._process(noGlobStar, index, false, cb);
  var isSym = this.symlinks[abs];
  var len = entries.length;
  if (isSym && inGlobStar)
    return cb();
  for (var i = 0; i < len; i++) {
    var e = entries[i];
    if (e.charAt(0) === "." && !this.dot)
      continue;
    var instead = gspref.concat(entries[i], remainWithoutGlobStar);
    this._process(instead, index, true, cb);
    var below = gspref.concat(entries[i], remain);
    this._process(below, index, true, cb);
  }
  cb();
};
Glob.prototype._processSimple = function(prefix, index, cb) {
  var self = this;
  this._stat(prefix, function(er, exists) {
    self._processSimple2(prefix, index, er, exists, cb);
  });
};
Glob.prototype._processSimple2 = function(prefix, index, er, exists, cb) {
  if (!this.matches[index])
    this.matches[index] = /* @__PURE__ */ Object.create(null);
  if (!exists)
    return cb();
  if (prefix && isAbsolute(prefix) && !this.nomount) {
    var trail = /[\/\\]$/.test(prefix);
    if (prefix.charAt(0) === "/") {
      prefix = path.join(this.root, prefix);
    } else {
      prefix = path.resolve(this.root, prefix);
      if (trail)
        prefix += "/";
    }
  }
  if (process.platform === "win32")
    prefix = prefix.replace(/\\/g, "/");
  this._emitMatch(index, prefix);
  cb();
};
Glob.prototype._stat = function(f, cb) {
  var abs = this._makeAbs(f);
  var needDir = f.slice(-1) === "/";
  if (f.length > this.maxLength)
    return cb();
  if (!this.stat && ownProp(this.cache, abs)) {
    var c = this.cache[abs];
    if (Array.isArray(c))
      c = "DIR";
    if (!needDir || c === "DIR")
      return cb(null, c);
    if (needDir && c === "FILE")
      return cb();
  }
  var exists;
  var stat = this.statCache[abs];
  if (stat !== void 0) {
    if (stat === false)
      return cb(null, stat);
    else {
      var type = stat.isDirectory() ? "DIR" : "FILE";
      if (needDir && type === "FILE")
        return cb();
      else
        return cb(null, type, stat);
    }
  }
  var self = this;
  var statcb = inflight("stat\0" + abs, lstatcb_);
  if (statcb)
    self.fs.lstat(abs, statcb);
  function lstatcb_(er, lstat) {
    if (lstat && lstat.isSymbolicLink()) {
      return self.fs.stat(abs, function(er2, stat2) {
        if (er2)
          self._stat2(f, abs, null, lstat, cb);
        else
          self._stat2(f, abs, er2, stat2, cb);
      });
    } else {
      self._stat2(f, abs, er, lstat, cb);
    }
  }
};
Glob.prototype._stat2 = function(f, abs, er, stat, cb) {
  if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
    this.statCache[abs] = false;
    return cb();
  }
  var needDir = f.slice(-1) === "/";
  this.statCache[abs] = stat;
  if (abs.slice(-1) === "/" && stat && !stat.isDirectory())
    return cb(null, false, stat);
  var c = true;
  if (stat)
    c = stat.isDirectory() ? "DIR" : "FILE";
  this.cache[abs] = this.cache[abs] || c;
  if (needDir && c === "FILE")
    return cb();
  return cb(null, c, stat);
};


/***/ }),

/***/ "../pyright-internal/node_modules/glob/sync.js":
/*!*****************************************************!*\
  !*** ../pyright-internal/node_modules/glob/sync.js ***!
  \*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = globSync;
globSync.GlobSync = GlobSync;
var rp = __webpack_require__(/*! fs.realpath */ "../pyright-internal/node_modules/fs.realpath/index.js");
var minimatch = __webpack_require__(/*! minimatch */ "../pyright-internal/node_modules/minimatch/minimatch.js");
var Minimatch = minimatch.Minimatch;
var Glob = (__webpack_require__(/*! ./glob.js */ "../pyright-internal/node_modules/glob/glob.js").Glob);
var util = __webpack_require__(/*! util */ "util");
var path = __webpack_require__(/*! path */ "path");
var assert = __webpack_require__(/*! assert */ "assert");
var isAbsolute = __webpack_require__(/*! path-is-absolute */ "../pyright-internal/node_modules/path-is-absolute/index.js");
var common = __webpack_require__(/*! ./common.js */ "../pyright-internal/node_modules/glob/common.js");
var setopts = common.setopts;
var ownProp = common.ownProp;
var childrenIgnored = common.childrenIgnored;
var isIgnored = common.isIgnored;
function globSync(pattern, options) {
  if (typeof options === "function" || arguments.length === 3)
    throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  return new GlobSync(pattern, options).found;
}
function GlobSync(pattern, options) {
  if (!pattern)
    throw new Error("must provide pattern");
  if (typeof options === "function" || arguments.length === 3)
    throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  if (!(this instanceof GlobSync))
    return new GlobSync(pattern, options);
  setopts(this, pattern, options);
  if (this.noprocess)
    return this;
  var n = this.minimatch.set.length;
  this.matches = new Array(n);
  for (var i = 0; i < n; i++) {
    this._process(this.minimatch.set[i], i, false);
  }
  this._finish();
}
GlobSync.prototype._finish = function() {
  assert.ok(this instanceof GlobSync);
  if (this.realpath) {
    var self = this;
    this.matches.forEach(function(matchset, index) {
      var set = self.matches[index] = /* @__PURE__ */ Object.create(null);
      for (var p in matchset) {
        try {
          p = self._makeAbs(p);
          var real = rp.realpathSync(p, self.realpathCache);
          set[real] = true;
        } catch (er) {
          if (er.syscall === "stat")
            set[self._makeAbs(p)] = true;
          else
            throw er;
        }
      }
    });
  }
  common.finish(this);
};
GlobSync.prototype._process = function(pattern, index, inGlobStar) {
  assert.ok(this instanceof GlobSync);
  var n = 0;
  while (typeof pattern[n] === "string") {
    n++;
  }
  var prefix;
  switch (n) {
    case pattern.length:
      this._processSimple(pattern.join("/"), index);
      return;
    case 0:
      prefix = null;
      break;
    default:
      prefix = pattern.slice(0, n).join("/");
      break;
  }
  var remain = pattern.slice(n);
  var read;
  if (prefix === null)
    read = ".";
  else if (isAbsolute(prefix) || isAbsolute(pattern.map(function(p) {
    return typeof p === "string" ? p : "[*]";
  }).join("/"))) {
    if (!prefix || !isAbsolute(prefix))
      prefix = "/" + prefix;
    read = prefix;
  } else
    read = prefix;
  var abs = this._makeAbs(read);
  if (childrenIgnored(this, read))
    return;
  var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  if (isGlobStar)
    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  else
    this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
};
GlobSync.prototype._processReaddir = function(prefix, read, abs, remain, index, inGlobStar) {
  var entries = this._readdir(abs, inGlobStar);
  if (!entries)
    return;
  var pn = remain[0];
  var negate = !!this.minimatch.negate;
  var rawGlob = pn._glob;
  var dotOk = this.dot || rawGlob.charAt(0) === ".";
  var matchedEntries = [];
  for (var i = 0; i < entries.length; i++) {
    var e = entries[i];
    if (e.charAt(0) !== "." || dotOk) {
      var m;
      if (negate && !prefix) {
        m = !e.match(pn);
      } else {
        m = e.match(pn);
      }
      if (m)
        matchedEntries.push(e);
    }
  }
  var len = matchedEntries.length;
  if (len === 0)
    return;
  if (remain.length === 1 && !this.mark && !this.stat) {
    if (!this.matches[index])
      this.matches[index] = /* @__PURE__ */ Object.create(null);
    for (var i = 0; i < len; i++) {
      var e = matchedEntries[i];
      if (prefix) {
        if (prefix.slice(-1) !== "/")
          e = prefix + "/" + e;
        else
          e = prefix + e;
      }
      if (e.charAt(0) === "/" && !this.nomount) {
        e = path.join(this.root, e);
      }
      this._emitMatch(index, e);
    }
    return;
  }
  remain.shift();
  for (var i = 0; i < len; i++) {
    var e = matchedEntries[i];
    var newPattern;
    if (prefix)
      newPattern = [prefix, e];
    else
      newPattern = [e];
    this._process(newPattern.concat(remain), index, inGlobStar);
  }
};
GlobSync.prototype._emitMatch = function(index, e) {
  if (isIgnored(this, e))
    return;
  var abs = this._makeAbs(e);
  if (this.mark)
    e = this._mark(e);
  if (this.absolute) {
    e = abs;
  }
  if (this.matches[index][e])
    return;
  if (this.nodir) {
    var c = this.cache[abs];
    if (c === "DIR" || Array.isArray(c))
      return;
  }
  this.matches[index][e] = true;
  if (this.stat)
    this._stat(e);
};
GlobSync.prototype._readdirInGlobStar = function(abs) {
  if (this.follow)
    return this._readdir(abs, false);
  var entries;
  var lstat;
  var stat;
  try {
    lstat = this.fs.lstatSync(abs);
  } catch (er) {
    if (er.code === "ENOENT") {
      return null;
    }
  }
  var isSym = lstat && lstat.isSymbolicLink();
  this.symlinks[abs] = isSym;
  if (!isSym && lstat && !lstat.isDirectory())
    this.cache[abs] = "FILE";
  else
    entries = this._readdir(abs, false);
  return entries;
};
GlobSync.prototype._readdir = function(abs, inGlobStar) {
  var entries;
  if (inGlobStar && !ownProp(this.symlinks, abs))
    return this._readdirInGlobStar(abs);
  if (ownProp(this.cache, abs)) {
    var c = this.cache[abs];
    if (!c || c === "FILE")
      return null;
    if (Array.isArray(c))
      return c;
  }
  try {
    return this._readdirEntries(abs, this.fs.readdirSync(abs));
  } catch (er) {
    this._readdirError(abs, er);
    return null;
  }
};
GlobSync.prototype._readdirEntries = function(abs, entries) {
  if (!this.mark && !this.stat) {
    for (var i = 0; i < entries.length; i++) {
      var e = entries[i];
      if (abs === "/")
        e = abs + e;
      else
        e = abs + "/" + e;
      this.cache[e] = true;
    }
  }
  this.cache[abs] = entries;
  return entries;
};
GlobSync.prototype._readdirError = function(f, er) {
  switch (er.code) {
    case "ENOTSUP":
    case "ENOTDIR":
      var abs = this._makeAbs(f);
      this.cache[abs] = "FILE";
      if (abs === this.cwdAbs) {
        var error = new Error(er.code + " invalid cwd " + this.cwd);
        error.path = this.cwd;
        error.code = er.code;
        throw error;
      }
      break;
    case "ENOENT":
    case "ELOOP":
    case "ENAMETOOLONG":
    case "UNKNOWN":
      this.cache[this._makeAbs(f)] = false;
      break;
    default:
      this.cache[this._makeAbs(f)] = false;
      if (this.strict)
        throw er;
      if (!this.silent)
        console.error("glob error", er);
      break;
  }
};
GlobSync.prototype._processGlobStar = function(prefix, read, abs, remain, index, inGlobStar) {
  var entries = this._readdir(abs, inGlobStar);
  if (!entries)
    return;
  var remainWithoutGlobStar = remain.slice(1);
  var gspref = prefix ? [prefix] : [];
  var noGlobStar = gspref.concat(remainWithoutGlobStar);
  this._process(noGlobStar, index, false);
  var len = entries.length;
  var isSym = this.symlinks[abs];
  if (isSym && inGlobStar)
    return;
  for (var i = 0; i < len; i++) {
    var e = entries[i];
    if (e.charAt(0) === "." && !this.dot)
      continue;
    var instead = gspref.concat(entries[i], remainWithoutGlobStar);
    this._process(instead, index, true);
    var below = gspref.concat(entries[i], remain);
    this._process(below, index, true);
  }
};
GlobSync.prototype._processSimple = function(prefix, index) {
  var exists = this._stat(prefix);
  if (!this.matches[index])
    this.matches[index] = /* @__PURE__ */ Object.create(null);
  if (!exists)
    return;
  if (prefix && isAbsolute(prefix) && !this.nomount) {
    var trail = /[\/\\]$/.test(prefix);
    if (prefix.charAt(0) === "/") {
      prefix = path.join(this.root, prefix);
    } else {
      prefix = path.resolve(this.root, prefix);
      if (trail)
        prefix += "/";
    }
  }
  if (process.platform === "win32")
    prefix = prefix.replace(/\\/g, "/");
  this._emitMatch(index, prefix);
};
GlobSync.prototype._stat = function(f) {
  var abs = this._makeAbs(f);
  var needDir = f.slice(-1) === "/";
  if (f.length > this.maxLength)
    return false;
  if (!this.stat && ownProp(this.cache, abs)) {
    var c = this.cache[abs];
    if (Array.isArray(c))
      c = "DIR";
    if (!needDir || c === "DIR")
      return c;
    if (needDir && c === "FILE")
      return false;
  }
  var exists;
  var stat = this.statCache[abs];
  if (!stat) {
    var lstat;
    try {
      lstat = this.fs.lstatSync(abs);
    } catch (er) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return false;
      }
    }
    if (lstat && lstat.isSymbolicLink()) {
      try {
        stat = this.fs.statSync(abs);
      } catch (er) {
        stat = lstat;
      }
    } else {
      stat = lstat;
    }
  }
  this.statCache[abs] = stat;
  var c = true;
  if (stat)
    c = stat.isDirectory() ? "DIR" : "FILE";
  this.cache[abs] = this.cache[abs] || c;
  if (needDir && c === "FILE")
    return false;
  return c;
};
GlobSync.prototype._mark = function(p) {
  return common.mark(this, p);
};
GlobSync.prototype._makeAbs = function(f) {
  return common.makeAbs(this, f);
};


/***/ }),

/***/ "../pyright-internal/node_modules/inflight/inflight.js":
/*!*************************************************************!*\
  !*** ../pyright-internal/node_modules/inflight/inflight.js ***!
  \*************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var wrappy = __webpack_require__(/*! wrappy */ "../pyright-internal/node_modules/wrappy/wrappy.js");
var reqs = /* @__PURE__ */ Object.create(null);
var once = __webpack_require__(/*! once */ "../pyright-internal/node_modules/once/once.js");
module.exports = wrappy(inflight);
function inflight(key, cb) {
  if (reqs[key]) {
    reqs[key].push(cb);
    return null;
  } else {
    reqs[key] = [cb];
    return makeres(key);
  }
}
function makeres(key) {
  return once(function RES() {
    var cbs = reqs[key];
    var len = cbs.length;
    var args = slice(arguments);
    try {
      for (var i = 0; i < len; i++) {
        cbs[i].apply(null, args);
      }
    } finally {
      if (cbs.length > len) {
        cbs.splice(0, len);
        process.nextTick(function() {
          RES.apply(null, args);
        });
      } else {
        delete reqs[key];
      }
    }
  });
}
function slice(args) {
  var length = args.length;
  var array = [];
  for (var i = 0; i < length; i++)
    array[i] = args[i];
  return array;
}


/***/ }),

/***/ "../pyright-internal/node_modules/inherits/inherits.js":
/*!*************************************************************!*\
  !*** ../pyright-internal/node_modules/inherits/inherits.js ***!
  \*************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

try {
  var util = __webpack_require__(/*! util */ "util");
  if (typeof util.inherits !== "function")
    throw "";
  module.exports = util.inherits;
} catch (e) {
  module.exports = __webpack_require__(/*! ./inherits_browser.js */ "../pyright-internal/node_modules/inherits/inherits_browser.js");
}


/***/ }),

/***/ "../pyright-internal/node_modules/inherits/inherits_browser.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/inherits/inherits_browser.js ***!
  \*********************************************************************/
/***/ ((module) => {

if (typeof Object.create === "function") {
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor;
      ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
          value: ctor,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
    }
  };
} else {
  module.exports = function inherits(ctor, superCtor) {
    if (superCtor) {
      ctor.super_ = superCtor;
      var TempCtor = function() {
      };
      TempCtor.prototype = superCtor.prototype;
      ctor.prototype = new TempCtor();
      ctor.prototype.constructor = ctor;
    }
  };
}


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/edit.js":
/*!**************************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/edit.js ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   applyEdit: () => (/* binding */ applyEdit),
/* harmony export */   isWS: () => (/* binding */ isWS),
/* harmony export */   removeProperty: () => (/* binding */ removeProperty),
/* harmony export */   setProperty: () => (/* binding */ setProperty)
/* harmony export */ });
/* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./format */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/format.js");
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./parser */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/parser.js");



function removeProperty(text, path, options) {
  return setProperty(text, path, void 0, options);
}
function setProperty(text, originalPath, value, options) {
  const path = originalPath.slice();
  const errors = [];
  const root = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.parseTree)(text, errors);
  let parent = void 0;
  let lastSegment = void 0;
  while (path.length > 0) {
    lastSegment = path.pop();
    parent = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.findNodeAtLocation)(root, path);
    if (parent === void 0 && value !== void 0) {
      if (typeof lastSegment === "string") {
        value = { [lastSegment]: value };
      } else {
        value = [value];
      }
    } else {
      break;
    }
  }
  if (!parent) {
    if (value === void 0) {
      throw new Error("Can not delete in empty document");
    }
    return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
  } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
    const existing = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.findNodeAtLocation)(parent, [lastSegment]);
    if (existing !== void 0) {
      if (value === void 0) {
        if (!existing.parent) {
          throw new Error("Malformed AST");
        }
        const propertyIndex = parent.children.indexOf(existing.parent);
        let removeBegin;
        let removeEnd = existing.parent.offset + existing.parent.length;
        if (propertyIndex > 0) {
          let previous = parent.children[propertyIndex - 1];
          removeBegin = previous.offset + previous.length;
        } else {
          removeBegin = parent.offset + 1;
          if (parent.children.length > 1) {
            let next = parent.children[1];
            removeEnd = next.offset;
          }
        }
        return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
      } else {
        return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
      }
    } else {
      if (value === void 0) {
        return [];
      }
      const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
      const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
      let edit;
      if (index > 0) {
        let previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      } else if (parent.children.length === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
      }
      return withFormatting(text, edit, options);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    const insertIndex = lastSegment;
    if (insertIndex === -1) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit;
      if (parent.children.length === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        const previous = parent.children[parent.children.length - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return withFormatting(text, edit, options);
    } else if (value === void 0 && parent.children.length >= 0) {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit;
      if (parent.children.length === 1) {
        edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
      } else if (parent.children.length - 1 === removalIndex) {
        let previous = parent.children[removalIndex - 1];
        let offset = previous.offset + previous.length;
        let parentEndOffset = parent.offset + parent.length;
        edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
      } else {
        edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
      }
      return withFormatting(text, edit, options);
    } else if (value !== void 0) {
      let edit;
      const newProperty = `${JSON.stringify(value)}`;
      if (!options.isArrayInsertion && parent.children.length > lastSegment) {
        const toModify = parent.children[lastSegment];
        edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
      } else if (parent.children.length === 0 || lastSegment === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
      } else {
        const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
        const previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return withFormatting(text, edit, options);
    } else {
      throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
    }
  } else {
    throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
  }
}
function withFormatting(text, edit, options) {
  if (!options.formattingOptions) {
    return [edit];
  }
  let newText = applyEdit(text, edit);
  let begin = edit.offset;
  let end = edit.offset + edit.content.length;
  if (edit.length === 0 || edit.content.length === 0) {
    while (begin > 0 && !(0,_format__WEBPACK_IMPORTED_MODULE_0__.isEOL)(newText, begin - 1)) {
      begin--;
    }
    while (end < newText.length && !(0,_format__WEBPACK_IMPORTED_MODULE_0__.isEOL)(newText, end)) {
      end++;
    }
  }
  const edits = (0,_format__WEBPACK_IMPORTED_MODULE_0__.format)(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
  for (let i = edits.length - 1; i >= 0; i--) {
    const edit2 = edits[i];
    newText = applyEdit(newText, edit2);
    begin = Math.min(begin, edit2.offset);
    end = Math.max(end, edit2.offset + edit2.length);
    end += edit2.content.length - edit2.length;
  }
  const editLength = text.length - (newText.length - end) - begin;
  return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
function applyEdit(text, edit) {
  return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
function isWS(text, offset) {
  return "\r\n 	".indexOf(text.charAt(offset)) !== -1;
}


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/format.js":
/*!****************************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/format.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   format: () => (/* binding */ format),
/* harmony export */   isEOL: () => (/* binding */ isEOL)
/* harmony export */ });
/* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scanner */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/scanner.js");
/* harmony import */ var _string_intern__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./string-intern */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/string-intern.js");



function format(documentText, range, options) {
  var _a;
  let initialIndentLevel;
  let formatText;
  let formatTextStart;
  let rangeStart;
  let rangeEnd;
  if (range) {
    rangeStart = range.offset;
    rangeEnd = rangeStart + range.length;
    formatTextStart = rangeStart;
    while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
      formatTextStart--;
    }
    let endOffset = rangeEnd;
    while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
      endOffset++;
    }
    formatText = documentText.substring(formatTextStart, endOffset);
    initialIndentLevel = computeIndentLevel(formatText, options);
  } else {
    formatText = documentText;
    initialIndentLevel = 0;
    formatTextStart = 0;
    rangeStart = 0;
    rangeEnd = documentText.length;
  }
  const eol = getEOL(options, documentText);
  const eolFastPathSupported = _string_intern__WEBPACK_IMPORTED_MODULE_1__.supportedEols.includes(eol);
  let numberLineBreaks = 0;
  let indentLevel = 0;
  let indentValue;
  if (options.insertSpaces) {
    indentValue = (_a = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[options.tabSize || 4]) != null ? _a : repeat(_string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1], options.tabSize || 4);
  } else {
    indentValue = "	";
  }
  const indentType = indentValue === "	" ? "	" : " ";
  let scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(formatText, false);
  let hasError = false;
  function newLinesAndIndent() {
    if (numberLineBreaks > 1) {
      return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
    }
    const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
    if (!eolFastPathSupported || amountOfSpaces > _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedBreakLinesWithSpaces[indentType][eol].length) {
      return eol + repeat(indentValue, initialIndentLevel + indentLevel);
    }
    if (amountOfSpaces <= 0) {
      return eol;
    }
    return _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
  }
  function scanNext() {
    let token = scanner.scan();
    numberLineBreaks = 0;
    while (token === 15 || token === 14) {
      if (token === 14 && options.keepLines) {
        numberLineBreaks += 1;
      } else if (token === 14) {
        numberLineBreaks = 1;
      }
      token = scanner.scan();
    }
    hasError = token === 16 || scanner.getTokenError() !== 0;
    return token;
  }
  const editOperations = [];
  function addEdit(text, startOffset, endOffset) {
    if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
      editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
    }
  }
  let firstToken = scanNext();
  if (options.keepLines && numberLineBreaks > 0) {
    addEdit(repeat(eol, numberLineBreaks), 0, 0);
  }
  if (firstToken !== 17) {
    let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
    let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
    addEdit(initialIndent, formatTextStart, firstTokenStart);
  }
  while (firstToken !== 17) {
    let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
    let secondToken = scanNext();
    let replaceContent = "";
    let needsLineBreak = false;
    while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
      let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
      addEdit(_string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1], firstTokenEnd, commentTokenStart);
      firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
      needsLineBreak = secondToken === 12;
      replaceContent = needsLineBreak ? newLinesAndIndent() : "";
      secondToken = scanNext();
    }
    if (secondToken === 2) {
      if (firstToken !== 1) {
        indentLevel--;
      }
      ;
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
        replaceContent = newLinesAndIndent();
      } else if (options.keepLines) {
        replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
      }
    } else if (secondToken === 4) {
      if (firstToken !== 3) {
        indentLevel--;
      }
      ;
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
        replaceContent = newLinesAndIndent();
      } else if (options.keepLines) {
        replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
      }
    } else {
      switch (firstToken) {
        case 3:
        case 1:
          indentLevel++;
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
            replaceContent = newLinesAndIndent();
          } else {
            replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
          }
          break;
        case 5:
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
            replaceContent = newLinesAndIndent();
          } else {
            replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
          }
          break;
        case 12:
          replaceContent = newLinesAndIndent();
          break;
        case 13:
          if (numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (!needsLineBreak) {
            replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
          }
          break;
        case 6:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (!needsLineBreak) {
            replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
          }
          break;
        case 10:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (secondToken === 6 && !needsLineBreak) {
            replaceContent = "";
          }
          break;
        case 7:
        case 8:
        case 9:
        case 11:
        case 2:
        case 4:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else {
            if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
              replaceContent = _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1];
            } else if (secondToken !== 5 && secondToken !== 17) {
              hasError = true;
            }
          }
          break;
        case 16:
          hasError = true;
          break;
      }
      if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
        replaceContent = newLinesAndIndent();
      }
    }
    if (secondToken === 17) {
      if (options.keepLines && numberLineBreaks > 0) {
        replaceContent = newLinesAndIndent();
      } else {
        replaceContent = options.insertFinalNewline ? eol : "";
      }
    }
    const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
    addEdit(replaceContent, firstTokenEnd, secondTokenStart);
    firstToken = secondToken;
  }
  return editOperations;
}
function repeat(s, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += s;
  }
  return result;
}
function computeIndentLevel(content, options) {
  let i = 0;
  let nChars = 0;
  const tabSize = options.tabSize || 4;
  while (i < content.length) {
    let ch = content.charAt(i);
    if (ch === _string_intern__WEBPACK_IMPORTED_MODULE_1__.cachedSpaces[1]) {
      nChars++;
    } else if (ch === "	") {
      nChars += tabSize;
    } else {
      break;
    }
    i++;
  }
  return Math.floor(nChars / tabSize);
}
function getEOL(options, text) {
  for (let i = 0; i < text.length; i++) {
    const ch = text.charAt(i);
    if (ch === "\r") {
      if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
        return "\r\n";
      }
      return "\r";
    } else if (ch === "\n") {
      return "\n";
    }
  }
  return options && options.eol || "\n";
}
function isEOL(text, offset) {
  return "\r\n".indexOf(text.charAt(offset)) !== -1;
}


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/parser.js":
/*!****************************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/parser.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   contains: () => (/* binding */ contains),
/* harmony export */   findNodeAtLocation: () => (/* binding */ findNodeAtLocation),
/* harmony export */   findNodeAtOffset: () => (/* binding */ findNodeAtOffset),
/* harmony export */   getLocation: () => (/* binding */ getLocation),
/* harmony export */   getNodePath: () => (/* binding */ getNodePath),
/* harmony export */   getNodeType: () => (/* binding */ getNodeType),
/* harmony export */   getNodeValue: () => (/* binding */ getNodeValue),
/* harmony export */   parse: () => (/* binding */ parse),
/* harmony export */   parseTree: () => (/* binding */ parseTree),
/* harmony export */   stripComments: () => (/* binding */ stripComments),
/* harmony export */   visit: () => (/* binding */ visit)
/* harmony export */ });
/* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scanner */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/scanner.js");


var ParseOptions;
(function(ParseOptions2) {
  ParseOptions2.DEFAULT = {
    allowTrailingComma: false
  };
})(ParseOptions || (ParseOptions = {}));
function getLocation(text, position) {
  const segments = [];
  const earlyReturnException = new Object();
  let previousNode = void 0;
  const previousNodeInst = {
    value: {},
    offset: 0,
    length: 0,
    type: "object",
    parent: void 0
  };
  let isAtPropertyKey = false;
  function setPreviousNode(value, offset, length, type) {
    previousNodeInst.value = value;
    previousNodeInst.offset = offset;
    previousNodeInst.length = length;
    previousNodeInst.type = type;
    previousNodeInst.colonOffset = void 0;
    previousNode = previousNodeInst;
  }
  try {
    visit(text, {
      onObjectBegin: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        isAtPropertyKey = position > offset;
        segments.push("");
      },
      onObjectProperty: (name, offset, length) => {
        if (position < offset) {
          throw earlyReturnException;
        }
        setPreviousNode(name, offset, length, "property");
        segments[segments.length - 1] = name;
        if (position <= offset + length) {
          throw earlyReturnException;
        }
      },
      onObjectEnd: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.pop();
      },
      onArrayBegin: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.push(0);
      },
      onArrayEnd: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.pop();
      },
      onLiteralValue: (value, offset, length) => {
        if (position < offset) {
          throw earlyReturnException;
        }
        setPreviousNode(value, offset, length, getNodeType(value));
        if (position <= offset + length) {
          throw earlyReturnException;
        }
      },
      onSeparator: (sep, offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        if (sep === ":" && previousNode && previousNode.type === "property") {
          previousNode.colonOffset = offset;
          isAtPropertyKey = false;
          previousNode = void 0;
        } else if (sep === ",") {
          const last = segments[segments.length - 1];
          if (typeof last === "number") {
            segments[segments.length - 1] = last + 1;
          } else {
            isAtPropertyKey = true;
            segments[segments.length - 1] = "";
          }
          previousNode = void 0;
        }
      }
    });
  } catch (e) {
    if (e !== earlyReturnException) {
      throw e;
    }
  }
  return {
    path: segments,
    previousNode,
    isAtPropertyKey,
    matches: (pattern) => {
      let k = 0;
      for (let i = 0; k < pattern.length && i < segments.length; i++) {
        if (pattern[k] === segments[i] || pattern[k] === "*") {
          k++;
        } else if (pattern[k] !== "**") {
          return false;
        }
      }
      return k === pattern.length;
    }
  };
}
function parse(text, errors = [], options = ParseOptions.DEFAULT) {
  let currentProperty = null;
  let currentParent = [];
  const previousParents = [];
  function onValue(value) {
    if (Array.isArray(currentParent)) {
      currentParent.push(value);
    } else if (currentProperty !== null) {
      currentParent[currentProperty] = value;
    }
  }
  const visitor = {
    onObjectBegin: () => {
      const object = {};
      onValue(object);
      previousParents.push(currentParent);
      currentParent = object;
      currentProperty = null;
    },
    onObjectProperty: (name) => {
      currentProperty = name;
    },
    onObjectEnd: () => {
      currentParent = previousParents.pop();
    },
    onArrayBegin: () => {
      const array = [];
      onValue(array);
      previousParents.push(currentParent);
      currentParent = array;
      currentProperty = null;
    },
    onArrayEnd: () => {
      currentParent = previousParents.pop();
    },
    onLiteralValue: onValue,
    onError: (error, offset, length) => {
      errors.push({ error, offset, length });
    }
  };
  visit(text, visitor, options);
  return currentParent[0];
}
function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
  let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
  function ensurePropertyComplete(endOffset) {
    if (currentParent.type === "property") {
      currentParent.length = endOffset - currentParent.offset;
      currentParent = currentParent.parent;
    }
  }
  function onValue(valueNode) {
    currentParent.children.push(valueNode);
    return valueNode;
  }
  const visitor = {
    onObjectBegin: (offset) => {
      currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
    },
    onObjectProperty: (name, offset, length) => {
      currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
      currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
    },
    onObjectEnd: (offset, length) => {
      ensurePropertyComplete(offset + length);
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    },
    onArrayBegin: (offset, length) => {
      currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
    },
    onArrayEnd: (offset, length) => {
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    },
    onLiteralValue: (value, offset, length) => {
      onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
      ensurePropertyComplete(offset + length);
    },
    onSeparator: (sep, offset, length) => {
      if (currentParent.type === "property") {
        if (sep === ":") {
          currentParent.colonOffset = offset;
        } else if (sep === ",") {
          ensurePropertyComplete(offset);
        }
      }
    },
    onError: (error, offset, length) => {
      errors.push({ error, offset, length });
    }
  };
  visit(text, visitor, options);
  const result = currentParent.children[0];
  if (result) {
    delete result.parent;
  }
  return result;
}
function findNodeAtLocation(root, path) {
  if (!root) {
    return void 0;
  }
  let node = root;
  for (let segment of path) {
    if (typeof segment === "string") {
      if (node.type !== "object" || !Array.isArray(node.children)) {
        return void 0;
      }
      let found = false;
      for (const propertyNode of node.children) {
        if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
          node = propertyNode.children[1];
          found = true;
          break;
        }
      }
      if (!found) {
        return void 0;
      }
    } else {
      const index = segment;
      if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
        return void 0;
      }
      node = node.children[index];
    }
  }
  return node;
}
function getNodePath(node) {
  if (!node.parent || !node.parent.children) {
    return [];
  }
  const path = getNodePath(node.parent);
  if (node.parent.type === "property") {
    const key = node.parent.children[0].value;
    path.push(key);
  } else if (node.parent.type === "array") {
    const index = node.parent.children.indexOf(node);
    if (index !== -1) {
      path.push(index);
    }
  }
  return path;
}
function getNodeValue(node) {
  switch (node.type) {
    case "array":
      return node.children.map(getNodeValue);
    case "object":
      const obj = /* @__PURE__ */ Object.create(null);
      for (let prop of node.children) {
        const valueNode = prop.children[1];
        if (valueNode) {
          obj[prop.children[0].value] = getNodeValue(valueNode);
        }
      }
      return obj;
    case "null":
    case "string":
    case "number":
    case "boolean":
      return node.value;
    default:
      return void 0;
  }
}
function contains(node, offset, includeRightBound = false) {
  return offset >= node.offset && offset < node.offset + node.length || includeRightBound && offset === node.offset + node.length;
}
function findNodeAtOffset(node, offset, includeRightBound = false) {
  if (contains(node, offset, includeRightBound)) {
    const children = node.children;
    if (Array.isArray(children)) {
      for (let i = 0; i < children.length && children[i].offset <= offset; i++) {
        const item = findNodeAtOffset(children[i], offset, includeRightBound);
        if (item) {
          return item;
        }
      }
    }
    return node;
  }
  return void 0;
}
function visit(text, visitor, options = ParseOptions.DEFAULT) {
  const _scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(text, false);
  const _jsonPath = [];
  function toNoArgVisit(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  function toNoArgVisitWithPath(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  function toOneArgVisit(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  function toOneArgVisitWithPath(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  const disallowComments = options && options.disallowComments;
  const allowTrailingComma = options && options.allowTrailingComma;
  function scanNext() {
    while (true) {
      const token = _scanner.scan();
      switch (_scanner.getTokenError()) {
        case 4:
          handleError(
            14
            /* ParseErrorCode.InvalidUnicode */
          );
          break;
        case 5:
          handleError(
            15
            /* ParseErrorCode.InvalidEscapeCharacter */
          );
          break;
        case 3:
          handleError(
            13
            /* ParseErrorCode.UnexpectedEndOfNumber */
          );
          break;
        case 1:
          if (!disallowComments) {
            handleError(
              11
              /* ParseErrorCode.UnexpectedEndOfComment */
            );
          }
          break;
        case 2:
          handleError(
            12
            /* ParseErrorCode.UnexpectedEndOfString */
          );
          break;
        case 6:
          handleError(
            16
            /* ParseErrorCode.InvalidCharacter */
          );
          break;
      }
      switch (token) {
        case 12:
        case 13:
          if (disallowComments) {
            handleError(
              10
              /* ParseErrorCode.InvalidCommentToken */
            );
          } else {
            onComment();
          }
          break;
        case 16:
          handleError(
            1
            /* ParseErrorCode.InvalidSymbol */
          );
          break;
        case 15:
        case 14:
          break;
        default:
          return token;
      }
    }
  }
  function handleError(error, skipUntilAfter = [], skipUntil = []) {
    onError(error);
    if (skipUntilAfter.length + skipUntil.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        if (skipUntilAfter.indexOf(token) !== -1) {
          scanNext();
          break;
        } else if (skipUntil.indexOf(token) !== -1) {
          break;
        }
        token = scanNext();
      }
    }
  }
  function parseString(isValue) {
    const value = _scanner.getTokenValue();
    if (isValue) {
      onLiteralValue(value);
    } else {
      onObjectProperty(value);
      _jsonPath.push(value);
    }
    scanNext();
    return true;
  }
  function parseLiteral() {
    switch (_scanner.getToken()) {
      case 11:
        const tokenValue = _scanner.getTokenValue();
        let value = Number(tokenValue);
        if (isNaN(value)) {
          handleError(
            2
            /* ParseErrorCode.InvalidNumberFormat */
          );
          value = 0;
        }
        onLiteralValue(value);
        break;
      case 7:
        onLiteralValue(null);
        break;
      case 8:
        onLiteralValue(true);
        break;
      case 9:
        onLiteralValue(false);
        break;
      default:
        return false;
    }
    scanNext();
    return true;
  }
  function parseProperty() {
    if (_scanner.getToken() !== 10) {
      handleError(3, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
      return false;
    }
    parseString(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
    } else {
      handleError(5, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
    }
    _jsonPath.pop();
    return true;
  }
  function parseObject() {
    onObjectBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 2 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseProperty()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onObjectEnd();
    if (_scanner.getToken() !== 2) {
      handleError(7, [
        2
        /* SyntaxKind.CloseBraceToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseArray() {
    onArrayBegin();
    scanNext();
    let isFirstElement = true;
    let needsComma = false;
    while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 4 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (isFirstElement) {
        _jsonPath.push(0);
        isFirstElement = false;
      } else {
        _jsonPath[_jsonPath.length - 1]++;
      }
      if (!parseValue()) {
        handleError(4, [], [
          4,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onArrayEnd();
    if (!isFirstElement) {
      _jsonPath.pop();
    }
    if (_scanner.getToken() !== 4) {
      handleError(8, [
        4
        /* SyntaxKind.CloseBracketToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  function parseValue() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray();
      case 1:
        return parseObject();
      case 10:
        return parseString(true);
      default:
        return parseLiteral();
    }
  }
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) {
    handleError(9, [], []);
  }
  return true;
}
function stripComments(text, replaceCh) {
  let _scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(text), parts = [], kind, offset = 0, pos;
  do {
    pos = _scanner.getPosition();
    kind = _scanner.scan();
    switch (kind) {
      case 12:
      case 13:
      case 17:
        if (offset !== pos) {
          parts.push(text.substring(offset, pos));
        }
        if (replaceCh !== void 0) {
          parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
        }
        offset = _scanner.getPosition();
        break;
    }
  } while (kind !== 17);
  return parts.join("");
}
function getNodeType(value) {
  switch (typeof value) {
    case "boolean":
      return "boolean";
    case "number":
      return "number";
    case "string":
      return "string";
    case "object": {
      if (!value) {
        return "null";
      } else if (Array.isArray(value)) {
        return "array";
      }
      return "object";
    }
    default:
      return "null";
  }
}


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/scanner.js":
/*!*****************************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/scanner.js ***!
  \*****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createScanner: () => (/* binding */ createScanner)
/* harmony export */ });

function createScanner(text, ignoreTrivia = false) {
  const len = text.length;
  let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
  function scanHexDigits(count, exact) {
    let digits = 0;
    let value2 = 0;
    while (digits < count || !exact) {
      let ch = text.charCodeAt(pos);
      if (ch >= 48 && ch <= 57) {
        value2 = value2 * 16 + ch - 48;
      } else if (ch >= 65 && ch <= 70) {
        value2 = value2 * 16 + ch - 65 + 10;
      } else if (ch >= 97 && ch <= 102) {
        value2 = value2 * 16 + ch - 97 + 10;
      } else {
        break;
      }
      pos++;
      digits++;
    }
    if (digits < count) {
      value2 = -1;
    }
    return value2;
  }
  function setPosition(newPosition) {
    pos = newPosition;
    value = "";
    tokenOffset = 0;
    token = 16;
    scanError = 0;
  }
  function scanNumber() {
    let start = pos;
    if (text.charCodeAt(pos) === 48) {
      pos++;
    } else {
      pos++;
      while (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
      }
    }
    if (pos < text.length && text.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
      } else {
        scanError = 3;
        return text.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
        pos++;
      }
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
        end = pos;
      } else {
        scanError = 3;
      }
    }
    return text.substring(start, end);
  }
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text.charCodeAt(pos);
      if (ch === 34) {
        result += text.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        const ch2 = text.charCodeAt(pos++);
        switch (ch2) {
          case 34:
            result += '"';
            break;
          case 92:
            result += "\\";
            break;
          case 47:
            result += "/";
            break;
          case 98:
            result += "\b";
            break;
          case 102:
            result += "\f";
            break;
          case 110:
            result += "\n";
            break;
          case 114:
            result += "\r";
            break;
          case 116:
            result += "	";
            break;
          case 117:
            const ch3 = scanHexDigits(4, true);
            if (ch3 >= 0) {
              result += String.fromCharCode(ch3);
            } else {
              scanError = 4;
            }
            break;
          default:
            scanError = 5;
        }
        start = pos;
        continue;
      }
      if (ch >= 0 && ch <= 31) {
        if (isLineBreak(ch)) {
          result += text.substring(start, pos);
          scanError = 2;
          break;
        } else {
          scanError = 6;
        }
      }
      pos++;
    }
    return result;
  }
  function scanNext() {
    value = "";
    scanError = 0;
    tokenOffset = pos;
    lineStartOffset = lineNumber;
    prevTokenLineStartOffset = tokenLineStartOffset;
    if (pos >= len) {
      tokenOffset = len;
      return token = 17;
    }
    let code = text.charCodeAt(pos);
    if (isWhiteSpace(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text.charCodeAt(pos);
      } while (isWhiteSpace(code));
      return token = 15;
    }
    if (isLineBreak(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      lineNumber++;
      tokenLineStartOffset = pos;
      return token = 14;
    }
    switch (code) {
      case 123:
        pos++;
        return token = 1;
      case 125:
        pos++;
        return token = 2;
      case 91:
        pos++;
        return token = 3;
      case 93:
        pos++;
        return token = 4;
      case 58:
        pos++;
        return token = 6;
      case 44:
        pos++;
        return token = 5;
      case 34:
        pos++;
        value = scanString();
        return token = 10;
      case 47:
        const start = pos - 1;
        if (text.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak(text.charCodeAt(pos))) {
              break;
            }
            pos++;
          }
          value = text.substring(start, pos);
          return token = 12;
        }
        if (text.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text.charCodeAt(pos);
            if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
            if (isLineBreak(ch)) {
              if (ch === 13 && text.charCodeAt(pos) === 10) {
                pos++;
              }
              lineNumber++;
              tokenLineStartOffset = pos;
            }
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text.substring(start, pos);
          return token = 13;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
      case 45:
        value += String.fromCharCode(code);
        pos++;
        if (pos === len || !isDigit(text.charCodeAt(pos))) {
          return token = 16;
        }
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        value += scanNumber();
        return token = 11;
      default:
        while (pos < len && isUnknownContentCharacter(code)) {
          pos++;
          code = text.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text.substring(tokenOffset, pos);
          switch (value) {
            case "true":
              return token = 8;
            case "false":
              return token = 9;
            case "null":
              return token = 7;
          }
          return token = 16;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
    }
  }
  function isUnknownContentCharacter(code) {
    if (isWhiteSpace(code) || isLineBreak(code)) {
      return false;
    }
    switch (code) {
      case 125:
      case 93:
      case 123:
      case 91:
      case 34:
      case 58:
      case 44:
      case 47:
        return false;
    }
    return true;
  }
  function scanNextNonTrivia() {
    let result;
    do {
      result = scanNext();
    } while (result >= 12 && result <= 15);
    return result;
  }
  return {
    setPosition,
    getPosition: () => pos,
    scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
    getToken: () => token,
    getTokenValue: () => value,
    getTokenOffset: () => tokenOffset,
    getTokenLength: () => pos - tokenOffset,
    getTokenStartLine: () => lineStartOffset,
    getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
    getTokenError: () => scanError
  };
}
function isWhiteSpace(ch) {
  return ch === 32 || ch === 9;
}
function isLineBreak(ch) {
  return ch === 10 || ch === 13;
}
function isDigit(ch) {
  return ch >= 48 && ch <= 57;
}
var CharacterCodes;
(function(CharacterCodes2) {
  CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
  CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
  CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
  CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
  CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
  CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
  CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
  CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
  CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
  CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
  CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
  CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
  CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
  CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
  CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
  CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
  CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
  CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
  CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
  CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
  CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
  CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
  CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
  CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
  CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
  CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
  CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
  CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
  CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
  CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
  CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
  CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
  CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
  CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
  CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
  CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
  CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
  CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
  CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
  CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
  CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
  CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
  CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
  CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
  CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
  CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
  CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
  CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
  CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
  CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
  CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
  CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
  CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
  CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
  CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
  CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
  CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
  CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
  CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
  CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
  CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
  CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
  CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
  CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
  CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
  CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
  CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
  CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
  CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
  CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
  CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
  CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
  CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
  CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
  CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
  CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
  CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
  CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
})(CharacterCodes || (CharacterCodes = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/string-intern.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/string-intern.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   cachedBreakLinesWithSpaces: () => (/* binding */ cachedBreakLinesWithSpaces),
/* harmony export */   cachedSpaces: () => (/* binding */ cachedSpaces),
/* harmony export */   supportedEols: () => (/* binding */ supportedEols)
/* harmony export */ });
const cachedSpaces = new Array(20).fill(0).map((_, index) => {
  return " ".repeat(index);
});
const maxCachedValues = 200;
const cachedBreakLinesWithSpaces = {
  " ": {
    "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\n" + " ".repeat(index);
    }),
    "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\r" + " ".repeat(index);
    }),
    "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\r\n" + " ".repeat(index);
    })
  },
  "	": {
    "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\n" + "	".repeat(index);
    }),
    "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\r" + "	".repeat(index);
    }),
    "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
      return "\r\n" + "	".repeat(index);
    })
  }
};
const supportedEols = ["\n", "\r", "\r\n"];


/***/ }),

/***/ "../pyright-internal/node_modules/jsonc-parser/lib/esm/main.js":
/*!*********************************************************************!*\
  !*** ../pyright-internal/node_modules/jsonc-parser/lib/esm/main.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ParseErrorCode: () => (/* binding */ ParseErrorCode),
/* harmony export */   ScanError: () => (/* binding */ ScanError),
/* harmony export */   SyntaxKind: () => (/* binding */ SyntaxKind),
/* harmony export */   applyEdits: () => (/* binding */ applyEdits),
/* harmony export */   createScanner: () => (/* binding */ createScanner),
/* harmony export */   findNodeAtLocation: () => (/* binding */ findNodeAtLocation),
/* harmony export */   findNodeAtOffset: () => (/* binding */ findNodeAtOffset),
/* harmony export */   format: () => (/* binding */ format),
/* harmony export */   getLocation: () => (/* binding */ getLocation),
/* harmony export */   getNodePath: () => (/* binding */ getNodePath),
/* harmony export */   getNodeValue: () => (/* binding */ getNodeValue),
/* harmony export */   modify: () => (/* binding */ modify),
/* harmony export */   parse: () => (/* binding */ parse),
/* harmony export */   parseTree: () => (/* binding */ parseTree),
/* harmony export */   printParseErrorCode: () => (/* binding */ printParseErrorCode),
/* harmony export */   stripComments: () => (/* binding */ stripComments),
/* harmony export */   visit: () => (/* binding */ visit)
/* harmony export */ });
/* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./impl/format */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/format.js");
/* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./impl/edit */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/edit.js");
/* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./impl/scanner */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/scanner.js");
/* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./impl/parser */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/impl/parser.js");





const createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__.createScanner;
var ScanError;
(function(ScanError2) {
  ScanError2[ScanError2["None"] = 0] = "None";
  ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
var SyntaxKind;
(function(SyntaxKind2) {
  SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
  SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
  SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
  SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
  SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
const getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.getLocation;
const parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.parse;
const parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.parseTree;
const findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.findNodeAtLocation;
const findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.findNodeAtOffset;
const getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.getNodePath;
const getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.getNodeValue;
const visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.visit;
const stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__.stripComments;
var ParseErrorCode;
(function(ParseErrorCode2) {
  ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
function printParseErrorCode(code) {
  switch (code) {
    case 1:
      return "InvalidSymbol";
    case 2:
      return "InvalidNumberFormat";
    case 3:
      return "PropertyNameExpected";
    case 4:
      return "ValueExpected";
    case 5:
      return "ColonExpected";
    case 6:
      return "CommaExpected";
    case 7:
      return "CloseBraceExpected";
    case 8:
      return "CloseBracketExpected";
    case 9:
      return "EndOfFileExpected";
    case 10:
      return "InvalidCommentToken";
    case 11:
      return "UnexpectedEndOfComment";
    case 12:
      return "UnexpectedEndOfString";
    case 13:
      return "UnexpectedEndOfNumber";
    case 14:
      return "InvalidUnicode";
    case 15:
      return "InvalidEscapeCharacter";
    case 16:
      return "InvalidCharacter";
  }
  return "<unknown ParseErrorCode>";
}
function format(documentText, range, options) {
  return _impl_format__WEBPACK_IMPORTED_MODULE_0__.format(documentText, range, options);
}
function modify(text, path, value, options) {
  return _impl_edit__WEBPACK_IMPORTED_MODULE_1__.setProperty(text, path, value, options);
}
function applyEdits(text, edits) {
  let sortedEdits = edits.slice(0).sort((a, b) => {
    const diff = a.offset - b.offset;
    if (diff === 0) {
      return a.length - b.length;
    }
    return diff;
  });
  let lastModifiedOffset = text.length;
  for (let i = sortedEdits.length - 1; i >= 0; i--) {
    let e = sortedEdits[i];
    if (e.offset + e.length <= lastModifiedOffset) {
      text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__.applyEdit(text, e);
    } else {
      throw new Error("Overlapping edit");
    }
    lastModifiedOffset = e.offset;
  }
  return text;
}


/***/ }),

/***/ "../pyright-internal/node_modules/leven/index.js":
/*!*******************************************************!*\
  !*** ../pyright-internal/node_modules/leven/index.js ***!
  \*******************************************************/
/***/ ((module) => {

"use strict";

const array = [];
const charCodeCache = [];
const leven = (left, right) => {
  if (left === right) {
    return 0;
  }
  const swap = left;
  if (left.length > right.length) {
    left = right;
    right = swap;
  }
  let leftLength = left.length;
  let rightLength = right.length;
  while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
    leftLength--;
    rightLength--;
  }
  let start = 0;
  while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
    start++;
  }
  leftLength -= start;
  rightLength -= start;
  if (leftLength === 0) {
    return rightLength;
  }
  let bCharCode;
  let result;
  let temp;
  let temp2;
  let i = 0;
  let j = 0;
  while (i < leftLength) {
    charCodeCache[i] = left.charCodeAt(start + i);
    array[i] = ++i;
  }
  while (j < rightLength) {
    bCharCode = right.charCodeAt(start + j);
    temp = j++;
    result = j;
    for (i = 0; i < leftLength; i++) {
      temp2 = bCharCode === charCodeCache[i] ? temp : temp + 1;
      temp = array[i];
      result = array[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
    }
  }
  return result;
};
module.exports = leven;
module.exports["default"] = leven;


/***/ }),

/***/ "../pyright-internal/node_modules/minimatch/minimatch.js":
/*!***************************************************************!*\
  !*** ../pyright-internal/node_modules/minimatch/minimatch.js ***!
  \***************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = minimatch;
minimatch.Minimatch = Minimatch;
var path = function() {
  try {
    return __webpack_require__(/*! path */ "path");
  } catch (e) {
  }
}() || {
  sep: "/"
};
minimatch.sep = path.sep;
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
var expand = __webpack_require__(/*! brace-expansion */ "../pyright-internal/node_modules/brace-expansion/index.js");
var plTypes = {
  "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
  "?": { open: "(?:", close: ")?" },
  "+": { open: "(?:", close: ")+" },
  "*": { open: "(?:", close: ")*" },
  "@": { open: "(?:", close: ")" }
};
var qmark = "[^/]";
var star = qmark + "*?";
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
var reSpecials = charSet("().*{}+?[]^$\\!");
function charSet(s) {
  return s.split("").reduce(function(set, c) {
    set[c] = true;
    return set;
  }, {});
}
var slashSplit = /\/+/;
minimatch.filter = filter;
function filter(pattern, options) {
  options = options || {};
  return function(p, i, list) {
    return minimatch(p, pattern, options);
  };
}
function ext(a, b) {
  b = b || {};
  var t = {};
  Object.keys(a).forEach(function(k) {
    t[k] = a[k];
  });
  Object.keys(b).forEach(function(k) {
    t[k] = b[k];
  });
  return t;
}
minimatch.defaults = function(def) {
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
    return minimatch;
  }
  var orig = minimatch;
  var m = function minimatch2(p, pattern, options) {
    return orig(p, pattern, ext(def, options));
  };
  m.Minimatch = function Minimatch2(pattern, options) {
    return new orig.Minimatch(pattern, ext(def, options));
  };
  m.Minimatch.defaults = function defaults(options) {
    return orig.defaults(ext(def, options)).Minimatch;
  };
  m.filter = function filter2(pattern, options) {
    return orig.filter(pattern, ext(def, options));
  };
  m.defaults = function defaults(options) {
    return orig.defaults(ext(def, options));
  };
  m.makeRe = function makeRe2(pattern, options) {
    return orig.makeRe(pattern, ext(def, options));
  };
  m.braceExpand = function braceExpand2(pattern, options) {
    return orig.braceExpand(pattern, ext(def, options));
  };
  m.match = function(list, pattern, options) {
    return orig.match(list, pattern, ext(def, options));
  };
  return m;
};
Minimatch.defaults = function(def) {
  return minimatch.defaults(def).Minimatch;
};
function minimatch(p, pattern, options) {
  assertValidPattern(pattern);
  if (!options)
    options = {};
  if (!options.nocomment && pattern.charAt(0) === "#") {
    return false;
  }
  return new Minimatch(pattern, options).match(p);
}
function Minimatch(pattern, options) {
  if (!(this instanceof Minimatch)) {
    return new Minimatch(pattern, options);
  }
  assertValidPattern(pattern);
  if (!options)
    options = {};
  pattern = pattern.trim();
  if (!options.allowWindowsEscape && path.sep !== "/") {
    pattern = pattern.split(path.sep).join("/");
  }
  this.options = options;
  this.set = [];
  this.pattern = pattern;
  this.regexp = null;
  this.negate = false;
  this.comment = false;
  this.empty = false;
  this.partial = !!options.partial;
  this.make();
}
Minimatch.prototype.debug = function() {
};
Minimatch.prototype.make = make;
function make() {
  var pattern = this.pattern;
  var options = this.options;
  if (!options.nocomment && pattern.charAt(0) === "#") {
    this.comment = true;
    return;
  }
  if (!pattern) {
    this.empty = true;
    return;
  }
  this.parseNegate();
  var set = this.globSet = this.braceExpand();
  if (options.debug)
    this.debug = function debug() {
      console.error.apply(console, arguments);
    };
  this.debug(this.pattern, set);
  set = this.globParts = set.map(function(s) {
    return s.split(slashSplit);
  });
  this.debug(this.pattern, set);
  set = set.map(function(s, si, set2) {
    return s.map(this.parse, this);
  }, this);
  this.debug(this.pattern, set);
  set = set.filter(function(s) {
    return s.indexOf(false) === -1;
  });
  this.debug(this.pattern, set);
  this.set = set;
}
Minimatch.prototype.parseNegate = parseNegate;
function parseNegate() {
  var pattern = this.pattern;
  var negate = false;
  var options = this.options;
  var negateOffset = 0;
  if (options.nonegate)
    return;
  for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
    negate = !negate;
    negateOffset++;
  }
  if (negateOffset)
    this.pattern = pattern.substr(negateOffset);
  this.negate = negate;
}
minimatch.braceExpand = function(pattern, options) {
  return braceExpand(pattern, options);
};
Minimatch.prototype.braceExpand = braceExpand;
function braceExpand(pattern, options) {
  if (!options) {
    if (this instanceof Minimatch) {
      options = this.options;
    } else {
      options = {};
    }
  }
  pattern = typeof pattern === "undefined" ? this.pattern : pattern;
  assertValidPattern(pattern);
  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
    return [pattern];
  }
  return expand(pattern);
}
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = function(pattern) {
  if (typeof pattern !== "string") {
    throw new TypeError("invalid pattern");
  }
  if (pattern.length > MAX_PATTERN_LENGTH) {
    throw new TypeError("pattern is too long");
  }
};
Minimatch.prototype.parse = parse;
var SUBPARSE = {};
function parse(pattern, isSub) {
  assertValidPattern(pattern);
  var options = this.options;
  if (pattern === "**") {
    if (!options.noglobstar)
      return GLOBSTAR;
    else
      pattern = "*";
  }
  if (pattern === "")
    return "";
  var re = "";
  var hasMagic = !!options.nocase;
  var escaping = false;
  var patternListStack = [];
  var negativeLists = [];
  var stateChar;
  var inClass = false;
  var reClassStart = -1;
  var classStart = -1;
  var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  var self = this;
  function clearStateChar() {
    if (stateChar) {
      switch (stateChar) {
        case "*":
          re += star;
          hasMagic = true;
          break;
        case "?":
          re += qmark;
          hasMagic = true;
          break;
        default:
          re += "\\" + stateChar;
          break;
      }
      self.debug("clearStateChar %j %j", stateChar, re);
      stateChar = false;
    }
  }
  for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
    this.debug("%s	%s %s %j", pattern, i, re, c);
    if (escaping && reSpecials[c]) {
      re += "\\" + c;
      escaping = false;
      continue;
    }
    switch (c) {
      case "/": {
        return false;
      }
      case "\\":
        clearStateChar();
        escaping = true;
        continue;
      case "?":
      case "*":
      case "+":
      case "@":
      case "!":
        this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
        if (inClass) {
          this.debug("  in class");
          if (c === "!" && i === classStart + 1)
            c = "^";
          re += c;
          continue;
        }
        self.debug("call clearStateChar %j", stateChar);
        clearStateChar();
        stateChar = c;
        if (options.noext)
          clearStateChar();
        continue;
      case "(":
        if (inClass) {
          re += "(";
          continue;
        }
        if (!stateChar) {
          re += "\\(";
          continue;
        }
        patternListStack.push({
          type: stateChar,
          start: i - 1,
          reStart: re.length,
          open: plTypes[stateChar].open,
          close: plTypes[stateChar].close
        });
        re += stateChar === "!" ? "(?:(?!(?:" : "(?:";
        this.debug("plType %j %j", stateChar, re);
        stateChar = false;
        continue;
      case ")":
        if (inClass || !patternListStack.length) {
          re += "\\)";
          continue;
        }
        clearStateChar();
        hasMagic = true;
        var pl = patternListStack.pop();
        re += pl.close;
        if (pl.type === "!") {
          negativeLists.push(pl);
        }
        pl.reEnd = re.length;
        continue;
      case "|":
        if (inClass || !patternListStack.length || escaping) {
          re += "\\|";
          escaping = false;
          continue;
        }
        clearStateChar();
        re += "|";
        continue;
      case "[":
        clearStateChar();
        if (inClass) {
          re += "\\" + c;
          continue;
        }
        inClass = true;
        classStart = i;
        reClassStart = re.length;
        re += c;
        continue;
      case "]":
        if (i === classStart + 1 || !inClass) {
          re += "\\" + c;
          escaping = false;
          continue;
        }
        var cs = pattern.substring(classStart + 1, i);
        try {
          RegExp("[" + cs + "]");
        } catch (er) {
          var sp = this.parse(cs, SUBPARSE);
          re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]";
          hasMagic = hasMagic || sp[1];
          inClass = false;
          continue;
        }
        hasMagic = true;
        inClass = false;
        re += c;
        continue;
      default:
        clearStateChar();
        if (escaping) {
          escaping = false;
        } else if (reSpecials[c] && !(c === "^" && inClass)) {
          re += "\\";
        }
        re += c;
    }
  }
  if (inClass) {
    cs = pattern.substr(classStart + 1);
    sp = this.parse(cs, SUBPARSE);
    re = re.substr(0, reClassStart) + "\\[" + sp[0];
    hasMagic = hasMagic || sp[1];
  }
  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
    var tail = re.slice(pl.reStart + pl.open.length);
    this.debug("setting tail", re, pl);
    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_, $1, $2) {
      if (!$2) {
        $2 = "\\";
      }
      return $1 + $1 + $2 + "|";
    });
    this.debug("tail=%j\n   %s", tail, tail, pl, re);
    var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
    hasMagic = true;
    re = re.slice(0, pl.reStart) + t + "\\(" + tail;
  }
  clearStateChar();
  if (escaping) {
    re += "\\\\";
  }
  var addPatternStart = false;
  switch (re.charAt(0)) {
    case "[":
    case ".":
    case "(":
      addPatternStart = true;
  }
  for (var n = negativeLists.length - 1; n > -1; n--) {
    var nl = negativeLists[n];
    var nlBefore = re.slice(0, nl.reStart);
    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
    var nlAfter = re.slice(nl.reEnd);
    nlLast += nlAfter;
    var openParensBefore = nlBefore.split("(").length - 1;
    var cleanAfter = nlAfter;
    for (i = 0; i < openParensBefore; i++) {
      cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
    }
    nlAfter = cleanAfter;
    var dollar = "";
    if (nlAfter === "" && isSub !== SUBPARSE) {
      dollar = "$";
    }
    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
    re = newRe;
  }
  if (re !== "" && hasMagic) {
    re = "(?=.)" + re;
  }
  if (addPatternStart) {
    re = patternStart + re;
  }
  if (isSub === SUBPARSE) {
    return [re, hasMagic];
  }
  if (!hasMagic) {
    return globUnescape(pattern);
  }
  var flags = options.nocase ? "i" : "";
  try {
    var regExp = new RegExp("^" + re + "$", flags);
  } catch (er) {
    return new RegExp("$.");
  }
  regExp._glob = pattern;
  regExp._src = re;
  return regExp;
}
minimatch.makeRe = function(pattern, options) {
  return new Minimatch(pattern, options || {}).makeRe();
};
Minimatch.prototype.makeRe = makeRe;
function makeRe() {
  if (this.regexp || this.regexp === false)
    return this.regexp;
  var set = this.set;
  if (!set.length) {
    this.regexp = false;
    return this.regexp;
  }
  var options = this.options;
  var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
  var flags = options.nocase ? "i" : "";
  var re = set.map(function(pattern) {
    return pattern.map(function(p) {
      return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
    }).join("\\/");
  }).join("|");
  re = "^(?:" + re + ")$";
  if (this.negate)
    re = "^(?!" + re + ").*$";
  try {
    this.regexp = new RegExp(re, flags);
  } catch (ex) {
    this.regexp = false;
  }
  return this.regexp;
}
minimatch.match = function(list, pattern, options) {
  options = options || {};
  var mm = new Minimatch(pattern, options);
  list = list.filter(function(f) {
    return mm.match(f);
  });
  if (mm.options.nonull && !list.length) {
    list.push(pattern);
  }
  return list;
};
Minimatch.prototype.match = function match(f, partial) {
  if (typeof partial === "undefined")
    partial = this.partial;
  this.debug("match", f, this.pattern);
  if (this.comment)
    return false;
  if (this.empty)
    return f === "";
  if (f === "/" && partial)
    return true;
  var options = this.options;
  if (path.sep !== "/") {
    f = f.split(path.sep).join("/");
  }
  f = f.split(slashSplit);
  this.debug(this.pattern, "split", f);
  var set = this.set;
  this.debug(this.pattern, "set", set);
  var filename;
  var i;
  for (i = f.length - 1; i >= 0; i--) {
    filename = f[i];
    if (filename)
      break;
  }
  for (i = 0; i < set.length; i++) {
    var pattern = set[i];
    var file = f;
    if (options.matchBase && pattern.length === 1) {
      file = [filename];
    }
    var hit = this.matchOne(file, pattern, partial);
    if (hit) {
      if (options.flipNegate)
        return true;
      return !this.negate;
    }
  }
  if (options.flipNegate)
    return false;
  return this.negate;
};
Minimatch.prototype.matchOne = function(file, pattern, partial) {
  var options = this.options;
  this.debug(
    "matchOne",
    { "this": this, file, pattern }
  );
  this.debug("matchOne", file.length, pattern.length);
  for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
    this.debug("matchOne loop");
    var p = pattern[pi];
    var f = file[fi];
    this.debug(pattern, p, f);
    if (p === false)
      return false;
    if (p === GLOBSTAR) {
      this.debug("GLOBSTAR", [pattern, p, f]);
      var fr = fi;
      var pr = pi + 1;
      if (pr === pl) {
        this.debug("** at the end");
        for (; fi < fl; fi++) {
          if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
            return false;
        }
        return true;
      }
      while (fr < fl) {
        var swallowee = file[fr];
        this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
          this.debug("globstar found match!", fr, fl, swallowee);
          return true;
        } else {
          if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
            this.debug("dot detected!", file, fr, pattern, pr);
            break;
          }
          this.debug("globstar swallow a segment, and continue");
          fr++;
        }
      }
      if (partial) {
        this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
        if (fr === fl)
          return true;
      }
      return false;
    }
    var hit;
    if (typeof p === "string") {
      hit = f === p;
      this.debug("string match", p, f, hit);
    } else {
      hit = f.match(p);
      this.debug("pattern match", p, f, hit);
    }
    if (!hit)
      return false;
  }
  if (fi === fl && pi === pl) {
    return true;
  } else if (fi === fl) {
    return partial;
  } else if (pi === pl) {
    return fi === fl - 1 && file[fi] === "";
  }
  throw new Error("wtf?");
};
function globUnescape(s) {
  return s.replace(/\\(.)/g, "$1");
}
function regExpEscape(s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}


/***/ }),

/***/ "../pyright-internal/node_modules/once/once.js":
/*!*****************************************************!*\
  !*** ../pyright-internal/node_modules/once/once.js ***!
  \*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var wrappy = __webpack_require__(/*! wrappy */ "../pyright-internal/node_modules/wrappy/wrappy.js");
module.exports = wrappy(once);
module.exports.strict = wrappy(onceStrict);
once.proto = once(function() {
  Object.defineProperty(Function.prototype, "once", {
    value: function() {
      return once(this);
    },
    configurable: true
  });
  Object.defineProperty(Function.prototype, "onceStrict", {
    value: function() {
      return onceStrict(this);
    },
    configurable: true
  });
});
function once(fn) {
  var f = function() {
    if (f.called)
      return f.value;
    f.called = true;
    return f.value = fn.apply(this, arguments);
  };
  f.called = false;
  return f;
}
function onceStrict(fn) {
  var f = function() {
    if (f.called)
      throw new Error(f.onceError);
    f.called = true;
    return f.value = fn.apply(this, arguments);
  };
  var name = fn.name || "Function wrapped with `once`";
  f.onceError = name + " shouldn't be called more than once";
  f.called = false;
  return f;
}


/***/ }),

/***/ "../pyright-internal/node_modules/path-is-absolute/index.js":
/*!******************************************************************!*\
  !*** ../pyright-internal/node_modules/path-is-absolute/index.js ***!
  \******************************************************************/
/***/ ((module) => {

"use strict";

function posix(path) {
  return path.charAt(0) === "/";
}
function win32(path) {
  var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  var result = splitDeviceRe.exec(path);
  var device = result[1] || "";
  var isUnc = Boolean(device && device.charAt(1) !== ":");
  return Boolean(result[2] || isUnc);
}
module.exports = process.platform === "win32" ? win32 : posix;
module.exports.posix = posix;
module.exports.win32 = win32;


/***/ }),

/***/ "../pyright-internal/node_modules/rimraf/rimraf.js":
/*!*********************************************************!*\
  !*** ../pyright-internal/node_modules/rimraf/rimraf.js ***!
  \*********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const assert = __webpack_require__(/*! assert */ "assert");
const path = __webpack_require__(/*! path */ "path");
const fs = __webpack_require__(/*! fs */ "fs");
let glob = void 0;
try {
  glob = __webpack_require__(/*! glob */ "../pyright-internal/node_modules/glob/glob.js");
} catch (_err) {
}
const defaultGlobOpts = {
  nosort: true,
  silent: true
};
let timeout = 0;
const isWindows = process.platform === "win32";
const defaults = (options) => {
  const methods = [
    "unlink",
    "chmod",
    "stat",
    "lstat",
    "rmdir",
    "readdir"
  ];
  methods.forEach((m) => {
    options[m] = options[m] || fs[m];
    m = m + "Sync";
    options[m] = options[m] || fs[m];
  });
  options.maxBusyTries = options.maxBusyTries || 3;
  options.emfileWait = options.emfileWait || 1e3;
  if (options.glob === false) {
    options.disableGlob = true;
  }
  if (options.disableGlob !== true && glob === void 0) {
    throw Error("glob dependency not found, set `options.disableGlob = true` if intentional");
  }
  options.disableGlob = options.disableGlob || false;
  options.glob = options.glob || defaultGlobOpts;
};
const rimraf = (p, options, cb) => {
  if (typeof options === "function") {
    cb = options;
    options = {};
  }
  assert(p, "rimraf: missing path");
  assert.equal(typeof p, "string", "rimraf: path should be a string");
  assert.equal(typeof cb, "function", "rimraf: callback function required");
  assert(options, "rimraf: invalid options argument provided");
  assert.equal(typeof options, "object", "rimraf: options should be object");
  defaults(options);
  let busyTries = 0;
  let errState = null;
  let n = 0;
  const next = (er) => {
    errState = errState || er;
    if (--n === 0)
      cb(errState);
  };
  const afterGlob = (er, results) => {
    if (er)
      return cb(er);
    n = results.length;
    if (n === 0)
      return cb();
    results.forEach((p2) => {
      const CB = (er2) => {
        if (er2) {
          if ((er2.code === "EBUSY" || er2.code === "ENOTEMPTY" || er2.code === "EPERM") && busyTries < options.maxBusyTries) {
            busyTries++;
            return setTimeout(() => rimraf_(p2, options, CB), busyTries * 100);
          }
          if (er2.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(() => rimraf_(p2, options, CB), timeout++);
          }
          if (er2.code === "ENOENT")
            er2 = null;
        }
        timeout = 0;
        next(er2);
      };
      rimraf_(p2, options, CB);
    });
  };
  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p]);
  options.lstat(p, (er, stat) => {
    if (!er)
      return afterGlob(null, [p]);
    glob(p, options.glob, afterGlob);
  });
};
const rimraf_ = (p, options, cb) => {
  assert(p);
  assert(options);
  assert(typeof cb === "function");
  options.lstat(p, (er, st) => {
    if (er && er.code === "ENOENT")
      return cb(null);
    if (er && er.code === "EPERM" && isWindows)
      fixWinEPERM(p, options, er, cb);
    if (st && st.isDirectory())
      return rmdir(p, options, er, cb);
    options.unlink(p, (er2) => {
      if (er2) {
        if (er2.code === "ENOENT")
          return cb(null);
        if (er2.code === "EPERM")
          return isWindows ? fixWinEPERM(p, options, er2, cb) : rmdir(p, options, er2, cb);
        if (er2.code === "EISDIR")
          return rmdir(p, options, er2, cb);
      }
      return cb(er2);
    });
  });
};
const fixWinEPERM = (p, options, er, cb) => {
  assert(p);
  assert(options);
  assert(typeof cb === "function");
  options.chmod(p, 438, (er2) => {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er);
    else
      options.stat(p, (er3, stats) => {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er);
        else if (stats.isDirectory())
          rmdir(p, options, er, cb);
        else
          options.unlink(p, cb);
      });
  });
};
const fixWinEPERMSync = (p, options, er) => {
  assert(p);
  assert(options);
  try {
    options.chmodSync(p, 438);
  } catch (er2) {
    if (er2.code === "ENOENT")
      return;
    else
      throw er;
  }
  let stats;
  try {
    stats = options.statSync(p);
  } catch (er3) {
    if (er3.code === "ENOENT")
      return;
    else
      throw er;
  }
  if (stats.isDirectory())
    rmdirSync(p, options, er);
  else
    options.unlinkSync(p);
};
const rmdir = (p, options, originalEr, cb) => {
  assert(p);
  assert(options);
  assert(typeof cb === "function");
  options.rmdir(p, (er) => {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb);
    else if (er && er.code === "ENOTDIR")
      cb(originalEr);
    else
      cb(er);
  });
};
const rmkids = (p, options, cb) => {
  assert(p);
  assert(options);
  assert(typeof cb === "function");
  options.readdir(p, (er, files) => {
    if (er)
      return cb(er);
    let n = files.length;
    if (n === 0)
      return options.rmdir(p, cb);
    let errState;
    files.forEach((f) => {
      rimraf(path.join(p, f), options, (er2) => {
        if (errState)
          return;
        if (er2)
          return cb(errState = er2);
        if (--n === 0)
          options.rmdir(p, cb);
      });
    });
  });
};
const rimrafSync = (p, options) => {
  options = options || {};
  defaults(options);
  assert(p, "rimraf: missing path");
  assert.equal(typeof p, "string", "rimraf: path should be a string");
  assert(options, "rimraf: missing options");
  assert.equal(typeof options, "object", "rimraf: options should be object");
  let results;
  if (options.disableGlob || !glob.hasMagic(p)) {
    results = [p];
  } else {
    try {
      options.lstatSync(p);
      results = [p];
    } catch (er) {
      results = glob.sync(p, options.glob);
    }
  }
  if (!results.length)
    return;
  for (let i = 0; i < results.length; i++) {
    const p2 = results[i];
    let st;
    try {
      st = options.lstatSync(p2);
    } catch (er) {
      if (er.code === "ENOENT")
        return;
      if (er.code === "EPERM" && isWindows)
        fixWinEPERMSync(p2, options, er);
    }
    try {
      if (st && st.isDirectory())
        rmdirSync(p2, options, null);
      else
        options.unlinkSync(p2);
    } catch (er) {
      if (er.code === "ENOENT")
        return;
      if (er.code === "EPERM")
        return isWindows ? fixWinEPERMSync(p2, options, er) : rmdirSync(p2, options, er);
      if (er.code !== "EISDIR")
        throw er;
      rmdirSync(p2, options, er);
    }
  }
};
const rmdirSync = (p, options, originalEr) => {
  assert(p);
  assert(options);
  try {
    options.rmdirSync(p);
  } catch (er) {
    if (er.code === "ENOENT")
      return;
    if (er.code === "ENOTDIR")
      throw originalEr;
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options);
  }
};
const rmkidsSync = (p, options) => {
  assert(p);
  assert(options);
  options.readdirSync(p).forEach((f) => rimrafSync(path.join(p, f), options));
  const retries = isWindows ? 100 : 1;
  let i = 0;
  do {
    let threw = true;
    try {
      const ret = options.rmdirSync(p, options);
      threw = false;
      return ret;
    } finally {
      if (++i < retries && threw)
        continue;
    }
  } while (true);
};
module.exports = rimraf;
rimraf.sync = rimrafSync;


/***/ }),

/***/ "../pyright-internal/node_modules/tmp/lib/tmp.js":
/*!*******************************************************!*\
  !*** ../pyright-internal/node_modules/tmp/lib/tmp.js ***!
  \*******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*!
 * Tmp
 *
 * Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
 *
 * MIT Licensed
 */
const fs = __webpack_require__(/*! fs */ "fs");
const os = __webpack_require__(/*! os */ "os");
const path = __webpack_require__(/*! path */ "path");
const crypto = __webpack_require__(/*! crypto */ "crypto");
const _c = { fs: fs.constants, os: os.constants };
const rimraf = __webpack_require__(/*! rimraf */ "../pyright-internal/node_modules/rimraf/rimraf.js");
const RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), IS_WIN32 = os.platform() === "win32", EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 448, FILE_MODE = 384, EXIT = "exit", _removeObjects = [], FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync;
let _gracefulCleanup = false;
function tmpName(options, callback) {
  const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
  try {
    _assertAndSanitizeOptions(opts);
  } catch (err) {
    return cb(err);
  }
  let tries = opts.tries;
  (function _getUniqueName() {
    try {
      const name = _generateTmpName(opts);
      fs.stat(name, function(err) {
        if (!err) {
          if (tries-- > 0)
            return _getUniqueName();
          return cb(new Error("Could not get a unique tmp filename, max tries reached " + name));
        }
        cb(null, name);
      });
    } catch (err) {
      cb(err);
    }
  })();
}
function tmpNameSync(options) {
  const args = _parseArguments(options), opts = args[0];
  _assertAndSanitizeOptions(opts);
  let tries = opts.tries;
  do {
    const name = _generateTmpName(opts);
    try {
      fs.statSync(name);
    } catch (e) {
      return name;
    }
  } while (tries-- > 0);
  throw new Error("Could not get a unique tmp filename, max tries reached");
}
function file(options, callback) {
  const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
  tmpName(opts, function _tmpNameCreated(err, name) {
    if (err)
      return cb(err);
    fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) {
      if (err2)
        return cb(err2);
      if (opts.discardDescriptor) {
        return fs.close(fd, function _discardCallback(possibleErr) {
          return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false));
        });
      } else {
        const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
        cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false));
      }
    });
  });
}
function fileSync(options) {
  const args = _parseArguments(options), opts = args[0];
  const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
  const name = tmpNameSync(opts);
  var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
  if (opts.discardDescriptor) {
    fs.closeSync(fd);
    fd = void 0;
  }
  return {
    name,
    fd,
    removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true)
  };
}
function dir(options, callback) {
  const args = _parseArguments(options, callback), opts = args[0], cb = args[1];
  tmpName(opts, function _tmpNameCreated(err, name) {
    if (err)
      return cb(err);
    fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) {
      if (err2)
        return cb(err2);
      cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false));
    });
  });
}
function dirSync(options) {
  const args = _parseArguments(options), opts = args[0];
  const name = tmpNameSync(opts);
  fs.mkdirSync(name, opts.mode || DIR_MODE);
  return {
    name,
    removeCallback: _prepareTmpDirRemoveCallback(name, opts, true)
  };
}
function _removeFileAsync(fdPath, next) {
  const _handler = function(err) {
    if (err && !_isENOENT(err)) {
      return next(err);
    }
    next();
  };
  if (0 <= fdPath[0])
    fs.close(fdPath[0], function() {
      fs.unlink(fdPath[1], _handler);
    });
  else
    fs.unlink(fdPath[1], _handler);
}
function _removeFileSync(fdPath) {
  let rethrownException = null;
  try {
    if (0 <= fdPath[0])
      fs.closeSync(fdPath[0]);
  } catch (e) {
    if (!_isEBADF(e) && !_isENOENT(e))
      throw e;
  } finally {
    try {
      fs.unlinkSync(fdPath[1]);
    } catch (e) {
      if (!_isENOENT(e))
        rethrownException = e;
    }
  }
  if (rethrownException !== null) {
    throw rethrownException;
  }
}
function _prepareTmpFileRemoveCallback(name, fd, opts, sync) {
  const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync);
  const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync);
  if (!opts.keep)
    _removeObjects.unshift(removeCallbackSync);
  return sync ? removeCallbackSync : removeCallback;
}
function _prepareTmpDirRemoveCallback(name, opts, sync) {
  const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs);
  const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC;
  const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync);
  const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync);
  if (!opts.keep)
    _removeObjects.unshift(removeCallbackSync);
  return sync ? removeCallbackSync : removeCallback;
}
function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) {
  let called = false;
  return function _cleanupCallback(next) {
    if (!called) {
      const toRemove = cleanupCallbackSync || _cleanupCallback;
      const index = _removeObjects.indexOf(toRemove);
      if (index >= 0)
        _removeObjects.splice(index, 1);
      called = true;
      if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) {
        return removeFunction(fileOrDirName);
      } else {
        return removeFunction(fileOrDirName, next || function() {
        });
      }
    }
  };
}
function _garbageCollector() {
  if (!_gracefulCleanup)
    return;
  while (_removeObjects.length) {
    try {
      _removeObjects[0]();
    } catch (e) {
    }
  }
}
function _randomChars(howMany) {
  let value = [], rnd = null;
  try {
    rnd = crypto.randomBytes(howMany);
  } catch (e) {
    rnd = crypto.pseudoRandomBytes(howMany);
  }
  for (var i = 0; i < howMany; i++) {
    value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
  }
  return value.join("");
}
function _isBlank(s) {
  return s === null || _isUndefined(s) || !s.trim();
}
function _isUndefined(obj) {
  return typeof obj === "undefined";
}
function _parseArguments(options, callback) {
  if (typeof options === "function") {
    return [{}, options];
  }
  if (_isUndefined(options)) {
    return [{}, callback];
  }
  const actualOptions = {};
  for (const key of Object.getOwnPropertyNames(options)) {
    actualOptions[key] = options[key];
  }
  return [actualOptions, callback];
}
function _generateTmpName(opts) {
  const tmpDir = opts.tmpdir;
  if (!_isUndefined(opts.name))
    return path.join(tmpDir, opts.dir, opts.name);
  if (!_isUndefined(opts.template))
    return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6));
  const name = [
    opts.prefix ? opts.prefix : "tmp",
    "-",
    process.pid,
    "-",
    _randomChars(12),
    opts.postfix ? "-" + opts.postfix : ""
  ].join("");
  return path.join(tmpDir, opts.dir, name);
}
function _assertAndSanitizeOptions(options) {
  options.tmpdir = _getTmpDir(options);
  const tmpDir = options.tmpdir;
  if (!_isUndefined(options.name))
    _assertIsRelative(options.name, "name", tmpDir);
  if (!_isUndefined(options.dir))
    _assertIsRelative(options.dir, "dir", tmpDir);
  if (!_isUndefined(options.template)) {
    _assertIsRelative(options.template, "template", tmpDir);
    if (!options.template.match(TEMPLATE_PATTERN))
      throw new Error(`Invalid template, found "${options.template}".`);
  }
  if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0)
    throw new Error(`Invalid tries, found "${options.tries}".`);
  options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1;
  options.keep = !!options.keep;
  options.detachDescriptor = !!options.detachDescriptor;
  options.discardDescriptor = !!options.discardDescriptor;
  options.unsafeCleanup = !!options.unsafeCleanup;
  options.dir = _isUndefined(options.dir) ? "" : path.relative(tmpDir, _resolvePath(options.dir, tmpDir));
  options.template = _isUndefined(options.template) ? void 0 : path.relative(tmpDir, _resolvePath(options.template, tmpDir));
  options.template = _isBlank(options.template) ? void 0 : path.relative(options.dir, options.template);
  options.name = _isUndefined(options.name) ? void 0 : _sanitizeName(options.name);
  options.prefix = _isUndefined(options.prefix) ? "" : options.prefix;
  options.postfix = _isUndefined(options.postfix) ? "" : options.postfix;
}
function _resolvePath(name, tmpDir) {
  const sanitizedName = _sanitizeName(name);
  if (sanitizedName.startsWith(tmpDir)) {
    return path.resolve(sanitizedName);
  } else {
    return path.resolve(path.join(tmpDir, sanitizedName));
  }
}
function _sanitizeName(name) {
  if (_isBlank(name)) {
    return name;
  }
  return name.replace(/["']/g, "");
}
function _assertIsRelative(name, option, tmpDir) {
  if (option === "name") {
    if (path.isAbsolute(name))
      throw new Error(`${option} option must not contain an absolute path, found "${name}".`);
    let basename = path.basename(name);
    if (basename === ".." || basename === "." || basename !== name)
      throw new Error(`${option} option must not contain a path, found "${name}".`);
  } else {
    if (path.isAbsolute(name) && !name.startsWith(tmpDir)) {
      throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`);
    }
    let resolvedPath = _resolvePath(name, tmpDir);
    if (!resolvedPath.startsWith(tmpDir))
      throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`);
  }
}
function _isEBADF(error) {
  return _isExpectedError(error, -EBADF, "EBADF");
}
function _isENOENT(error) {
  return _isExpectedError(error, -ENOENT, "ENOENT");
}
function _isExpectedError(error, errno, code) {
  return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno;
}
function setGracefulCleanup() {
  _gracefulCleanup = true;
}
function _getTmpDir(options) {
  return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir()));
}
process.addListener(EXIT, _garbageCollector);
Object.defineProperty(module.exports, "tmpdir", ({
  enumerable: true,
  configurable: false,
  get: function() {
    return _getTmpDir();
  }
}));
module.exports.dir = dir;
module.exports.dirSync = dirSync;
module.exports.file = file;
module.exports.fileSync = fileSync;
module.exports.tmpName = tmpName;
module.exports.tmpNameSync = tmpNameSync;
module.exports.setGracefulCleanup = setGracefulCleanup;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/api.js":
/*!*************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/api.js ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;
exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.TraceValue = exports.Trace = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messages.js");
Object.defineProperty(exports, "Message", ({ enumerable: true, get: function() {
  return messages_1.Message;
} }));
Object.defineProperty(exports, "RequestType", ({ enumerable: true, get: function() {
  return messages_1.RequestType;
} }));
Object.defineProperty(exports, "RequestType0", ({ enumerable: true, get: function() {
  return messages_1.RequestType0;
} }));
Object.defineProperty(exports, "RequestType1", ({ enumerable: true, get: function() {
  return messages_1.RequestType1;
} }));
Object.defineProperty(exports, "RequestType2", ({ enumerable: true, get: function() {
  return messages_1.RequestType2;
} }));
Object.defineProperty(exports, "RequestType3", ({ enumerable: true, get: function() {
  return messages_1.RequestType3;
} }));
Object.defineProperty(exports, "RequestType4", ({ enumerable: true, get: function() {
  return messages_1.RequestType4;
} }));
Object.defineProperty(exports, "RequestType5", ({ enumerable: true, get: function() {
  return messages_1.RequestType5;
} }));
Object.defineProperty(exports, "RequestType6", ({ enumerable: true, get: function() {
  return messages_1.RequestType6;
} }));
Object.defineProperty(exports, "RequestType7", ({ enumerable: true, get: function() {
  return messages_1.RequestType7;
} }));
Object.defineProperty(exports, "RequestType8", ({ enumerable: true, get: function() {
  return messages_1.RequestType8;
} }));
Object.defineProperty(exports, "RequestType9", ({ enumerable: true, get: function() {
  return messages_1.RequestType9;
} }));
Object.defineProperty(exports, "ResponseError", ({ enumerable: true, get: function() {
  return messages_1.ResponseError;
} }));
Object.defineProperty(exports, "ErrorCodes", ({ enumerable: true, get: function() {
  return messages_1.ErrorCodes;
} }));
Object.defineProperty(exports, "NotificationType", ({ enumerable: true, get: function() {
  return messages_1.NotificationType;
} }));
Object.defineProperty(exports, "NotificationType0", ({ enumerable: true, get: function() {
  return messages_1.NotificationType0;
} }));
Object.defineProperty(exports, "NotificationType1", ({ enumerable: true, get: function() {
  return messages_1.NotificationType1;
} }));
Object.defineProperty(exports, "NotificationType2", ({ enumerable: true, get: function() {
  return messages_1.NotificationType2;
} }));
Object.defineProperty(exports, "NotificationType3", ({ enumerable: true, get: function() {
  return messages_1.NotificationType3;
} }));
Object.defineProperty(exports, "NotificationType4", ({ enumerable: true, get: function() {
  return messages_1.NotificationType4;
} }));
Object.defineProperty(exports, "NotificationType5", ({ enumerable: true, get: function() {
  return messages_1.NotificationType5;
} }));
Object.defineProperty(exports, "NotificationType6", ({ enumerable: true, get: function() {
  return messages_1.NotificationType6;
} }));
Object.defineProperty(exports, "NotificationType7", ({ enumerable: true, get: function() {
  return messages_1.NotificationType7;
} }));
Object.defineProperty(exports, "NotificationType8", ({ enumerable: true, get: function() {
  return messages_1.NotificationType8;
} }));
Object.defineProperty(exports, "NotificationType9", ({ enumerable: true, get: function() {
  return messages_1.NotificationType9;
} }));
Object.defineProperty(exports, "ParameterStructures", ({ enumerable: true, get: function() {
  return messages_1.ParameterStructures;
} }));
const linkedMap_1 = __webpack_require__(/*! ./linkedMap */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/linkedMap.js");
Object.defineProperty(exports, "LinkedMap", ({ enumerable: true, get: function() {
  return linkedMap_1.LinkedMap;
} }));
Object.defineProperty(exports, "LRUCache", ({ enumerable: true, get: function() {
  return linkedMap_1.LRUCache;
} }));
Object.defineProperty(exports, "Touch", ({ enumerable: true, get: function() {
  return linkedMap_1.Touch;
} }));
const disposable_1 = __webpack_require__(/*! ./disposable */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/disposable.js");
Object.defineProperty(exports, "Disposable", ({ enumerable: true, get: function() {
  return disposable_1.Disposable;
} }));
const events_1 = __webpack_require__(/*! ./events */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js");
Object.defineProperty(exports, "Event", ({ enumerable: true, get: function() {
  return events_1.Event;
} }));
Object.defineProperty(exports, "Emitter", ({ enumerable: true, get: function() {
  return events_1.Emitter;
} }));
const cancellation_1 = __webpack_require__(/*! ./cancellation */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/cancellation.js");
Object.defineProperty(exports, "CancellationTokenSource", ({ enumerable: true, get: function() {
  return cancellation_1.CancellationTokenSource;
} }));
Object.defineProperty(exports, "CancellationToken", ({ enumerable: true, get: function() {
  return cancellation_1.CancellationToken;
} }));
const sharedArrayCancellation_1 = __webpack_require__(/*! ./sharedArrayCancellation */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js");
Object.defineProperty(exports, "SharedArraySenderStrategy", ({ enumerable: true, get: function() {
  return sharedArrayCancellation_1.SharedArraySenderStrategy;
} }));
Object.defineProperty(exports, "SharedArrayReceiverStrategy", ({ enumerable: true, get: function() {
  return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
} }));
const messageReader_1 = __webpack_require__(/*! ./messageReader */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageReader.js");
Object.defineProperty(exports, "MessageReader", ({ enumerable: true, get: function() {
  return messageReader_1.MessageReader;
} }));
Object.defineProperty(exports, "AbstractMessageReader", ({ enumerable: true, get: function() {
  return messageReader_1.AbstractMessageReader;
} }));
Object.defineProperty(exports, "ReadableStreamMessageReader", ({ enumerable: true, get: function() {
  return messageReader_1.ReadableStreamMessageReader;
} }));
const messageWriter_1 = __webpack_require__(/*! ./messageWriter */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageWriter.js");
Object.defineProperty(exports, "MessageWriter", ({ enumerable: true, get: function() {
  return messageWriter_1.MessageWriter;
} }));
Object.defineProperty(exports, "AbstractMessageWriter", ({ enumerable: true, get: function() {
  return messageWriter_1.AbstractMessageWriter;
} }));
Object.defineProperty(exports, "WriteableStreamMessageWriter", ({ enumerable: true, get: function() {
  return messageWriter_1.WriteableStreamMessageWriter;
} }));
const messageBuffer_1 = __webpack_require__(/*! ./messageBuffer */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js");
Object.defineProperty(exports, "AbstractMessageBuffer", ({ enumerable: true, get: function() {
  return messageBuffer_1.AbstractMessageBuffer;
} }));
const connection_1 = __webpack_require__(/*! ./connection */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/connection.js");
Object.defineProperty(exports, "ConnectionStrategy", ({ enumerable: true, get: function() {
  return connection_1.ConnectionStrategy;
} }));
Object.defineProperty(exports, "ConnectionOptions", ({ enumerable: true, get: function() {
  return connection_1.ConnectionOptions;
} }));
Object.defineProperty(exports, "NullLogger", ({ enumerable: true, get: function() {
  return connection_1.NullLogger;
} }));
Object.defineProperty(exports, "createMessageConnection", ({ enumerable: true, get: function() {
  return connection_1.createMessageConnection;
} }));
Object.defineProperty(exports, "ProgressToken", ({ enumerable: true, get: function() {
  return connection_1.ProgressToken;
} }));
Object.defineProperty(exports, "ProgressType", ({ enumerable: true, get: function() {
  return connection_1.ProgressType;
} }));
Object.defineProperty(exports, "Trace", ({ enumerable: true, get: function() {
  return connection_1.Trace;
} }));
Object.defineProperty(exports, "TraceValue", ({ enumerable: true, get: function() {
  return connection_1.TraceValue;
} }));
Object.defineProperty(exports, "TraceFormat", ({ enumerable: true, get: function() {
  return connection_1.TraceFormat;
} }));
Object.defineProperty(exports, "SetTraceNotification", ({ enumerable: true, get: function() {
  return connection_1.SetTraceNotification;
} }));
Object.defineProperty(exports, "LogTraceNotification", ({ enumerable: true, get: function() {
  return connection_1.LogTraceNotification;
} }));
Object.defineProperty(exports, "ConnectionErrors", ({ enumerable: true, get: function() {
  return connection_1.ConnectionErrors;
} }));
Object.defineProperty(exports, "ConnectionError", ({ enumerable: true, get: function() {
  return connection_1.ConnectionError;
} }));
Object.defineProperty(exports, "CancellationReceiverStrategy", ({ enumerable: true, get: function() {
  return connection_1.CancellationReceiverStrategy;
} }));
Object.defineProperty(exports, "CancellationSenderStrategy", ({ enumerable: true, get: function() {
  return connection_1.CancellationSenderStrategy;
} }));
Object.defineProperty(exports, "CancellationStrategy", ({ enumerable: true, get: function() {
  return connection_1.CancellationStrategy;
} }));
Object.defineProperty(exports, "MessageStrategy", ({ enumerable: true, get: function() {
  return connection_1.MessageStrategy;
} }));
Object.defineProperty(exports, "TraceValues", ({ enumerable: true, get: function() {
  return connection_1.TraceValues;
} }));
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
exports.RAL = ral_1.default;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/cancellation.js":
/*!**********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/cancellation.js ***!
  \**********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CancellationTokenSource = exports.CancellationToken = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
const Is = __webpack_require__(/*! ./is */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js");
const events_1 = __webpack_require__(/*! ./events */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js");
var CancellationToken;
(function(CancellationToken2) {
  CancellationToken2.None = Object.freeze({
    isCancellationRequested: false,
    onCancellationRequested: events_1.Event.None
  });
  CancellationToken2.Cancelled = Object.freeze({
    isCancellationRequested: true,
    onCancellationRequested: events_1.Event.None
  });
  function is(value) {
    const candidate = value;
    return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
  }
  CancellationToken2.is = is;
})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
const shortcutEvent = Object.freeze(function(callback, context) {
  const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
  return { dispose() {
    handle.dispose();
  } };
});
class MutableToken {
  constructor() {
    this._isCancelled = false;
  }
  cancel() {
    if (!this._isCancelled) {
      this._isCancelled = true;
      if (this._emitter) {
        this._emitter.fire(void 0);
        this.dispose();
      }
    }
  }
  get isCancellationRequested() {
    return this._isCancelled;
  }
  get onCancellationRequested() {
    if (this._isCancelled) {
      return shortcutEvent;
    }
    if (!this._emitter) {
      this._emitter = new events_1.Emitter();
    }
    return this._emitter.event;
  }
  dispose() {
    if (this._emitter) {
      this._emitter.dispose();
      this._emitter = void 0;
    }
  }
}
class CancellationTokenSource {
  get token() {
    if (!this._token) {
      this._token = new MutableToken();
    }
    return this._token;
  }
  cancel() {
    if (!this._token) {
      this._token = CancellationToken.Cancelled;
    } else {
      this._token.cancel();
    }
  }
  dispose() {
    if (!this._token) {
      this._token = CancellationToken.None;
    } else if (this._token instanceof MutableToken) {
      this._token.dispose();
    }
  }
}
exports.CancellationTokenSource = CancellationTokenSource;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/connection.js":
/*!********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/connection.js ***!
  \********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.TraceValue = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
const Is = __webpack_require__(/*! ./is */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js");
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messages.js");
const linkedMap_1 = __webpack_require__(/*! ./linkedMap */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/linkedMap.js");
const events_1 = __webpack_require__(/*! ./events */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js");
const cancellation_1 = __webpack_require__(/*! ./cancellation */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/cancellation.js");
var CancelNotification;
(function(CancelNotification2) {
  CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
})(CancelNotification || (CancelNotification = {}));
var ProgressToken;
(function(ProgressToken2) {
  function is(value) {
    return typeof value === "string" || typeof value === "number";
  }
  ProgressToken2.is = is;
})(ProgressToken || (exports.ProgressToken = ProgressToken = {}));
var ProgressNotification;
(function(ProgressNotification2) {
  ProgressNotification2.type = new messages_1.NotificationType("$/progress");
})(ProgressNotification || (ProgressNotification = {}));
class ProgressType {
  constructor() {
  }
}
exports.ProgressType = ProgressType;
var StarRequestHandler;
(function(StarRequestHandler2) {
  function is(value) {
    return Is.func(value);
  }
  StarRequestHandler2.is = is;
})(StarRequestHandler || (StarRequestHandler = {}));
exports.NullLogger = Object.freeze({
  error: () => {
  },
  warn: () => {
  },
  info: () => {
  },
  log: () => {
  }
});
var Trace;
(function(Trace2) {
  Trace2[Trace2["Off"] = 0] = "Off";
  Trace2[Trace2["Messages"] = 1] = "Messages";
  Trace2[Trace2["Compact"] = 2] = "Compact";
  Trace2[Trace2["Verbose"] = 3] = "Verbose";
})(Trace || (exports.Trace = Trace = {}));
var TraceValue;
(function(TraceValue2) {
  TraceValue2.Off = "off";
  TraceValue2.Messages = "messages";
  TraceValue2.Compact = "compact";
  TraceValue2.Verbose = "verbose";
})(TraceValue || (exports.TraceValue = TraceValue = {}));
exports.TraceValues = TraceValue;
(function(Trace2) {
  function fromString(value) {
    if (!Is.string(value)) {
      return Trace2.Off;
    }
    value = value.toLowerCase();
    switch (value) {
      case "off":
        return Trace2.Off;
      case "messages":
        return Trace2.Messages;
      case "compact":
        return Trace2.Compact;
      case "verbose":
        return Trace2.Verbose;
      default:
        return Trace2.Off;
    }
  }
  Trace2.fromString = fromString;
  function toString(value) {
    switch (value) {
      case Trace2.Off:
        return "off";
      case Trace2.Messages:
        return "messages";
      case Trace2.Compact:
        return "compact";
      case Trace2.Verbose:
        return "verbose";
      default:
        return "off";
    }
  }
  Trace2.toString = toString;
})(Trace || (exports.Trace = Trace = {}));
var TraceFormat;
(function(TraceFormat2) {
  TraceFormat2["Text"] = "text";
  TraceFormat2["JSON"] = "json";
})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
(function(TraceFormat2) {
  function fromString(value) {
    if (!Is.string(value)) {
      return TraceFormat2.Text;
    }
    value = value.toLowerCase();
    if (value === "json") {
      return TraceFormat2.JSON;
    } else {
      return TraceFormat2.Text;
    }
  }
  TraceFormat2.fromString = fromString;
})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
var SetTraceNotification;
(function(SetTraceNotification2) {
  SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
})(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));
var LogTraceNotification;
(function(LogTraceNotification2) {
  LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
})(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));
var ConnectionErrors;
(function(ConnectionErrors2) {
  ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
  ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
  ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
})(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));
class ConnectionError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
    Object.setPrototypeOf(this, ConnectionError.prototype);
  }
}
exports.ConnectionError = ConnectionError;
var ConnectionStrategy;
(function(ConnectionStrategy2) {
  function is(value) {
    const candidate = value;
    return candidate && Is.func(candidate.cancelUndispatched);
  }
  ConnectionStrategy2.is = is;
})(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));
var IdCancellationReceiverStrategy;
(function(IdCancellationReceiverStrategy2) {
  function is(value) {
    const candidate = value;
    return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
  }
  IdCancellationReceiverStrategy2.is = is;
})(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
var RequestCancellationReceiverStrategy;
(function(RequestCancellationReceiverStrategy2) {
  function is(value) {
    const candidate = value;
    return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
  }
  RequestCancellationReceiverStrategy2.is = is;
})(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
var CancellationReceiverStrategy;
(function(CancellationReceiverStrategy2) {
  CancellationReceiverStrategy2.Message = Object.freeze({
    createCancellationTokenSource(_) {
      return new cancellation_1.CancellationTokenSource();
    }
  });
  function is(value) {
    return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
  }
  CancellationReceiverStrategy2.is = is;
})(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
var CancellationSenderStrategy;
(function(CancellationSenderStrategy2) {
  CancellationSenderStrategy2.Message = Object.freeze({
    sendCancellation(conn, id) {
      return conn.sendNotification(CancelNotification.type, { id });
    },
    cleanup(_) {
    }
  });
  function is(value) {
    const candidate = value;
    return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
  }
  CancellationSenderStrategy2.is = is;
})(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));
var CancellationStrategy;
(function(CancellationStrategy2) {
  CancellationStrategy2.Message = Object.freeze({
    receiver: CancellationReceiverStrategy.Message,
    sender: CancellationSenderStrategy.Message
  });
  function is(value) {
    const candidate = value;
    return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
  }
  CancellationStrategy2.is = is;
})(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));
var MessageStrategy;
(function(MessageStrategy2) {
  function is(value) {
    const candidate = value;
    return candidate && Is.func(candidate.handleMessage);
  }
  MessageStrategy2.is = is;
})(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));
var ConnectionOptions;
(function(ConnectionOptions2) {
  function is(value) {
    const candidate = value;
    return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy) || Is.number(candidate.maxParallelism));
  }
  ConnectionOptions2.is = is;
})(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));
var ConnectionState;
(function(ConnectionState2) {
  ConnectionState2[ConnectionState2["New"] = 1] = "New";
  ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
  ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
  ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
})(ConnectionState || (ConnectionState = {}));
function createMessageConnection(messageReader, messageWriter, _logger, options) {
  var _a;
  const logger = _logger !== void 0 ? _logger : exports.NullLogger;
  let sequenceNumber = 0;
  let notificationSequenceNumber = 0;
  let unknownResponseSequenceNumber = 0;
  const version = "2.0";
  const maxParallelism = (_a = options == null ? void 0 : options.maxParallelism) != null ? _a : -1;
  let inFlight = 0;
  let starRequestHandler = void 0;
  const requestHandlers = /* @__PURE__ */ new Map();
  let starNotificationHandler = void 0;
  const notificationHandlers = /* @__PURE__ */ new Map();
  const progressHandlers = /* @__PURE__ */ new Map();
  let timer;
  let messageQueue = new linkedMap_1.LinkedMap();
  let responsePromises = /* @__PURE__ */ new Map();
  let knownCanceledRequests = /* @__PURE__ */ new Set();
  let requestTokens = /* @__PURE__ */ new Map();
  let trace = Trace.Off;
  let traceFormat = TraceFormat.Text;
  let tracer;
  let state = ConnectionState.New;
  const errorEmitter = new events_1.Emitter();
  const closeEmitter = new events_1.Emitter();
  const unhandledNotificationEmitter = new events_1.Emitter();
  const unhandledProgressEmitter = new events_1.Emitter();
  const disposeEmitter = new events_1.Emitter();
  const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
  function cancelUndispatched(_message) {
    return void 0;
  }
  function isListening() {
    return state === ConnectionState.Listening;
  }
  function isClosed() {
    return state === ConnectionState.Closed;
  }
  function isDisposed() {
    return state === ConnectionState.Disposed;
  }
  function closeHandler() {
    if (state === ConnectionState.New || state === ConnectionState.Listening) {
      state = ConnectionState.Closed;
      closeEmitter.fire(void 0);
    }
  }
  function readErrorHandler(error) {
    errorEmitter.fire([error, void 0, void 0]);
  }
  function writeErrorHandler(data) {
    errorEmitter.fire(data);
  }
  messageReader.onClose(closeHandler);
  messageReader.onError(readErrorHandler);
  messageWriter.onClose(closeHandler);
  messageWriter.onError(writeErrorHandler);
  function createRequestQueueKey(id) {
    if (id === null) {
      throw new Error(`Can't send requests with id null since the response can't be correlated.`);
    }
    return "req-" + id.toString();
  }
  function createResponseQueueKey(id) {
    if (id === null) {
      return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
    } else {
      return "res-" + id.toString();
    }
  }
  function createNotificationQueueKey() {
    return "not-" + (++notificationSequenceNumber).toString();
  }
  function addMessageToQueue(queue, message) {
    if (messages_1.Message.isRequest(message)) {
      queue.set(createRequestQueueKey(message.id), message);
    } else if (messages_1.Message.isResponse(message)) {
      if (maxParallelism === -1) {
        queue.set(createResponseQueueKey(message.id), message);
      } else {
        handleResponse(message);
      }
    } else {
      queue.set(createNotificationQueueKey(), message);
    }
  }
  function triggerMessageQueue() {
    if (timer || messageQueue.size === 0) {
      return;
    }
    if (maxParallelism !== -1 && inFlight >= maxParallelism) {
      return;
    }
    timer = (0, ral_1.default)().timer.setImmediate(async () => {
      timer = void 0;
      if (messageQueue.size === 0) {
        return;
      }
      if (maxParallelism !== -1 && inFlight >= maxParallelism) {
        return;
      }
      const message = messageQueue.shift();
      let result;
      try {
        inFlight++;
        const messageStrategy = options == null ? void 0 : options.messageStrategy;
        if (MessageStrategy.is(messageStrategy)) {
          result = messageStrategy.handleMessage(message, handleMessage);
        } else {
          result = handleMessage(message);
        }
      } catch (error) {
        logger.error(`Processing message queue failed: ${error.toString()}`);
      } finally {
        if (result instanceof Promise) {
          result.then(() => {
            inFlight--;
            triggerMessageQueue();
          }).catch((error) => {
            logger.error(`Processing message queue failed: ${error.toString()}`);
          });
        } else {
          inFlight--;
        }
        triggerMessageQueue();
      }
    });
  }
  async function handleMessage(message) {
    if (messages_1.Message.isRequest(message)) {
      return handleRequest(message);
    } else if (messages_1.Message.isNotification(message)) {
      return handleNotification(message);
    } else if (messages_1.Message.isResponse(message)) {
      return handleResponse(message);
    } else {
      return handleInvalidMessage(message);
    }
  }
  const callback = (message) => {
    try {
      if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
        const cancelId = message.params.id;
        const key = createRequestQueueKey(cancelId);
        const toCancel = messageQueue.get(key);
        if (messages_1.Message.isRequest(toCancel)) {
          const strategy = options == null ? void 0 : options.connectionStrategy;
          const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
          if (response && (response.error !== void 0 || response.result !== void 0)) {
            messageQueue.delete(key);
            requestTokens.delete(cancelId);
            response.id = toCancel.id;
            traceSendingResponse(response, message.method, Date.now());
            messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
            return;
          }
        }
        const cancellationToken = requestTokens.get(cancelId);
        if (cancellationToken !== void 0) {
          cancellationToken.cancel();
          traceReceivedNotification(message);
          return;
        } else {
          knownCanceledRequests.add(cancelId);
        }
      }
      addMessageToQueue(messageQueue, message);
    } finally {
      triggerMessageQueue();
    }
  };
  async function handleRequest(requestMessage) {
    var _a2;
    if (isDisposed()) {
      return Promise.resolve();
    }
    function reply(resultOrError, method, startTime2) {
      const message = {
        jsonrpc: version,
        id: requestMessage.id
      };
      if (resultOrError instanceof messages_1.ResponseError) {
        message.error = resultOrError.toJson();
      } else {
        message.result = resultOrError === void 0 ? null : resultOrError;
      }
      traceSendingResponse(message, method, startTime2);
      return messageWriter.write(message);
    }
    function replyError(error, method, startTime2) {
      const message = {
        jsonrpc: version,
        id: requestMessage.id,
        error: error.toJson()
      };
      traceSendingResponse(message, method, startTime2);
      return messageWriter.write(message);
    }
    traceReceivedRequest(requestMessage);
    const element = requestHandlers.get(requestMessage.method);
    let type;
    let requestHandler;
    if (element) {
      type = element.type;
      requestHandler = element.handler;
    }
    const startTime = Date.now();
    if (requestHandler || starRequestHandler) {
      const tokenKey = (_a2 = requestMessage.id) != null ? _a2 : String(Date.now());
      const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
      if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
        cancellationSource.cancel();
      }
      if (requestMessage.id !== null) {
        requestTokens.set(tokenKey, cancellationSource);
      }
      try {
        let handlerResult;
        if (requestHandler) {
          if (requestMessage.params === void 0) {
            if (type !== void 0 && type.numberOfParams !== 0) {
              return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
            }
            handlerResult = requestHandler(cancellationSource.token);
          } else if (Array.isArray(requestMessage.params)) {
            if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
              return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
            }
            handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
          } else {
            if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
              return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
            }
            handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
          }
        } else if (starRequestHandler) {
          handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
        }
        const resultOrError = await handlerResult;
        await reply(resultOrError, requestMessage.method, startTime);
      } catch (error) {
        if (error instanceof messages_1.ResponseError) {
          await reply(error, requestMessage.method, startTime);
        } else if (error && Is.string(error.message)) {
          await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
        } else {
          await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
        }
      } finally {
        requestTokens.delete(tokenKey);
      }
    } else {
      await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
    }
  }
  function handleResponse(responseMessage) {
    if (isDisposed()) {
      return;
    }
    if (responseMessage.id === null) {
      if (responseMessage.error) {
        logger.error(`Received response message without id: Error is: 
${JSON.stringify(responseMessage.error, void 0, 4)}`);
      } else {
        logger.error(`Received response message without id. No further error information provided.`);
      }
    } else {
      const key = responseMessage.id;
      const responsePromise = responsePromises.get(key);
      traceReceivedResponse(responseMessage, responsePromise);
      if (responsePromise !== void 0) {
        responsePromises.delete(key);
        try {
          if (responseMessage.error) {
            const error = responseMessage.error;
            responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
          } else if (responseMessage.result !== void 0) {
            responsePromise.resolve(responseMessage.result);
          } else {
            throw new Error("Should never happen.");
          }
        } catch (error) {
          if (error.message) {
            logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
          } else {
            logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
          }
        }
      }
    }
  }
  async function handleNotification(message) {
    if (isDisposed()) {
      return;
    }
    let type = void 0;
    let notificationHandler;
    if (message.method === CancelNotification.type.method) {
      const cancelId = message.params.id;
      knownCanceledRequests.delete(cancelId);
      traceReceivedNotification(message);
      return;
    } else {
      const element = notificationHandlers.get(message.method);
      if (element) {
        notificationHandler = element.handler;
        type = element.type;
      }
    }
    if (notificationHandler || starNotificationHandler) {
      try {
        traceReceivedNotification(message);
        if (notificationHandler) {
          if (message.params === void 0) {
            if (type !== void 0) {
              if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
                logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
              }
            }
            await notificationHandler();
          } else if (Array.isArray(message.params)) {
            const params = message.params;
            if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
              await notificationHandler({ token: params[0], value: params[1] });
            } else {
              if (type !== void 0) {
                if (type.parameterStructures === messages_1.ParameterStructures.byName) {
                  logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
                }
                if (type.numberOfParams !== message.params.length) {
                  logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
                }
              }
              await notificationHandler(...params);
            }
          } else {
            if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
              logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
            }
            await notificationHandler(message.params);
          }
        } else if (starNotificationHandler) {
          await starNotificationHandler(message.method, message.params);
        }
      } catch (error) {
        if (error.message) {
          logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
        } else {
          logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
        }
      }
    } else {
      unhandledNotificationEmitter.fire(message);
    }
  }
  function handleInvalidMessage(message) {
    if (!message) {
      logger.error("Received empty message.");
      return;
    }
    logger.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(message, null, 4)}`);
    const responseMessage = message;
    if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
      const key = responseMessage.id;
      const responseHandler = responsePromises.get(key);
      if (responseHandler) {
        responseHandler.reject(new Error("The received response has neither a result nor an error property."));
      }
    }
  }
  function stringifyTrace(params) {
    if (params === void 0 || params === null) {
      return void 0;
    }
    switch (trace) {
      case Trace.Verbose:
        return JSON.stringify(params, null, 4);
      case Trace.Compact:
        return JSON.stringify(params);
      default:
        return void 0;
    }
  }
  function traceSendingRequest(message) {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
        data = `Params: ${stringifyTrace(message.params)}

`;
      }
      tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
    } else {
      logLSPMessage("send-request", message);
    }
  }
  function traceSendingNotification(message) {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if (trace === Trace.Verbose || trace === Trace.Compact) {
        if (message.params) {
          data = `Params: ${stringifyTrace(message.params)}

`;
        } else {
          data = "No parameters provided.\n\n";
        }
      }
      tracer.log(`Sending notification '${message.method}'.`, data);
    } else {
      logLSPMessage("send-notification", message);
    }
  }
  function traceSendingResponse(message, method, startTime) {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if (trace === Trace.Verbose || trace === Trace.Compact) {
        if (message.error && message.error.data) {
          data = `Error data: ${stringifyTrace(message.error.data)}

`;
        } else {
          if (message.result) {
            data = `Result: ${stringifyTrace(message.result)}

`;
          } else if (message.error === void 0) {
            data = "No result returned.\n\n";
          }
        }
      }
      tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
    } else {
      logLSPMessage("send-response", message);
    }
  }
  function traceReceivedRequest(message) {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
        data = `Params: ${stringifyTrace(message.params)}

`;
      }
      tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
    } else {
      logLSPMessage("receive-request", message);
    }
  }
  function traceReceivedNotification(message) {
    if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if (trace === Trace.Verbose || trace === Trace.Compact) {
        if (message.params) {
          data = `Params: ${stringifyTrace(message.params)}

`;
        } else {
          data = "No parameters provided.\n\n";
        }
      }
      tracer.log(`Received notification '${message.method}'.`, data);
    } else {
      logLSPMessage("receive-notification", message);
    }
  }
  function traceReceivedResponse(message, responsePromise) {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    if (traceFormat === TraceFormat.Text) {
      let data = void 0;
      if (trace === Trace.Verbose || trace === Trace.Compact) {
        if (message.error && message.error.data) {
          data = `Error data: ${stringifyTrace(message.error.data)}

`;
        } else {
          if (message.result) {
            data = `Result: ${stringifyTrace(message.result)}

`;
          } else if (message.error === void 0) {
            data = "No result returned.\n\n";
          }
        }
      }
      if (responsePromise) {
        const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
        tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
      } else {
        tracer.log(`Received response ${message.id} without active response promise.`, data);
      }
    } else {
      logLSPMessage("receive-response", message);
    }
  }
  function logLSPMessage(type, message) {
    if (!tracer || trace === Trace.Off) {
      return;
    }
    const lspMessage = {
      isLSPMessage: true,
      type,
      message,
      timestamp: Date.now()
    };
    tracer.log(lspMessage);
  }
  function throwIfClosedOrDisposed() {
    if (isClosed()) {
      throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
    }
    if (isDisposed()) {
      throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
    }
  }
  function throwIfListening() {
    if (isListening()) {
      throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
    }
  }
  function throwIfNotListening() {
    if (!isListening()) {
      throw new Error("Call listen() first.");
    }
  }
  function undefinedToNull(param) {
    if (param === void 0) {
      return null;
    } else {
      return param;
    }
  }
  function nullToUndefined(param) {
    if (param === null) {
      return void 0;
    } else {
      return param;
    }
  }
  function isNamedParam(param) {
    return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
  }
  function computeSingleParam(parameterStructures, param) {
    switch (parameterStructures) {
      case messages_1.ParameterStructures.auto:
        if (isNamedParam(param)) {
          return nullToUndefined(param);
        } else {
          return [undefinedToNull(param)];
        }
      case messages_1.ParameterStructures.byName:
        if (!isNamedParam(param)) {
          throw new Error(`Received parameters by name but param is not an object literal.`);
        }
        return nullToUndefined(param);
      case messages_1.ParameterStructures.byPosition:
        return [undefinedToNull(param)];
      default:
        throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
    }
  }
  function computeMessageParams(type, params) {
    let result;
    const numberOfParams = type.numberOfParams;
    switch (numberOfParams) {
      case 0:
        result = void 0;
        break;
      case 1:
        result = computeSingleParam(type.parameterStructures, params[0]);
        break;
      default:
        result = [];
        for (let i = 0; i < params.length && i < numberOfParams; i++) {
          result.push(undefinedToNull(params[i]));
        }
        if (params.length < numberOfParams) {
          for (let i = params.length; i < numberOfParams; i++) {
            result.push(null);
          }
        }
        break;
    }
    return result;
  }
  const connection = {
    sendNotification: (type, ...args) => {
      throwIfClosedOrDisposed();
      let method;
      let messageParams;
      if (Is.string(type)) {
        method = type;
        const first = args[0];
        let paramStart = 0;
        let parameterStructures = messages_1.ParameterStructures.auto;
        if (messages_1.ParameterStructures.is(first)) {
          paramStart = 1;
          parameterStructures = first;
        }
        const paramEnd = args.length;
        const numberOfParams = paramEnd - paramStart;
        switch (numberOfParams) {
          case 0:
            messageParams = void 0;
            break;
          case 1:
            messageParams = computeSingleParam(parameterStructures, args[paramStart]);
            break;
          default:
            if (parameterStructures === messages_1.ParameterStructures.byName) {
              throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
            }
            messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
            break;
        }
      } else {
        const params = args;
        method = type.method;
        messageParams = computeMessageParams(type, params);
      }
      const notificationMessage = {
        jsonrpc: version,
        method,
        params: messageParams
      };
      traceSendingNotification(notificationMessage);
      return messageWriter.write(notificationMessage).catch((error) => {
        logger.error(`Sending notification failed.`);
        throw error;
      });
    },
    onNotification: (type, handler) => {
      throwIfClosedOrDisposed();
      let method;
      if (Is.func(type)) {
        starNotificationHandler = type;
      } else if (handler) {
        if (Is.string(type)) {
          method = type;
          notificationHandlers.set(type, { type: void 0, handler });
        } else {
          method = type.method;
          notificationHandlers.set(type.method, { type, handler });
        }
      }
      return {
        dispose: () => {
          if (method !== void 0) {
            notificationHandlers.delete(method);
          } else {
            starNotificationHandler = void 0;
          }
        }
      };
    },
    onProgress: (_type, token, handler) => {
      if (progressHandlers.has(token)) {
        throw new Error(`Progress handler for token ${token} already registered`);
      }
      progressHandlers.set(token, handler);
      return {
        dispose: () => {
          progressHandlers.delete(token);
        }
      };
    },
    sendProgress: (_type, token, value) => {
      return connection.sendNotification(ProgressNotification.type, { token, value });
    },
    onUnhandledProgress: unhandledProgressEmitter.event,
    sendRequest: (type, ...args) => {
      throwIfClosedOrDisposed();
      throwIfNotListening();
      function sendCancellation(connection2, id2) {
        const p = cancellationStrategy.sender.sendCancellation(connection2, id2);
        if (p === void 0) {
          logger.log(`Received no promise from cancellation strategy when cancelling id ${id2}`);
        } else {
          p.catch(() => {
            logger.log(`Sending cancellation messages for id ${id2} failed.`);
          });
        }
      }
      let method;
      let messageParams;
      let token = void 0;
      if (Is.string(type)) {
        method = type;
        const first = args[0];
        const last = args[args.length - 1];
        let paramStart = 0;
        let parameterStructures = messages_1.ParameterStructures.auto;
        if (messages_1.ParameterStructures.is(first)) {
          paramStart = 1;
          parameterStructures = first;
        }
        let paramEnd = args.length;
        if (cancellation_1.CancellationToken.is(last)) {
          paramEnd = paramEnd - 1;
          token = last;
        }
        const numberOfParams = paramEnd - paramStart;
        switch (numberOfParams) {
          case 0:
            messageParams = void 0;
            break;
          case 1:
            messageParams = computeSingleParam(parameterStructures, args[paramStart]);
            break;
          default:
            if (parameterStructures === messages_1.ParameterStructures.byName) {
              throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
            }
            messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
            break;
        }
      } else {
        const params = args;
        method = type.method;
        messageParams = computeMessageParams(type, params);
        const numberOfParams = type.numberOfParams;
        token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
      }
      const id = sequenceNumber++;
      let disposable;
      let tokenWasCancelled = false;
      if (token !== void 0) {
        if (token.isCancellationRequested) {
          tokenWasCancelled = true;
        } else {
          disposable = token.onCancellationRequested(() => {
            sendCancellation(connection, id);
          });
        }
      }
      const requestMessage = {
        jsonrpc: version,
        id,
        method,
        params: messageParams
      };
      traceSendingRequest(requestMessage);
      if (typeof cancellationStrategy.sender.enableCancellation === "function") {
        cancellationStrategy.sender.enableCancellation(requestMessage);
      }
      return new Promise(async (resolve, reject) => {
        const resolveWithCleanup = (r) => {
          resolve(r);
          cancellationStrategy.sender.cleanup(id);
          disposable == null ? void 0 : disposable.dispose();
        };
        const rejectWithCleanup = (r) => {
          reject(r);
          cancellationStrategy.sender.cleanup(id);
          disposable == null ? void 0 : disposable.dispose();
        };
        const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
        try {
          await messageWriter.write(requestMessage);
          responsePromises.set(id, responsePromise);
          if (tokenWasCancelled) {
            sendCancellation(connection, id);
          }
        } catch (error) {
          logger.error(`Sending request failed.`);
          responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
          throw error;
        }
      });
    },
    onRequest: (type, handler) => {
      throwIfClosedOrDisposed();
      let method = null;
      if (StarRequestHandler.is(type)) {
        method = void 0;
        starRequestHandler = type;
      } else if (Is.string(type)) {
        method = null;
        if (handler !== void 0) {
          method = type;
          requestHandlers.set(type, { handler, type: void 0 });
        }
      } else {
        if (handler !== void 0) {
          method = type.method;
          requestHandlers.set(type.method, { type, handler });
        }
      }
      return {
        dispose: () => {
          if (method === null) {
            return;
          }
          if (method !== void 0) {
            requestHandlers.delete(method);
          } else {
            starRequestHandler = void 0;
          }
        }
      };
    },
    hasPendingResponse: () => {
      return responsePromises.size > 0;
    },
    trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
      let _sendNotification = false;
      let _traceFormat = TraceFormat.Text;
      if (sendNotificationOrTraceOptions !== void 0) {
        if (Is.boolean(sendNotificationOrTraceOptions)) {
          _sendNotification = sendNotificationOrTraceOptions;
        } else {
          _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
          _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
        }
      }
      trace = _value;
      traceFormat = _traceFormat;
      if (trace === Trace.Off) {
        tracer = void 0;
      } else {
        tracer = _tracer;
      }
      if (_sendNotification && !isClosed() && !isDisposed()) {
        await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
      }
    },
    onError: errorEmitter.event,
    onClose: closeEmitter.event,
    onUnhandledNotification: unhandledNotificationEmitter.event,
    onDispose: disposeEmitter.event,
    end: () => {
      messageWriter.end();
    },
    dispose: () => {
      if (isDisposed()) {
        return;
      }
      state = ConnectionState.Disposed;
      disposeEmitter.fire(void 0);
      const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
      for (const promise of responsePromises.values()) {
        promise.reject(error);
      }
      responsePromises = /* @__PURE__ */ new Map();
      requestTokens = /* @__PURE__ */ new Map();
      knownCanceledRequests = /* @__PURE__ */ new Set();
      messageQueue = new linkedMap_1.LinkedMap();
      if (Is.func(messageWriter.dispose)) {
        messageWriter.dispose();
      }
      if (Is.func(messageReader.dispose)) {
        messageReader.dispose();
      }
    },
    listen: () => {
      throwIfClosedOrDisposed();
      throwIfListening();
      state = ConnectionState.Listening;
      messageReader.listen(callback);
    },
    inspect: () => {
      (0, ral_1.default)().console.log("inspect");
    }
  };
  connection.onNotification(LogTraceNotification.type, (params) => {
    if (trace === Trace.Off || !tracer) {
      return;
    }
    const verbose = trace === Trace.Verbose || trace === Trace.Compact;
    tracer.log(params.message, verbose ? params.verbose : void 0);
  });
  connection.onNotification(ProgressNotification.type, async (params) => {
    const handler = progressHandlers.get(params.token);
    if (handler) {
      await handler(params.value);
    } else {
      unhandledProgressEmitter.fire(params);
    }
  });
  return connection;
}
exports.createMessageConnection = createMessageConnection;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/disposable.js":
/*!********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/disposable.js ***!
  \********************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Disposable = void 0;
var Disposable;
(function(Disposable2) {
  function create(func) {
    return {
      dispose: func
    };
  }
  Disposable2.create = create;
})(Disposable || (exports.Disposable = Disposable = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js":
/*!****************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Emitter = exports.Event = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
var Event;
(function(Event2) {
  const _disposable = { dispose() {
  } };
  Event2.None = function() {
    return _disposable;
  };
})(Event || (exports.Event = Event = {}));
class CallbackList {
  add(callback, context = null, bucket) {
    if (!this._callbacks) {
      this._callbacks = [];
      this._contexts = [];
    }
    this._callbacks.push(callback);
    this._contexts.push(context);
    if (Array.isArray(bucket)) {
      bucket.push({ dispose: () => this.remove(callback, context) });
    }
  }
  remove(callback, context = null) {
    if (!this._callbacks) {
      return;
    }
    let foundCallbackWithDifferentContext = false;
    for (let i = 0, len = this._callbacks.length; i < len; i++) {
      if (this._callbacks[i] === callback) {
        if (this._contexts[i] === context) {
          this._callbacks.splice(i, 1);
          this._contexts.splice(i, 1);
          return;
        } else {
          foundCallbackWithDifferentContext = true;
        }
      }
    }
    if (foundCallbackWithDifferentContext) {
      throw new Error("When adding a listener with a context, you should remove it with the same context");
    }
  }
  invoke(...args) {
    if (!this._callbacks) {
      return [];
    }
    const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
    for (let i = 0, len = callbacks.length; i < len; i++) {
      try {
        ret.push(callbacks[i].apply(contexts[i], args));
      } catch (e) {
        (0, ral_1.default)().console.error(e);
      }
    }
    return ret;
  }
  isEmpty() {
    return !this._callbacks || this._callbacks.length === 0;
  }
  dispose() {
    this._callbacks = void 0;
    this._contexts = void 0;
  }
}
class Emitter {
  constructor(_options) {
    this._options = _options;
  }
  /**
   * For the public to allow to subscribe
   * to events from this Emitter
   */
  get event() {
    if (!this._event) {
      this._event = (listener, thisArgs, disposables) => {
        if (!this._callbacks) {
          this._callbacks = new CallbackList();
        }
        if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
          this._options.onFirstListenerAdd(this);
        }
        this._callbacks.add(listener, thisArgs);
        const result = {
          dispose: () => {
            if (!this._callbacks) {
              return;
            }
            this._callbacks.remove(listener, thisArgs);
            result.dispose = Emitter._noop;
            if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
              this._options.onLastListenerRemove(this);
            }
          }
        };
        if (Array.isArray(disposables)) {
          disposables.push(result);
        }
        return result;
      };
    }
    return this._event;
  }
  /**
   * To be kept private to fire an event to
   * subscribers
   */
  fire(event) {
    if (this._callbacks) {
      this._callbacks.invoke.call(this._callbacks, event);
    }
  }
  dispose() {
    if (this._callbacks) {
      this._callbacks.dispose();
      this._callbacks = void 0;
    }
  }
}
exports.Emitter = Emitter;
Emitter._noop = function() {
};


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js ***!
  \************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
  return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
  return typeof value === "string" || value instanceof String;
}
exports.string = string;
function number(value) {
  return typeof value === "number" || value instanceof Number;
}
exports.number = number;
function error(value) {
  return value instanceof Error;
}
exports.error = error;
function func(value) {
  return typeof value === "function";
}
exports.func = func;
function array(value) {
  return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
  return array(value) && value.every((elem) => string(elem));
}
exports.stringArray = stringArray;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/linkedMap.js":
/*!*******************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/linkedMap.js ***!
  \*******************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LRUCache = exports.LinkedMap = exports.Touch = void 0;
var Touch;
(function(Touch2) {
  Touch2.None = 0;
  Touch2.First = 1;
  Touch2.AsOld = Touch2.First;
  Touch2.Last = 2;
  Touch2.AsNew = Touch2.Last;
})(Touch || (exports.Touch = Touch = {}));
class LinkedMap {
  constructor() {
    this[_a] = "LinkedMap";
    this._map = /* @__PURE__ */ new Map();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state = 0;
  }
  clear() {
    this._map.clear();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state++;
  }
  isEmpty() {
    return !this._head && !this._tail;
  }
  get size() {
    return this._size;
  }
  get first() {
    var _a2;
    return (_a2 = this._head) == null ? void 0 : _a2.value;
  }
  get last() {
    var _a2;
    return (_a2 = this._tail) == null ? void 0 : _a2.value;
  }
  before(key) {
    var _a2;
    const item = this._map.get(key);
    return item ? (_a2 = item.previous) == null ? void 0 : _a2.value : void 0;
  }
  after(key) {
    var _a2;
    const item = this._map.get(key);
    return item ? (_a2 = item.next) == null ? void 0 : _a2.value : void 0;
  }
  has(key) {
    return this._map.has(key);
  }
  get(key, touch = Touch.None) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    if (touch !== Touch.None) {
      this.touch(item, touch);
    }
    return item.value;
  }
  set(key, value, touch = Touch.None) {
    let item = this._map.get(key);
    if (item) {
      item.value = value;
      if (touch !== Touch.None) {
        this.touch(item, touch);
      }
    } else {
      item = { key, value, next: void 0, previous: void 0 };
      switch (touch) {
        case Touch.None:
          this.addItemLast(item);
          break;
        case Touch.First:
          this.addItemFirst(item);
          break;
        case Touch.Last:
          this.addItemLast(item);
          break;
        default:
          this.addItemLast(item);
          break;
      }
      this._map.set(key, item);
      this._size++;
    }
    return this;
  }
  delete(key) {
    return !!this.remove(key);
  }
  remove(key) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    this._map.delete(key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  shift() {
    if (!this._head && !this._tail) {
      return void 0;
    }
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    const item = this._head;
    this._map.delete(item.key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  forEach(callbackfn, thisArg) {
    const state = this._state;
    let current = this._head;
    while (current) {
      if (thisArg) {
        callbackfn.bind(thisArg)(current.value, current.key, this);
      } else {
        callbackfn(current.value, current.key, this);
      }
      if (this._state !== state) {
        throw new Error(`LinkedMap got modified during iteration.`);
      }
      current = current.next;
    }
  }
  keys() {
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]: () => {
        return iterator;
      },
      next: () => {
        if (this._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.key, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  values() {
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]: () => {
        return iterator;
      },
      next: () => {
        if (this._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: current.value, done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  entries() {
    const state = this._state;
    let current = this._head;
    const iterator = {
      [Symbol.iterator]: () => {
        return iterator;
      },
      next: () => {
        if (this._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result = { value: [current.key, current.value], done: false };
          current = current.next;
          return result;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator;
  }
  [(_a = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
  trimOld(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this._head;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this._map.delete(current.key);
      current = current.next;
      currentSize--;
    }
    this._head = current;
    this._size = currentSize;
    if (current) {
      current.previous = void 0;
    }
    this._state++;
  }
  addItemFirst(item) {
    if (!this._head && !this._tail) {
      this._tail = item;
    } else if (!this._head) {
      throw new Error("Invalid list");
    } else {
      item.next = this._head;
      this._head.previous = item;
    }
    this._head = item;
    this._state++;
  }
  addItemLast(item) {
    if (!this._head && !this._tail) {
      this._head = item;
    } else if (!this._tail) {
      throw new Error("Invalid list");
    } else {
      item.previous = this._tail;
      this._tail.next = item;
    }
    this._tail = item;
    this._state++;
  }
  removeItem(item) {
    if (item === this._head && item === this._tail) {
      this._head = void 0;
      this._tail = void 0;
    } else if (item === this._head) {
      if (!item.next) {
        throw new Error("Invalid list");
      }
      item.next.previous = void 0;
      this._head = item.next;
    } else if (item === this._tail) {
      if (!item.previous) {
        throw new Error("Invalid list");
      }
      item.previous.next = void 0;
      this._tail = item.previous;
    } else {
      const next = item.next;
      const previous = item.previous;
      if (!next || !previous) {
        throw new Error("Invalid list");
      }
      next.previous = previous;
      previous.next = next;
    }
    item.next = void 0;
    item.previous = void 0;
    this._state++;
  }
  touch(item, touch) {
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    if (touch !== Touch.First && touch !== Touch.Last) {
      return;
    }
    if (touch === Touch.First) {
      if (item === this._head) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._tail) {
        previous.next = void 0;
        this._tail = previous;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.previous = void 0;
      item.next = this._head;
      this._head.previous = item;
      this._head = item;
      this._state++;
    } else if (touch === Touch.Last) {
      if (item === this._tail) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._head) {
        next.previous = void 0;
        this._head = next;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.next = void 0;
      item.previous = this._tail;
      this._tail.next = item;
      this._tail = item;
      this._state++;
    }
  }
  toJSON() {
    const data = [];
    this.forEach((value, key) => {
      data.push([key, value]);
    });
    return data;
  }
  fromJSON(data) {
    this.clear();
    for (const [key, value] of data) {
      this.set(key, value);
    }
  }
}
exports.LinkedMap = LinkedMap;
class LRUCache extends LinkedMap {
  constructor(limit, ratio = 1) {
    super();
    this._limit = limit;
    this._ratio = Math.min(Math.max(0, ratio), 1);
  }
  get limit() {
    return this._limit;
  }
  set limit(limit) {
    this._limit = limit;
    this.checkTrim();
  }
  get ratio() {
    return this._ratio;
  }
  set ratio(ratio) {
    this._ratio = Math.min(Math.max(0, ratio), 1);
    this.checkTrim();
  }
  get(key, touch = Touch.AsNew) {
    return super.get(key, touch);
  }
  peek(key) {
    return super.get(key, Touch.None);
  }
  set(key, value) {
    super.set(key, value, Touch.Last);
    this.checkTrim();
    return this;
  }
  checkTrim() {
    if (this.size > this._limit) {
      this.trimOld(Math.round(this._limit * this._ratio));
    }
  }
}
exports.LRUCache = LRUCache;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AbstractMessageBuffer = void 0;
const CR = 13;
const LF = 10;
const CRLF = "\r\n";
class AbstractMessageBuffer {
  constructor(encoding = "utf-8") {
    this._encoding = encoding;
    this._chunks = [];
    this._totalLength = 0;
  }
  get encoding() {
    return this._encoding;
  }
  append(chunk) {
    const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
    this._chunks.push(toAppend);
    this._totalLength += toAppend.byteLength;
  }
  tryReadHeaders(lowerCaseKeys = false) {
    if (this._chunks.length === 0) {
      return void 0;
    }
    let state = 0;
    let chunkIndex = 0;
    let offset = 0;
    let chunkBytesRead = 0;
    row:
      while (chunkIndex < this._chunks.length) {
        const chunk = this._chunks[chunkIndex];
        offset = 0;
        while (offset < chunk.length) {
          const value = chunk[offset];
          switch (value) {
            case CR:
              switch (state) {
                case 0:
                  state = 1;
                  break;
                case 2:
                  state = 3;
                  break;
                default:
                  state = 0;
              }
              break;
            case LF:
              switch (state) {
                case 1:
                  state = 2;
                  break;
                case 3:
                  state = 4;
                  offset++;
                  break row;
                default:
                  state = 0;
              }
              break;
            default:
              state = 0;
          }
          offset++;
        }
        chunkBytesRead += chunk.byteLength;
        chunkIndex++;
      }
    if (state !== 4) {
      return void 0;
    }
    const buffer = this._read(chunkBytesRead + offset);
    const result = /* @__PURE__ */ new Map();
    const headers = this.toString(buffer, "ascii").split(CRLF);
    if (headers.length < 2) {
      return result;
    }
    for (let i = 0; i < headers.length - 2; i++) {
      const header = headers[i];
      const index = header.indexOf(":");
      if (index === -1) {
        throw new Error(`Message header must separate key and value using ':'
${header}`);
      }
      const key = header.substr(0, index);
      const value = header.substr(index + 1).trim();
      result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
    }
    return result;
  }
  tryReadBody(length) {
    if (this._totalLength < length) {
      return void 0;
    }
    return this._read(length);
  }
  get numberOfBytes() {
    return this._totalLength;
  }
  _read(byteCount) {
    if (byteCount === 0) {
      return this.emptyBuffer();
    }
    if (byteCount > this._totalLength) {
      throw new Error(`Cannot read so many bytes!`);
    }
    if (this._chunks[0].byteLength === byteCount) {
      const chunk = this._chunks[0];
      this._chunks.shift();
      this._totalLength -= byteCount;
      return this.asNative(chunk);
    }
    if (this._chunks[0].byteLength > byteCount) {
      const chunk = this._chunks[0];
      const result2 = this.asNative(chunk, byteCount);
      this._chunks[0] = chunk.slice(byteCount);
      this._totalLength -= byteCount;
      return result2;
    }
    const result = this.allocNative(byteCount);
    let resultOffset = 0;
    const chunkIndex = 0;
    while (byteCount > 0) {
      const chunk = this._chunks[chunkIndex];
      if (chunk.byteLength > byteCount) {
        const chunkPart = chunk.slice(0, byteCount);
        result.set(chunkPart, resultOffset);
        resultOffset += byteCount;
        this._chunks[chunkIndex] = chunk.slice(byteCount);
        this._totalLength -= byteCount;
        byteCount -= byteCount;
      } else {
        result.set(chunk, resultOffset);
        resultOffset += chunk.byteLength;
        this._chunks.shift();
        this._totalLength -= chunk.byteLength;
        byteCount -= chunk.byteLength;
      }
    }
    return result;
  }
}
exports.AbstractMessageBuffer = AbstractMessageBuffer;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageReader.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageReader.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
const Is = __webpack_require__(/*! ./is */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js");
const events_1 = __webpack_require__(/*! ./events */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js");
const semaphore_1 = __webpack_require__(/*! ./semaphore */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/semaphore.js");
var MessageReader;
(function(MessageReader2) {
  function is(value) {
    const candidate = value;
    return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
  }
  MessageReader2.is = is;
})(MessageReader || (exports.MessageReader = MessageReader = {}));
class AbstractMessageReader {
  constructor() {
    this.errorEmitter = new events_1.Emitter();
    this.closeEmitter = new events_1.Emitter();
    this.partialMessageEmitter = new events_1.Emitter();
  }
  dispose() {
    this.errorEmitter.dispose();
    this.closeEmitter.dispose();
  }
  get onError() {
    return this.errorEmitter.event;
  }
  fireError(error) {
    this.errorEmitter.fire(this.asError(error));
  }
  get onClose() {
    return this.closeEmitter.event;
  }
  fireClose() {
    this.closeEmitter.fire(void 0);
  }
  get onPartialMessage() {
    return this.partialMessageEmitter.event;
  }
  firePartialMessage(info) {
    this.partialMessageEmitter.fire(info);
  }
  asError(error) {
    if (error instanceof Error) {
      return error;
    } else {
      return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
    }
  }
}
exports.AbstractMessageReader = AbstractMessageReader;
var ResolvedMessageReaderOptions;
(function(ResolvedMessageReaderOptions2) {
  function fromOptions(options) {
    var _a;
    let charset;
    let result;
    let contentDecoder;
    const contentDecoders = /* @__PURE__ */ new Map();
    let contentTypeDecoder;
    const contentTypeDecoders = /* @__PURE__ */ new Map();
    if (options === void 0 || typeof options === "string") {
      charset = options != null ? options : "utf-8";
    } else {
      charset = (_a = options.charset) != null ? _a : "utf-8";
      if (options.contentDecoder !== void 0) {
        contentDecoder = options.contentDecoder;
        contentDecoders.set(contentDecoder.name, contentDecoder);
      }
      if (options.contentDecoders !== void 0) {
        for (const decoder of options.contentDecoders) {
          contentDecoders.set(decoder.name, decoder);
        }
      }
      if (options.contentTypeDecoder !== void 0) {
        contentTypeDecoder = options.contentTypeDecoder;
        contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
      }
      if (options.contentTypeDecoders !== void 0) {
        for (const decoder of options.contentTypeDecoders) {
          contentTypeDecoders.set(decoder.name, decoder);
        }
      }
    }
    if (contentTypeDecoder === void 0) {
      contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
      contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
    }
    return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
  }
  ResolvedMessageReaderOptions2.fromOptions = fromOptions;
})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
class ReadableStreamMessageReader extends AbstractMessageReader {
  constructor(readable, options) {
    super();
    this.readable = readable;
    this.options = ResolvedMessageReaderOptions.fromOptions(options);
    this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
    this._partialMessageTimeout = 1e4;
    this.nextMessageLength = -1;
    this.messageToken = 0;
    this.readSemaphore = new semaphore_1.Semaphore(1);
  }
  set partialMessageTimeout(timeout) {
    this._partialMessageTimeout = timeout;
  }
  get partialMessageTimeout() {
    return this._partialMessageTimeout;
  }
  listen(callback) {
    this.nextMessageLength = -1;
    this.messageToken = 0;
    this.partialMessageTimer = void 0;
    this.callback = callback;
    const result = this.readable.onData((data) => {
      this.onData(data);
    });
    this.readable.onError((error) => this.fireError(error));
    this.readable.onClose(() => this.fireClose());
    return result;
  }
  onData(data) {
    try {
      this.buffer.append(data);
      while (true) {
        if (this.nextMessageLength === -1) {
          const headers = this.buffer.tryReadHeaders(true);
          if (!headers) {
            return;
          }
          const contentLength = headers.get("content-length");
          if (!contentLength) {
            this.fireError(new Error(`Header must provide a Content-Length property.
${JSON.stringify(Object.fromEntries(headers))}`));
            return;
          }
          const length = parseInt(contentLength);
          if (isNaN(length)) {
            this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
            return;
          }
          this.nextMessageLength = length;
        }
        const body = this.buffer.tryReadBody(this.nextMessageLength);
        if (body === void 0) {
          this.setPartialMessageTimer();
          return;
        }
        this.clearPartialMessageTimer();
        this.nextMessageLength = -1;
        this.readSemaphore.lock(async () => {
          const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body;
          const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
          this.callback(message);
        }).catch((error) => {
          this.fireError(error);
        });
      }
    } catch (error) {
      this.fireError(error);
    }
  }
  clearPartialMessageTimer() {
    if (this.partialMessageTimer) {
      this.partialMessageTimer.dispose();
      this.partialMessageTimer = void 0;
    }
  }
  setPartialMessageTimer() {
    this.clearPartialMessageTimer();
    if (this._partialMessageTimeout <= 0) {
      return;
    }
    this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
      this.partialMessageTimer = void 0;
      if (token === this.messageToken) {
        this.firePartialMessage({ messageToken: token, waitingTime: timeout });
        this.setPartialMessageTimer();
      }
    }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
  }
}
exports.ReadableStreamMessageReader = ReadableStreamMessageReader;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageWriter.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messageWriter.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
const Is = __webpack_require__(/*! ./is */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js");
const semaphore_1 = __webpack_require__(/*! ./semaphore */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/semaphore.js");
const events_1 = __webpack_require__(/*! ./events */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/events.js");
const ContentLength = "Content-Length: ";
const CRLF = "\r\n";
var MessageWriter;
(function(MessageWriter2) {
  function is(value) {
    const candidate = value;
    return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
  }
  MessageWriter2.is = is;
})(MessageWriter || (exports.MessageWriter = MessageWriter = {}));
class AbstractMessageWriter {
  constructor() {
    this.errorEmitter = new events_1.Emitter();
    this.closeEmitter = new events_1.Emitter();
  }
  dispose() {
    this.errorEmitter.dispose();
    this.closeEmitter.dispose();
  }
  get onError() {
    return this.errorEmitter.event;
  }
  fireError(error, message, count) {
    this.errorEmitter.fire([this.asError(error), message, count]);
  }
  get onClose() {
    return this.closeEmitter.event;
  }
  fireClose() {
    this.closeEmitter.fire(void 0);
  }
  asError(error) {
    if (error instanceof Error) {
      return error;
    } else {
      return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
    }
  }
}
exports.AbstractMessageWriter = AbstractMessageWriter;
var ResolvedMessageWriterOptions;
(function(ResolvedMessageWriterOptions2) {
  function fromOptions(options) {
    var _a, _b;
    if (options === void 0 || typeof options === "string") {
      return { charset: options != null ? options : "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
    } else {
      return { charset: (_a = options.charset) != null ? _a : "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: (_b = options.contentTypeEncoder) != null ? _b : (0, ral_1.default)().applicationJson.encoder };
    }
  }
  ResolvedMessageWriterOptions2.fromOptions = fromOptions;
})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
class WriteableStreamMessageWriter extends AbstractMessageWriter {
  constructor(writable, options) {
    super();
    this.writable = writable;
    this.options = ResolvedMessageWriterOptions.fromOptions(options);
    this.errorCount = 0;
    this.writeSemaphore = new semaphore_1.Semaphore(1);
    this.writable.onError((error) => this.fireError(error));
    this.writable.onClose(() => this.fireClose());
  }
  async write(msg) {
    return this.writeSemaphore.lock(async () => {
      const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
        if (this.options.contentEncoder !== void 0) {
          return this.options.contentEncoder.encode(buffer);
        } else {
          return buffer;
        }
      });
      return payload.then((buffer) => {
        const headers = [];
        headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
        headers.push(CRLF);
        return this.doWrite(msg, headers, buffer);
      }, (error) => {
        this.fireError(error);
        throw error;
      });
    });
  }
  async doWrite(msg, headers, data) {
    try {
      await this.writable.write(headers.join(""), "ascii");
      return this.writable.write(data);
    } catch (error) {
      this.handleError(error, msg);
      return Promise.reject(error);
    }
  }
  handleError(error, msg) {
    this.errorCount++;
    this.fireError(error, msg, this.errorCount);
  }
  end() {
    this.writable.end();
  }
}
exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messages.js":
/*!******************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/messages.js ***!
  \******************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;
const is = __webpack_require__(/*! ./is */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/is.js");
var ErrorCodes;
(function(ErrorCodes2) {
  ErrorCodes2.ParseError = -32700;
  ErrorCodes2.InvalidRequest = -32600;
  ErrorCodes2.MethodNotFound = -32601;
  ErrorCodes2.InvalidParams = -32602;
  ErrorCodes2.InternalError = -32603;
  ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
  ErrorCodes2.serverErrorStart = -32099;
  ErrorCodes2.MessageWriteError = -32099;
  ErrorCodes2.MessageReadError = -32098;
  ErrorCodes2.PendingResponseRejected = -32097;
  ErrorCodes2.ConnectionInactive = -32096;
  ErrorCodes2.ServerNotInitialized = -32002;
  ErrorCodes2.UnknownErrorCode = -32001;
  ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3;
  ErrorCodes2.serverErrorEnd = -32e3;
})(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));
class ResponseError extends Error {
  constructor(code, message, data) {
    super(message);
    this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
    this.data = data;
    Object.setPrototypeOf(this, ResponseError.prototype);
  }
  toJson() {
    const result = {
      code: this.code,
      message: this.message
    };
    if (this.data !== void 0) {
      result.data = this.data;
    }
    return result;
  }
}
exports.ResponseError = ResponseError;
class ParameterStructures {
  constructor(kind) {
    this.kind = kind;
  }
  static is(value) {
    return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
  }
  toString() {
    return this.kind;
  }
}
exports.ParameterStructures = ParameterStructures;
ParameterStructures.auto = new ParameterStructures("auto");
ParameterStructures.byPosition = new ParameterStructures("byPosition");
ParameterStructures.byName = new ParameterStructures("byName");
class AbstractMessageSignature {
  constructor(method, numberOfParams) {
    this.method = method;
    this.numberOfParams = numberOfParams;
  }
  get parameterStructures() {
    return ParameterStructures.auto;
  }
}
exports.AbstractMessageSignature = AbstractMessageSignature;
class RequestType0 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 0);
  }
}
exports.RequestType0 = RequestType0;
class RequestType extends AbstractMessageSignature {
  constructor(method, _parameterStructures = ParameterStructures.auto) {
    super(method, 1);
    this._parameterStructures = _parameterStructures;
  }
  get parameterStructures() {
    return this._parameterStructures;
  }
}
exports.RequestType = RequestType;
class RequestType1 extends AbstractMessageSignature {
  constructor(method, _parameterStructures = ParameterStructures.auto) {
    super(method, 1);
    this._parameterStructures = _parameterStructures;
  }
  get parameterStructures() {
    return this._parameterStructures;
  }
}
exports.RequestType1 = RequestType1;
class RequestType2 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 2);
  }
}
exports.RequestType2 = RequestType2;
class RequestType3 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 3);
  }
}
exports.RequestType3 = RequestType3;
class RequestType4 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 4);
  }
}
exports.RequestType4 = RequestType4;
class RequestType5 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 5);
  }
}
exports.RequestType5 = RequestType5;
class RequestType6 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 6);
  }
}
exports.RequestType6 = RequestType6;
class RequestType7 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 7);
  }
}
exports.RequestType7 = RequestType7;
class RequestType8 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 8);
  }
}
exports.RequestType8 = RequestType8;
class RequestType9 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 9);
  }
}
exports.RequestType9 = RequestType9;
class NotificationType extends AbstractMessageSignature {
  constructor(method, _parameterStructures = ParameterStructures.auto) {
    super(method, 1);
    this._parameterStructures = _parameterStructures;
  }
  get parameterStructures() {
    return this._parameterStructures;
  }
}
exports.NotificationType = NotificationType;
class NotificationType0 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 0);
  }
}
exports.NotificationType0 = NotificationType0;
class NotificationType1 extends AbstractMessageSignature {
  constructor(method, _parameterStructures = ParameterStructures.auto) {
    super(method, 1);
    this._parameterStructures = _parameterStructures;
  }
  get parameterStructures() {
    return this._parameterStructures;
  }
}
exports.NotificationType1 = NotificationType1;
class NotificationType2 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 2);
  }
}
exports.NotificationType2 = NotificationType2;
class NotificationType3 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 3);
  }
}
exports.NotificationType3 = NotificationType3;
class NotificationType4 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 4);
  }
}
exports.NotificationType4 = NotificationType4;
class NotificationType5 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 5);
  }
}
exports.NotificationType5 = NotificationType5;
class NotificationType6 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 6);
  }
}
exports.NotificationType6 = NotificationType6;
class NotificationType7 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 7);
  }
}
exports.NotificationType7 = NotificationType7;
class NotificationType8 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 8);
  }
}
exports.NotificationType8 = NotificationType8;
class NotificationType9 extends AbstractMessageSignature {
  constructor(method) {
    super(method, 9);
  }
}
exports.NotificationType9 = NotificationType9;
var Message;
(function(Message2) {
  function isRequest(message) {
    const candidate = message;
    return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
  }
  Message2.isRequest = isRequest;
  function isNotification(message) {
    const candidate = message;
    return candidate && is.string(candidate.method) && message.id === void 0;
  }
  Message2.isNotification = isNotification;
  function isResponse(message) {
    const candidate = message;
    return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
  }
  Message2.isResponse = isResponse;
})(Message || (exports.Message = Message = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js":
/*!*************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
let _ral;
function RAL() {
  if (_ral === void 0) {
    throw new Error(`No runtime abstraction layer installed`);
  }
  return _ral;
}
(function(RAL2) {
  function install(ral) {
    if (ral === void 0) {
      throw new Error(`No runtime abstraction layer provided`);
    }
    _ral = ral;
  }
  RAL2.install = install;
})(RAL || (RAL = {}));
exports["default"] = RAL;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/semaphore.js":
/*!*******************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/semaphore.js ***!
  \*******************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Semaphore = void 0;
const ral_1 = __webpack_require__(/*! ./ral */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/ral.js");
class Semaphore {
  constructor(capacity = 1) {
    if (capacity <= 0) {
      throw new Error("Capacity must be greater than 0");
    }
    this._capacity = capacity;
    this._active = 0;
    this._waiting = [];
  }
  lock(thunk) {
    return new Promise((resolve, reject) => {
      this._waiting.push({ thunk, resolve, reject });
      this.runNext();
    });
  }
  get active() {
    return this._active;
  }
  runNext() {
    if (this._waiting.length === 0 || this._active === this._capacity) {
      return;
    }
    (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
  }
  doRunNext() {
    if (this._waiting.length === 0 || this._active === this._capacity) {
      return;
    }
    const next = this._waiting.shift();
    this._active++;
    if (this._active > this._capacity) {
      throw new Error(`To many thunks active`);
    }
    try {
      const result = next.thunk();
      if (result instanceof Promise) {
        result.then((value) => {
          this._active--;
          next.resolve(value);
          this.runNext();
        }, (err) => {
          this._active--;
          next.reject(err);
          this.runNext();
        });
      } else {
        this._active--;
        next.resolve(result);
        this.runNext();
      }
    } catch (err) {
      this._active--;
      next.reject(err);
      this.runNext();
    }
  }
}
exports.Semaphore = Semaphore;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js":
/*!*********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js ***!
  \*********************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;
const cancellation_1 = __webpack_require__(/*! ./cancellation */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/cancellation.js");
var CancellationState;
(function(CancellationState2) {
  CancellationState2.Continue = 0;
  CancellationState2.Cancelled = 1;
})(CancellationState || (CancellationState = {}));
class SharedArraySenderStrategy {
  constructor() {
    this.buffers = /* @__PURE__ */ new Map();
  }
  enableCancellation(request) {
    if (request.id === null) {
      return;
    }
    const buffer = new SharedArrayBuffer(4);
    const data = new Int32Array(buffer, 0, 1);
    data[0] = CancellationState.Continue;
    this.buffers.set(request.id, buffer);
    request.$cancellationData = buffer;
  }
  async sendCancellation(_conn, id) {
    const buffer = this.buffers.get(id);
    if (buffer === void 0) {
      return;
    }
    const data = new Int32Array(buffer, 0, 1);
    Atomics.store(data, 0, CancellationState.Cancelled);
  }
  cleanup(id) {
    this.buffers.delete(id);
  }
  dispose() {
    this.buffers.clear();
  }
}
exports.SharedArraySenderStrategy = SharedArraySenderStrategy;
class SharedArrayBufferCancellationToken {
  constructor(buffer) {
    this.data = new Int32Array(buffer, 0, 1);
  }
  get isCancellationRequested() {
    return Atomics.load(this.data, 0) === CancellationState.Cancelled;
  }
  get onCancellationRequested() {
    throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
  }
}
class SharedArrayBufferCancellationTokenSource {
  constructor(buffer) {
    this.token = new SharedArrayBufferCancellationToken(buffer);
  }
  cancel() {
  }
  dispose() {
  }
}
class SharedArrayReceiverStrategy {
  constructor() {
    this.kind = "request";
  }
  createCancellationTokenSource(request) {
    const buffer = request.$cancellationData;
    if (buffer === void 0) {
      return new cancellation_1.CancellationTokenSource();
    }
    return new SharedArrayBufferCancellationTokenSource(buffer);
  }
}
exports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js":
/*!************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js ***!
  \************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: function() {
      return m[k];
    } };
  }
  Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
});
var __exportStar = this && this.__exportStar || function(m, exports2) {
  for (var p in m)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
      __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createMessageConnection = exports.createServerSocketTransport = exports.createClientSocketTransport = exports.createServerPipeTransport = exports.createClientPipeTransport = exports.generateRandomPipeName = exports.StreamMessageWriter = exports.StreamMessageReader = exports.SocketMessageWriter = exports.SocketMessageReader = exports.PortMessageWriter = exports.PortMessageReader = exports.IPCMessageWriter = exports.IPCMessageReader = void 0;
const ril_1 = __webpack_require__(/*! ./ril */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/ril.js");
ril_1.default.install();
const path = __webpack_require__(/*! path */ "path");
const os = __webpack_require__(/*! os */ "os");
const fs = __webpack_require__(/*! fs */ "fs");
const crypto_1 = __webpack_require__(/*! crypto */ "crypto");
const net_1 = __webpack_require__(/*! net */ "net");
const api_1 = __webpack_require__(/*! ../common/api */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/api.js");
__exportStar(__webpack_require__(/*! ../common/api */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/api.js"), exports);
class IPCMessageReader extends api_1.AbstractMessageReader {
  constructor(process2) {
    super();
    this.process = process2;
    const eventEmitter = this.process;
    eventEmitter.on("error", (error) => this.fireError(error));
    eventEmitter.on("close", () => this.fireClose());
  }
  listen(callback) {
    this.process.on("message", callback);
    return api_1.Disposable.create(() => this.process.off("message", callback));
  }
}
exports.IPCMessageReader = IPCMessageReader;
class IPCMessageWriter extends api_1.AbstractMessageWriter {
  constructor(process2) {
    super();
    this.process = process2;
    this.errorCount = 0;
    const eventEmitter = this.process;
    eventEmitter.on("error", (error) => this.fireError(error));
    eventEmitter.on("close", () => this.fireClose);
  }
  write(msg) {
    try {
      if (typeof this.process.send === "function") {
        this.process.send(msg, void 0, void 0, (error) => {
          if (error) {
            this.errorCount++;
            this.handleError(error, msg);
          } else {
            this.errorCount = 0;
          }
        });
      }
      return Promise.resolve();
    } catch (error) {
      this.handleError(error, msg);
      return Promise.reject(error);
    }
  }
  handleError(error, msg) {
    this.errorCount++;
    this.fireError(error, msg, this.errorCount);
  }
  end() {
  }
}
exports.IPCMessageWriter = IPCMessageWriter;
class PortMessageReader extends api_1.AbstractMessageReader {
  constructor(port) {
    super();
    this.onData = new api_1.Emitter();
    port.on("close", () => this.fireClose);
    port.on("error", (error) => this.fireError(error));
    port.on("message", (message) => {
      this.onData.fire(message);
    });
  }
  listen(callback) {
    return this.onData.event(callback);
  }
}
exports.PortMessageReader = PortMessageReader;
class PortMessageWriter extends api_1.AbstractMessageWriter {
  constructor(port) {
    super();
    this.port = port;
    this.errorCount = 0;
    port.on("close", () => this.fireClose());
    port.on("error", (error) => this.fireError(error));
  }
  write(msg) {
    try {
      this.port.postMessage(msg);
      return Promise.resolve();
    } catch (error) {
      this.handleError(error, msg);
      return Promise.reject(error);
    }
  }
  handleError(error, msg) {
    this.errorCount++;
    this.fireError(error, msg, this.errorCount);
  }
  end() {
  }
}
exports.PortMessageWriter = PortMessageWriter;
class SocketMessageReader extends api_1.ReadableStreamMessageReader {
  constructor(socket, encoding = "utf-8") {
    super((0, ril_1.default)().stream.asReadableStream(socket), encoding);
  }
}
exports.SocketMessageReader = SocketMessageReader;
class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
  constructor(socket, options) {
    super((0, ril_1.default)().stream.asWritableStream(socket), options);
    this.socket = socket;
  }
  dispose() {
    super.dispose();
    this.socket.destroy();
  }
}
exports.SocketMessageWriter = SocketMessageWriter;
class StreamMessageReader extends api_1.ReadableStreamMessageReader {
  constructor(readable, encoding) {
    super((0, ril_1.default)().stream.asReadableStream(readable), encoding);
  }
}
exports.StreamMessageReader = StreamMessageReader;
class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
  constructor(writable, options) {
    super((0, ril_1.default)().stream.asWritableStream(writable), options);
  }
}
exports.StreamMessageWriter = StreamMessageWriter;
const XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
const safeIpcPathLengths = /* @__PURE__ */ new Map([
  ["linux", 107],
  ["darwin", 103]
]);
function generateRandomPipeName() {
  if (process.platform === "win32") {
    return `\\\\.\\pipe\\lsp-${(0, crypto_1.randomBytes)(16).toString("hex")}-sock`;
  }
  let randomLength = 32;
  const fixedLength = "lsp-.sock".length;
  const tmpDir = fs.realpathSync(XDG_RUNTIME_DIR != null ? XDG_RUNTIME_DIR : os.tmpdir());
  const limit = safeIpcPathLengths.get(process.platform);
  if (limit !== void 0) {
    randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength);
  }
  if (randomLength < 16) {
    throw new Error(`Unable to generate a random pipe name with ${randomLength} characters.`);
  }
  const randomSuffix = (0, crypto_1.randomBytes)(Math.floor(randomLength / 2)).toString("hex");
  return path.join(tmpDir, `lsp-${randomSuffix}.sock`);
}
exports.generateRandomPipeName = generateRandomPipeName;
function createClientPipeTransport(pipeName, encoding = "utf-8") {
  let connectResolve;
  const connected = new Promise((resolve, _reject) => {
    connectResolve = resolve;
  });
  return new Promise((resolve, reject) => {
    const server = (0, net_1.createServer)((socket) => {
      server.close();
      connectResolve([
        new SocketMessageReader(socket, encoding),
        new SocketMessageWriter(socket, encoding)
      ]);
    });
    server.on("error", reject);
    server.listen(pipeName, () => {
      server.removeListener("error", reject);
      resolve({
        onConnected: () => {
          return connected;
        }
      });
    });
  });
}
exports.createClientPipeTransport = createClientPipeTransport;
function createServerPipeTransport(pipeName, encoding = "utf-8") {
  const socket = (0, net_1.createConnection)(pipeName);
  return [
    new SocketMessageReader(socket, encoding),
    new SocketMessageWriter(socket, encoding)
  ];
}
exports.createServerPipeTransport = createServerPipeTransport;
function createClientSocketTransport(port, encoding = "utf-8") {
  let connectResolve;
  const connected = new Promise((resolve, _reject) => {
    connectResolve = resolve;
  });
  return new Promise((resolve, reject) => {
    const server = (0, net_1.createServer)((socket) => {
      server.close();
      connectResolve([
        new SocketMessageReader(socket, encoding),
        new SocketMessageWriter(socket, encoding)
      ]);
    });
    server.on("error", reject);
    server.listen(port, "127.0.0.1", () => {
      server.removeListener("error", reject);
      resolve({
        onConnected: () => {
          return connected;
        }
      });
    });
  });
}
exports.createClientSocketTransport = createClientSocketTransport;
function createServerSocketTransport(port, encoding = "utf-8") {
  const socket = (0, net_1.createConnection)(port, "127.0.0.1");
  return [
    new SocketMessageReader(socket, encoding),
    new SocketMessageWriter(socket, encoding)
  ];
}
exports.createServerSocketTransport = createServerSocketTransport;
function isReadableStream(value) {
  const candidate = value;
  return candidate.read !== void 0 && candidate.addListener !== void 0;
}
function isWritableStream(value) {
  const candidate = value;
  return candidate.write !== void 0 && candidate.addListener !== void 0;
}
function createMessageConnection(input, output, logger, options) {
  if (!logger) {
    logger = api_1.NullLogger;
  }
  const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;
  const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;
  if (api_1.ConnectionStrategy.is(options)) {
    options = { connectionStrategy: options };
  }
  return (0, api_1.createMessageConnection)(reader, writer, logger, options);
}
exports.createMessageConnection = createMessageConnection;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/ril.js":
/*!***********************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/lib/node/ril.js ***!
  \***********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
const util_1 = __webpack_require__(/*! util */ "util");
const api_1 = __webpack_require__(/*! ../common/api */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/common/api.js");
class MessageBuffer extends api_1.AbstractMessageBuffer {
  constructor(encoding = "utf-8") {
    super(encoding);
  }
  emptyBuffer() {
    return MessageBuffer.emptyBuffer;
  }
  fromString(value, encoding) {
    return Buffer.from(value, encoding);
  }
  toString(value, encoding) {
    if (value instanceof Buffer) {
      return value.toString(encoding);
    } else {
      return new util_1.TextDecoder(encoding).decode(value);
    }
  }
  asNative(buffer, length) {
    if (length === void 0) {
      return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
    } else {
      return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
    }
  }
  allocNative(length) {
    return Buffer.allocUnsafe(length);
  }
}
MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);
class ReadableStreamWrapper {
  constructor(stream) {
    this.stream = stream;
  }
  onClose(listener) {
    this.stream.on("close", listener);
    return api_1.Disposable.create(() => this.stream.off("close", listener));
  }
  onError(listener) {
    this.stream.on("error", listener);
    return api_1.Disposable.create(() => this.stream.off("error", listener));
  }
  onEnd(listener) {
    this.stream.on("end", listener);
    return api_1.Disposable.create(() => this.stream.off("end", listener));
  }
  onData(listener) {
    this.stream.on("data", listener);
    return api_1.Disposable.create(() => this.stream.off("data", listener));
  }
}
class WritableStreamWrapper {
  constructor(stream) {
    this.stream = stream;
  }
  onClose(listener) {
    this.stream.on("close", listener);
    return api_1.Disposable.create(() => this.stream.off("close", listener));
  }
  onError(listener) {
    this.stream.on("error", listener);
    return api_1.Disposable.create(() => this.stream.off("error", listener));
  }
  onEnd(listener) {
    this.stream.on("end", listener);
    return api_1.Disposable.create(() => this.stream.off("end", listener));
  }
  write(data, encoding) {
    return new Promise((resolve, reject) => {
      const callback = (error) => {
        if (error === void 0 || error === null) {
          resolve();
        } else {
          reject(error);
        }
      };
      if (typeof data === "string") {
        this.stream.write(data, encoding, callback);
      } else {
        this.stream.write(data, callback);
      }
    });
  }
  end() {
    this.stream.end();
  }
}
const _ril = Object.freeze({
  messageBuffer: Object.freeze({
    create: (encoding) => new MessageBuffer(encoding)
  }),
  applicationJson: Object.freeze({
    encoder: Object.freeze({
      name: "application/json",
      encode: (msg, options) => {
        try {
          return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset));
        } catch (err) {
          return Promise.reject(err);
        }
      }
    }),
    decoder: Object.freeze({
      name: "application/json",
      decode: (buffer, options) => {
        try {
          if (buffer instanceof Buffer) {
            return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
          } else {
            return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
          }
        } catch (err) {
          return Promise.reject(err);
        }
      }
    })
  }),
  stream: Object.freeze({
    asReadableStream: (stream) => new ReadableStreamWrapper(stream),
    asWritableStream: (stream) => new WritableStreamWrapper(stream)
  }),
  console,
  timer: Object.freeze({
    setTimeout(callback, ms, ...args) {
      const handle = setTimeout(callback, ms, ...args);
      return { dispose: () => clearTimeout(handle) };
    },
    setImmediate(callback, ...args) {
      const handle = setImmediate(callback, ...args);
      return { dispose: () => clearImmediate(handle) };
    },
    setInterval(callback, ms, ...args) {
      const handle = setInterval(callback, ms, ...args);
      return { dispose: () => clearInterval(handle) };
    }
  })
});
function RIL() {
  return _ril;
}
(function(RIL2) {
  function install() {
    api_1.RAL.install(_ril);
  }
  RIL2.install = install;
})(RIL || (RIL = {}));
exports["default"] = RIL;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-jsonrpc/node.js":
/*!***************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-jsonrpc/node.js ***!
  \***************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = __webpack_require__(/*! ./lib/node/main */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/api.js":
/*!*****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/api.js ***!
  \*****************************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: function() {
      return m[k];
    } };
  }
  Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
});
var __exportStar = this && this.__exportStar || function(m, exports2) {
  for (var p in m)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
      __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LSPErrorCodes = exports.createProtocolConnection = void 0;
__exportStar(__webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js"), exports);
__exportStar(__webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js"), exports);
__exportStar(__webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js"), exports);
__exportStar(__webpack_require__(/*! ./protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.js"), exports);
var connection_1 = __webpack_require__(/*! ./connection */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/connection.js");
Object.defineProperty(exports, "createProtocolConnection", ({ enumerable: true, get: function() {
  return connection_1.createProtocolConnection;
} }));
var LSPErrorCodes;
(function(LSPErrorCodes2) {
  LSPErrorCodes2.lspReservedErrorRangeStart = -32899;
  LSPErrorCodes2.RequestFailed = -32803;
  LSPErrorCodes2.ServerCancelled = -32802;
  LSPErrorCodes2.ContentModified = -32801;
  LSPErrorCodes2.RequestCancelled = -32800;
  LSPErrorCodes2.lspReservedErrorRangeEnd = -32800;
})(LSPErrorCodes || (exports.LSPErrorCodes = LSPErrorCodes = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/connection.js":
/*!************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/connection.js ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createProtocolConnection = void 0;
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
function createProtocolConnection(input, output, logger, options) {
  if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
    options = { connectionStrategy: options };
  }
  return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
}
exports.createProtocolConnection = createProtocolConnection;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js":
/*!**********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProtocolNotificationType = exports.ProtocolNotificationType0 = exports.ProtocolRequestType = exports.ProtocolRequestType0 = exports.RegistrationType = exports.MessageDirection = void 0;
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
var MessageDirection;
(function(MessageDirection2) {
  MessageDirection2["clientToServer"] = "clientToServer";
  MessageDirection2["serverToClient"] = "serverToClient";
  MessageDirection2["both"] = "both";
})(MessageDirection || (exports.MessageDirection = MessageDirection = {}));
class RegistrationType {
  constructor(method) {
    this.method = method;
  }
}
exports.RegistrationType = RegistrationType;
class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
  constructor(method) {
    super(method);
  }
}
exports.ProtocolRequestType0 = ProtocolRequestType0;
class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
  constructor(method) {
    super(method, vscode_jsonrpc_1.ParameterStructures.byName);
  }
}
exports.ProtocolRequestType = ProtocolRequestType;
class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
  constructor(method) {
    super(method);
  }
}
exports.ProtocolNotificationType0 = ProtocolNotificationType0;
class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
  constructor(method) {
    super(method, vscode_jsonrpc_1.ParameterStructures.byName);
  }
}
exports.ProtocolNotificationType = ProtocolNotificationType;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js":
/*!************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js ***!
  \************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.CallHierarchyPrepareRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var CallHierarchyPrepareRequest;
(function(CallHierarchyPrepareRequest2) {
  CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
  CallHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
})(CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));
var CallHierarchyIncomingCallsRequest;
(function(CallHierarchyIncomingCallsRequest2) {
  CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
  CallHierarchyIncomingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
})(CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));
var CallHierarchyOutgoingCallsRequest;
(function(CallHierarchyOutgoingCallsRequest2) {
  CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
  CallHierarchyOutgoingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
})(CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js":
/*!************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js ***!
  \************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ColorPresentationRequest = exports.DocumentColorRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var DocumentColorRequest;
(function(DocumentColorRequest2) {
  DocumentColorRequest2.method = "textDocument/documentColor";
  DocumentColorRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
})(DocumentColorRequest || (exports.DocumentColorRequest = DocumentColorRequest = {}));
var ColorPresentationRequest;
(function(ColorPresentationRequest2) {
  ColorPresentationRequest2.method = "textDocument/colorPresentation";
  ColorPresentationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  ColorPresentationRequest2.type = new messages_1.ProtocolRequestType(ColorPresentationRequest2.method);
})(ColorPresentationRequest || (exports.ColorPresentationRequest = ColorPresentationRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js":
/*!************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js ***!
  \************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConfigurationRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var ConfigurationRequest;
(function(ConfigurationRequest2) {
  ConfigurationRequest2.method = "workspace/configuration";
  ConfigurationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  ConfigurationRequest2.type = new messages_1.ProtocolRequestType(ConfigurationRequest2.method);
})(ConfigurationRequest || (exports.ConfigurationRequest = ConfigurationRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js":
/*!**********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js ***!
  \**********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DeclarationRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
let __noDynamicImport;
var DeclarationRequest;
(function(DeclarationRequest2) {
  DeclarationRequest2.method = "textDocument/declaration";
  DeclarationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
})(DeclarationRequest || (exports.DeclarationRequest = DeclarationRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js":
/*!*********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js ***!
  \*********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = void 0;
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
const Is = __webpack_require__(/*! ./utils/is */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js");
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var DiagnosticServerCancellationData;
(function(DiagnosticServerCancellationData2) {
  function is(value) {
    const candidate = value;
    return candidate && Is.boolean(candidate.retriggerRequest);
  }
  DiagnosticServerCancellationData2.is = is;
})(DiagnosticServerCancellationData || (exports.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));
var DocumentDiagnosticReportKind;
(function(DocumentDiagnosticReportKind2) {
  DocumentDiagnosticReportKind2.Full = "full";
  DocumentDiagnosticReportKind2.Unchanged = "unchanged";
})(DocumentDiagnosticReportKind || (exports.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));
var DocumentDiagnosticRequest;
(function(DocumentDiagnosticRequest2) {
  DocumentDiagnosticRequest2.method = "textDocument/diagnostic";
  DocumentDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentDiagnosticRequest2.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method);
  DocumentDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
})(DocumentDiagnosticRequest || (exports.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));
var WorkspaceDiagnosticRequest;
(function(WorkspaceDiagnosticRequest2) {
  WorkspaceDiagnosticRequest2.method = "workspace/diagnostic";
  WorkspaceDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WorkspaceDiagnosticRequest2.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method);
  WorkspaceDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
})(WorkspaceDiagnosticRequest || (exports.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));
var DiagnosticRefreshRequest;
(function(DiagnosticRefreshRequest2) {
  DiagnosticRefreshRequest2.method = `workspace/diagnostic/refresh`;
  DiagnosticRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  DiagnosticRefreshRequest2.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method);
})(DiagnosticRefreshRequest || (exports.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js":
/*!*************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.DidRenameFilesNotification = exports.WillRenameFilesRequest = exports.DidCreateFilesNotification = exports.WillCreateFilesRequest = exports.FileOperationPatternKind = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var FileOperationPatternKind;
(function(FileOperationPatternKind2) {
  FileOperationPatternKind2.file = "file";
  FileOperationPatternKind2.folder = "folder";
})(FileOperationPatternKind || (exports.FileOperationPatternKind = FileOperationPatternKind = {}));
var WillCreateFilesRequest;
(function(WillCreateFilesRequest2) {
  WillCreateFilesRequest2.method = "workspace/willCreateFiles";
  WillCreateFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method);
})(WillCreateFilesRequest || (exports.WillCreateFilesRequest = WillCreateFilesRequest = {}));
var DidCreateFilesNotification;
(function(DidCreateFilesNotification2) {
  DidCreateFilesNotification2.method = "workspace/didCreateFiles";
  DidCreateFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method);
})(DidCreateFilesNotification || (exports.DidCreateFilesNotification = DidCreateFilesNotification = {}));
var WillRenameFilesRequest;
(function(WillRenameFilesRequest2) {
  WillRenameFilesRequest2.method = "workspace/willRenameFiles";
  WillRenameFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method);
})(WillRenameFilesRequest || (exports.WillRenameFilesRequest = WillRenameFilesRequest = {}));
var DidRenameFilesNotification;
(function(DidRenameFilesNotification2) {
  DidRenameFilesNotification2.method = "workspace/didRenameFiles";
  DidRenameFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method);
})(DidRenameFilesNotification || (exports.DidRenameFilesNotification = DidRenameFilesNotification = {}));
var DidDeleteFilesNotification;
(function(DidDeleteFilesNotification2) {
  DidDeleteFilesNotification2.method = "workspace/didDeleteFiles";
  DidDeleteFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method);
})(DidDeleteFilesNotification || (exports.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));
var WillDeleteFilesRequest;
(function(WillDeleteFilesRequest2) {
  WillDeleteFilesRequest2.method = "workspace/willDeleteFiles";
  WillDeleteFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method);
})(WillDeleteFilesRequest || (exports.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js":
/*!***********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var FoldingRangeRequest;
(function(FoldingRangeRequest2) {
  FoldingRangeRequest2.method = "textDocument/foldingRange";
  FoldingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
})(FoldingRangeRequest || (exports.FoldingRangeRequest = FoldingRangeRequest = {}));
var FoldingRangeRefreshRequest;
(function(FoldingRangeRefreshRequest2) {
  FoldingRangeRefreshRequest2.method = `workspace/foldingRange/refresh`;
  FoldingRangeRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  FoldingRangeRefreshRequest2.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method);
})(FoldingRangeRefreshRequest || (exports.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js":
/*!*************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ImplementationRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
let __noDynamicImport;
var ImplementationRequest;
(function(ImplementationRequest2) {
  ImplementationRequest2.method = "textDocument/implementation";
  ImplementationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
})(ImplementationRequest || (exports.ImplementationRequest = ImplementationRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js":
/*!********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js ***!
  \********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var InlayHintRequest;
(function(InlayHintRequest2) {
  InlayHintRequest2.method = "textDocument/inlayHint";
  InlayHintRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  InlayHintRequest2.type = new messages_1.ProtocolRequestType(InlayHintRequest2.method);
})(InlayHintRequest || (exports.InlayHintRequest = InlayHintRequest = {}));
var InlayHintResolveRequest;
(function(InlayHintResolveRequest2) {
  InlayHintResolveRequest2.method = "inlayHint/resolve";
  InlayHintResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  InlayHintResolveRequest2.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method);
})(InlayHintResolveRequest || (exports.InlayHintResolveRequest = InlayHintResolveRequest = {}));
var InlayHintRefreshRequest;
(function(InlayHintRefreshRequest2) {
  InlayHintRefreshRequest2.method = `workspace/inlayHint/refresh`;
  InlayHintRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  InlayHintRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method);
})(InlayHintRefreshRequest || (exports.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js":
/*!***************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js ***!
  \***************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlineCompletionRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var InlineCompletionRequest;
(function(InlineCompletionRequest2) {
  InlineCompletionRequest2.method = "textDocument/inlineCompletion";
  InlineCompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  InlineCompletionRequest2.type = new messages_1.ProtocolRequestType(InlineCompletionRequest2.method);
})(InlineCompletionRequest || (exports.InlineCompletionRequest = InlineCompletionRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js":
/*!**********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js ***!
  \**********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlineValueRefreshRequest = exports.InlineValueRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var InlineValueRequest;
(function(InlineValueRequest2) {
  InlineValueRequest2.method = "textDocument/inlineValue";
  InlineValueRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  InlineValueRequest2.type = new messages_1.ProtocolRequestType(InlineValueRequest2.method);
})(InlineValueRequest || (exports.InlineValueRequest = InlineValueRequest = {}));
var InlineValueRefreshRequest;
(function(InlineValueRefreshRequest2) {
  InlineValueRefreshRequest2.method = `workspace/inlineValue/refresh`;
  InlineValueRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  InlineValueRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method);
})(InlineValueRefreshRequest || (exports.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.js":
/*!**********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CodeActionResolveRequest = exports.CodeActionRequest = exports.DocumentSymbolRequest = exports.DocumentHighlightRequest = exports.ReferencesRequest = exports.DefinitionRequest = exports.SignatureHelpRequest = exports.SignatureHelpTriggerKind = exports.HoverRequest = exports.CompletionResolveRequest = exports.CompletionRequest = exports.CompletionTriggerKind = exports.PublishDiagnosticsNotification = exports.WatchKind = exports.RelativePattern = exports.FileChangeType = exports.DidChangeWatchedFilesNotification = exports.WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentNotification = exports.TextDocumentSaveReason = exports.DidSaveTextDocumentNotification = exports.DidCloseTextDocumentNotification = exports.DidChangeTextDocumentNotification = exports.TextDocumentContentChangeEvent = exports.DidOpenTextDocumentNotification = exports.TextDocumentSyncKind = exports.TelemetryEventNotification = exports.LogMessageNotification = exports.ShowMessageRequest = exports.ShowMessageNotification = exports.MessageType = exports.DidChangeConfigurationNotification = exports.ExitNotification = exports.ShutdownRequest = exports.InitializedNotification = exports.InitializeErrorCodes = exports.InitializeRequest = exports.WorkDoneProgressOptions = exports.TextDocumentRegistrationOptions = exports.StaticRegistrationOptions = exports.PositionEncodingKind = exports.RegularExpressionEngineKind = exports.FailureHandlingKind = exports.ResourceOperationKind = exports.UnregistrationRequest = exports.RegistrationRequest = exports.DocumentSelector = exports.NotebookCellTextDocumentFilter = exports.NotebookDocumentFilter = exports.TextDocumentFilter = void 0;
exports.MonikerKind = exports.UniquenessLevel = exports.WillDeleteFilesRequest = exports.DidDeleteFilesNotification = exports.WillRenameFilesRequest = exports.DidRenameFilesNotification = exports.WillCreateFilesRequest = exports.DidCreateFilesNotification = exports.FileOperationPatternKind = exports.LinkedEditingRangeRequest = exports.ShowDocumentRequest = exports.SemanticTokensRegistrationType = exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.TokenFormat = exports.CallHierarchyPrepareRequest = exports.CallHierarchyOutgoingCallsRequest = exports.CallHierarchyIncomingCallsRequest = exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = exports.SelectionRangeRequest = exports.DeclarationRequest = exports.FoldingRangeRefreshRequest = exports.FoldingRangeRequest = exports.ColorPresentationRequest = exports.DocumentColorRequest = exports.ConfigurationRequest = exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = exports.TypeDefinitionRequest = exports.ImplementationRequest = exports.ApplyWorkspaceEditRequest = exports.ExecuteCommandRequest = exports.PrepareRenameRequest = exports.RenameRequest = exports.PrepareSupportDefaultBehavior = exports.DocumentOnTypeFormattingRequest = exports.DocumentRangesFormattingRequest = exports.DocumentRangeFormattingRequest = exports.DocumentFormattingRequest = exports.DocumentLinkResolveRequest = exports.DocumentLinkRequest = exports.CodeLensRefreshRequest = exports.CodeLensResolveRequest = exports.CodeLensRequest = exports.WorkspaceSymbolResolveRequest = exports.WorkspaceSymbolRequest = void 0;
exports.InlineCompletionRequest = exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = exports.DiagnosticRefreshRequest = exports.WorkspaceDiagnosticRequest = exports.DocumentDiagnosticRequest = exports.DocumentDiagnosticReportKind = exports.DiagnosticServerCancellationData = exports.InlayHintRefreshRequest = exports.InlayHintResolveRequest = exports.InlayHintRequest = exports.InlineValueRefreshRequest = exports.InlineValueRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchySubtypesRequest = exports.TypeHierarchyPrepareRequest = exports.MonikerRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
const Is = __webpack_require__(/*! ./utils/is */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js");
const protocol_implementation_1 = __webpack_require__(/*! ./protocol.implementation */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js");
Object.defineProperty(exports, "ImplementationRequest", ({ enumerable: true, get: function() {
  return protocol_implementation_1.ImplementationRequest;
} }));
const protocol_typeDefinition_1 = __webpack_require__(/*! ./protocol.typeDefinition */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js");
Object.defineProperty(exports, "TypeDefinitionRequest", ({ enumerable: true, get: function() {
  return protocol_typeDefinition_1.TypeDefinitionRequest;
} }));
const protocol_workspaceFolder_1 = __webpack_require__(/*! ./protocol.workspaceFolder */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js");
Object.defineProperty(exports, "WorkspaceFoldersRequest", ({ enumerable: true, get: function() {
  return protocol_workspaceFolder_1.WorkspaceFoldersRequest;
} }));
Object.defineProperty(exports, "DidChangeWorkspaceFoldersNotification", ({ enumerable: true, get: function() {
  return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification;
} }));
const protocol_configuration_1 = __webpack_require__(/*! ./protocol.configuration */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js");
Object.defineProperty(exports, "ConfigurationRequest", ({ enumerable: true, get: function() {
  return protocol_configuration_1.ConfigurationRequest;
} }));
const protocol_colorProvider_1 = __webpack_require__(/*! ./protocol.colorProvider */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js");
Object.defineProperty(exports, "DocumentColorRequest", ({ enumerable: true, get: function() {
  return protocol_colorProvider_1.DocumentColorRequest;
} }));
Object.defineProperty(exports, "ColorPresentationRequest", ({ enumerable: true, get: function() {
  return protocol_colorProvider_1.ColorPresentationRequest;
} }));
const protocol_foldingRange_1 = __webpack_require__(/*! ./protocol.foldingRange */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js");
Object.defineProperty(exports, "FoldingRangeRequest", ({ enumerable: true, get: function() {
  return protocol_foldingRange_1.FoldingRangeRequest;
} }));
Object.defineProperty(exports, "FoldingRangeRefreshRequest", ({ enumerable: true, get: function() {
  return protocol_foldingRange_1.FoldingRangeRefreshRequest;
} }));
const protocol_declaration_1 = __webpack_require__(/*! ./protocol.declaration */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js");
Object.defineProperty(exports, "DeclarationRequest", ({ enumerable: true, get: function() {
  return protocol_declaration_1.DeclarationRequest;
} }));
const protocol_selectionRange_1 = __webpack_require__(/*! ./protocol.selectionRange */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js");
Object.defineProperty(exports, "SelectionRangeRequest", ({ enumerable: true, get: function() {
  return protocol_selectionRange_1.SelectionRangeRequest;
} }));
const protocol_progress_1 = __webpack_require__(/*! ./protocol.progress */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js");
Object.defineProperty(exports, "WorkDoneProgress", ({ enumerable: true, get: function() {
  return protocol_progress_1.WorkDoneProgress;
} }));
Object.defineProperty(exports, "WorkDoneProgressCreateRequest", ({ enumerable: true, get: function() {
  return protocol_progress_1.WorkDoneProgressCreateRequest;
} }));
Object.defineProperty(exports, "WorkDoneProgressCancelNotification", ({ enumerable: true, get: function() {
  return protocol_progress_1.WorkDoneProgressCancelNotification;
} }));
const protocol_callHierarchy_1 = __webpack_require__(/*! ./protocol.callHierarchy */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js");
Object.defineProperty(exports, "CallHierarchyIncomingCallsRequest", ({ enumerable: true, get: function() {
  return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
} }));
Object.defineProperty(exports, "CallHierarchyOutgoingCallsRequest", ({ enumerable: true, get: function() {
  return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
} }));
Object.defineProperty(exports, "CallHierarchyPrepareRequest", ({ enumerable: true, get: function() {
  return protocol_callHierarchy_1.CallHierarchyPrepareRequest;
} }));
const protocol_semanticTokens_1 = __webpack_require__(/*! ./protocol.semanticTokens */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js");
Object.defineProperty(exports, "TokenFormat", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.TokenFormat;
} }));
Object.defineProperty(exports, "SemanticTokensRequest", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.SemanticTokensRequest;
} }));
Object.defineProperty(exports, "SemanticTokensDeltaRequest", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.SemanticTokensDeltaRequest;
} }));
Object.defineProperty(exports, "SemanticTokensRangeRequest", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.SemanticTokensRangeRequest;
} }));
Object.defineProperty(exports, "SemanticTokensRefreshRequest", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.SemanticTokensRefreshRequest;
} }));
Object.defineProperty(exports, "SemanticTokensRegistrationType", ({ enumerable: true, get: function() {
  return protocol_semanticTokens_1.SemanticTokensRegistrationType;
} }));
const protocol_showDocument_1 = __webpack_require__(/*! ./protocol.showDocument */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js");
Object.defineProperty(exports, "ShowDocumentRequest", ({ enumerable: true, get: function() {
  return protocol_showDocument_1.ShowDocumentRequest;
} }));
const protocol_linkedEditingRange_1 = __webpack_require__(/*! ./protocol.linkedEditingRange */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js");
Object.defineProperty(exports, "LinkedEditingRangeRequest", ({ enumerable: true, get: function() {
  return protocol_linkedEditingRange_1.LinkedEditingRangeRequest;
} }));
const protocol_fileOperations_1 = __webpack_require__(/*! ./protocol.fileOperations */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js");
Object.defineProperty(exports, "FileOperationPatternKind", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.FileOperationPatternKind;
} }));
Object.defineProperty(exports, "DidCreateFilesNotification", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.DidCreateFilesNotification;
} }));
Object.defineProperty(exports, "WillCreateFilesRequest", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.WillCreateFilesRequest;
} }));
Object.defineProperty(exports, "DidRenameFilesNotification", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.DidRenameFilesNotification;
} }));
Object.defineProperty(exports, "WillRenameFilesRequest", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.WillRenameFilesRequest;
} }));
Object.defineProperty(exports, "DidDeleteFilesNotification", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.DidDeleteFilesNotification;
} }));
Object.defineProperty(exports, "WillDeleteFilesRequest", ({ enumerable: true, get: function() {
  return protocol_fileOperations_1.WillDeleteFilesRequest;
} }));
const protocol_moniker_1 = __webpack_require__(/*! ./protocol.moniker */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js");
Object.defineProperty(exports, "UniquenessLevel", ({ enumerable: true, get: function() {
  return protocol_moniker_1.UniquenessLevel;
} }));
Object.defineProperty(exports, "MonikerKind", ({ enumerable: true, get: function() {
  return protocol_moniker_1.MonikerKind;
} }));
Object.defineProperty(exports, "MonikerRequest", ({ enumerable: true, get: function() {
  return protocol_moniker_1.MonikerRequest;
} }));
const protocol_typeHierarchy_1 = __webpack_require__(/*! ./protocol.typeHierarchy */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js");
Object.defineProperty(exports, "TypeHierarchyPrepareRequest", ({ enumerable: true, get: function() {
  return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest;
} }));
Object.defineProperty(exports, "TypeHierarchySubtypesRequest", ({ enumerable: true, get: function() {
  return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest;
} }));
Object.defineProperty(exports, "TypeHierarchySupertypesRequest", ({ enumerable: true, get: function() {
  return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest;
} }));
const protocol_inlineValue_1 = __webpack_require__(/*! ./protocol.inlineValue */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js");
Object.defineProperty(exports, "InlineValueRequest", ({ enumerable: true, get: function() {
  return protocol_inlineValue_1.InlineValueRequest;
} }));
Object.defineProperty(exports, "InlineValueRefreshRequest", ({ enumerable: true, get: function() {
  return protocol_inlineValue_1.InlineValueRefreshRequest;
} }));
const protocol_inlayHint_1 = __webpack_require__(/*! ./protocol.inlayHint */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js");
Object.defineProperty(exports, "InlayHintRequest", ({ enumerable: true, get: function() {
  return protocol_inlayHint_1.InlayHintRequest;
} }));
Object.defineProperty(exports, "InlayHintResolveRequest", ({ enumerable: true, get: function() {
  return protocol_inlayHint_1.InlayHintResolveRequest;
} }));
Object.defineProperty(exports, "InlayHintRefreshRequest", ({ enumerable: true, get: function() {
  return protocol_inlayHint_1.InlayHintRefreshRequest;
} }));
const protocol_diagnostic_1 = __webpack_require__(/*! ./protocol.diagnostic */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js");
Object.defineProperty(exports, "DiagnosticServerCancellationData", ({ enumerable: true, get: function() {
  return protocol_diagnostic_1.DiagnosticServerCancellationData;
} }));
Object.defineProperty(exports, "DocumentDiagnosticReportKind", ({ enumerable: true, get: function() {
  return protocol_diagnostic_1.DocumentDiagnosticReportKind;
} }));
Object.defineProperty(exports, "DocumentDiagnosticRequest", ({ enumerable: true, get: function() {
  return protocol_diagnostic_1.DocumentDiagnosticRequest;
} }));
Object.defineProperty(exports, "WorkspaceDiagnosticRequest", ({ enumerable: true, get: function() {
  return protocol_diagnostic_1.WorkspaceDiagnosticRequest;
} }));
Object.defineProperty(exports, "DiagnosticRefreshRequest", ({ enumerable: true, get: function() {
  return protocol_diagnostic_1.DiagnosticRefreshRequest;
} }));
const protocol_notebook_1 = __webpack_require__(/*! ./protocol.notebook */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js");
Object.defineProperty(exports, "NotebookCellKind", ({ enumerable: true, get: function() {
  return protocol_notebook_1.NotebookCellKind;
} }));
Object.defineProperty(exports, "ExecutionSummary", ({ enumerable: true, get: function() {
  return protocol_notebook_1.ExecutionSummary;
} }));
Object.defineProperty(exports, "NotebookCell", ({ enumerable: true, get: function() {
  return protocol_notebook_1.NotebookCell;
} }));
Object.defineProperty(exports, "NotebookDocument", ({ enumerable: true, get: function() {
  return protocol_notebook_1.NotebookDocument;
} }));
Object.defineProperty(exports, "NotebookDocumentSyncRegistrationType", ({ enumerable: true, get: function() {
  return protocol_notebook_1.NotebookDocumentSyncRegistrationType;
} }));
Object.defineProperty(exports, "DidOpenNotebookDocumentNotification", ({ enumerable: true, get: function() {
  return protocol_notebook_1.DidOpenNotebookDocumentNotification;
} }));
Object.defineProperty(exports, "NotebookCellArrayChange", ({ enumerable: true, get: function() {
  return protocol_notebook_1.NotebookCellArrayChange;
} }));
Object.defineProperty(exports, "DidChangeNotebookDocumentNotification", ({ enumerable: true, get: function() {
  return protocol_notebook_1.DidChangeNotebookDocumentNotification;
} }));
Object.defineProperty(exports, "DidSaveNotebookDocumentNotification", ({ enumerable: true, get: function() {
  return protocol_notebook_1.DidSaveNotebookDocumentNotification;
} }));
Object.defineProperty(exports, "DidCloseNotebookDocumentNotification", ({ enumerable: true, get: function() {
  return protocol_notebook_1.DidCloseNotebookDocumentNotification;
} }));
const protocol_inlineCompletion_1 = __webpack_require__(/*! ./protocol.inlineCompletion */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js");
Object.defineProperty(exports, "InlineCompletionRequest", ({ enumerable: true, get: function() {
  return protocol_inlineCompletion_1.InlineCompletionRequest;
} }));
let __noDynamicImport;
var TextDocumentFilter;
(function(TextDocumentFilter2) {
  function is(value) {
    const candidate = value;
    return Is.string(candidate) || (Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
  }
  TextDocumentFilter2.is = is;
})(TextDocumentFilter || (exports.TextDocumentFilter = TextDocumentFilter = {}));
var NotebookDocumentFilter;
(function(NotebookDocumentFilter2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
  }
  NotebookDocumentFilter2.is = is;
})(NotebookDocumentFilter || (exports.NotebookDocumentFilter = NotebookDocumentFilter = {}));
var NotebookCellTextDocumentFilter;
(function(NotebookCellTextDocumentFilter2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook)) && (candidate.language === void 0 || Is.string(candidate.language));
  }
  NotebookCellTextDocumentFilter2.is = is;
})(NotebookCellTextDocumentFilter || (exports.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));
var DocumentSelector;
(function(DocumentSelector2) {
  function is(value) {
    if (!Array.isArray(value)) {
      return false;
    }
    for (const elem of value) {
      if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
        return false;
      }
    }
    return true;
  }
  DocumentSelector2.is = is;
})(DocumentSelector || (exports.DocumentSelector = DocumentSelector = {}));
var RegistrationRequest;
(function(RegistrationRequest2) {
  RegistrationRequest2.method = "client/registerCapability";
  RegistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  RegistrationRequest2.type = new messages_1.ProtocolRequestType(RegistrationRequest2.method);
})(RegistrationRequest || (exports.RegistrationRequest = RegistrationRequest = {}));
var UnregistrationRequest;
(function(UnregistrationRequest2) {
  UnregistrationRequest2.method = "client/unregisterCapability";
  UnregistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  UnregistrationRequest2.type = new messages_1.ProtocolRequestType(UnregistrationRequest2.method);
})(UnregistrationRequest || (exports.UnregistrationRequest = UnregistrationRequest = {}));
var ResourceOperationKind;
(function(ResourceOperationKind2) {
  ResourceOperationKind2.Create = "create";
  ResourceOperationKind2.Rename = "rename";
  ResourceOperationKind2.Delete = "delete";
})(ResourceOperationKind || (exports.ResourceOperationKind = ResourceOperationKind = {}));
var FailureHandlingKind;
(function(FailureHandlingKind2) {
  FailureHandlingKind2.Abort = "abort";
  FailureHandlingKind2.Transactional = "transactional";
  FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
  FailureHandlingKind2.Undo = "undo";
})(FailureHandlingKind || (exports.FailureHandlingKind = FailureHandlingKind = {}));
var RegularExpressionEngineKind;
(function(RegularExpressionEngineKind2) {
  RegularExpressionEngineKind2.ES2020 = "ES2020";
})(RegularExpressionEngineKind || (exports.RegularExpressionEngineKind = RegularExpressionEngineKind = {}));
var PositionEncodingKind;
(function(PositionEncodingKind2) {
  PositionEncodingKind2.UTF8 = "utf-8";
  PositionEncodingKind2.UTF16 = "utf-16";
  PositionEncodingKind2.UTF32 = "utf-32";
})(PositionEncodingKind || (exports.PositionEncodingKind = PositionEncodingKind = {}));
var StaticRegistrationOptions;
(function(StaticRegistrationOptions2) {
  function hasId(value) {
    const candidate = value;
    return candidate && Is.string(candidate.id) && candidate.id.length > 0;
  }
  StaticRegistrationOptions2.hasId = hasId;
})(StaticRegistrationOptions || (exports.StaticRegistrationOptions = StaticRegistrationOptions = {}));
var TextDocumentRegistrationOptions;
(function(TextDocumentRegistrationOptions2) {
  function is(value) {
    const candidate = value;
    return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
  }
  TextDocumentRegistrationOptions2.is = is;
})(TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));
var WorkDoneProgressOptions;
(function(WorkDoneProgressOptions2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is.boolean(candidate.workDoneProgress));
  }
  WorkDoneProgressOptions2.is = is;
  function hasWorkDoneProgress(value) {
    const candidate = value;
    return candidate && Is.boolean(candidate.workDoneProgress);
  }
  WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
})(WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));
var InitializeRequest;
(function(InitializeRequest2) {
  InitializeRequest2.method = "initialize";
  InitializeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  InitializeRequest2.type = new messages_1.ProtocolRequestType(InitializeRequest2.method);
})(InitializeRequest || (exports.InitializeRequest = InitializeRequest = {}));
var InitializeErrorCodes;
(function(InitializeErrorCodes2) {
  InitializeErrorCodes2.unknownProtocolVersion = 1;
})(InitializeErrorCodes || (exports.InitializeErrorCodes = InitializeErrorCodes = {}));
var InitializedNotification;
(function(InitializedNotification2) {
  InitializedNotification2.method = "initialized";
  InitializedNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  InitializedNotification2.type = new messages_1.ProtocolNotificationType(InitializedNotification2.method);
})(InitializedNotification || (exports.InitializedNotification = InitializedNotification = {}));
var ShutdownRequest;
(function(ShutdownRequest2) {
  ShutdownRequest2.method = "shutdown";
  ShutdownRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  ShutdownRequest2.type = new messages_1.ProtocolRequestType0(ShutdownRequest2.method);
})(ShutdownRequest || (exports.ShutdownRequest = ShutdownRequest = {}));
var ExitNotification;
(function(ExitNotification2) {
  ExitNotification2.method = "exit";
  ExitNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  ExitNotification2.type = new messages_1.ProtocolNotificationType0(ExitNotification2.method);
})(ExitNotification || (exports.ExitNotification = ExitNotification = {}));
var DidChangeConfigurationNotification;
(function(DidChangeConfigurationNotification2) {
  DidChangeConfigurationNotification2.method = "workspace/didChangeConfiguration";
  DidChangeConfigurationNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method);
})(DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));
var MessageType;
(function(MessageType2) {
  MessageType2.Error = 1;
  MessageType2.Warning = 2;
  MessageType2.Info = 3;
  MessageType2.Log = 4;
  MessageType2.Debug = 5;
})(MessageType || (exports.MessageType = MessageType = {}));
var ShowMessageNotification;
(function(ShowMessageNotification2) {
  ShowMessageNotification2.method = "window/showMessage";
  ShowMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
  ShowMessageNotification2.type = new messages_1.ProtocolNotificationType(ShowMessageNotification2.method);
})(ShowMessageNotification || (exports.ShowMessageNotification = ShowMessageNotification = {}));
var ShowMessageRequest;
(function(ShowMessageRequest2) {
  ShowMessageRequest2.method = "window/showMessageRequest";
  ShowMessageRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  ShowMessageRequest2.type = new messages_1.ProtocolRequestType(ShowMessageRequest2.method);
})(ShowMessageRequest || (exports.ShowMessageRequest = ShowMessageRequest = {}));
var LogMessageNotification;
(function(LogMessageNotification2) {
  LogMessageNotification2.method = "window/logMessage";
  LogMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
  LogMessageNotification2.type = new messages_1.ProtocolNotificationType(LogMessageNotification2.method);
})(LogMessageNotification || (exports.LogMessageNotification = LogMessageNotification = {}));
var TelemetryEventNotification;
(function(TelemetryEventNotification2) {
  TelemetryEventNotification2.method = "telemetry/event";
  TelemetryEventNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
  TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method);
})(TelemetryEventNotification || (exports.TelemetryEventNotification = TelemetryEventNotification = {}));
var TextDocumentSyncKind;
(function(TextDocumentSyncKind2) {
  TextDocumentSyncKind2.None = 0;
  TextDocumentSyncKind2.Full = 1;
  TextDocumentSyncKind2.Incremental = 2;
})(TextDocumentSyncKind || (exports.TextDocumentSyncKind = TextDocumentSyncKind = {}));
var DidOpenTextDocumentNotification;
(function(DidOpenTextDocumentNotification2) {
  DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
  DidOpenTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
})(DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));
var TextDocumentContentChangeEvent;
(function(TextDocumentContentChangeEvent2) {
  function isIncremental(event) {
    const candidate = event;
    return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
  }
  TextDocumentContentChangeEvent2.isIncremental = isIncremental;
  function isFull(event) {
    const candidate = event;
    return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
  }
  TextDocumentContentChangeEvent2.isFull = isFull;
})(TextDocumentContentChangeEvent || (exports.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));
var DidChangeTextDocumentNotification;
(function(DidChangeTextDocumentNotification2) {
  DidChangeTextDocumentNotification2.method = "textDocument/didChange";
  DidChangeTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
})(DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));
var DidCloseTextDocumentNotification;
(function(DidCloseTextDocumentNotification2) {
  DidCloseTextDocumentNotification2.method = "textDocument/didClose";
  DidCloseTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
})(DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));
var DidSaveTextDocumentNotification;
(function(DidSaveTextDocumentNotification2) {
  DidSaveTextDocumentNotification2.method = "textDocument/didSave";
  DidSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
})(DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));
var TextDocumentSaveReason;
(function(TextDocumentSaveReason2) {
  TextDocumentSaveReason2.Manual = 1;
  TextDocumentSaveReason2.AfterDelay = 2;
  TextDocumentSaveReason2.FocusOut = 3;
})(TextDocumentSaveReason || (exports.TextDocumentSaveReason = TextDocumentSaveReason = {}));
var WillSaveTextDocumentNotification;
(function(WillSaveTextDocumentNotification2) {
  WillSaveTextDocumentNotification2.method = "textDocument/willSave";
  WillSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
})(WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));
var WillSaveTextDocumentWaitUntilRequest;
(function(WillSaveTextDocumentWaitUntilRequest2) {
  WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
  WillSaveTextDocumentWaitUntilRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
})(WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));
var DidChangeWatchedFilesNotification;
(function(DidChangeWatchedFilesNotification2) {
  DidChangeWatchedFilesNotification2.method = "workspace/didChangeWatchedFiles";
  DidChangeWatchedFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method);
})(DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));
var FileChangeType;
(function(FileChangeType2) {
  FileChangeType2.Created = 1;
  FileChangeType2.Changed = 2;
  FileChangeType2.Deleted = 3;
})(FileChangeType || (exports.FileChangeType = FileChangeType = {}));
var RelativePattern;
(function(RelativePattern2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern);
  }
  RelativePattern2.is = is;
})(RelativePattern || (exports.RelativePattern = RelativePattern = {}));
var WatchKind;
(function(WatchKind2) {
  WatchKind2.Create = 1;
  WatchKind2.Change = 2;
  WatchKind2.Delete = 4;
})(WatchKind || (exports.WatchKind = WatchKind = {}));
var PublishDiagnosticsNotification;
(function(PublishDiagnosticsNotification2) {
  PublishDiagnosticsNotification2.method = "textDocument/publishDiagnostics";
  PublishDiagnosticsNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
  PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method);
})(PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind2) {
  CompletionTriggerKind2.Invoked = 1;
  CompletionTriggerKind2.TriggerCharacter = 2;
  CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
})(CompletionTriggerKind || (exports.CompletionTriggerKind = CompletionTriggerKind = {}));
var CompletionRequest;
(function(CompletionRequest2) {
  CompletionRequest2.method = "textDocument/completion";
  CompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
})(CompletionRequest || (exports.CompletionRequest = CompletionRequest = {}));
var CompletionResolveRequest;
(function(CompletionResolveRequest2) {
  CompletionResolveRequest2.method = "completionItem/resolve";
  CompletionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
})(CompletionResolveRequest || (exports.CompletionResolveRequest = CompletionResolveRequest = {}));
var HoverRequest;
(function(HoverRequest2) {
  HoverRequest2.method = "textDocument/hover";
  HoverRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
})(HoverRequest || (exports.HoverRequest = HoverRequest = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind2) {
  SignatureHelpTriggerKind2.Invoked = 1;
  SignatureHelpTriggerKind2.TriggerCharacter = 2;
  SignatureHelpTriggerKind2.ContentChange = 3;
})(SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
var SignatureHelpRequest;
(function(SignatureHelpRequest2) {
  SignatureHelpRequest2.method = "textDocument/signatureHelp";
  SignatureHelpRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
})(SignatureHelpRequest || (exports.SignatureHelpRequest = SignatureHelpRequest = {}));
var DefinitionRequest;
(function(DefinitionRequest2) {
  DefinitionRequest2.method = "textDocument/definition";
  DefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
})(DefinitionRequest || (exports.DefinitionRequest = DefinitionRequest = {}));
var ReferencesRequest;
(function(ReferencesRequest2) {
  ReferencesRequest2.method = "textDocument/references";
  ReferencesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
})(ReferencesRequest || (exports.ReferencesRequest = ReferencesRequest = {}));
var DocumentHighlightRequest;
(function(DocumentHighlightRequest2) {
  DocumentHighlightRequest2.method = "textDocument/documentHighlight";
  DocumentHighlightRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
})(DocumentHighlightRequest || (exports.DocumentHighlightRequest = DocumentHighlightRequest = {}));
var DocumentSymbolRequest;
(function(DocumentSymbolRequest2) {
  DocumentSymbolRequest2.method = "textDocument/documentSymbol";
  DocumentSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
})(DocumentSymbolRequest || (exports.DocumentSymbolRequest = DocumentSymbolRequest = {}));
var CodeActionRequest;
(function(CodeActionRequest2) {
  CodeActionRequest2.method = "textDocument/codeAction";
  CodeActionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
})(CodeActionRequest || (exports.CodeActionRequest = CodeActionRequest = {}));
var CodeActionResolveRequest;
(function(CodeActionResolveRequest2) {
  CodeActionResolveRequest2.method = "codeAction/resolve";
  CodeActionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method);
})(CodeActionResolveRequest || (exports.CodeActionResolveRequest = CodeActionResolveRequest = {}));
var WorkspaceSymbolRequest;
(function(WorkspaceSymbolRequest2) {
  WorkspaceSymbolRequest2.method = "workspace/symbol";
  WorkspaceSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
})(WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));
var WorkspaceSymbolResolveRequest;
(function(WorkspaceSymbolResolveRequest2) {
  WorkspaceSymbolResolveRequest2.method = "workspaceSymbol/resolve";
  WorkspaceSymbolResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  WorkspaceSymbolResolveRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method);
})(WorkspaceSymbolResolveRequest || (exports.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));
var CodeLensRequest;
(function(CodeLensRequest2) {
  CodeLensRequest2.method = "textDocument/codeLens";
  CodeLensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method);
})(CodeLensRequest || (exports.CodeLensRequest = CodeLensRequest = {}));
var CodeLensResolveRequest;
(function(CodeLensResolveRequest2) {
  CodeLensResolveRequest2.method = "codeLens/resolve";
  CodeLensResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method);
})(CodeLensResolveRequest || (exports.CodeLensResolveRequest = CodeLensResolveRequest = {}));
var CodeLensRefreshRequest;
(function(CodeLensRefreshRequest2) {
  CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`;
  CodeLensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method);
})(CodeLensRefreshRequest || (exports.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));
var DocumentLinkRequest;
(function(DocumentLinkRequest2) {
  DocumentLinkRequest2.method = "textDocument/documentLink";
  DocumentLinkRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
})(DocumentLinkRequest || (exports.DocumentLinkRequest = DocumentLinkRequest = {}));
var DocumentLinkResolveRequest;
(function(DocumentLinkResolveRequest2) {
  DocumentLinkResolveRequest2.method = "documentLink/resolve";
  DocumentLinkResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method);
})(DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));
var DocumentFormattingRequest;
(function(DocumentFormattingRequest2) {
  DocumentFormattingRequest2.method = "textDocument/formatting";
  DocumentFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
})(DocumentFormattingRequest || (exports.DocumentFormattingRequest = DocumentFormattingRequest = {}));
var DocumentRangeFormattingRequest;
(function(DocumentRangeFormattingRequest2) {
  DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
  DocumentRangeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
})(DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));
var DocumentRangesFormattingRequest;
(function(DocumentRangesFormattingRequest2) {
  DocumentRangesFormattingRequest2.method = "textDocument/rangesFormatting";
  DocumentRangesFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentRangesFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method);
})(DocumentRangesFormattingRequest || (exports.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));
var DocumentOnTypeFormattingRequest;
(function(DocumentOnTypeFormattingRequest2) {
  DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
  DocumentOnTypeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
})(DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));
var PrepareSupportDefaultBehavior;
(function(PrepareSupportDefaultBehavior2) {
  PrepareSupportDefaultBehavior2.Identifier = 1;
})(PrepareSupportDefaultBehavior || (exports.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));
var RenameRequest;
(function(RenameRequest2) {
  RenameRequest2.method = "textDocument/rename";
  RenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
})(RenameRequest || (exports.RenameRequest = RenameRequest = {}));
var PrepareRenameRequest;
(function(PrepareRenameRequest2) {
  PrepareRenameRequest2.method = "textDocument/prepareRename";
  PrepareRenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
})(PrepareRenameRequest || (exports.PrepareRenameRequest = PrepareRenameRequest = {}));
var ExecuteCommandRequest;
(function(ExecuteCommandRequest2) {
  ExecuteCommandRequest2.method = "workspace/executeCommand";
  ExecuteCommandRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method);
})(ExecuteCommandRequest || (exports.ExecuteCommandRequest = ExecuteCommandRequest = {}));
var ApplyWorkspaceEditRequest;
(function(ApplyWorkspaceEditRequest2) {
  ApplyWorkspaceEditRequest2.method = "workspace/applyEdit";
  ApplyWorkspaceEditRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
})(ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js":
/*!*****************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js ***!
  \*****************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LinkedEditingRangeRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var LinkedEditingRangeRequest;
(function(LinkedEditingRangeRequest2) {
  LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange";
  LinkedEditingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method);
})(LinkedEditingRangeRequest || (exports.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js":
/*!******************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js ***!
  \******************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MonikerRequest = exports.MonikerKind = exports.UniquenessLevel = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var UniquenessLevel;
(function(UniquenessLevel2) {
  UniquenessLevel2.document = "document";
  UniquenessLevel2.project = "project";
  UniquenessLevel2.group = "group";
  UniquenessLevel2.scheme = "scheme";
  UniquenessLevel2.global = "global";
})(UniquenessLevel || (exports.UniquenessLevel = UniquenessLevel = {}));
var MonikerKind;
(function(MonikerKind2) {
  MonikerKind2.$import = "import";
  MonikerKind2.$export = "export";
  MonikerKind2.local = "local";
})(MonikerKind || (exports.MonikerKind = MonikerKind = {}));
var MonikerRequest;
(function(MonikerRequest2) {
  MonikerRequest2.method = "textDocument/moniker";
  MonikerRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method);
})(MonikerRequest || (exports.MonikerRequest = MonikerRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js":
/*!*******************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DidCloseNotebookDocumentNotification = exports.DidSaveNotebookDocumentNotification = exports.DidChangeNotebookDocumentNotification = exports.NotebookCellArrayChange = exports.DidOpenNotebookDocumentNotification = exports.NotebookDocumentSyncRegistrationType = exports.NotebookDocument = exports.NotebookCell = exports.ExecutionSummary = exports.NotebookCellKind = void 0;
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
const Is = __webpack_require__(/*! ./utils/is */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js");
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var NotebookCellKind;
(function(NotebookCellKind2) {
  NotebookCellKind2.Markup = 1;
  NotebookCellKind2.Code = 2;
  function is(value) {
    return value === 1 || value === 2;
  }
  NotebookCellKind2.is = is;
})(NotebookCellKind || (exports.NotebookCellKind = NotebookCellKind = {}));
var ExecutionSummary;
(function(ExecutionSummary2) {
  function create(executionOrder, success) {
    const result = { executionOrder };
    if (success === true || success === false) {
      result.success = success;
    }
    return result;
  }
  ExecutionSummary2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === void 0 || Is.boolean(candidate.success));
  }
  ExecutionSummary2.is = is;
  function equals(one, other) {
    if (one === other) {
      return true;
    }
    if (one === null || one === void 0 || other === null || other === void 0) {
      return false;
    }
    return one.executionOrder === other.executionOrder && one.success === other.success;
  }
  ExecutionSummary2.equals = equals;
})(ExecutionSummary || (exports.ExecutionSummary = ExecutionSummary = {}));
var NotebookCell;
(function(NotebookCell2) {
  function create(kind, document) {
    return { kind, document };
  }
  NotebookCell2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) && (candidate.metadata === void 0 || Is.objectLiteral(candidate.metadata));
  }
  NotebookCell2.is = is;
  function diff(one, two) {
    const result = /* @__PURE__ */ new Set();
    if (one.document !== two.document) {
      result.add("document");
    }
    if (one.kind !== two.kind) {
      result.add("kind");
    }
    if (one.executionSummary !== two.executionSummary) {
      result.add("executionSummary");
    }
    if ((one.metadata !== void 0 || two.metadata !== void 0) && !equalsMetadata(one.metadata, two.metadata)) {
      result.add("metadata");
    }
    if ((one.executionSummary !== void 0 || two.executionSummary !== void 0) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
      result.add("executionSummary");
    }
    return result;
  }
  NotebookCell2.diff = diff;
  function equalsMetadata(one, other) {
    if (one === other) {
      return true;
    }
    if (one === null || one === void 0 || other === null || other === void 0) {
      return false;
    }
    if (typeof one !== typeof other) {
      return false;
    }
    if (typeof one !== "object") {
      return false;
    }
    const oneArray = Array.isArray(one);
    const otherArray = Array.isArray(other);
    if (oneArray !== otherArray) {
      return false;
    }
    if (oneArray && otherArray) {
      if (one.length !== other.length) {
        return false;
      }
      for (let i = 0; i < one.length; i++) {
        if (!equalsMetadata(one[i], other[i])) {
          return false;
        }
      }
    }
    if (Is.objectLiteral(one) && Is.objectLiteral(other)) {
      const oneKeys = Object.keys(one);
      const otherKeys = Object.keys(other);
      if (oneKeys.length !== otherKeys.length) {
        return false;
      }
      oneKeys.sort();
      otherKeys.sort();
      if (!equalsMetadata(oneKeys, otherKeys)) {
        return false;
      }
      for (let i = 0; i < oneKeys.length; i++) {
        const prop = oneKeys[i];
        if (!equalsMetadata(one[prop], other[prop])) {
          return false;
        }
      }
    }
    return true;
  }
})(NotebookCell || (exports.NotebookCell = NotebookCell = {}));
var NotebookDocument;
(function(NotebookDocument2) {
  function create(uri, notebookType, version, cells) {
    return { uri, notebookType, version, cells };
  }
  NotebookDocument2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is.typedArray(candidate.cells, NotebookCell.is);
  }
  NotebookDocument2.is = is;
})(NotebookDocument || (exports.NotebookDocument = NotebookDocument = {}));
var NotebookDocumentSyncRegistrationType;
(function(NotebookDocumentSyncRegistrationType2) {
  NotebookDocumentSyncRegistrationType2.method = "notebookDocument/sync";
  NotebookDocumentSyncRegistrationType2.messageDirection = messages_1.MessageDirection.clientToServer;
  NotebookDocumentSyncRegistrationType2.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method);
})(NotebookDocumentSyncRegistrationType || (exports.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));
var DidOpenNotebookDocumentNotification;
(function(DidOpenNotebookDocumentNotification2) {
  DidOpenNotebookDocumentNotification2.method = "notebookDocument/didOpen";
  DidOpenNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidOpenNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method);
  DidOpenNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidOpenNotebookDocumentNotification || (exports.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));
var NotebookCellArrayChange;
(function(NotebookCellArrayChange2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === void 0 || Is.typedArray(candidate.cells, NotebookCell.is));
  }
  NotebookCellArrayChange2.is = is;
  function create(start, deleteCount, cells) {
    const result = { start, deleteCount };
    if (cells !== void 0) {
      result.cells = cells;
    }
    return result;
  }
  NotebookCellArrayChange2.create = create;
})(NotebookCellArrayChange || (exports.NotebookCellArrayChange = NotebookCellArrayChange = {}));
var DidChangeNotebookDocumentNotification;
(function(DidChangeNotebookDocumentNotification2) {
  DidChangeNotebookDocumentNotification2.method = "notebookDocument/didChange";
  DidChangeNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidChangeNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method);
  DidChangeNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidChangeNotebookDocumentNotification || (exports.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));
var DidSaveNotebookDocumentNotification;
(function(DidSaveNotebookDocumentNotification2) {
  DidSaveNotebookDocumentNotification2.method = "notebookDocument/didSave";
  DidSaveNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidSaveNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method);
  DidSaveNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidSaveNotebookDocumentNotification || (exports.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));
var DidCloseNotebookDocumentNotification;
(function(DidCloseNotebookDocumentNotification2) {
  DidCloseNotebookDocumentNotification2.method = "notebookDocument/didClose";
  DidCloseNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidCloseNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method);
  DidCloseNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidCloseNotebookDocumentNotification || (exports.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js":
/*!*******************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkDoneProgressCancelNotification = exports.WorkDoneProgressCreateRequest = exports.WorkDoneProgress = void 0;
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var WorkDoneProgress;
(function(WorkDoneProgress2) {
  WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
  function is(value) {
    return value === WorkDoneProgress2.type;
  }
  WorkDoneProgress2.is = is;
})(WorkDoneProgress || (exports.WorkDoneProgress = WorkDoneProgress = {}));
var WorkDoneProgressCreateRequest;
(function(WorkDoneProgressCreateRequest2) {
  WorkDoneProgressCreateRequest2.method = "window/workDoneProgress/create";
  WorkDoneProgressCreateRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method);
})(WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));
var WorkDoneProgressCancelNotification;
(function(WorkDoneProgressCancelNotification2) {
  WorkDoneProgressCancelNotification2.method = "window/workDoneProgress/cancel";
  WorkDoneProgressCancelNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method);
})(WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js":
/*!*************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SelectionRangeRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var SelectionRangeRequest;
(function(SelectionRangeRequest2) {
  SelectionRangeRequest2.method = "textDocument/selectionRange";
  SelectionRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
})(SelectionRangeRequest || (exports.SelectionRangeRequest = SelectionRangeRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js":
/*!*************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SemanticTokensRefreshRequest = exports.SemanticTokensRangeRequest = exports.SemanticTokensDeltaRequest = exports.SemanticTokensRequest = exports.SemanticTokensRegistrationType = exports.TokenFormat = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var TokenFormat;
(function(TokenFormat2) {
  TokenFormat2.Relative = "relative";
})(TokenFormat || (exports.TokenFormat = TokenFormat = {}));
var SemanticTokensRegistrationType;
(function(SemanticTokensRegistrationType2) {
  SemanticTokensRegistrationType2.method = "textDocument/semanticTokens";
  SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method);
})(SemanticTokensRegistrationType || (exports.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));
var SemanticTokensRequest;
(function(SemanticTokensRequest2) {
  SemanticTokensRequest2.method = "textDocument/semanticTokens/full";
  SemanticTokensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
  SemanticTokensRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRequest || (exports.SemanticTokensRequest = SemanticTokensRequest = {}));
var SemanticTokensDeltaRequest;
(function(SemanticTokensDeltaRequest2) {
  SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta";
  SemanticTokensDeltaRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method);
  SemanticTokensDeltaRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensDeltaRequest || (exports.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));
var SemanticTokensRangeRequest;
(function(SemanticTokensRangeRequest2) {
  SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
  SemanticTokensRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
  SemanticTokensRangeRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));
var SemanticTokensRefreshRequest;
(function(SemanticTokensRefreshRequest2) {
  SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`;
  SemanticTokensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method);
})(SemanticTokensRefreshRequest || (exports.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js":
/*!***********************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js ***!
  \***********************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ShowDocumentRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var ShowDocumentRequest;
(function(ShowDocumentRequest2) {
  ShowDocumentRequest2.method = "window/showDocument";
  ShowDocumentRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method);
})(ShowDocumentRequest || (exports.ShowDocumentRequest = ShowDocumentRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js":
/*!*************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeDefinitionRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
let __noDynamicImport;
var TypeDefinitionRequest;
(function(TypeDefinitionRequest2) {
  TypeDefinitionRequest2.method = "textDocument/typeDefinition";
  TypeDefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
})(TypeDefinitionRequest || (exports.TypeDefinitionRequest = TypeDefinitionRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js":
/*!************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js ***!
  \************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeHierarchySubtypesRequest = exports.TypeHierarchySupertypesRequest = exports.TypeHierarchyPrepareRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var TypeHierarchyPrepareRequest;
(function(TypeHierarchyPrepareRequest2) {
  TypeHierarchyPrepareRequest2.method = "textDocument/prepareTypeHierarchy";
  TypeHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  TypeHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method);
})(TypeHierarchyPrepareRequest || (exports.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));
var TypeHierarchySupertypesRequest;
(function(TypeHierarchySupertypesRequest2) {
  TypeHierarchySupertypesRequest2.method = "typeHierarchy/supertypes";
  TypeHierarchySupertypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  TypeHierarchySupertypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method);
})(TypeHierarchySupertypesRequest || (exports.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));
var TypeHierarchySubtypesRequest;
(function(TypeHierarchySubtypesRequest2) {
  TypeHierarchySubtypesRequest2.method = "typeHierarchy/subtypes";
  TypeHierarchySubtypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
  TypeHierarchySubtypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method);
})(TypeHierarchySubtypesRequest || (exports.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js":
/*!**************************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js ***!
  \**************************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DidChangeWorkspaceFoldersNotification = exports.WorkspaceFoldersRequest = void 0;
const messages_1 = __webpack_require__(/*! ./messages */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/messages.js");
var WorkspaceFoldersRequest;
(function(WorkspaceFoldersRequest2) {
  WorkspaceFoldersRequest2.method = "workspace/workspaceFolders";
  WorkspaceFoldersRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
  WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method);
})(WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));
var DidChangeWorkspaceFoldersNotification;
(function(DidChangeWorkspaceFoldersNotification2) {
  DidChangeWorkspaceFoldersNotification2.method = "workspace/didChangeWorkspaceFolders";
  DidChangeWorkspaceFoldersNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
  DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method);
})(DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js":
/*!**********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js ***!
  \**********************************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.objectLiteral = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
  return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
  return typeof value === "string" || value instanceof String;
}
exports.string = string;
function number(value) {
  return typeof value === "number" || value instanceof Number;
}
exports.number = number;
function error(value) {
  return value instanceof Error;
}
exports.error = error;
function func(value) {
  return typeof value === "function";
}
exports.func = func;
function array(value) {
  return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
  return array(value) && value.every((elem) => string(elem));
}
exports.stringArray = stringArray;
function typedArray(value, check) {
  return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function objectLiteral(value) {
  return value !== null && typeof value === "object";
}
exports.objectLiteral = objectLiteral;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js":
/*!****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js ***!
  \****************************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: function() {
      return m[k];
    } };
  }
  Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
});
var __exportStar = this && this.__exportStar || function(m, exports2) {
  for (var p in m)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
      __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createProtocolConnection = void 0;
const node_1 = __webpack_require__(/*! vscode-jsonrpc/node */ "../pyright-internal/node_modules/vscode-jsonrpc/node.js");
__exportStar(__webpack_require__(/*! vscode-jsonrpc/node */ "../pyright-internal/node_modules/vscode-jsonrpc/node.js"), exports);
__exportStar(__webpack_require__(/*! ../common/api */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/common/api.js"), exports);
function createProtocolConnection(input, output, logger, options) {
  return (0, node_1.createMessageConnection)(input, output, logger, options);
}
exports.createProtocolConnection = createProtocolConnection;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-protocol/node.js":
/*!*******************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-protocol/node.js ***!
  \*******************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = __webpack_require__(/*! ./lib/node/main */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/main.js":
/*!*******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/main.js ***!
  \*******************************************************************************************/
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var __spreadArray = this && this.__spreadArray || function(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i);
        ar[i] = from[i];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
};
(function(factory) {
  if ( true && typeof module.exports === "object") {
    var v = factory(__webpack_require__("../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd sync recursive"), exports);
    if (v !== void 0)
      module.exports = v;
  } else if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  }
})(function(require2, exports2) {
  "use strict";
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.TextDocument = void 0;
  var FullTextDocument = (
    /** @class */
    function() {
      function FullTextDocument2(uri, languageId, version, content) {
        this._uri = uri;
        this._languageId = languageId;
        this._version = version;
        this._content = content;
        this._lineOffsets = void 0;
      }
      Object.defineProperty(FullTextDocument2.prototype, "uri", {
        get: function() {
          return this._uri;
        },
        enumerable: false,
        configurable: true
      });
      Object.defineProperty(FullTextDocument2.prototype, "languageId", {
        get: function() {
          return this._languageId;
        },
        enumerable: false,
        configurable: true
      });
      Object.defineProperty(FullTextDocument2.prototype, "version", {
        get: function() {
          return this._version;
        },
        enumerable: false,
        configurable: true
      });
      FullTextDocument2.prototype.getText = function(range) {
        if (range) {
          var start = this.offsetAt(range.start);
          var end = this.offsetAt(range.end);
          return this._content.substring(start, end);
        }
        return this._content;
      };
      FullTextDocument2.prototype.update = function(changes, version) {
        for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
          var change = changes_1[_i];
          if (FullTextDocument2.isIncremental(change)) {
            var range = getWellformedRange(change.range);
            var startOffset = this.offsetAt(range.start);
            var endOffset = this.offsetAt(range.end);
            this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
            var startLine = Math.max(range.start.line, 0);
            var endLine = Math.max(range.end.line, 0);
            var lineOffsets = this._lineOffsets;
            var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
            if (endLine - startLine === addedLineOffsets.length) {
              for (var i = 0, len = addedLineOffsets.length; i < len; i++) {
                lineOffsets[i + startLine + 1] = addedLineOffsets[i];
              }
            } else {
              if (addedLineOffsets.length < 1e4) {
                lineOffsets.splice.apply(lineOffsets, __spreadArray([startLine + 1, endLine - startLine], addedLineOffsets, false));
              } else {
                this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
              }
            }
            var diff = change.text.length - (endOffset - startOffset);
            if (diff !== 0) {
              for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
                lineOffsets[i] = lineOffsets[i] + diff;
              }
            }
          } else if (FullTextDocument2.isFull(change)) {
            this._content = change.text;
            this._lineOffsets = void 0;
          } else {
            throw new Error("Unknown change event received");
          }
        }
        this._version = version;
      };
      FullTextDocument2.prototype.getLineOffsets = function() {
        if (this._lineOffsets === void 0) {
          this._lineOffsets = computeLineOffsets(this._content, true);
        }
        return this._lineOffsets;
      };
      FullTextDocument2.prototype.positionAt = function(offset) {
        offset = Math.max(Math.min(offset, this._content.length), 0);
        var lineOffsets = this.getLineOffsets();
        var low = 0, high = lineOffsets.length;
        if (high === 0) {
          return { line: 0, character: offset };
        }
        while (low < high) {
          var mid = Math.floor((low + high) / 2);
          if (lineOffsets[mid] > offset) {
            high = mid;
          } else {
            low = mid + 1;
          }
        }
        var line = low - 1;
        return { line, character: offset - lineOffsets[line] };
      };
      FullTextDocument2.prototype.offsetAt = function(position) {
        var lineOffsets = this.getLineOffsets();
        if (position.line >= lineOffsets.length) {
          return this._content.length;
        } else if (position.line < 0) {
          return 0;
        }
        var lineOffset = lineOffsets[position.line];
        var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
        return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
      };
      Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
        get: function() {
          return this.getLineOffsets().length;
        },
        enumerable: false,
        configurable: true
      });
      FullTextDocument2.isIncremental = function(event) {
        var candidate = event;
        return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
      };
      FullTextDocument2.isFull = function(event) {
        var candidate = event;
        return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
      };
      return FullTextDocument2;
    }()
  );
  var TextDocument;
  (function(TextDocument2) {
    function create(uri, languageId, version, content) {
      return new FullTextDocument(uri, languageId, version, content);
    }
    TextDocument2.create = create;
    function update(document, changes, version) {
      if (document instanceof FullTextDocument) {
        document.update(changes, version);
        return document;
      } else {
        throw new Error("TextDocument.update: document must be created by TextDocument.create");
      }
    }
    TextDocument2.update = update;
    function applyEdits(document, edits) {
      var text = document.getText();
      var sortedEdits = mergeSort(edits.map(getWellformedEdit), function(a, b) {
        var diff = a.range.start.line - b.range.start.line;
        if (diff === 0) {
          return a.range.start.character - b.range.start.character;
        }
        return diff;
      });
      var lastModifiedOffset = 0;
      var spans = [];
      for (var _i = 0, sortedEdits_1 = sortedEdits; _i < sortedEdits_1.length; _i++) {
        var e = sortedEdits_1[_i];
        var startOffset = document.offsetAt(e.range.start);
        if (startOffset < lastModifiedOffset) {
          throw new Error("Overlapping edit");
        } else if (startOffset > lastModifiedOffset) {
          spans.push(text.substring(lastModifiedOffset, startOffset));
        }
        if (e.newText.length) {
          spans.push(e.newText);
        }
        lastModifiedOffset = document.offsetAt(e.range.end);
      }
      spans.push(text.substr(lastModifiedOffset));
      return spans.join("");
    }
    TextDocument2.applyEdits = applyEdits;
  })(TextDocument || (exports2.TextDocument = TextDocument = {}));
  function mergeSort(data, compare) {
    if (data.length <= 1) {
      return data;
    }
    var p = data.length / 2 | 0;
    var left = data.slice(0, p);
    var right = data.slice(p);
    mergeSort(left, compare);
    mergeSort(right, compare);
    var leftIdx = 0;
    var rightIdx = 0;
    var i = 0;
    while (leftIdx < left.length && rightIdx < right.length) {
      var ret = compare(left[leftIdx], right[rightIdx]);
      if (ret <= 0) {
        data[i++] = left[leftIdx++];
      } else {
        data[i++] = right[rightIdx++];
      }
    }
    while (leftIdx < left.length) {
      data[i++] = left[leftIdx++];
    }
    while (rightIdx < right.length) {
      data[i++] = right[rightIdx++];
    }
    return data;
  }
  function computeLineOffsets(text, isAtLineStart, textOffset) {
    if (textOffset === void 0) {
      textOffset = 0;
    }
    var result = isAtLineStart ? [textOffset] : [];
    for (var i = 0; i < text.length; i++) {
      var ch = text.charCodeAt(i);
      if (ch === 13 || ch === 10) {
        if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) {
          i++;
        }
        result.push(textOffset + i + 1);
      }
    }
    return result;
  }
  function getWellformedRange(range) {
    var start = range.start;
    var end = range.end;
    if (start.line > end.line || start.line === end.line && start.character > end.character) {
      return { start: end, end: start };
    }
    return range;
  }
  function getWellformedEdit(textEdit) {
    var range = getWellformedRange(textEdit.range);
    if (range !== textEdit.range) {
      return { newText: textEdit.newText, range };
    }
    return textEdit;
  }
});


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/api.js":
/*!********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/api.js ***!
  \********************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: function() {
      return m[k];
    } };
  }
  Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
});
var __exportStar = this && this.__exportStar || function(m, exports2) {
  for (var p in m)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
      __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProposedFeatures = exports.NotebookDocuments = exports.TextDocuments = exports.SemanticTokensBuilder = void 0;
const semanticTokens_1 = __webpack_require__(/*! ./semanticTokens */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/semanticTokens.js");
Object.defineProperty(exports, "SemanticTokensBuilder", ({ enumerable: true, get: function() {
  return semanticTokens_1.SemanticTokensBuilder;
} }));
const ic = __webpack_require__(/*! ./inlineCompletion.proposed */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineCompletion.proposed.js");
__exportStar(__webpack_require__(/*! vscode-languageserver-protocol/ */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js"), exports);
const textDocuments_1 = __webpack_require__(/*! ./textDocuments */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/textDocuments.js");
Object.defineProperty(exports, "TextDocuments", ({ enumerable: true, get: function() {
  return textDocuments_1.TextDocuments;
} }));
const notebook_1 = __webpack_require__(/*! ./notebook */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/notebook.js");
Object.defineProperty(exports, "NotebookDocuments", ({ enumerable: true, get: function() {
  return notebook_1.NotebookDocuments;
} }));
__exportStar(__webpack_require__(/*! ./server */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/server.js"), exports);
var ProposedFeatures;
(function(ProposedFeatures2) {
  ProposedFeatures2.all = {
    __brand: "features",
    languages: ic.InlineCompletionFeature
  };
})(ProposedFeatures || (exports.ProposedFeatures = ProposedFeatures = {}));


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/callHierarchy.js":
/*!******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/callHierarchy.js ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallHierarchyFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const CallHierarchyFeature = (Base) => {
  return class extends Base {
    get callHierarchy() {
      return {
        onPrepare: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
          });
        },
        onIncomingCalls: (handler) => {
          const type = vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        },
        onOutgoingCalls: (handler) => {
          const type = vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        }
      };
    }
  };
};
exports.CallHierarchyFeature = CallHierarchyFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/configuration.js":
/*!******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/configuration.js ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConfigurationFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const Is = __webpack_require__(/*! ./utils/is */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/is.js");
const ConfigurationFeature = (Base) => {
  return class extends Base {
    getConfiguration(arg) {
      if (!arg) {
        return this._getConfiguration({});
      } else if (Is.string(arg)) {
        return this._getConfiguration({ section: arg });
      } else {
        return this._getConfiguration(arg);
      }
    }
    _getConfiguration(arg) {
      const params = {
        items: Array.isArray(arg) ? arg : [arg]
      };
      return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {
        if (Array.isArray(result)) {
          return Array.isArray(arg) ? result : result[0];
        } else {
          return Array.isArray(arg) ? [] : null;
        }
      });
    }
  };
};
exports.ConfigurationFeature = ConfigurationFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/diagnostic.js":
/*!***************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/diagnostic.js ***!
  \***************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const DiagnosticFeature = (Base) => {
  return class extends Base {
    get diagnostics() {
      return {
        refresh: () => {
          return this.connection.sendRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type);
        },
        on: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.partialResult, params));
          });
        },
        onWorkspace: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, params));
          });
        }
      };
    }
  };
};
exports.DiagnosticFeature = DiagnosticFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/fileOperations.js":
/*!*******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/fileOperations.js ***!
  \*******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FileOperationsFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const FileOperationsFeature = (Base) => {
  return class extends Base {
    onDidCreateFiles(handler) {
      return this.connection.onNotification(vscode_languageserver_protocol_1.DidCreateFilesNotification.type, (params) => {
        return handler(params);
      });
    }
    onDidRenameFiles(handler) {
      return this.connection.onNotification(vscode_languageserver_protocol_1.DidRenameFilesNotification.type, (params) => {
        return handler(params);
      });
    }
    onDidDeleteFiles(handler) {
      return this.connection.onNotification(vscode_languageserver_protocol_1.DidDeleteFilesNotification.type, (params) => {
        return handler(params);
      });
    }
    onWillCreateFiles(handler) {
      return this.connection.onRequest(vscode_languageserver_protocol_1.WillCreateFilesRequest.type, (params, cancel) => {
        return handler(params, cancel);
      });
    }
    onWillRenameFiles(handler) {
      return this.connection.onRequest(vscode_languageserver_protocol_1.WillRenameFilesRequest.type, (params, cancel) => {
        return handler(params, cancel);
      });
    }
    onWillDeleteFiles(handler) {
      return this.connection.onRequest(vscode_languageserver_protocol_1.WillDeleteFilesRequest.type, (params, cancel) => {
        return handler(params, cancel);
      });
    }
  };
};
exports.FileOperationsFeature = FileOperationsFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/foldingRange.js":
/*!*****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/foldingRange.js ***!
  \*****************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FoldingRangeFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const FoldingRangeFeature = (Base) => {
  return class extends Base {
    get foldingRange() {
      return {
        refresh: () => {
          return this.connection.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type);
        },
        on: (handler) => {
          const type = vscode_languageserver_protocol_1.FoldingRangeRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        }
      };
    }
  };
};
exports.FoldingRangeFeature = FoldingRangeFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlayHint.js":
/*!**************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/inlayHint.js ***!
  \**************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlayHintFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const InlayHintFeature = (Base) => {
  return class extends Base {
    get inlayHint() {
      return {
        refresh: () => {
          return this.connection.sendRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type);
        },
        on: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params));
          });
        },
        resolve: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
          });
        }
      };
    }
  };
};
exports.InlayHintFeature = InlayHintFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineCompletion.proposed.js":
/*!******************************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineCompletion.proposed.js ***!
  \******************************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlineCompletionFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const InlineCompletionFeature = (Base) => {
  return class extends Base {
    get inlineCompletion() {
      return {
        on: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params));
          });
        }
      };
    }
  };
};
exports.InlineCompletionFeature = InlineCompletionFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineValue.js":
/*!****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineValue.js ***!
  \****************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlineValueFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const InlineValueFeature = (Base) => {
  return class extends Base {
    get inlineValue() {
      return {
        refresh: () => {
          return this.connection.sendRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type);
        },
        on: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params));
          });
        }
      };
    }
  };
};
exports.InlineValueFeature = InlineValueFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/linkedEditingRange.js":
/*!***********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/linkedEditingRange.js ***!
  \***********************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LinkedEditingRangeFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const LinkedEditingRangeFeature = (Base) => {
  return class extends Base {
    onLinkedEditingRange(handler) {
      return this.connection.onRequest(vscode_languageserver_protocol_1.LinkedEditingRangeRequest.type, (params, cancel) => {
        return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
      });
    }
  };
};
exports.LinkedEditingRangeFeature = LinkedEditingRangeFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/moniker.js":
/*!************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/moniker.js ***!
  \************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MonikerFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const MonikerFeature = (Base) => {
  return class extends Base {
    get moniker() {
      return {
        on: (handler) => {
          const type = vscode_languageserver_protocol_1.MonikerRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        }
      };
    }
  };
};
exports.MonikerFeature = MonikerFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/notebook.js":
/*!*************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/notebook.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NotebookDocuments = exports.NotebookSyncFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const textDocuments_1 = __webpack_require__(/*! ./textDocuments */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/textDocuments.js");
const NotebookSyncFeature = (Base) => {
  return class extends Base {
    get synchronization() {
      return {
        onDidOpenNotebookDocument: (handler) => {
          return this.connection.onNotification(vscode_languageserver_protocol_1.DidOpenNotebookDocumentNotification.type, (params) => {
            return handler(params);
          });
        },
        onDidChangeNotebookDocument: (handler) => {
          return this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeNotebookDocumentNotification.type, (params) => {
            return handler(params);
          });
        },
        onDidSaveNotebookDocument: (handler) => {
          return this.connection.onNotification(vscode_languageserver_protocol_1.DidSaveNotebookDocumentNotification.type, (params) => {
            return handler(params);
          });
        },
        onDidCloseNotebookDocument: (handler) => {
          return this.connection.onNotification(vscode_languageserver_protocol_1.DidCloseNotebookDocumentNotification.type, (params) => {
            return handler(params);
          });
        }
      };
    }
  };
};
exports.NotebookSyncFeature = NotebookSyncFeature;
class CellTextDocumentConnection {
  onDidOpenTextDocument(handler) {
    this.openHandler = handler;
    return vscode_languageserver_protocol_1.Disposable.create(() => {
      this.openHandler = void 0;
    });
  }
  openTextDocument(params) {
    return this.openHandler && this.openHandler(params);
  }
  onDidChangeTextDocument(handler) {
    this.changeHandler = handler;
    return vscode_languageserver_protocol_1.Disposable.create(() => {
      this.changeHandler = handler;
    });
  }
  changeTextDocument(params) {
    return this.changeHandler && this.changeHandler(params);
  }
  onDidCloseTextDocument(handler) {
    this.closeHandler = handler;
    return vscode_languageserver_protocol_1.Disposable.create(() => {
      this.closeHandler = void 0;
    });
  }
  closeTextDocument(params) {
    return this.closeHandler && this.closeHandler(params);
  }
  onWillSaveTextDocument() {
    return CellTextDocumentConnection.NULL_DISPOSE;
  }
  onWillSaveTextDocumentWaitUntil() {
    return CellTextDocumentConnection.NULL_DISPOSE;
  }
  onDidSaveTextDocument() {
    return CellTextDocumentConnection.NULL_DISPOSE;
  }
}
CellTextDocumentConnection.NULL_DISPOSE = Object.freeze({ dispose: () => {
} });
class NotebookDocuments {
  constructor(configurationOrTextDocuments) {
    if (configurationOrTextDocuments instanceof textDocuments_1.TextDocuments) {
      this._cellTextDocuments = configurationOrTextDocuments;
    } else {
      this._cellTextDocuments = new textDocuments_1.TextDocuments(configurationOrTextDocuments);
    }
    this.notebookDocuments = /* @__PURE__ */ new Map();
    this.notebookCellMap = /* @__PURE__ */ new Map();
    this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
    this._onDidChange = new vscode_languageserver_protocol_1.Emitter();
    this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
    this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
  }
  get cellTextDocuments() {
    return this._cellTextDocuments;
  }
  getCellTextDocument(cell) {
    return this._cellTextDocuments.get(cell.document);
  }
  getNotebookDocument(uri) {
    return this.notebookDocuments.get(uri);
  }
  getNotebookCell(uri) {
    const value = this.notebookCellMap.get(uri);
    return value && value[0];
  }
  findNotebookDocumentForCell(cell) {
    const key = typeof cell === "string" ? cell : cell.document;
    const value = this.notebookCellMap.get(key);
    return value && value[1];
  }
  get onDidOpen() {
    return this._onDidOpen.event;
  }
  get onDidSave() {
    return this._onDidSave.event;
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  get onDidClose() {
    return this._onDidClose.event;
  }
  /**
   * Listens for `low level` notification on the given connection to
   * update the notebook documents managed by this instance.
   *
   * Please note that the connection only provides handlers not an event model. Therefore
   * listening on a connection will overwrite the following handlers on a connection:
   * `onDidOpenNotebookDocument`, `onDidChangeNotebookDocument`, `onDidSaveNotebookDocument`,
   *  and `onDidCloseNotebookDocument`.
   *
   * @param connection The connection to listen on.
   */
  listen(connection) {
    const cellTextDocumentConnection = new CellTextDocumentConnection();
    const disposables = [];
    disposables.push(this.cellTextDocuments.listen(cellTextDocumentConnection));
    disposables.push(connection.notebooks.synchronization.onDidOpenNotebookDocument(async (params) => {
      this.notebookDocuments.set(params.notebookDocument.uri, params.notebookDocument);
      for (const cellTextDocument of params.cellTextDocuments) {
        await cellTextDocumentConnection.openTextDocument({ textDocument: cellTextDocument });
      }
      this.updateCellMap(params.notebookDocument);
      this._onDidOpen.fire(params.notebookDocument);
    }));
    disposables.push(connection.notebooks.synchronization.onDidChangeNotebookDocument(async (params) => {
      const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
      if (notebookDocument === void 0) {
        return;
      }
      notebookDocument.version = params.notebookDocument.version;
      const oldMetadata = notebookDocument.metadata;
      let metadataChanged = false;
      const change = params.change;
      if (change.metadata !== void 0) {
        metadataChanged = true;
        notebookDocument.metadata = change.metadata;
      }
      const opened = [];
      const closed = [];
      const data = [];
      const text = [];
      if (change.cells !== void 0) {
        const changedCells = change.cells;
        if (changedCells.structure !== void 0) {
          const array = changedCells.structure.array;
          notebookDocument.cells.splice(array.start, array.deleteCount, ...array.cells !== void 0 ? array.cells : []);
          if (changedCells.structure.didOpen !== void 0) {
            for (const open of changedCells.structure.didOpen) {
              await cellTextDocumentConnection.openTextDocument({ textDocument: open });
              opened.push(open.uri);
            }
          }
          if (changedCells.structure.didClose) {
            for (const close of changedCells.structure.didClose) {
              await cellTextDocumentConnection.closeTextDocument({ textDocument: close });
              closed.push(close.uri);
            }
          }
        }
        if (changedCells.data !== void 0) {
          const cellUpdates = new Map(changedCells.data.map((cell) => [cell.document, cell]));
          for (let i = 0; i <= notebookDocument.cells.length; i++) {
            const change2 = cellUpdates.get(notebookDocument.cells[i].document);
            if (change2 !== void 0) {
              const old = notebookDocument.cells.splice(i, 1, change2);
              data.push({ old: old[0], new: change2 });
              cellUpdates.delete(change2.document);
              if (cellUpdates.size === 0) {
                break;
              }
            }
          }
        }
        if (changedCells.textContent !== void 0) {
          for (const cellTextDocument of changedCells.textContent) {
            await cellTextDocumentConnection.changeTextDocument({ textDocument: cellTextDocument.document, contentChanges: cellTextDocument.changes });
            text.push(cellTextDocument.document.uri);
          }
        }
      }
      this.updateCellMap(notebookDocument);
      const changeEvent = { notebookDocument };
      if (metadataChanged) {
        changeEvent.metadata = { old: oldMetadata, new: notebookDocument.metadata };
      }
      const added = [];
      for (const open of opened) {
        added.push(this.getNotebookCell(open));
      }
      const removed = [];
      for (const close of closed) {
        removed.push(this.getNotebookCell(close));
      }
      const textContent = [];
      for (const change2 of text) {
        textContent.push(this.getNotebookCell(change2));
      }
      if (added.length > 0 || removed.length > 0 || data.length > 0 || textContent.length > 0) {
        changeEvent.cells = { added, removed, changed: { data, textContent } };
      }
      if (changeEvent.metadata !== void 0 || changeEvent.cells !== void 0) {
        this._onDidChange.fire(changeEvent);
      }
    }));
    disposables.push(connection.notebooks.synchronization.onDidSaveNotebookDocument((params) => {
      const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
      if (notebookDocument === void 0) {
        return;
      }
      this._onDidSave.fire(notebookDocument);
    }));
    disposables.push(connection.notebooks.synchronization.onDidCloseNotebookDocument(async (params) => {
      const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
      if (notebookDocument === void 0) {
        return;
      }
      this._onDidClose.fire(notebookDocument);
      for (const cellTextDocument of params.cellTextDocuments) {
        await cellTextDocumentConnection.closeTextDocument({ textDocument: cellTextDocument });
      }
      this.notebookDocuments.delete(params.notebookDocument.uri);
      for (const cell of notebookDocument.cells) {
        this.notebookCellMap.delete(cell.document);
      }
    }));
    return vscode_languageserver_protocol_1.Disposable.create(() => {
      disposables.forEach((disposable) => disposable.dispose());
    });
  }
  updateCellMap(notebookDocument) {
    for (const cell of notebookDocument.cells) {
      this.notebookCellMap.set(cell.document, [cell, notebookDocument]);
    }
  }
}
exports.NotebookDocuments = NotebookDocuments;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/progress.js":
/*!*************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/progress.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.attachPartialResult = exports.ProgressFeature = exports.attachWorkDone = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const uuid_1 = __webpack_require__(/*! ./utils/uuid */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/uuid.js");
class WorkDoneProgressReporterImpl {
  constructor(_connection, _token) {
    this._connection = _connection;
    this._token = _token;
    WorkDoneProgressReporterImpl.Instances.set(this._token, this);
  }
  begin(title, percentage, message, cancellable) {
    const param = {
      kind: "begin",
      title,
      message,
      cancellable
    };
    if (typeof percentage === "number") {
      param.percentage = Math.round(percentage);
    }
    this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
  }
  report(arg0, arg1) {
    const param = {
      kind: "report"
    };
    if (typeof arg0 === "number") {
      param.percentage = Math.round(arg0);
      if (arg1 !== void 0) {
        param.message = arg1;
      }
    } else {
      param.message = arg0;
    }
    this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
  }
  done() {
    WorkDoneProgressReporterImpl.Instances.delete(this._token);
    this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, { kind: "end" });
  }
}
WorkDoneProgressReporterImpl.Instances = /* @__PURE__ */ new Map();
class WorkDoneProgressServerReporterImpl extends WorkDoneProgressReporterImpl {
  constructor(connection, token) {
    super(connection, token);
    this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
  }
  get token() {
    return this._source.token;
  }
  done() {
    this._source.dispose();
    super.done();
  }
  cancel() {
    this._source.cancel();
  }
}
class NullProgressReporter {
  constructor() {
  }
  begin() {
  }
  report() {
  }
  done() {
  }
}
class NullProgressServerReporter extends NullProgressReporter {
  constructor() {
    super();
    this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
  }
  get token() {
    return this._source.token;
  }
  done() {
    this._source.dispose();
  }
  cancel() {
    this._source.cancel();
  }
}
function attachWorkDone(connection, params) {
  if (params === void 0 || params.workDoneToken === void 0) {
    return new NullProgressReporter();
  }
  const token = params.workDoneToken;
  delete params.workDoneToken;
  return new WorkDoneProgressReporterImpl(connection, token);
}
exports.attachWorkDone = attachWorkDone;
const ProgressFeature = (Base) => {
  return class extends Base {
    constructor() {
      super();
      this._progressSupported = false;
    }
    initialize(capabilities) {
      var _a;
      super.initialize(capabilities);
      if (((_a = capabilities == null ? void 0 : capabilities.window) == null ? void 0 : _a.workDoneProgress) === true) {
        this._progressSupported = true;
        this.connection.onNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, (params) => {
          const progress = WorkDoneProgressReporterImpl.Instances.get(params.token);
          if (progress instanceof WorkDoneProgressServerReporterImpl || progress instanceof NullProgressServerReporter) {
            progress.cancel();
          }
        });
      }
    }
    attachWorkDoneProgress(token) {
      if (token === void 0) {
        return new NullProgressReporter();
      } else {
        return new WorkDoneProgressReporterImpl(this.connection, token);
      }
    }
    createWorkDoneProgress() {
      if (this._progressSupported) {
        const token = (0, uuid_1.generateUuid)();
        return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, { token }).then(() => {
          const result = new WorkDoneProgressServerReporterImpl(this.connection, token);
          return result;
        });
      } else {
        return Promise.resolve(new NullProgressServerReporter());
      }
    }
  };
};
exports.ProgressFeature = ProgressFeature;
var ResultProgress;
(function(ResultProgress2) {
  ResultProgress2.type = new vscode_languageserver_protocol_1.ProgressType();
})(ResultProgress || (ResultProgress = {}));
class ResultProgressReporterImpl {
  constructor(_connection, _token) {
    this._connection = _connection;
    this._token = _token;
  }
  report(data) {
    this._connection.sendProgress(ResultProgress.type, this._token, data);
  }
}
function attachPartialResult(connection, params) {
  if (params === void 0 || params.partialResultToken === void 0) {
    return void 0;
  }
  const token = params.partialResultToken;
  delete params.partialResultToken;
  return new ResultProgressReporterImpl(connection, token);
}
exports.attachPartialResult = attachPartialResult;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/semanticTokens.js":
/*!*******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/semanticTokens.js ***!
  \*******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SemanticTokensBuilder = exports.SemanticTokensDiff = exports.SemanticTokensFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const SemanticTokensFeature = (Base) => {
  return class extends Base {
    get semanticTokens() {
      return {
        refresh: () => {
          return this.connection.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type);
        },
        on: (handler) => {
          const type = vscode_languageserver_protocol_1.SemanticTokensRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        },
        onDelta: (handler) => {
          const type = vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        },
        onRange: (handler) => {
          const type = vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        }
      };
    }
  };
};
exports.SemanticTokensFeature = SemanticTokensFeature;
class SemanticTokensDiff {
  constructor(originalSequence, modifiedSequence) {
    this.originalSequence = originalSequence;
    this.modifiedSequence = modifiedSequence;
  }
  computeDiff() {
    const originalLength = this.originalSequence.length;
    const modifiedLength = this.modifiedSequence.length;
    let startIndex = 0;
    while (startIndex < modifiedLength && startIndex < originalLength && this.originalSequence[startIndex] === this.modifiedSequence[startIndex]) {
      startIndex++;
    }
    if (startIndex < modifiedLength && startIndex < originalLength) {
      let originalEndIndex = originalLength - 1;
      let modifiedEndIndex = modifiedLength - 1;
      while (originalEndIndex >= startIndex && modifiedEndIndex >= startIndex && this.originalSequence[originalEndIndex] === this.modifiedSequence[modifiedEndIndex]) {
        originalEndIndex--;
        modifiedEndIndex--;
      }
      if (originalEndIndex < startIndex || modifiedEndIndex < startIndex) {
        originalEndIndex++;
        modifiedEndIndex++;
      }
      const deleteCount = originalEndIndex - startIndex + 1;
      const newData = this.modifiedSequence.slice(startIndex, modifiedEndIndex + 1);
      if (newData.length === 1 && newData[0] === this.originalSequence[originalEndIndex]) {
        return [
          { start: startIndex, deleteCount: deleteCount - 1 }
        ];
      } else {
        return [
          { start: startIndex, deleteCount, data: newData }
        ];
      }
    } else if (startIndex < modifiedLength) {
      return [
        { start: startIndex, deleteCount: 0, data: this.modifiedSequence.slice(startIndex) }
      ];
    } else if (startIndex < originalLength) {
      return [
        { start: startIndex, deleteCount: originalLength - startIndex }
      ];
    } else {
      return [];
    }
  }
}
exports.SemanticTokensDiff = SemanticTokensDiff;
class SemanticTokensBuilder {
  constructor() {
    this._prevData = void 0;
    this.initialize();
  }
  initialize() {
    this._id = Date.now();
    this._prevLine = 0;
    this._prevChar = 0;
    this._data = [];
    this._dataLen = 0;
  }
  push(line, char, length, tokenType, tokenModifiers) {
    let pushLine = line;
    let pushChar = char;
    if (this._dataLen > 0) {
      pushLine -= this._prevLine;
      if (pushLine === 0) {
        pushChar -= this._prevChar;
      }
    }
    this._data[this._dataLen++] = pushLine;
    this._data[this._dataLen++] = pushChar;
    this._data[this._dataLen++] = length;
    this._data[this._dataLen++] = tokenType;
    this._data[this._dataLen++] = tokenModifiers;
    this._prevLine = line;
    this._prevChar = char;
  }
  get id() {
    return this._id.toString();
  }
  previousResult(id) {
    if (this.id === id) {
      this._prevData = this._data;
    }
    this.initialize();
  }
  build() {
    this._prevData = void 0;
    return {
      resultId: this.id,
      data: this._data
    };
  }
  canBuildEdits() {
    return this._prevData !== void 0;
  }
  buildEdits() {
    if (this._prevData !== void 0) {
      return {
        resultId: this.id,
        edits: new SemanticTokensDiff(this._prevData, this._data).computeDiff()
      };
    } else {
      return this.build();
    }
  }
}
exports.SemanticTokensBuilder = SemanticTokensBuilder;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/server.js":
/*!***********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/server.js ***!
  \***********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createConnection = exports.combineFeatures = exports.combineNotebooksFeatures = exports.combineLanguagesFeatures = exports.combineWorkspaceFeatures = exports.combineWindowFeatures = exports.combineClientFeatures = exports.combineTracerFeatures = exports.combineTelemetryFeatures = exports.combineConsoleFeatures = exports._NotebooksImpl = exports._LanguagesImpl = exports.BulkUnregistration = exports.BulkRegistration = exports.ErrorMessageTracker = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const Is = __webpack_require__(/*! ./utils/is */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/is.js");
const UUID = __webpack_require__(/*! ./utils/uuid */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/uuid.js");
const progress_1 = __webpack_require__(/*! ./progress */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/progress.js");
const configuration_1 = __webpack_require__(/*! ./configuration */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/configuration.js");
const workspaceFolder_1 = __webpack_require__(/*! ./workspaceFolder */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/workspaceFolder.js");
const callHierarchy_1 = __webpack_require__(/*! ./callHierarchy */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/callHierarchy.js");
const semanticTokens_1 = __webpack_require__(/*! ./semanticTokens */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/semanticTokens.js");
const showDocument_1 = __webpack_require__(/*! ./showDocument */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/showDocument.js");
const fileOperations_1 = __webpack_require__(/*! ./fileOperations */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/fileOperations.js");
const linkedEditingRange_1 = __webpack_require__(/*! ./linkedEditingRange */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/linkedEditingRange.js");
const typeHierarchy_1 = __webpack_require__(/*! ./typeHierarchy */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/typeHierarchy.js");
const inlineValue_1 = __webpack_require__(/*! ./inlineValue */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlineValue.js");
const foldingRange_1 = __webpack_require__(/*! ./foldingRange */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/foldingRange.js");
const inlayHint_1 = __webpack_require__(/*! ./inlayHint */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/inlayHint.js");
const diagnostic_1 = __webpack_require__(/*! ./diagnostic */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/diagnostic.js");
const notebook_1 = __webpack_require__(/*! ./notebook */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/notebook.js");
const moniker_1 = __webpack_require__(/*! ./moniker */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/moniker.js");
function null2Undefined(value) {
  if (value === null) {
    return void 0;
  }
  return value;
}
class ErrorMessageTracker {
  constructor() {
    this._messages = /* @__PURE__ */ Object.create(null);
  }
  /**
   * Add a message to the tracker.
   *
   * @param message The message to add.
   */
  add(message) {
    let count = this._messages[message];
    if (!count) {
      count = 0;
    }
    count++;
    this._messages[message] = count;
  }
  /**
   * Send all tracked messages to the connection's window.
   *
   * @param connection The connection established between client and server.
   */
  sendErrors(connection) {
    Object.keys(this._messages).forEach((message) => {
      connection.window.showErrorMessage(message);
    });
  }
}
exports.ErrorMessageTracker = ErrorMessageTracker;
class RemoteConsoleImpl {
  constructor() {
  }
  rawAttach(connection) {
    this._rawConnection = connection;
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  fillServerCapabilities(_capabilities) {
  }
  initialize(_capabilities) {
  }
  error(message) {
    this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
  }
  warn(message) {
    this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
  }
  info(message) {
    this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
  }
  log(message) {
    this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
  }
  debug(message) {
    this.send(vscode_languageserver_protocol_1.MessageType.Debug, message);
  }
  send(type, message) {
    if (this._rawConnection) {
      this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message }).catch(() => {
        (0, vscode_languageserver_protocol_1.RAL)().console.error(`Sending log message failed`);
      });
    }
  }
}
class _RemoteWindowImpl {
  constructor() {
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  showErrorMessage(message, ...actions) {
    const params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  }
  showWarningMessage(message, ...actions) {
    const params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  }
  showInformationMessage(message, ...actions) {
    const params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
  }
}
const RemoteWindowImpl = (0, showDocument_1.ShowDocumentFeature)((0, progress_1.ProgressFeature)(_RemoteWindowImpl));
var BulkRegistration;
(function(BulkRegistration2) {
  function create() {
    return new BulkRegistrationImpl();
  }
  BulkRegistration2.create = create;
})(BulkRegistration || (exports.BulkRegistration = BulkRegistration = {}));
class BulkRegistrationImpl {
  constructor() {
    this._registrations = [];
    this._registered = /* @__PURE__ */ new Set();
  }
  add(type, registerOptions) {
    const method = Is.string(type) ? type : type.method;
    if (this._registered.has(method)) {
      throw new Error(`${method} is already added to this registration`);
    }
    const id = UUID.generateUuid();
    this._registrations.push({
      id,
      method,
      registerOptions: registerOptions || {}
    });
    this._registered.add(method);
  }
  asRegistrationParams() {
    return {
      registrations: this._registrations
    };
  }
}
var BulkUnregistration;
(function(BulkUnregistration2) {
  function create() {
    return new BulkUnregistrationImpl(void 0, []);
  }
  BulkUnregistration2.create = create;
})(BulkUnregistration || (exports.BulkUnregistration = BulkUnregistration = {}));
class BulkUnregistrationImpl {
  constructor(_connection, unregistrations) {
    this._connection = _connection;
    this._unregistrations = /* @__PURE__ */ new Map();
    unregistrations.forEach((unregistration) => {
      this._unregistrations.set(unregistration.method, unregistration);
    });
  }
  get isAttached() {
    return !!this._connection;
  }
  attach(connection) {
    this._connection = connection;
  }
  add(unregistration) {
    this._unregistrations.set(unregistration.method, unregistration);
  }
  dispose() {
    const unregistrations = [];
    for (const unregistration of this._unregistrations.values()) {
      unregistrations.push(unregistration);
    }
    const params = {
      unregisterations: unregistrations
    };
    this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
      this._connection.console.info(`Bulk unregistration failed.`);
    });
  }
  disposeSingle(arg) {
    const method = Is.string(arg) ? arg : arg.method;
    const unregistration = this._unregistrations.get(method);
    if (!unregistration) {
      return false;
    }
    const params = {
      unregisterations: [unregistration]
    };
    this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
      this._unregistrations.delete(method);
    }, (_error) => {
      this._connection.console.info(`Un-registering request handler for ${unregistration.id} failed.`);
    });
    return true;
  }
}
class RemoteClientImpl {
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
    if (typeOrRegistrations instanceof BulkRegistrationImpl) {
      return this.registerMany(typeOrRegistrations);
    } else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
      return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
    } else {
      return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
    }
  }
  registerSingle1(unregistration, type, registerOptions) {
    const method = Is.string(type) ? type : type.method;
    const id = UUID.generateUuid();
    const params = {
      registrations: [{ id, method, registerOptions: registerOptions || {} }]
    };
    if (!unregistration.isAttached) {
      unregistration.attach(this.connection);
    }
    return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
      unregistration.add({ id, method });
      return unregistration;
    }, (_error) => {
      this.connection.console.info(`Registering request handler for ${method} failed.`);
      return Promise.reject(_error);
    });
  }
  registerSingle2(type, registerOptions) {
    const method = Is.string(type) ? type : type.method;
    const id = UUID.generateUuid();
    const params = {
      registrations: [{ id, method, registerOptions: registerOptions || {} }]
    };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
      return vscode_languageserver_protocol_1.Disposable.create(() => {
        this.unregisterSingle(id, method).catch(() => {
          this.connection.console.info(`Un-registering capability with id ${id} failed.`);
        });
      });
    }, (_error) => {
      this.connection.console.info(`Registering request handler for ${method} failed.`);
      return Promise.reject(_error);
    });
  }
  unregisterSingle(id, method) {
    const params = {
      unregisterations: [{ id, method }]
    };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
      this.connection.console.info(`Un-registering request handler for ${id} failed.`);
    });
  }
  registerMany(registrations) {
    const params = registrations.asRegistrationParams();
    return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
      return new BulkUnregistrationImpl(this._connection, params.registrations.map((registration) => {
        return { id: registration.id, method: registration.method };
      }));
    }, (_error) => {
      this.connection.console.info(`Bulk registration failed.`);
      return Promise.reject(_error);
    });
  }
}
class _RemoteWorkspaceImpl {
  constructor() {
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  applyEdit(paramOrEdit) {
    function isApplyWorkspaceEditParams(value) {
      return value && !!value.edit;
    }
    const params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
    return this.connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
  }
}
const RemoteWorkspaceImpl = (0, fileOperations_1.FileOperationsFeature)((0, workspaceFolder_1.WorkspaceFoldersFeature)((0, configuration_1.ConfigurationFeature)(_RemoteWorkspaceImpl)));
class TracerImpl {
  constructor() {
    this._trace = vscode_languageserver_protocol_1.Trace.Off;
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  set trace(value) {
    this._trace = value;
  }
  log(message, verbose) {
    if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
      return;
    }
    this.connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
      message,
      verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : void 0
    }).catch(() => {
    });
  }
}
class TelemetryImpl {
  constructor() {
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  logEvent(data) {
    this.connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data).catch(() => {
      this.connection.console.log(`Sending TelemetryEventNotification failed`);
    });
  }
}
class _LanguagesImpl {
  constructor() {
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  attachWorkDoneProgress(params) {
    return (0, progress_1.attachWorkDone)(this.connection, params);
  }
  attachPartialResultProgress(_type, params) {
    return (0, progress_1.attachPartialResult)(this.connection, params);
  }
}
exports._LanguagesImpl = _LanguagesImpl;
const LanguagesImpl = (0, foldingRange_1.FoldingRangeFeature)((0, moniker_1.MonikerFeature)((0, diagnostic_1.DiagnosticFeature)((0, inlayHint_1.InlayHintFeature)((0, inlineValue_1.InlineValueFeature)((0, typeHierarchy_1.TypeHierarchyFeature)((0, linkedEditingRange_1.LinkedEditingRangeFeature)((0, semanticTokens_1.SemanticTokensFeature)((0, callHierarchy_1.CallHierarchyFeature)(_LanguagesImpl)))))))));
class _NotebooksImpl {
  constructor() {
  }
  attach(connection) {
    this._connection = connection;
  }
  get connection() {
    if (!this._connection) {
      throw new Error("Remote is not attached to a connection yet.");
    }
    return this._connection;
  }
  initialize(_capabilities) {
  }
  fillServerCapabilities(_capabilities) {
  }
  attachWorkDoneProgress(params) {
    return (0, progress_1.attachWorkDone)(this.connection, params);
  }
  attachPartialResultProgress(_type, params) {
    return (0, progress_1.attachPartialResult)(this.connection, params);
  }
}
exports._NotebooksImpl = _NotebooksImpl;
const NotebooksImpl = (0, notebook_1.NotebookSyncFeature)(_NotebooksImpl);
function combineConsoleFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineConsoleFeatures = combineConsoleFeatures;
function combineTelemetryFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineTelemetryFeatures = combineTelemetryFeatures;
function combineTracerFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineTracerFeatures = combineTracerFeatures;
function combineClientFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineClientFeatures = combineClientFeatures;
function combineWindowFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineWindowFeatures = combineWindowFeatures;
function combineWorkspaceFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineWorkspaceFeatures = combineWorkspaceFeatures;
function combineLanguagesFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineLanguagesFeatures = combineLanguagesFeatures;
function combineNotebooksFeatures(one, two) {
  return function(Base) {
    return two(one(Base));
  };
}
exports.combineNotebooksFeatures = combineNotebooksFeatures;
function combineFeatures(one, two) {
  function combine(one2, two2, func) {
    if (one2 && two2) {
      return func(one2, two2);
    } else if (one2) {
      return one2;
    } else {
      return two2;
    }
  }
  const result = {
    __brand: "features",
    console: combine(one.console, two.console, combineConsoleFeatures),
    tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
    telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
    client: combine(one.client, two.client, combineClientFeatures),
    window: combine(one.window, two.window, combineWindowFeatures),
    workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures),
    languages: combine(one.languages, two.languages, combineLanguagesFeatures),
    notebooks: combine(one.notebooks, two.notebooks, combineNotebooksFeatures)
  };
  return result;
}
exports.combineFeatures = combineFeatures;
function createConnection(connectionFactory, watchDog, factories) {
  const logger = factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl();
  const connection = connectionFactory(logger);
  logger.rawAttach(connection);
  const tracer = factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl();
  const telemetry = factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl();
  const client = factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl();
  const remoteWindow = factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl();
  const workspace = factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl();
  const languages = factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl();
  const notebooks = factories && factories.notebooks ? new (factories.notebooks(NotebooksImpl))() : new NotebooksImpl();
  const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages, notebooks];
  function asPromise(value) {
    if (value instanceof Promise) {
      return value;
    } else if (Is.thenable(value)) {
      return new Promise((resolve, reject) => {
        value.then((resolved) => resolve(resolved), (error) => reject(error));
      });
    } else {
      return Promise.resolve(value);
    }
  }
  let shutdownHandler = void 0;
  let initializeHandler = void 0;
  let exitHandler = void 0;
  const protocolConnection = {
    listen: () => connection.listen(),
    sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
    onRequest: (type, handler) => connection.onRequest(type, handler),
    sendNotification: (type, param) => {
      const method = Is.string(type) ? type : type.method;
      return connection.sendNotification(method, param);
    },
    onNotification: (type, handler) => connection.onNotification(type, handler),
    onProgress: connection.onProgress,
    sendProgress: connection.sendProgress,
    onInitialize: (handler) => {
      initializeHandler = handler;
      return {
        dispose: () => {
          initializeHandler = void 0;
        }
      };
    },
    onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
    onShutdown: (handler) => {
      shutdownHandler = handler;
      return {
        dispose: () => {
          shutdownHandler = void 0;
        }
      };
    },
    onExit: (handler) => {
      exitHandler = handler;
      return {
        dispose: () => {
          exitHandler = void 0;
        }
      };
    },
    get console() {
      return logger;
    },
    get telemetry() {
      return telemetry;
    },
    get tracer() {
      return tracer;
    },
    get client() {
      return client;
    },
    get window() {
      return remoteWindow;
    },
    get workspace() {
      return workspace;
    },
    get languages() {
      return languages;
    },
    get notebooks() {
      return notebooks;
    },
    onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
    onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
    __textDocumentSync: void 0,
    onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
    onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
    onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
    onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
    onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
    onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
    sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
    onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
    onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onWorkspaceSymbolResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, handler),
    onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onCodeActionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, (params, cancel) => {
      return handler(params, cancel);
    }),
    onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => {
      return handler(params, cancel);
    }),
    onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => {
      return handler(params, cancel);
    }),
    onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => {
      return handler(params, cancel);
    }),
    onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => {
      return handler(params, cancel);
    }),
    onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onSelectionRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), (0, progress_1.attachPartialResult)(connection, params));
    }),
    onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => {
      return handler(params, cancel, (0, progress_1.attachWorkDone)(connection, params), void 0);
    }),
    dispose: () => connection.dispose()
  };
  for (const remote of allRemotes) {
    remote.attach(protocolConnection);
  }
  connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
    watchDog.initialize(params);
    if (Is.string(params.trace)) {
      tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
    }
    for (const remote of allRemotes) {
      remote.initialize(params.capabilities);
    }
    if (initializeHandler) {
      const result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, (0, progress_1.attachWorkDone)(connection, params), void 0);
      return asPromise(result).then((value) => {
        if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
          return value;
        }
        let result2 = value;
        if (!result2) {
          result2 = { capabilities: {} };
        }
        let capabilities = result2.capabilities;
        if (!capabilities) {
          capabilities = {};
          result2.capabilities = capabilities;
        }
        if (capabilities.textDocumentSync === void 0 || capabilities.textDocumentSync === null) {
          capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
        } else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {
          capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
        }
        for (const remote of allRemotes) {
          remote.fillServerCapabilities(capabilities);
        }
        return result2;
      });
    } else {
      const result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
      for (const remote of allRemotes) {
        remote.fillServerCapabilities(result.capabilities);
      }
      return result;
    }
  });
  connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
    watchDog.shutdownReceived = true;
    if (shutdownHandler) {
      return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
    } else {
      return void 0;
    }
  });
  connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
    try {
      if (exitHandler) {
        return exitHandler();
      }
    } finally {
      if (watchDog.shutdownReceived) {
        watchDog.exit(0);
      } else {
        watchDog.exit(1);
      }
    }
  });
  connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
    tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
  });
  return protocolConnection;
}
exports.createConnection = createConnection;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/showDocument.js":
/*!*****************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/showDocument.js ***!
  \*****************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ShowDocumentFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const ShowDocumentFeature = (Base) => {
  return class extends Base {
    showDocument(params) {
      return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, params);
    }
  };
};
exports.ShowDocumentFeature = ShowDocumentFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/textDocuments.js":
/*!******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/textDocuments.js ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TextDocuments = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
class TextDocuments {
  /**
   * Create a new text document manager.
   */
  constructor(configuration) {
    this._configuration = configuration;
    this._syncedDocuments = /* @__PURE__ */ new Map();
    this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();
    this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
    this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
    this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
    this._onWillSave = new vscode_languageserver_protocol_1.Emitter();
  }
  /**
   * An event that fires when a text document managed by this manager
   * has been opened.
   */
  get onDidOpen() {
    return this._onDidOpen.event;
  }
  /**
   * An event that fires when a text document managed by this manager
   * has been opened or the content changes.
   */
  get onDidChangeContent() {
    return this._onDidChangeContent.event;
  }
  /**
   * An event that fires when a text document managed by this manager
   * will be saved.
   */
  get onWillSave() {
    return this._onWillSave.event;
  }
  /**
   * Sets a handler that will be called if a participant wants to provide
   * edits during a text document save.
   */
  onWillSaveWaitUntil(handler) {
    this._willSaveWaitUntil = handler;
  }
  /**
   * An event that fires when a text document managed by this manager
   * has been saved.
   */
  get onDidSave() {
    return this._onDidSave.event;
  }
  /**
   * An event that fires when a text document managed by this manager
   * has been closed.
   */
  get onDidClose() {
    return this._onDidClose.event;
  }
  /**
   * Returns the document for the given URI. Returns undefined if
   * the document is not managed by this instance.
   *
   * @param uri The text document's URI to retrieve.
   * @return the text document or `undefined`.
   */
  get(uri) {
    return this._syncedDocuments.get(uri);
  }
  /**
   * Returns all text documents managed by this instance.
   *
   * @return all text documents.
   */
  all() {
    return Array.from(this._syncedDocuments.values());
  }
  /**
   * Returns the URIs of all text documents managed by this instance.
   *
   * @return the URI's of all text documents.
   */
  keys() {
    return Array.from(this._syncedDocuments.keys());
  }
  /**
   * Listens for `low level` notification on the given connection to
   * update the text documents managed by this instance.
   *
   * Please note that the connection only provides handlers not an event model. Therefore
   * listening on a connection will overwrite the following handlers on a connection:
   * `onDidOpenTextDocument`, `onDidChangeTextDocument`, `onDidCloseTextDocument`,
   * `onWillSaveTextDocument`, `onWillSaveTextDocumentWaitUntil` and `onDidSaveTextDocument`.
   *
   * Use the corresponding events on the TextDocuments instance instead.
   *
   * @param connection The connection to listen on.
   */
  listen(connection) {
    connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental;
    const disposables = [];
    disposables.push(connection.onDidOpenTextDocument((event) => {
      const td = event.textDocument;
      const document = this._configuration.create(td.uri, td.languageId, td.version, td.text);
      this._syncedDocuments.set(td.uri, document);
      const toFire = Object.freeze({ document });
      this._onDidOpen.fire(toFire);
      this._onDidChangeContent.fire(toFire);
    }));
    disposables.push(connection.onDidChangeTextDocument((event) => {
      const td = event.textDocument;
      const changes = event.contentChanges;
      if (changes.length === 0) {
        return;
      }
      const { version } = td;
      if (version === null || version === void 0) {
        throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
      }
      let syncedDocument = this._syncedDocuments.get(td.uri);
      if (syncedDocument !== void 0) {
        syncedDocument = this._configuration.update(syncedDocument, changes, version);
        this._syncedDocuments.set(td.uri, syncedDocument);
        this._onDidChangeContent.fire(Object.freeze({ document: syncedDocument }));
      }
    }));
    disposables.push(connection.onDidCloseTextDocument((event) => {
      const syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
      if (syncedDocument !== void 0) {
        this._syncedDocuments.delete(event.textDocument.uri);
        this._onDidClose.fire(Object.freeze({ document: syncedDocument }));
      }
    }));
    disposables.push(connection.onWillSaveTextDocument((event) => {
      const syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
      if (syncedDocument !== void 0) {
        this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason }));
      }
    }));
    disposables.push(connection.onWillSaveTextDocumentWaitUntil((event, token) => {
      const syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
      if (syncedDocument !== void 0 && this._willSaveWaitUntil) {
        return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token);
      } else {
        return [];
      }
    }));
    disposables.push(connection.onDidSaveTextDocument((event) => {
      const syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
      if (syncedDocument !== void 0) {
        this._onDidSave.fire(Object.freeze({ document: syncedDocument }));
      }
    }));
    return vscode_languageserver_protocol_1.Disposable.create(() => {
      disposables.forEach((disposable) => disposable.dispose());
    });
  }
}
exports.TextDocuments = TextDocuments;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/typeHierarchy.js":
/*!******************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/typeHierarchy.js ***!
  \******************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeHierarchyFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const TypeHierarchyFeature = (Base) => {
  return class extends Base {
    get typeHierarchy() {
      return {
        onPrepare: (handler) => {
          return this.connection.onRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
          });
        },
        onSupertypes: (handler) => {
          const type = vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        },
        onSubtypes: (handler) => {
          const type = vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type;
          return this.connection.onRequest(type, (params, cancel) => {
            return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
          });
        }
      };
    }
  };
};
exports.TypeHierarchyFeature = TypeHierarchyFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/is.js":
/*!*************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/is.js ***!
  \*************************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.thenable = exports.typedArray = exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
function boolean(value) {
  return value === true || value === false;
}
exports.boolean = boolean;
function string(value) {
  return typeof value === "string" || value instanceof String;
}
exports.string = string;
function number(value) {
  return typeof value === "number" || value instanceof Number;
}
exports.number = number;
function error(value) {
  return value instanceof Error;
}
exports.error = error;
function func(value) {
  return typeof value === "function";
}
exports.func = func;
function array(value) {
  return Array.isArray(value);
}
exports.array = array;
function stringArray(value) {
  return array(value) && value.every((elem) => string(elem));
}
exports.stringArray = stringArray;
function typedArray(value, check) {
  return Array.isArray(value) && value.every(check);
}
exports.typedArray = typedArray;
function thenable(value) {
  return value && func(value.then);
}
exports.thenable = thenable;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/uuid.js":
/*!***************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/uuid.js ***!
  \***************************************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.generateUuid = exports.parse = exports.isUUID = exports.v4 = exports.empty = void 0;
class ValueUUID {
  constructor(_value) {
    this._value = _value;
  }
  asHex() {
    return this._value;
  }
  equals(other) {
    return this.asHex() === other.asHex();
  }
}
class V4UUID extends ValueUUID {
  static _oneOf(array) {
    return array[Math.floor(array.length * Math.random())];
  }
  static _randomHex() {
    return V4UUID._oneOf(V4UUID._chars);
  }
  constructor() {
    super([
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      "-",
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      "-",
      "4",
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      "-",
      V4UUID._oneOf(V4UUID._timeHighBits),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      "-",
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex(),
      V4UUID._randomHex()
    ].join(""));
  }
}
V4UUID._chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
V4UUID._timeHighBits = ["8", "9", "a", "b"];
exports.empty = new ValueUUID("00000000-0000-0000-0000-000000000000");
function v4() {
  return new V4UUID();
}
exports.v4 = v4;
const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isUUID(value) {
  return _UUIDPattern.test(value);
}
exports.isUUID = isUUID;
function parse(value) {
  if (!isUUID(value)) {
    throw new Error("invalid uuid");
  }
  return new ValueUUID(value);
}
exports.parse = parse;
function generateUuid() {
  return v4().asHex();
}
exports.generateUuid = generateUuid;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/common/workspaceFolder.js":
/*!********************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/common/workspaceFolder.js ***!
  \********************************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceFoldersFeature = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const WorkspaceFoldersFeature = (Base) => {
  return class extends Base {
    constructor() {
      super();
      this._notificationIsAutoRegistered = false;
    }
    initialize(capabilities) {
      super.initialize(capabilities);
      const workspaceCapabilities = capabilities.workspace;
      if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
        this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();
        this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {
          this._onDidChangeWorkspaceFolders.fire(params.event);
        });
      }
    }
    fillServerCapabilities(capabilities) {
      var _a, _b;
      super.fillServerCapabilities(capabilities);
      const changeNotifications = (_b = (_a = capabilities.workspace) == null ? void 0 : _a.workspaceFolders) == null ? void 0 : _b.changeNotifications;
      this._notificationIsAutoRegistered = changeNotifications === true || typeof changeNotifications === "string";
    }
    getWorkspaceFolders() {
      return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);
    }
    get onDidChangeWorkspaceFolders() {
      if (!this._onDidChangeWorkspaceFolders) {
        throw new Error("Client doesn't support sending workspace folder change events.");
      }
      if (!this._notificationIsAutoRegistered && !this._unregistration) {
        this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);
      }
      return this._onDidChangeWorkspaceFolders.event;
    }
  };
};
exports.WorkspaceFoldersFeature = WorkspaceFoldersFeature;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/node/files.js":
/*!********************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/node/files.js ***!
  \********************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveModulePath = exports.FileSystem = exports.resolveGlobalYarnPath = exports.resolveGlobalNodePath = exports.resolve = exports.uriToFilePath = void 0;
const url = __webpack_require__(/*! url */ "url");
const path = __webpack_require__(/*! path */ "path");
const fs = __webpack_require__(/*! fs */ "fs");
const child_process_1 = __webpack_require__(/*! child_process */ "child_process");
function uriToFilePath(uri) {
  const parsed = url.parse(uri);
  if (parsed.protocol !== "file:" || !parsed.path) {
    return void 0;
  }
  const segments = parsed.path.split("/");
  for (let i = 0, len = segments.length; i < len; i++) {
    segments[i] = decodeURIComponent(segments[i]);
  }
  if (process.platform === "win32" && segments.length > 1) {
    const first = segments[0];
    const second = segments[1];
    if (first.length === 0 && second.length > 1 && second[1] === ":") {
      segments.shift();
    }
  }
  return path.normalize(segments.join("/"));
}
exports.uriToFilePath = uriToFilePath;
function isWindows() {
  return process.platform === "win32";
}
function resolve(moduleName, nodePath, cwd, tracer) {
  const nodePathKey = "NODE_PATH";
  const app = [
    "var p = process;",
    "p.on('message',function(m){",
    "if(m.c==='e'){",
    "p.exit(0);",
    "}",
    "else if(m.c==='rs'){",
    "try{",
    "var r=require.resolve(m.a);",
    "p.send({c:'r',s:true,r:r});",
    "}",
    "catch(err){",
    "p.send({c:'r',s:false});",
    "}",
    "}",
    "});"
  ].join("");
  return new Promise((resolve2, reject) => {
    const env = process.env;
    const newEnv = /* @__PURE__ */ Object.create(null);
    Object.keys(env).forEach((key) => newEnv[key] = env[key]);
    if (nodePath && fs.existsSync(nodePath)) {
      if (newEnv[nodePathKey]) {
        newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
      } else {
        newEnv[nodePathKey] = nodePath;
      }
      if (tracer) {
        tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
      }
    }
    newEnv["ELECTRON_RUN_AS_NODE"] = "1";
    try {
      const cp = (0, child_process_1.fork)("", [], {
        cwd,
        env: newEnv,
        execArgv: ["-e", app]
      });
      if (cp.pid === void 0) {
        reject(new Error(`Starting process to resolve node module  ${moduleName} failed`));
        return;
      }
      cp.on("error", (error) => {
        reject(error);
      });
      cp.on("message", (message2) => {
        if (message2.c === "r") {
          cp.send({ c: "e" });
          if (message2.s) {
            resolve2(message2.r);
          } else {
            reject(new Error(`Failed to resolve module: ${moduleName}`));
          }
        }
      });
      const message = {
        c: "rs",
        a: moduleName
      };
      cp.send(message);
    } catch (error) {
      reject(error);
    }
  });
}
exports.resolve = resolve;
function resolveGlobalNodePath(tracer) {
  let npmCommand = "npm";
  const env = /* @__PURE__ */ Object.create(null);
  Object.keys(process.env).forEach((key) => env[key] = process.env[key]);
  env["NO_UPDATE_NOTIFIER"] = "true";
  const options = {
    encoding: "utf8",
    env
  };
  if (isWindows()) {
    npmCommand = "npm.cmd";
    options.shell = true;
  }
  const handler = () => {
  };
  try {
    process.on("SIGPIPE", handler);
    const stdout = (0, child_process_1.spawnSync)(npmCommand, ["config", "get", "prefix"], options).stdout;
    if (!stdout) {
      if (tracer) {
        tracer(`'npm config get prefix' didn't return a value.`);
      }
      return void 0;
    }
    const prefix = stdout.trim();
    if (tracer) {
      tracer(`'npm config get prefix' value is: ${prefix}`);
    }
    if (prefix.length > 0) {
      if (isWindows()) {
        return path.join(prefix, "node_modules");
      } else {
        return path.join(prefix, "lib", "node_modules");
      }
    }
    return void 0;
  } catch (err) {
    return void 0;
  } finally {
    process.removeListener("SIGPIPE", handler);
  }
}
exports.resolveGlobalNodePath = resolveGlobalNodePath;
function resolveGlobalYarnPath(tracer) {
  let yarnCommand = "yarn";
  const options = {
    encoding: "utf8"
  };
  if (isWindows()) {
    yarnCommand = "yarn.cmd";
    options.shell = true;
  }
  const handler = () => {
  };
  try {
    process.on("SIGPIPE", handler);
    const results = (0, child_process_1.spawnSync)(yarnCommand, ["global", "dir", "--json"], options);
    const stdout = results.stdout;
    if (!stdout) {
      if (tracer) {
        tracer(`'yarn global dir' didn't return a value.`);
        if (results.stderr) {
          tracer(results.stderr);
        }
      }
      return void 0;
    }
    const lines = stdout.trim().split(/\r?\n/);
    for (const line of lines) {
      try {
        const yarn = JSON.parse(line);
        if (yarn.type === "log") {
          return path.join(yarn.data, "node_modules");
        }
      } catch (e) {
      }
    }
    return void 0;
  } catch (err) {
    return void 0;
  } finally {
    process.removeListener("SIGPIPE", handler);
  }
}
exports.resolveGlobalYarnPath = resolveGlobalYarnPath;
var FileSystem;
(function(FileSystem2) {
  let _isCaseSensitive = void 0;
  function isCaseSensitive() {
    if (_isCaseSensitive !== void 0) {
      return _isCaseSensitive;
    }
    if (process.platform === "win32") {
      _isCaseSensitive = false;
    } else {
      _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase());
    }
    return _isCaseSensitive;
  }
  FileSystem2.isCaseSensitive = isCaseSensitive;
  function isParent(parent, child) {
    if (isCaseSensitive()) {
      return path.normalize(child).indexOf(path.normalize(parent)) === 0;
    } else {
      return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) === 0;
    }
  }
  FileSystem2.isParent = isParent;
})(FileSystem || (exports.FileSystem = FileSystem = {}));
function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {
  if (nodePath) {
    if (!path.isAbsolute(nodePath)) {
      nodePath = path.join(workspaceRoot, nodePath);
    }
    return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {
      if (FileSystem.isParent(nodePath, value)) {
        return value;
      } else {
        return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));
      }
    }).then(void 0, (_error) => {
      return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
    });
  } else {
    return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
  }
}
exports.resolveModulePath = resolveModulePath;


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js":
/*!*******************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js ***!
  \*******************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = { enumerable: true, get: function() {
      return m[k];
    } };
  }
  Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
  if (k2 === void 0)
    k2 = k;
  o[k2] = m[k];
});
var __exportStar = this && this.__exportStar || function(m, exports2) {
  for (var p in m)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
      __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createConnection = exports.Files = void 0;
const node_util_1 = __webpack_require__(/*! node:util */ "node:util");
const Is = __webpack_require__(/*! ../common/utils/is */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/utils/is.js");
const server_1 = __webpack_require__(/*! ../common/server */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/server.js");
const fm = __webpack_require__(/*! ./files */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/files.js");
const node_1 = __webpack_require__(/*! vscode-languageserver-protocol/node */ "../pyright-internal/node_modules/vscode-languageserver-protocol/node.js");
__exportStar(__webpack_require__(/*! vscode-languageserver-protocol/node */ "../pyright-internal/node_modules/vscode-languageserver-protocol/node.js"), exports);
__exportStar(__webpack_require__(/*! ../common/api */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/api.js"), exports);
var Files;
(function(Files2) {
  Files2.uriToFilePath = fm.uriToFilePath;
  Files2.resolveGlobalNodePath = fm.resolveGlobalNodePath;
  Files2.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;
  Files2.resolve = fm.resolve;
  Files2.resolveModulePath = fm.resolveModulePath;
})(Files || (exports.Files = Files = {}));
let _protocolConnection;
function endProtocolConnection() {
  if (_protocolConnection === void 0) {
    return;
  }
  try {
    _protocolConnection.end();
  } catch (_err) {
  }
}
let _shutdownReceived = false;
let exitTimer = void 0;
function setupExitTimer() {
  const argName = "--clientProcessId";
  function runTimer(value) {
    try {
      const processId = parseInt(value);
      if (!isNaN(processId)) {
        exitTimer = setInterval(() => {
          try {
            process.kill(processId, 0);
          } catch (ex) {
            endProtocolConnection();
            process.exit(_shutdownReceived ? 0 : 1);
          }
        }, 3e3);
      }
    } catch (e) {
    }
  }
  for (let i = 2; i < process.argv.length; i++) {
    const arg = process.argv[i];
    if (arg === argName && i + 1 < process.argv.length) {
      runTimer(process.argv[i + 1]);
      return;
    } else {
      const args = arg.split("=");
      if (args[0] === argName) {
        runTimer(args[1]);
      }
    }
  }
}
setupExitTimer();
const watchDog = {
  initialize: (params) => {
    const processId = params.processId;
    if (Is.number(processId) && exitTimer === void 0) {
      setInterval(() => {
        try {
          process.kill(processId, 0);
        } catch (ex) {
          process.exit(_shutdownReceived ? 0 : 1);
        }
      }, 3e3);
    }
  },
  get shutdownReceived() {
    return _shutdownReceived;
  },
  set shutdownReceived(value) {
    _shutdownReceived = value;
  },
  exit: (code) => {
    endProtocolConnection();
    process.exit(code);
  }
};
function createConnection(arg1, arg2, arg3, arg4) {
  let factories;
  let input;
  let output;
  let options;
  if (arg1 !== void 0 && arg1.__brand === "features") {
    factories = arg1;
    arg1 = arg2;
    arg2 = arg3;
    arg3 = arg4;
  }
  if (node_1.ConnectionStrategy.is(arg1) || node_1.ConnectionOptions.is(arg1)) {
    options = arg1;
  } else {
    input = arg1;
    output = arg2;
    options = arg3;
  }
  return _createConnection(input, output, options, factories);
}
exports.createConnection = createConnection;
function _createConnection(input, output, options, factories) {
  let stdio = false;
  if (!input && !output && process.argv.length > 2) {
    let port = void 0;
    let pipeName = void 0;
    const argv = process.argv.slice(2);
    for (let i = 0; i < argv.length; i++) {
      const arg = argv[i];
      if (arg === "--node-ipc") {
        input = new node_1.IPCMessageReader(process);
        output = new node_1.IPCMessageWriter(process);
        break;
      } else if (arg === "--stdio") {
        stdio = true;
        input = process.stdin;
        output = process.stdout;
        break;
      } else if (arg === "--socket") {
        port = parseInt(argv[i + 1]);
        break;
      } else if (arg === "--pipe") {
        pipeName = argv[i + 1];
        break;
      } else {
        const args = arg.split("=");
        if (args[0] === "--socket") {
          port = parseInt(args[1]);
          break;
        } else if (args[0] === "--pipe") {
          pipeName = args[1];
          break;
        }
      }
    }
    if (port) {
      const transport = (0, node_1.createServerSocketTransport)(port);
      input = transport[0];
      output = transport[1];
    } else if (pipeName) {
      const transport = (0, node_1.createServerPipeTransport)(pipeName);
      input = transport[0];
      output = transport[1];
    }
  }
  const commandLineMessage = "Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'";
  if (!input) {
    throw new Error("Connection input stream is not set. " + commandLineMessage);
  }
  if (!output) {
    throw new Error("Connection output stream is not set. " + commandLineMessage);
  }
  if (Is.func(input.read) && Is.func(input.on)) {
    const inputStream = input;
    inputStream.on("end", () => {
      endProtocolConnection();
      process.exit(_shutdownReceived ? 0 : 1);
    });
    inputStream.on("close", () => {
      endProtocolConnection();
      process.exit(_shutdownReceived ? 0 : 1);
    });
  }
  const connectionFactory = (logger) => {
    const result = (0, node_1.createProtocolConnection)(input, output, logger, options);
    if (stdio) {
      patchConsole(logger);
    }
    return result;
  };
  return (0, server_1.createConnection)(connectionFactory, watchDog, factories);
}
function patchConsole(logger) {
  function serialize(args) {
    return args.map((arg) => typeof arg === "string" ? arg : (0, node_util_1.inspect)(arg)).join(" ");
  }
  const counters = /* @__PURE__ */ new Map();
  console.assert = function assert(assertion, ...args) {
    if (assertion) {
      return;
    }
    if (args.length === 0) {
      logger.error("Assertion failed");
    } else {
      const [message, ...rest] = args;
      logger.error(`Assertion failed: ${message} ${serialize(rest)}`);
    }
  };
  console.count = function count(label = "default") {
    var _a;
    const message = String(label);
    let counter = (_a = counters.get(message)) != null ? _a : 0;
    counter += 1;
    counters.set(message, counter);
    logger.log(`${message}: ${message}`);
  };
  console.countReset = function countReset(label) {
    if (label === void 0) {
      counters.clear();
    } else {
      counters.delete(String(label));
    }
  };
  console.debug = function debug(...args) {
    logger.log(serialize(args));
  };
  console.dir = function dir(arg, options) {
    logger.log((0, node_util_1.inspect)(arg, options));
  };
  console.log = function log(...args) {
    logger.log(serialize(args));
  };
  console.error = function error(...args) {
    logger.error(serialize(args));
  };
  console.trace = function trace(...args) {
    const stack = new Error().stack.replace(/(.+\n){2}/, "");
    let message = "Trace";
    if (args.length !== 0) {
      message += `: ${serialize(args)}`;
    }
    logger.log(`${message}
${stack}`);
  };
  console.warn = function warn(...args) {
    logger.warn(serialize(args));
  };
}


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver/node.js":
/*!**********************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver/node.js ***!
  \**********************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

module.exports = __webpack_require__(/*! ./lib/node/main */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");


/***/ }),

/***/ "../pyright-internal/node_modules/vscode-uri/lib/umd/index.js":
/*!********************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-uri/lib/umd/index.js ***!
  \********************************************************************/
/***/ (function(module) {

!function(t, e) {
  if (true)
    module.exports = e();
  else { var n, r; }
}(this, () => (() => {
  "use strict";
  var t = { 470: (t2) => {
    function e2(t3) {
      if ("string" != typeof t3)
        throw new TypeError("Path must be a string. Received " + JSON.stringify(t3));
    }
    function r2(t3, e3) {
      for (var r3, n3 = "", i = 0, o = -1, s = 0, a = 0; a <= t3.length; ++a) {
        if (a < t3.length)
          r3 = t3.charCodeAt(a);
        else {
          if (47 === r3)
            break;
          r3 = 47;
        }
        if (47 === r3) {
          if (o === a - 1 || 1 === s)
            ;
          else if (o !== a - 1 && 2 === s) {
            if (n3.length < 2 || 2 !== i || 46 !== n3.charCodeAt(n3.length - 1) || 46 !== n3.charCodeAt(n3.length - 2)) {
              if (n3.length > 2) {
                var h = n3.lastIndexOf("/");
                if (h !== n3.length - 1) {
                  -1 === h ? (n3 = "", i = 0) : i = (n3 = n3.slice(0, h)).length - 1 - n3.lastIndexOf("/"), o = a, s = 0;
                  continue;
                }
              } else if (2 === n3.length || 1 === n3.length) {
                n3 = "", i = 0, o = a, s = 0;
                continue;
              }
            }
            e3 && (n3.length > 0 ? n3 += "/.." : n3 = "..", i = 2);
          } else
            n3.length > 0 ? n3 += "/" + t3.slice(o + 1, a) : n3 = t3.slice(o + 1, a), i = a - o - 1;
          o = a, s = 0;
        } else
          46 === r3 && -1 !== s ? ++s : s = -1;
      }
      return n3;
    }
    var n2 = { resolve: function() {
      for (var t3, n3 = "", i = false, o = arguments.length - 1; o >= -1 && !i; o--) {
        var s;
        o >= 0 ? s = arguments[o] : (void 0 === t3 && (t3 = process.cwd()), s = t3), e2(s), 0 !== s.length && (n3 = s + "/" + n3, i = 47 === s.charCodeAt(0));
      }
      return n3 = r2(n3, !i), i ? n3.length > 0 ? "/" + n3 : "/" : n3.length > 0 ? n3 : ".";
    }, normalize: function(t3) {
      if (e2(t3), 0 === t3.length)
        return ".";
      var n3 = 47 === t3.charCodeAt(0), i = 47 === t3.charCodeAt(t3.length - 1);
      return 0 !== (t3 = r2(t3, !n3)).length || n3 || (t3 = "."), t3.length > 0 && i && (t3 += "/"), n3 ? "/" + t3 : t3;
    }, isAbsolute: function(t3) {
      return e2(t3), t3.length > 0 && 47 === t3.charCodeAt(0);
    }, join: function() {
      if (0 === arguments.length)
        return ".";
      for (var t3, r3 = 0; r3 < arguments.length; ++r3) {
        var i = arguments[r3];
        e2(i), i.length > 0 && (void 0 === t3 ? t3 = i : t3 += "/" + i);
      }
      return void 0 === t3 ? "." : n2.normalize(t3);
    }, relative: function(t3, r3) {
      if (e2(t3), e2(r3), t3 === r3)
        return "";
      if ((t3 = n2.resolve(t3)) === (r3 = n2.resolve(r3)))
        return "";
      for (var i = 1; i < t3.length && 47 === t3.charCodeAt(i); ++i)
        ;
      for (var o = t3.length, s = o - i, a = 1; a < r3.length && 47 === r3.charCodeAt(a); ++a)
        ;
      for (var h = r3.length - a, c = s < h ? s : h, f = -1, u = 0; u <= c; ++u) {
        if (u === c) {
          if (h > c) {
            if (47 === r3.charCodeAt(a + u))
              return r3.slice(a + u + 1);
            if (0 === u)
              return r3.slice(a + u);
          } else
            s > c && (47 === t3.charCodeAt(i + u) ? f = u : 0 === u && (f = 0));
          break;
        }
        var l = t3.charCodeAt(i + u);
        if (l !== r3.charCodeAt(a + u))
          break;
        47 === l && (f = u);
      }
      var d = "";
      for (u = i + f + 1; u <= o; ++u)
        u !== o && 47 !== t3.charCodeAt(u) || (0 === d.length ? d += ".." : d += "/..");
      return d.length > 0 ? d + r3.slice(a + f) : (a += f, 47 === r3.charCodeAt(a) && ++a, r3.slice(a));
    }, _makeLong: function(t3) {
      return t3;
    }, dirname: function(t3) {
      if (e2(t3), 0 === t3.length)
        return ".";
      for (var r3 = t3.charCodeAt(0), n3 = 47 === r3, i = -1, o = true, s = t3.length - 1; s >= 1; --s)
        if (47 === (r3 = t3.charCodeAt(s))) {
          if (!o) {
            i = s;
            break;
          }
        } else
          o = false;
      return -1 === i ? n3 ? "/" : "." : n3 && 1 === i ? "//" : t3.slice(0, i);
    }, basename: function(t3, r3) {
      if (void 0 !== r3 && "string" != typeof r3)
        throw new TypeError('"ext" argument must be a string');
      e2(t3);
      var n3, i = 0, o = -1, s = true;
      if (void 0 !== r3 && r3.length > 0 && r3.length <= t3.length) {
        if (r3.length === t3.length && r3 === t3)
          return "";
        var a = r3.length - 1, h = -1;
        for (n3 = t3.length - 1; n3 >= 0; --n3) {
          var c = t3.charCodeAt(n3);
          if (47 === c) {
            if (!s) {
              i = n3 + 1;
              break;
            }
          } else
            -1 === h && (s = false, h = n3 + 1), a >= 0 && (c === r3.charCodeAt(a) ? -1 == --a && (o = n3) : (a = -1, o = h));
        }
        return i === o ? o = h : -1 === o && (o = t3.length), t3.slice(i, o);
      }
      for (n3 = t3.length - 1; n3 >= 0; --n3)
        if (47 === t3.charCodeAt(n3)) {
          if (!s) {
            i = n3 + 1;
            break;
          }
        } else
          -1 === o && (s = false, o = n3 + 1);
      return -1 === o ? "" : t3.slice(i, o);
    }, extname: function(t3) {
      e2(t3);
      for (var r3 = -1, n3 = 0, i = -1, o = true, s = 0, a = t3.length - 1; a >= 0; --a) {
        var h = t3.charCodeAt(a);
        if (47 !== h)
          -1 === i && (o = false, i = a + 1), 46 === h ? -1 === r3 ? r3 = a : 1 !== s && (s = 1) : -1 !== r3 && (s = -1);
        else if (!o) {
          n3 = a + 1;
          break;
        }
      }
      return -1 === r3 || -1 === i || 0 === s || 1 === s && r3 === i - 1 && r3 === n3 + 1 ? "" : t3.slice(r3, i);
    }, format: function(t3) {
      if (null === t3 || "object" != typeof t3)
        throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof t3);
      return function(t4, e3) {
        var r3 = e3.dir || e3.root, n3 = e3.base || (e3.name || "") + (e3.ext || "");
        return r3 ? r3 === e3.root ? r3 + n3 : r3 + "/" + n3 : n3;
      }(0, t3);
    }, parse: function(t3) {
      e2(t3);
      var r3 = { root: "", dir: "", base: "", ext: "", name: "" };
      if (0 === t3.length)
        return r3;
      var n3, i = t3.charCodeAt(0), o = 47 === i;
      o ? (r3.root = "/", n3 = 1) : n3 = 0;
      for (var s = -1, a = 0, h = -1, c = true, f = t3.length - 1, u = 0; f >= n3; --f)
        if (47 !== (i = t3.charCodeAt(f)))
          -1 === h && (c = false, h = f + 1), 46 === i ? -1 === s ? s = f : 1 !== u && (u = 1) : -1 !== s && (u = -1);
        else if (!c) {
          a = f + 1;
          break;
        }
      return -1 === s || -1 === h || 0 === u || 1 === u && s === h - 1 && s === a + 1 ? -1 !== h && (r3.base = r3.name = 0 === a && o ? t3.slice(1, h) : t3.slice(a, h)) : (0 === a && o ? (r3.name = t3.slice(1, s), r3.base = t3.slice(1, h)) : (r3.name = t3.slice(a, s), r3.base = t3.slice(a, h)), r3.ext = t3.slice(s, h)), a > 0 ? r3.dir = t3.slice(0, a - 1) : o && (r3.dir = "/"), r3;
    }, sep: "/", delimiter: ":", win32: null, posix: null };
    n2.posix = n2, t2.exports = n2;
  }, 674: (t2, e2) => {
    if (Object.defineProperty(e2, "__esModule", { value: true }), e2.isWindows = void 0, "object" == typeof process)
      e2.isWindows = "win32" === process.platform;
    else if ("object" == typeof navigator) {
      let t3 = navigator.userAgent;
      e2.isWindows = t3.indexOf("Windows") >= 0;
    }
  }, 796: (t2, e2, r2) => {
    Object.defineProperty(e2, "__esModule", { value: true }), e2.uriToFsPath = e2.URI = void 0;
    const n2 = r2(674), i = /^\w[\w\d+.-]*$/, o = /^\//, s = /^\/\//;
    function a(t3, e3) {
      if (!t3.scheme && e3)
        throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t3.authority}", path: "${t3.path}", query: "${t3.query}", fragment: "${t3.fragment}"}`);
      if (t3.scheme && !i.test(t3.scheme))
        throw new Error("[UriError]: Scheme contains illegal characters.");
      if (t3.path) {
        if (t3.authority) {
          if (!o.test(t3.path))
            throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
        } else if (s.test(t3.path))
          throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
      }
    }
    const h = "", c = "/", f = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
    class u {
      static isUri(t3) {
        return t3 instanceof u || !!t3 && "string" == typeof t3.authority && "string" == typeof t3.fragment && "string" == typeof t3.path && "string" == typeof t3.query && "string" == typeof t3.scheme && "string" == typeof t3.fsPath && "function" == typeof t3.with && "function" == typeof t3.toString;
      }
      scheme;
      authority;
      path;
      query;
      fragment;
      constructor(t3, e3, r3, n3, i2, o2 = false) {
        "object" == typeof t3 ? (this.scheme = t3.scheme || h, this.authority = t3.authority || h, this.path = t3.path || h, this.query = t3.query || h, this.fragment = t3.fragment || h) : (this.scheme = /* @__PURE__ */ function(t4, e4) {
          return t4 || e4 ? t4 : "file";
        }(t3, o2), this.authority = e3 || h, this.path = function(t4, e4) {
          switch (t4) {
            case "https":
            case "http":
            case "file":
              e4 ? e4[0] !== c && (e4 = c + e4) : e4 = c;
          }
          return e4;
        }(this.scheme, r3 || h), this.query = n3 || h, this.fragment = i2 || h, a(this, o2));
      }
      get fsPath() {
        return v(this, false);
      }
      with(t3) {
        if (!t3)
          return this;
        let { scheme: e3, authority: r3, path: n3, query: i2, fragment: o2 } = t3;
        return void 0 === e3 ? e3 = this.scheme : null === e3 && (e3 = h), void 0 === r3 ? r3 = this.authority : null === r3 && (r3 = h), void 0 === n3 ? n3 = this.path : null === n3 && (n3 = h), void 0 === i2 ? i2 = this.query : null === i2 && (i2 = h), void 0 === o2 ? o2 = this.fragment : null === o2 && (o2 = h), e3 === this.scheme && r3 === this.authority && n3 === this.path && i2 === this.query && o2 === this.fragment ? this : new d(e3, r3, n3, i2, o2);
      }
      static parse(t3, e3 = false) {
        const r3 = f.exec(t3);
        return r3 ? new d(r3[2] || h, w(r3[4] || h), w(r3[5] || h), w(r3[7] || h), w(r3[9] || h), e3) : new d(h, h, h, h, h);
      }
      static file(t3) {
        let e3 = h;
        if (n2.isWindows && (t3 = t3.replace(/\\/g, c)), t3[0] === c && t3[1] === c) {
          const r3 = t3.indexOf(c, 2);
          -1 === r3 ? (e3 = t3.substring(2), t3 = c) : (e3 = t3.substring(2, r3), t3 = t3.substring(r3) || c);
        }
        return new d("file", e3, t3, h, h);
      }
      static from(t3) {
        const e3 = new d(t3.scheme, t3.authority, t3.path, t3.query, t3.fragment);
        return a(e3, true), e3;
      }
      toString(t3 = false) {
        return y(this, t3);
      }
      toJSON() {
        return this;
      }
      static revive(t3) {
        if (t3) {
          if (t3 instanceof u)
            return t3;
          {
            const e3 = new d(t3);
            return e3._formatted = t3.external, e3._fsPath = t3._sep === l ? t3.fsPath : null, e3;
          }
        }
        return t3;
      }
    }
    e2.URI = u;
    const l = n2.isWindows ? 1 : void 0;
    class d extends u {
      _formatted = null;
      _fsPath = null;
      get fsPath() {
        return this._fsPath || (this._fsPath = v(this, false)), this._fsPath;
      }
      toString(t3 = false) {
        return t3 ? y(this, true) : (this._formatted || (this._formatted = y(this, false)), this._formatted);
      }
      toJSON() {
        const t3 = { $mid: 1 };
        return this._fsPath && (t3.fsPath = this._fsPath, t3._sep = l), this._formatted && (t3.external = this._formatted), this.path && (t3.path = this.path), this.scheme && (t3.scheme = this.scheme), this.authority && (t3.authority = this.authority), this.query && (t3.query = this.query), this.fragment && (t3.fragment = this.fragment), t3;
      }
    }
    const p = { 58: "%3A", 47: "%2F", 63: "%3F", 35: "%23", 91: "%5B", 93: "%5D", 64: "%40", 33: "%21", 36: "%24", 38: "%26", 39: "%27", 40: "%28", 41: "%29", 42: "%2A", 43: "%2B", 44: "%2C", 59: "%3B", 61: "%3D", 32: "%20" };
    function g(t3, e3, r3) {
      let n3, i2 = -1;
      for (let o2 = 0; o2 < t3.length; o2++) {
        const s2 = t3.charCodeAt(o2);
        if (s2 >= 97 && s2 <= 122 || s2 >= 65 && s2 <= 90 || s2 >= 48 && s2 <= 57 || 45 === s2 || 46 === s2 || 95 === s2 || 126 === s2 || e3 && 47 === s2 || r3 && 91 === s2 || r3 && 93 === s2 || r3 && 58 === s2)
          -1 !== i2 && (n3 += encodeURIComponent(t3.substring(i2, o2)), i2 = -1), void 0 !== n3 && (n3 += t3.charAt(o2));
        else {
          void 0 === n3 && (n3 = t3.substr(0, o2));
          const e4 = p[s2];
          void 0 !== e4 ? (-1 !== i2 && (n3 += encodeURIComponent(t3.substring(i2, o2)), i2 = -1), n3 += e4) : -1 === i2 && (i2 = o2);
        }
      }
      return -1 !== i2 && (n3 += encodeURIComponent(t3.substring(i2))), void 0 !== n3 ? n3 : t3;
    }
    function m(t3) {
      let e3;
      for (let r3 = 0; r3 < t3.length; r3++) {
        const n3 = t3.charCodeAt(r3);
        35 === n3 || 63 === n3 ? (void 0 === e3 && (e3 = t3.substr(0, r3)), e3 += p[n3]) : void 0 !== e3 && (e3 += t3[r3]);
      }
      return void 0 !== e3 ? e3 : t3;
    }
    function v(t3, e3) {
      let r3;
      return r3 = t3.authority && t3.path.length > 1 && "file" === t3.scheme ? `//${t3.authority}${t3.path}` : 47 === t3.path.charCodeAt(0) && (t3.path.charCodeAt(1) >= 65 && t3.path.charCodeAt(1) <= 90 || t3.path.charCodeAt(1) >= 97 && t3.path.charCodeAt(1) <= 122) && 58 === t3.path.charCodeAt(2) ? e3 ? t3.path.substr(1) : t3.path[1].toLowerCase() + t3.path.substr(2) : t3.path, n2.isWindows && (r3 = r3.replace(/\//g, "\\")), r3;
    }
    function y(t3, e3) {
      const r3 = e3 ? m : g;
      let n3 = "", { scheme: i2, authority: o2, path: s2, query: a2, fragment: h2 } = t3;
      if (i2 && (n3 += i2, n3 += ":"), (o2 || "file" === i2) && (n3 += c, n3 += c), o2) {
        let t4 = o2.indexOf("@");
        if (-1 !== t4) {
          const e4 = o2.substr(0, t4);
          o2 = o2.substr(t4 + 1), t4 = e4.lastIndexOf(":"), -1 === t4 ? n3 += r3(e4, false, false) : (n3 += r3(e4.substr(0, t4), false, false), n3 += ":", n3 += r3(e4.substr(t4 + 1), false, true)), n3 += "@";
        }
        o2 = o2.toLowerCase(), t4 = o2.lastIndexOf(":"), -1 === t4 ? n3 += r3(o2, false, true) : (n3 += r3(o2.substr(0, t4), false, true), n3 += o2.substr(t4));
      }
      if (s2) {
        if (s2.length >= 3 && 47 === s2.charCodeAt(0) && 58 === s2.charCodeAt(2)) {
          const t4 = s2.charCodeAt(1);
          t4 >= 65 && t4 <= 90 && (s2 = `/${String.fromCharCode(t4 + 32)}:${s2.substr(3)}`);
        } else if (s2.length >= 2 && 58 === s2.charCodeAt(1)) {
          const t4 = s2.charCodeAt(0);
          t4 >= 65 && t4 <= 90 && (s2 = `${String.fromCharCode(t4 + 32)}:${s2.substr(2)}`);
        }
        n3 += r3(s2, true, false);
      }
      return a2 && (n3 += "?", n3 += r3(a2, false, false)), h2 && (n3 += "#", n3 += e3 ? h2 : g(h2, false, false)), n3;
    }
    function b(t3) {
      try {
        return decodeURIComponent(t3);
      } catch {
        return t3.length > 3 ? t3.substr(0, 3) + b(t3.substr(3)) : t3;
      }
    }
    e2.uriToFsPath = v;
    const C = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
    function w(t3) {
      return t3.match(C) ? t3.replace(C, (t4) => b(t4)) : t3;
    }
  }, 679: function(t2, e2, r2) {
    var n2 = this && this.__createBinding || (Object.create ? function(t3, e3, r3, n3) {
      void 0 === n3 && (n3 = r3);
      var i2 = Object.getOwnPropertyDescriptor(e3, r3);
      i2 && !("get" in i2 ? !e3.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() {
        return e3[r3];
      } }), Object.defineProperty(t3, n3, i2);
    } : function(t3, e3, r3, n3) {
      void 0 === n3 && (n3 = r3), t3[n3] = e3[r3];
    }), i = this && this.__setModuleDefault || (Object.create ? function(t3, e3) {
      Object.defineProperty(t3, "default", { enumerable: true, value: e3 });
    } : function(t3, e3) {
      t3.default = e3;
    }), o = this && this.__importStar || function(t3) {
      if (t3 && t3.__esModule)
        return t3;
      var e3 = {};
      if (null != t3)
        for (var r3 in t3)
          "default" !== r3 && Object.prototype.hasOwnProperty.call(t3, r3) && n2(e3, t3, r3);
      return i(e3, t3), e3;
    };
    Object.defineProperty(e2, "__esModule", { value: true }), e2.Utils = void 0;
    const s = o(r2(470)), a = s.posix || s, h = "/";
    var c;
    !function(t3) {
      t3.joinPath = function(t4, ...e3) {
        return t4.with({ path: a.join(t4.path, ...e3) });
      }, t3.resolvePath = function(t4, ...e3) {
        let r3 = t4.path, n3 = false;
        r3[0] !== h && (r3 = h + r3, n3 = true);
        let i2 = a.resolve(r3, ...e3);
        return n3 && i2[0] === h && !t4.authority && (i2 = i2.substring(1)), t4.with({ path: i2 });
      }, t3.dirname = function(t4) {
        if (0 === t4.path.length || t4.path === h)
          return t4;
        let e3 = a.dirname(t4.path);
        return 1 === e3.length && 46 === e3.charCodeAt(0) && (e3 = ""), t4.with({ path: e3 });
      }, t3.basename = function(t4) {
        return a.basename(t4.path);
      }, t3.extname = function(t4) {
        return a.extname(t4.path);
      };
    }(c || (e2.Utils = c = {}));
  } }, e = {};
  function r(n2) {
    var i = e[n2];
    if (void 0 !== i)
      return i.exports;
    var o = e[n2] = { exports: {} };
    return t[n2].call(o.exports, o, o.exports, r), o.exports;
  }
  var n = {};
  return (() => {
    var t2 = n;
    Object.defineProperty(t2, "__esModule", { value: true }), t2.Utils = t2.URI = void 0;
    const e2 = r(796);
    Object.defineProperty(t2, "URI", { enumerable: true, get: function() {
      return e2.URI;
    } });
    const i = r(679);
    Object.defineProperty(t2, "Utils", { enumerable: true, get: function() {
      return i.Utils;
    } });
  })(), n;
})());


/***/ }),

/***/ "../pyright-internal/node_modules/wrappy/wrappy.js":
/*!*********************************************************!*\
  !*** ../pyright-internal/node_modules/wrappy/wrappy.js ***!
  \*********************************************************/
/***/ ((module) => {

module.exports = wrappy;
function wrappy(fn, cb) {
  if (fn && cb)
    return wrappy(fn)(cb);
  if (typeof fn !== "function")
    throw new TypeError("need wrapper function");
  Object.keys(fn).forEach(function(k) {
    wrapper[k] = fn[k];
  });
  return wrapper;
  function wrapper() {
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    var ret = fn.apply(this, args);
    var cb2 = args[args.length - 1];
    if (typeof ret === "function" && ret !== cb2) {
      Object.keys(cb2).forEach(function(k) {
        ret[k] = cb2[k];
      });
    }
    return ret;
  }
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/analysis.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/analyzer/analysis.ts ***!
  \****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * analysis.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Various analysis helper types and functions
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.analyzeProgram = exports.nullCallback = void 0;
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const debug = __importStar(__webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts"));
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const nullCallback = () => {
    /* empty */
};
exports.nullCallback = nullCallback;
function analyzeProgram(program, maxTime, configOptions, callback, console, token) {
    let moreToAnalyze = false;
    callback = callback !== null && callback !== void 0 ? callback : exports.nullCallback;
    try {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const duration = new timing_1.Duration();
        moreToAnalyze = program.analyze(maxTime, token);
        const filesLeftToAnalyze = program.getFilesToAnalyzeCount();
        // If we're using command-line mode, the maxTime will be undefined, and we'll
        // want to report all diagnostics rather than just the ones that have changed.
        const reportDiagnosticDeltasOnly = maxTime !== undefined;
        const diagnostics = program.getDiagnostics(configOptions, reportDiagnosticDeltasOnly);
        const diagnosticFileCount = diagnostics.length;
        const elapsedTime = duration.getDurationInSeconds();
        // Report any diagnostics or completion.
        if (diagnosticFileCount > 0 || !moreToAnalyze) {
            callback({
                diagnostics,
                filesInProgram: program.getFileCount(),
                filesRequiringAnalysis: filesLeftToAnalyze,
                checkingOnlyOpenFiles: program.isCheckingOnlyOpenFiles(),
                fatalErrorOccurred: false,
                configParseErrorOccurred: false,
                elapsedTime,
            });
        }
    }
    catch (e) {
        if (cancellationUtils_1.OperationCanceledException.is(e)) {
            return false;
        }
        const message = debug.getErrorString(e);
        console.error('Error performing analysis: ' + message);
        callback({
            diagnostics: [],
            filesInProgram: 0,
            filesRequiringAnalysis: 0,
            checkingOnlyOpenFiles: true,
            fatalErrorOccurred: true,
            configParseErrorOccurred: false,
            elapsedTime: 0,
            error: debug.getSerializableError(e),
        });
    }
    return moreToAnalyze;
}
exports.analyzeProgram = analyzeProgram;


/***/ }),

/***/ "../pyright-internal/src/analyzer/analyzerFileInfo.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/analyzer/analyzerFileInfo.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * analyzerFileInfo.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Information associated with a source file that is used
 * by the binder and checker.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isAnnotationEvaluationPostponed = void 0;
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
function isAnnotationEvaluationPostponed(fileInfo) {
    if (fileInfo.isStubFile) {
        return true;
    }
    if (fileInfo.futureImports.has('annotations')) {
        return true;
    }
    // As of May 2023, the Python steering council has approved PEP 649 for Python 3.13.
    // It was tentatively approved for 3.12, but they decided to defer until the next
    // release to reduce the risk.
    // https://discuss.python.org/t/pep-649-deferred-evaluation-of-annotations-tentatively-accepted/21331
    if (fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_13)) {
        return true;
    }
    return false;
}
exports.isAnnotationEvaluationPostponed = isAnnotationEvaluationPostponed;


/***/ }),

/***/ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/analyzer/analyzerNodeInfo.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * analyzerNodeInfo.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Defines objects that hang off the parse nodes in the parse tree.
 * It contains information collected during the binder phase that
 * can be used for later analysis steps or for language services
 * (e.g. hover information).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCodeUnreachable = exports.setTypeParameterSymbol = exports.getTypeParameterSymbol = exports.setDunderAllInfo = exports.getDunderAllInfo = exports.setCodeFlowComplexity = exports.getCodeFlowComplexity = exports.setCodeFlowExpressions = exports.getCodeFlowExpressions = exports.setFileInfo = exports.getFileInfo = exports.setAfterFlowNode = exports.getAfterFlowNode = exports.setFlowNode = exports.getFlowNode = exports.setDeclaration = exports.getDeclaration = exports.setScope = exports.getScope = exports.setImportInfo = exports.getImportInfo = exports.cleanNodeAnalysisInfo = void 0;
const codeFlowTypes_1 = __webpack_require__(/*! ./codeFlowTypes */ "../pyright-internal/src/analyzer/codeFlowTypes.ts");
// Cleans out all fields that are added by the analyzer phases
// (after the post-parse walker).
function cleanNodeAnalysisInfo(node) {
    const analyzerNode = node;
    delete analyzerNode.scope;
    delete analyzerNode.declaration;
    delete analyzerNode.flowNode;
    delete analyzerNode.afterFlowNode;
    delete analyzerNode.fileInfo;
    delete analyzerNode.codeFlowExpressions;
    delete analyzerNode.codeFlowComplexity;
    delete analyzerNode.dunderAllInfo;
    delete analyzerNode.typeParameterSymbol;
}
exports.cleanNodeAnalysisInfo = cleanNodeAnalysisInfo;
function getImportInfo(node) {
    const analyzerNode = node;
    return analyzerNode.importInfo;
}
exports.getImportInfo = getImportInfo;
function setImportInfo(node, importInfo) {
    const analyzerNode = node;
    analyzerNode.importInfo = importInfo;
}
exports.setImportInfo = setImportInfo;
function getScope(node) {
    const analyzerNode = node;
    return analyzerNode.scope;
}
exports.getScope = getScope;
function setScope(node, scope) {
    const analyzerNode = node;
    analyzerNode.scope = scope;
}
exports.setScope = setScope;
function getDeclaration(node) {
    const analyzerNode = node;
    return analyzerNode.declaration;
}
exports.getDeclaration = getDeclaration;
function setDeclaration(node, decl) {
    const analyzerNode = node;
    analyzerNode.declaration = decl;
}
exports.setDeclaration = setDeclaration;
function getFlowNode(node) {
    const analyzerNode = node;
    return analyzerNode.flowNode;
}
exports.getFlowNode = getFlowNode;
function setFlowNode(node, flowNode) {
    const analyzerNode = node;
    analyzerNode.flowNode = flowNode;
}
exports.setFlowNode = setFlowNode;
function getAfterFlowNode(node) {
    const analyzerNode = node;
    return analyzerNode.afterFlowNode;
}
exports.getAfterFlowNode = getAfterFlowNode;
function setAfterFlowNode(node, flowNode) {
    const analyzerNode = node;
    analyzerNode.afterFlowNode = flowNode;
}
exports.setAfterFlowNode = setAfterFlowNode;
function getFileInfo(node) {
    while (node.nodeType !== 36 /* ParseNodeType.Module */) {
        node = node.parent;
    }
    const analyzerNode = node;
    return analyzerNode.fileInfo;
}
exports.getFileInfo = getFileInfo;
function setFileInfo(node, fileInfo) {
    const analyzerNode = node;
    analyzerNode.fileInfo = fileInfo;
}
exports.setFileInfo = setFileInfo;
function getCodeFlowExpressions(node) {
    const analyzerNode = node;
    return analyzerNode.codeFlowExpressions;
}
exports.getCodeFlowExpressions = getCodeFlowExpressions;
function setCodeFlowExpressions(node, expressions) {
    const analyzerNode = node;
    analyzerNode.codeFlowExpressions = expressions;
}
exports.setCodeFlowExpressions = setCodeFlowExpressions;
function getCodeFlowComplexity(node) {
    var _a;
    const analyzerNode = node;
    return (_a = analyzerNode.codeFlowComplexity) !== null && _a !== void 0 ? _a : 0;
}
exports.getCodeFlowComplexity = getCodeFlowComplexity;
function setCodeFlowComplexity(node, complexity) {
    const analyzerNode = node;
    analyzerNode.codeFlowComplexity = complexity;
}
exports.setCodeFlowComplexity = setCodeFlowComplexity;
function getDunderAllInfo(node) {
    const analyzerNode = node;
    return analyzerNode.dunderAllInfo;
}
exports.getDunderAllInfo = getDunderAllInfo;
function setDunderAllInfo(node, names) {
    const analyzerNode = node;
    analyzerNode.dunderAllInfo = names;
}
exports.setDunderAllInfo = setDunderAllInfo;
function getTypeParameterSymbol(node) {
    const analyzerNode = node;
    return analyzerNode.typeParameterSymbol;
}
exports.getTypeParameterSymbol = getTypeParameterSymbol;
function setTypeParameterSymbol(node, symbol) {
    const analyzerNode = node;
    analyzerNode.typeParameterSymbol = symbol;
}
exports.setTypeParameterSymbol = setTypeParameterSymbol;
function isCodeUnreachable(node) {
    let curNode = node;
    // Walk up the parse tree until we find a node with
    // an associated flow node.
    while (curNode) {
        const flowNode = getFlowNode(curNode);
        if (flowNode) {
            return !!(flowNode.flags & codeFlowTypes_1.FlowFlags.Unreachable);
        }
        curNode = curNode.parent;
    }
    return false;
}
exports.isCodeUnreachable = isCodeUnreachable;


/***/ }),

/***/ "../pyright-internal/src/analyzer/backgroundAnalysisProgram.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/analyzer/backgroundAnalysisProgram.ts ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * BackgroundAnalysisProgram.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Applies operations to both the foreground program and a background
 * analysis running in a worker process.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BackgroundAnalysisProgram = exports.InvalidatedReason = void 0;
__webpack_require__(/*! ../common/serviceProviderExtensions */ "../pyright-internal/src/common/serviceProviderExtensions.ts");
const analysis_1 = __webpack_require__(/*! ./analysis */ "../pyright-internal/src/analyzer/analysis.ts");
const program_1 = __webpack_require__(/*! ./program */ "../pyright-internal/src/analyzer/program.ts");
var InvalidatedReason;
(function (InvalidatedReason) {
    InvalidatedReason[InvalidatedReason["Reanalyzed"] = 0] = "Reanalyzed";
    InvalidatedReason[InvalidatedReason["SourceWatcherChanged"] = 1] = "SourceWatcherChanged";
    InvalidatedReason[InvalidatedReason["LibraryWatcherChanged"] = 2] = "LibraryWatcherChanged";
    InvalidatedReason[InvalidatedReason["LibraryWatcherContentOnlyChanged"] = 3] = "LibraryWatcherContentOnlyChanged";
})(InvalidatedReason || (exports.InvalidatedReason = InvalidatedReason = {}));
class BackgroundAnalysisProgram {
    constructor(serviceId, _serviceProvider, _configOptions, _importResolver, _backgroundAnalysis, _maxAnalysisTime, _disableChecker) {
        this.serviceId = serviceId;
        this._serviceProvider = _serviceProvider;
        this._configOptions = _configOptions;
        this._importResolver = _importResolver;
        this._backgroundAnalysis = _backgroundAnalysis;
        this._maxAnalysisTime = _maxAnalysisTime;
        this._disableChecker = _disableChecker;
        this._disposed = false;
        this._program = new program_1.Program(this.importResolver, this.configOptions, this._serviceProvider, undefined, this._disableChecker, serviceId);
    }
    get configOptions() {
        return this._configOptions;
    }
    get importResolver() {
        return this._importResolver;
    }
    get program() {
        return this._program;
    }
    get host() {
        return this._importResolver.host;
    }
    get backgroundAnalysis() {
        return this._backgroundAnalysis;
    }
    hasSourceFile(fileUri) {
        return !!this._program.getSourceFile(fileUri);
    }
    setConfigOptions(configOptions) {
        var _a;
        this._configOptions = configOptions;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setConfigOptions(configOptions);
        this._program.setConfigOptions(configOptions);
    }
    setImportResolver(importResolver) {
        var _a;
        this._importResolver = importResolver;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setImportResolver(importResolver);
        this._program.setImportResolver(importResolver);
        this.configOptions.getExecutionEnvironments().forEach((e) => this._ensurePartialStubPackages(e));
    }
    setTrackedFiles(fileUris) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setTrackedFiles(fileUris);
        const diagnostics = this._program.setTrackedFiles(fileUris);
        this._reportDiagnosticsForRemovedFiles(diagnostics);
    }
    setAllowedThirdPartyImports(importNames) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setAllowedThirdPartyImports(importNames);
        this._program.setAllowedThirdPartyImports(importNames);
    }
    setFileOpened(fileUri, version, contents, options) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setFileOpened(fileUri, version, contents, options);
        this._program.setFileOpened(fileUri, version, contents, options);
    }
    getChainedUri(fileUri) {
        return this._program.getChainedUri(fileUri);
    }
    updateChainedUri(fileUri, chainedUri) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.updateChainedUri(fileUri, chainedUri);
        this._program.updateChainedUri(fileUri, chainedUri);
    }
    updateOpenFileContents(uri, version, contents, options) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setFileOpened(uri, version, contents, options);
        this._program.setFileOpened(uri, version, contents, options);
        this.markFilesDirty([uri], /* evenIfContentsAreSame */ true);
    }
    setFileClosed(fileUri, isTracked) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setFileClosed(fileUri, isTracked);
        const diagnostics = this._program.setFileClosed(fileUri, isTracked);
        this._reportDiagnosticsForRemovedFiles(diagnostics);
    }
    addInterimFile(fileUri) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.addInterimFile(fileUri);
        this._program.addInterimFile(fileUri);
    }
    markAllFilesDirty(evenIfContentsAreSame) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.markAllFilesDirty(evenIfContentsAreSame);
        this._program.markAllFilesDirty(evenIfContentsAreSame);
    }
    markFilesDirty(fileUris, evenIfContentsAreSame) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.markFilesDirty(fileUris, evenIfContentsAreSame);
        this._program.markFilesDirty(fileUris, evenIfContentsAreSame);
    }
    setCompletionCallback(callback) {
        var _a;
        this._onAnalysisCompletion = callback;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.setCompletionCallback(callback);
    }
    startAnalysis(token) {
        if (this._backgroundAnalysis) {
            this._backgroundAnalysis.startAnalysis(this, token);
            return false;
        }
        return (0, analysis_1.analyzeProgram)(this._program, this._maxAnalysisTime, this._configOptions, this._onAnalysisCompletion, this._serviceProvider.console(), token);
    }
    async analyzeFile(fileUri, token) {
        if (this._backgroundAnalysis) {
            return this._backgroundAnalysis.analyzeFile(fileUri, token);
        }
        return this._program.analyzeFile(fileUri, token);
    }
    libraryUpdated() {
        return false;
    }
    async getDiagnosticsForRange(fileUri, range, token) {
        if (this._backgroundAnalysis) {
            return this._backgroundAnalysis.getDiagnosticsForRange(fileUri, range, token);
        }
        return this._program.getDiagnosticsForRange(fileUri, range);
    }
    async writeTypeStub(targetImportUri, targetIsSingleFile, stubUri, token) {
        if (this._backgroundAnalysis) {
            return this._backgroundAnalysis.writeTypeStub(targetImportUri, targetIsSingleFile, stubUri, token);
        }
        (0, analysis_1.analyzeProgram)(this._program, 
        /* maxTime */ undefined, this._configOptions, this._onAnalysisCompletion, this._serviceProvider.console(), token);
        return this._program.writeTypeStub(targetImportUri, targetIsSingleFile, stubUri, token);
    }
    invalidateAndForceReanalysis(reason) {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.invalidateAndForceReanalysis(reason);
        // Make sure the import resolver doesn't have invalid
        // cached entries.
        this._importResolver.invalidateCache();
        // Mark all files with one or more errors dirty.
        this._program.markAllFilesDirty(/* evenIfContentsAreSame */ true);
    }
    restart() {
        var _a;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.restart();
    }
    dispose() {
        var _a;
        if (this._disposed) {
            return;
        }
        this._disposed = true;
        this._program.dispose();
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.shutdown();
    }
    enterEditMode() {
        // Turn off analysis while in edit mode.
        this._preEditAnalysis = this._backgroundAnalysis;
        this._backgroundAnalysis = undefined;
        // Forward this request to the program.
        this._program.enterEditMode();
    }
    exitEditMode() {
        this._backgroundAnalysis = this._preEditAnalysis;
        this._preEditAnalysis = undefined;
        return this._program.exitEditMode();
    }
    _ensurePartialStubPackages(execEnv) {
        var _a, _b;
        (_a = this._backgroundAnalysis) === null || _a === void 0 ? void 0 : _a.ensurePartialStubPackages((_b = execEnv.root) === null || _b === void 0 ? void 0 : _b.toString());
        return this._importResolver.ensurePartialStubPackages(execEnv);
    }
    _reportDiagnosticsForRemovedFiles(fileDiags) {
        if (fileDiags.length === 0) {
            return;
        }
        // If analysis is running in the foreground process, report any
        // diagnostics that resulted from the close operation (used to
        // clear diagnostics that are no longer of interest).
        if (!this._backgroundAnalysis && this._onAnalysisCompletion) {
            this._onAnalysisCompletion({
                diagnostics: fileDiags,
                filesInProgram: this._program.getFileCount(),
                filesRequiringAnalysis: this._program.getFilesToAnalyzeCount(),
                checkingOnlyOpenFiles: this._program.isCheckingOnlyOpenFiles(),
                fatalErrorOccurred: false,
                configParseErrorOccurred: false,
                elapsedTime: 0,
            });
        }
    }
}
exports.BackgroundAnalysisProgram = BackgroundAnalysisProgram;


/***/ }),

/***/ "../pyright-internal/src/analyzer/binder.ts":
/*!**************************************************!*\
  !*** ../pyright-internal/src/analyzer/binder.ts ***!
  \**************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * binder.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A parse tree walker that performs basic name binding (creation of
 * scopes and associated symbol tables).
 * The binder walks the parse tree by scopes starting at the module
 * level. When a new scope is detected, it is pushed onto a list and
 * walked separately at a later time. (The exception is a class scope,
 * which is immediately walked.) Walking the tree in this manner
 * simulates the order in which execution normally occurs in a Python
 * file. The binder attempts to statically detect runtime errors that
 * would be reported by the python interpreter when executing the code.
 * This binder doesn't perform any static type checking.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DummyScopeGenerator = exports.ReturnFinder = exports.YieldFinder = exports.Binder = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const codeFlowTypes_1 = __webpack_require__(/*! ./codeFlowTypes */ "../pyright-internal/src/analyzer/codeFlowTypes.ts");
const declaration_1 = __webpack_require__(/*! ./declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const docStringUtils_1 = __webpack_require__(/*! ./docStringUtils */ "../pyright-internal/src/analyzer/docStringUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const scope_1 = __webpack_require__(/*! ./scope */ "../pyright-internal/src/analyzer/scope.ts");
const scopeUtils_1 = __webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const StaticExpressions = __importStar(__webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts"));
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
// For each flow node within an execution context, we'll add a small
// amount to the complexity factor. Without this, the complexity
// calculation fails to take into account large numbers of non-cyclical
// flow nodes. This number is somewhat arbitrary and is tuned empirically.
const flowNodeComplexityContribution = 0.05;
class Binder extends parseTreeWalker_1.ParseTreeWalker {
    constructor(fileInfo, _moduleSymbolOnly = false) {
        super();
        this._moduleSymbolOnly = _moduleSymbolOnly;
        // A queue of deferred analysis operations.
        this._deferredBindingTasks = [];
        // Tracks the type parameters that are currently active within the
        // scope and any outer scopes.
        this._activeTypeParams = new Map();
        // Flow nodes used within try blocks.
        this._currentExceptTargets = [];
        // Flow nodes used within try/finally flows.
        this._finallyTargets = [];
        // Aliases of "typing" and "typing_extensions".
        this._typingImportAliases = [];
        // Aliases of "sys".
        this._sysImportAliases = [];
        // Aliases of "dataclasses".
        this._dataclassesImportAliases = [];
        // Map of imports of specific symbols imported from "typing" and "typing_extensions"
        // and the names they alias to.
        this._typingSymbolAliases = new Map();
        // Map of imports of specific symbols imported from "dataclasses"
        // and the names they alias to.
        this._dataclassesSymbolAliases = new Map();
        // List of string nodes associated with the "__all__" symbol.
        this._dunderAllStringNodes = [];
        // One or more statements are manipulating __all__ in a manner that a
        // static analyzer doesn't understand.
        this._usesUnsupportedDunderAllForm = false;
        // Are we currently binding code located within an except block?
        this._isInExceptSuite = false;
        // Are we currently walking the type arguments to an Annotated type annotation?
        this._isInAnnotatedAnnotation = false;
        // Map of symbols at the module level that may be externally
        // hidden depending on whether they are listed in the __all__ list.
        this._potentialHiddenSymbols = new Map();
        // Map of symbols at the module level that may be private depending
        // on whether they are listed in the __all__ list.
        this._potentialPrivateSymbols = new Map();
        // Estimates the overall complexity of the code flow graph for
        // the current function.
        this._codeFlowComplexity = 0;
        this._fileInfo = fileInfo;
    }
    bindModule(node) {
        var _a;
        // We'll assume that if there is no builtins scope provided, we must be
        // binding the builtins module itself.
        const isBuiltInModule = this._fileInfo.builtinsScope === undefined;
        this._createNewScope(isBuiltInModule ? 4 /* ScopeType.Builtin */ : 3 /* ScopeType.Module */, this._fileInfo.builtinsScope, () => {
            AnalyzerNodeInfo.setScope(node, this._currentScope);
            AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
            // Bind implicit names.
            // List taken from https://docs.python.org/3/reference/import.html#__name__
            this._addImplicitSymbolToCurrentScope('__name__', node, 'str');
            this._addImplicitSymbolToCurrentScope('__loader__', node, 'Any');
            this._addImplicitSymbolToCurrentScope('__package__', node, 'str | None');
            this._addImplicitSymbolToCurrentScope('__spec__', node, 'Any');
            this._addImplicitSymbolToCurrentScope('__path__', node, 'Iterable[str]');
            this._addImplicitSymbolToCurrentScope('__file__', node, 'str');
            this._addImplicitSymbolToCurrentScope('__cached__', node, 'str');
            this._addImplicitSymbolToCurrentScope('__dict__', node, 'Dict[str, Any]');
            this._addImplicitSymbolToCurrentScope('__annotations__', node, 'Dict[str, Any]');
            this._addImplicitSymbolToCurrentScope('__builtins__', node, 'Any');
            // If there is a static docstring provided in the module, assume
            // that the type of `__doc__` is `str` rather than `str | None`. This
            // doesn't apply to stub files.
            const moduleDocString = ParseTreeUtils.getDocString(node.statements);
            this._addImplicitSymbolToCurrentScope('__doc__', node, !this._fileInfo.isStubFile && moduleDocString ? 'str' : 'str | None');
            // Create a start node for the module.
            this._currentFlowNode = this._createStartFlowNode();
            this._walkStatementsAndReportUnreachable(node.statements);
            // Associate the code flow node at the end of the module with the module.
            AnalyzerNodeInfo.setAfterFlowNode(node, this._currentFlowNode);
            AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions);
            AnalyzerNodeInfo.setCodeFlowComplexity(node, this._codeFlowComplexity);
        });
        // Perform all analysis that was deferred during the first pass.
        this._bindDeferred();
        // Use the __all__ list to determine whether any potential private
        // symbols should be made externally hidden or private.
        this._potentialHiddenSymbols.forEach((symbol, name) => {
            var _a;
            if (!((_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.some((sym) => sym === name))) {
                if (this._fileInfo.isStubFile) {
                    symbol.setIsExternallyHidden();
                }
                else if (this._fileInfo.isInPyTypedPackage) {
                    symbol.setPrivatePyTypedImport();
                }
                else if (!this._fileInfo.isThirdParty) {
                    symbol.setPrivateLocalImport();
                }
            }
        });
        this._potentialPrivateSymbols.forEach((symbol, name) => {
            var _a;
            if (!((_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.some((sym) => sym === name))) {
                symbol.setIsPrivateMember();
            }
        });
        if (this._dunderAllNames) {
            AnalyzerNodeInfo.setDunderAllInfo(node, {
                names: this._dunderAllNames,
                stringNodes: this._dunderAllStringNodes,
                usesUnsupportedDunderAllForm: this._usesUnsupportedDunderAllForm,
            });
        }
        else {
            AnalyzerNodeInfo.setDunderAllInfo(node, /* names */ undefined);
        }
        // Set __all__ flags on the module symbols.
        const scope = AnalyzerNodeInfo.getScope(node);
        if (scope && this._dunderAllNames) {
            for (const name of this._dunderAllNames) {
                (_a = scope.symbolTable.get(name)) === null || _a === void 0 ? void 0 : _a.setIsInDunderAll();
            }
        }
    }
    visitModule(node) {
        // Tree walking should start with the children of
        // the node, so we should never get here.
        (0, debug_1.fail)('We should never get here');
        return false;
    }
    visitSuite(node) {
        this._walkStatementsAndReportUnreachable(node.statements);
        return false;
    }
    visitModuleName(node) {
        const importResult = AnalyzerNodeInfo.getImportInfo(node);
        (0, debug_1.assert)(importResult !== undefined);
        if (importResult.isNativeLib) {
            return true;
        }
        if (!importResult.isImportFound) {
            this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportMissingImports, diagnosticRules_1.DiagnosticRule.reportMissingImports, localize_1.LocMessage.importResolveFailure().format({
                importName: importResult.importName,
                venv: this._fileInfo.executionEnvironment.name,
            }), node);
            return true;
        }
        else if (importResult.isImplicitlyRelative) {
            const diagAddendum = new diagnostic_1.DiagnosticAddendum();
            diagAddendum.addMessage(localize_1.LocAddendum.explicitRelativeImportSuggestion().format({ importName: importResult.importName }));
            // TODO: is there a better way to get the package name here? i think this would always match but idk for sure
            const currentModuleRegex = /\.[^.]*$/;
            if (this._fileInfo.moduleName.match(currentModuleRegex)) {
                const fullModuleName = `${this._fileInfo.moduleName.replace(currentModuleRegex, '')}.${importResult.importName}`;
                diagAddendum.addMessage(localize_1.LocAddendum.fullPathImportSuggestion().format({ importName: fullModuleName }));
            }
            this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportImplicitRelativeImport, diagnosticRules_1.DiagnosticRule.reportImplicitRelativeImport, localize_1.LocMessage.implicitRelativeImport().format({
                importName: importResult.importName,
            }) + diagAddendum.getString(), node);
        }
        // A source file was found, but the type stub was missing.
        if (!importResult.isStubFile &&
            importResult.importType === 1 /* ImportType.ThirdParty */ &&
            !importResult.pyTypedInfo) {
            const diagnostic = this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportMissingTypeStubs, diagnosticRules_1.DiagnosticRule.reportMissingTypeStubs, localize_1.LocMessage.stubFileMissing().format({ importName: importResult.importName }), node);
            if (diagnostic) {
                // Add a diagnostic action for resolving this diagnostic.
                const createTypeStubAction = {
                    action: "basedpyright.createtypestub" /* Commands.createTypeStub */,
                    moduleName: importResult.importName,
                };
                diagnostic.addAction(createTypeStubAction);
            }
        }
        return true;
    }
    visitClass(node) {
        this.walkMultiple(node.decorators);
        const classDeclaration = {
            type: 6 /* DeclarationType.Class */,
            node,
            uri: this._fileInfo.fileUri,
            range: (0, positionUtils_1.convertTextRangeToRange)(node.name, this._fileInfo.lines),
            moduleName: this._fileInfo.moduleName,
            isInExceptSuite: this._isInExceptSuite,
        };
        const symbol = this._bindNameToScope(this._currentScope, node.name);
        if (symbol) {
            symbol.addDeclaration(classDeclaration);
        }
        // Stash the declaration in the parse node for later access.
        AnalyzerNodeInfo.setDeclaration(node, classDeclaration);
        if (node.typeParameters) {
            this.walk(node.typeParameters);
        }
        this.walkMultiple(node.arguments);
        this._createNewScope(2 /* ScopeType.Class */, this._getNonClassParentScope(), () => {
            AnalyzerNodeInfo.setScope(node, this._currentScope);
            this._addImplicitSymbolToCurrentScope('__doc__', node, 'str | None');
            this._addImplicitSymbolToCurrentScope('__module__', node, 'str');
            this._addImplicitSymbolToCurrentScope('__qualname__', node, 'str');
            this._dunderSlotsEntries = undefined;
            if (!this._moduleSymbolOnly) {
                // Analyze the suite.
                this.walk(node.suite);
            }
            if (this._dunderSlotsEntries) {
                this._addSlotsToCurrentScope(this._dunderSlotsEntries);
            }
            this._dunderSlotsEntries = undefined;
        });
        this._createAssignmentTargetFlowNodes(node.name, /* walkTargets */ false, /* unbound */ false);
        if (node.typeParameters) {
            this._removeActiveTypeParameters(node.typeParameters);
        }
        return false;
    }
    visitFunction(node) {
        this._createVariableAnnotationFlowNode();
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        const symbol = this._bindNameToScope(this._currentScope, node.name);
        const containingClassNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true);
        const functionDeclaration = {
            type: 5 /* DeclarationType.Function */,
            node,
            isMethod: !!containingClassNode,
            isGenerator: false,
            uri: this._fileInfo.fileUri,
            range: (0, positionUtils_1.convertTextRangeToRange)(node.name, this._fileInfo.lines),
            moduleName: this._fileInfo.moduleName,
            isInExceptSuite: this._isInExceptSuite,
        };
        if (symbol) {
            symbol.addDeclaration(functionDeclaration);
        }
        // Stash the declaration in the parse node for later access.
        AnalyzerNodeInfo.setDeclaration(node, functionDeclaration);
        // Walk the default values prior to the type parameters.
        node.parameters.forEach((param) => {
            if (param.defaultValue) {
                this.walk(param.defaultValue);
            }
        });
        if (node.typeParameters) {
            this.walk(node.typeParameters);
        }
        this.walkMultiple(node.decorators);
        node.parameters.forEach((param) => {
            if (param.typeAnnotation) {
                this.walk(param.typeAnnotation);
            }
            if (param.typeAnnotationComment) {
                this.walk(param.typeAnnotationComment);
            }
        });
        if (node.returnTypeAnnotation) {
            this.walk(node.returnTypeAnnotation);
        }
        if (node.functionAnnotationComment) {
            this.walk(node.functionAnnotationComment);
        }
        // Don't walk the body of the function until we're done analyzing
        // the current scope.
        this._createNewScope(1 /* ScopeType.Function */, this._getNonClassParentScope(), () => {
            AnalyzerNodeInfo.setScope(node, this._currentScope);
            const enclosingClass = ParseTreeUtils.getEnclosingClass(node);
            if (enclosingClass) {
                // Add the implicit "__class__" symbol described in PEP 3135.
                this._addImplicitSymbolToCurrentScope('__class__', node, 'class');
            }
            this._deferBinding(() => {
                // Create a start node for the function.
                this._currentFlowNode = this._createStartFlowNode();
                this._codeFlowComplexity = 0;
                node.parameters.forEach((paramNode) => {
                    var _a, _b;
                    if (paramNode.name) {
                        const symbol = this._bindNameToScope(this._currentScope, paramNode.name);
                        // Extract the parameter docString from the function docString
                        let docString = ParseTreeUtils.getDocString((_b = (_a = node === null || node === void 0 ? void 0 : node.suite) === null || _a === void 0 ? void 0 : _a.statements) !== null && _b !== void 0 ? _b : []);
                        if (docString !== undefined) {
                            docString = (0, docStringUtils_1.extractParameterDocumentation)(docString, paramNode.name.value);
                        }
                        if (symbol) {
                            const paramDeclaration = {
                                type: 2 /* DeclarationType.Parameter */,
                                node: paramNode,
                                uri: this._fileInfo.fileUri,
                                range: (0, positionUtils_1.convertTextRangeToRange)(paramNode, this._fileInfo.lines),
                                moduleName: this._fileInfo.moduleName,
                                isInExceptSuite: this._isInExceptSuite,
                                docString: docString,
                            };
                            symbol.addDeclaration(paramDeclaration);
                            AnalyzerNodeInfo.setDeclaration(paramNode.name, paramDeclaration);
                        }
                        this._createFlowAssignment(paramNode.name);
                    }
                });
                this._targetFunctionDeclaration = functionDeclaration;
                this._currentReturnTarget = this._createBranchLabel();
                // Walk the statements that make up the function.
                this.walk(node.suite);
                // Associate the code flow node at the end of the suite with
                // the suite.
                AnalyzerNodeInfo.setAfterFlowNode(node.suite, this._currentFlowNode);
                // Compute the final return flow node and associate it with
                // the function's parse node. If this node is unreachable, then
                // the function never returns.
                this._addAntecedent(this._currentReturnTarget, this._currentFlowNode);
                const returnFlowNode = this._finishFlowLabel(this._currentReturnTarget);
                AnalyzerNodeInfo.setAfterFlowNode(node, returnFlowNode);
                AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions);
                AnalyzerNodeInfo.setCodeFlowComplexity(node, this._codeFlowComplexity);
            });
        });
        this._createAssignmentTargetFlowNodes(node.name, /* walkTargets */ false, /* unbound */ false);
        if (node.typeParameters) {
            this._removeActiveTypeParameters(node.typeParameters);
        }
        // We'll walk the child nodes in a deferred manner, so don't walk them now.
        return false;
    }
    visitLambda(node) {
        this._createVariableAnnotationFlowNode();
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        // Analyze the parameter defaults in the context of the parent's scope
        // before we add any names from the function's scope.
        node.parameters.forEach((param) => {
            if (param.defaultValue) {
                this.walk(param.defaultValue);
            }
        });
        this._createNewScope(1 /* ScopeType.Function */, this._getNonClassParentScope(), () => {
            AnalyzerNodeInfo.setScope(node, this._currentScope);
            this._deferBinding(() => {
                // Create a start node for the lambda.
                this._currentFlowNode = this._createStartFlowNode();
                node.parameters.forEach((paramNode) => {
                    if (paramNode.name) {
                        const symbol = this._bindNameToScope(this._currentScope, paramNode.name);
                        if (symbol) {
                            const paramDeclaration = {
                                type: 2 /* DeclarationType.Parameter */,
                                node: paramNode,
                                uri: this._fileInfo.fileUri,
                                range: (0, positionUtils_1.convertTextRangeToRange)(paramNode, this._fileInfo.lines),
                                moduleName: this._fileInfo.moduleName,
                                isInExceptSuite: this._isInExceptSuite,
                            };
                            symbol.addDeclaration(paramDeclaration);
                            AnalyzerNodeInfo.setDeclaration(paramNode.name, paramDeclaration);
                        }
                        this._createFlowAssignment(paramNode.name);
                        this.walk(paramNode.name);
                        AnalyzerNodeInfo.setFlowNode(paramNode, this._currentFlowNode);
                    }
                });
                // Walk the expression that make up the lambda body.
                this.walk(node.expression);
                AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions);
            });
        });
        // We'll walk the child nodes in a deferred manner.
        return false;
    }
    visitCall(node) {
        var _a, _b;
        this._disableTrueFalseTargets(() => {
            this.walk(node.leftExpression);
            const sortedArgs = ParseTreeUtils.getArgumentsByRuntimeOrder(node);
            sortedArgs.forEach((argNode) => {
                if (this._currentFlowNode) {
                    AnalyzerNodeInfo.setFlowNode(argNode, this._currentFlowNode);
                }
                this.walk(argNode);
            });
        });
        // Create a call flow node. We'll skip this if the call is part of
        // a decorator. We assume that decorators are not NoReturn functions.
        // There are libraries that make extensive use of unannotated decorators,
        // and this can lead to a performance issue when walking the control
        // flow graph if we need to evaluate every decorator.
        if (!ParseTreeUtils.isNodeContainedWithinNodeType(node, 13 /* ParseNodeType.Decorator */)) {
            // Skip if we're in an 'Annotated' annotation because this creates
            // problems for "No Return" return type analysis when annotation
            // evaluation is deferred.
            if (!this._isInAnnotatedAnnotation) {
                this._createCallFlowNode(node);
            }
        }
        // Is this an manipulation of dunder all?
        if (this._currentScope.type === 3 /* ScopeType.Module */ &&
            node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
            node.leftExpression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            node.leftExpression.leftExpression.value === '__all__') {
            let emitDunderAllWarning = true;
            // Is this a call to "__all__.extend()"?
            if (node.leftExpression.memberName.value === 'extend' && node.arguments.length === 1) {
                const argExpr = node.arguments[0].valueExpression;
                // Is this a call to "__all__.extend([<list>])"?
                if (argExpr.nodeType === 31 /* ParseNodeType.List */) {
                    argExpr.entries.forEach((listEntryNode) => {
                        var _a, _b;
                        if (listEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                            listEntryNode.strings.length === 1 &&
                            listEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                            (_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.push(listEntryNode.strings[0].value);
                            (_b = this._dunderAllStringNodes) === null || _b === void 0 ? void 0 : _b.push(listEntryNode.strings[0]);
                            emitDunderAllWarning = false;
                        }
                    });
                }
                else if (argExpr.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                    argExpr.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    argExpr.memberName.value === '__all__') {
                    // Is this a call to "__all__.extend(<mod>.__all__)"?
                    const namesToAdd = this._getDunderAllNamesFromImport(argExpr.leftExpression.value);
                    if (namesToAdd && namesToAdd.length > 0) {
                        namesToAdd.forEach((name) => {
                            var _a;
                            (_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.push(name);
                        });
                        emitDunderAllWarning = false;
                    }
                }
            }
            else if (node.leftExpression.memberName.value === 'remove' && node.arguments.length === 1) {
                // Is this a call to "__all__.remove()"?
                const argExpr = node.arguments[0].valueExpression;
                if (argExpr.nodeType === 48 /* ParseNodeType.StringList */ &&
                    argExpr.strings.length === 1 &&
                    argExpr.strings[0].nodeType === 49 /* ParseNodeType.String */ &&
                    this._dunderAllNames) {
                    this._dunderAllNames = this._dunderAllNames.filter((name) => name !== argExpr.strings[0].value);
                    this._dunderAllStringNodes = this._dunderAllStringNodes.filter((node) => node.value !== argExpr.strings[0].value);
                    emitDunderAllWarning = false;
                }
            }
            else if (node.leftExpression.memberName.value === 'append' && node.arguments.length === 1) {
                // Is this a call to "__all__.append()"?
                const argExpr = node.arguments[0].valueExpression;
                if (argExpr.nodeType === 48 /* ParseNodeType.StringList */ &&
                    argExpr.strings.length === 1 &&
                    argExpr.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                    (_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.push(argExpr.strings[0].value);
                    (_b = this._dunderAllStringNodes) === null || _b === void 0 ? void 0 : _b.push(argExpr.strings[0]);
                    emitDunderAllWarning = false;
                }
            }
            if (emitDunderAllWarning) {
                this._usesUnsupportedDunderAllForm = true;
                this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportUnsupportedDunderAll, diagnosticRules_1.DiagnosticRule.reportUnsupportedDunderAll, localize_1.LocMessage.unsupportedDunderAllOperation(), node);
            }
        }
        return false;
    }
    visitTypeParameterList(node) {
        node.parameters.forEach((param) => {
            if (param.boundExpression) {
                this.walk(param.boundExpression);
            }
        });
        node.parameters.forEach((param) => {
            const name = param.name;
            const symbol = new symbol_1.Symbol(0 /* SymbolFlags.None */);
            const paramDeclaration = {
                type: 3 /* DeclarationType.TypeParameter */,
                node: param,
                uri: this._fileInfo.fileUri,
                range: (0, positionUtils_1.convertTextRangeToRange)(node, this._fileInfo.lines),
                moduleName: this._fileInfo.moduleName,
                isInExceptSuite: this._isInExceptSuite,
            };
            symbol.addDeclaration(paramDeclaration);
            AnalyzerNodeInfo.setDeclaration(name, paramDeclaration);
            AnalyzerNodeInfo.setTypeParameterSymbol(name, symbol);
            if (this._activeTypeParams.has(name.value)) {
                this._addSyntaxError(localize_1.LocMessage.typeParameterExistingTypeParameter().format({ name: name.value }), name);
            }
            else {
                this._activeTypeParams.set(name.value, { symbol, scope: this._currentScope });
            }
        });
        node.parameters.forEach((param) => {
            if (param.defaultExpression) {
                this.walk(param.defaultExpression);
            }
        });
        return false;
    }
    visitTypeAlias(node) {
        this._bindNameToScope(this._currentScope, node.name);
        this.walk(node.name);
        if (node.typeParameters) {
            this.walk(node.typeParameters);
        }
        const typeAliasDeclaration = {
            type: 4 /* DeclarationType.TypeAlias */,
            node,
            uri: this._fileInfo.fileUri,
            range: (0, positionUtils_1.convertTextRangeToRange)(node.name, this._fileInfo.lines),
            moduleName: this._fileInfo.moduleName,
            isInExceptSuite: this._isInExceptSuite,
            docString: this._getVariableDocString(node.expression),
        };
        const symbol = this._bindNameToScope(this._currentScope, node.name);
        if (symbol) {
            symbol.addDeclaration(typeAliasDeclaration);
        }
        // Stash the declaration in the parse node for later access.
        AnalyzerNodeInfo.setDeclaration(node, typeAliasDeclaration);
        this._createAssignmentTargetFlowNodes(node.name, /* walkTargets */ true, /* unbound */ false);
        this.walk(node.expression);
        if (node.typeParameters) {
            this._removeActiveTypeParameters(node.typeParameters);
        }
        return false;
    }
    visitAssignment(node) {
        if (this._handleTypingStubAssignmentOrAnnotation(node)) {
            return false;
        }
        this._bindPossibleTupleNamedTarget(node.leftExpression);
        if (node.typeAnnotationComment) {
            this.walk(node.typeAnnotationComment);
            this._addTypeDeclarationForVariable(node.leftExpression, node.typeAnnotationComment);
        }
        if (node.chainedTypeAnnotationComment) {
            this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportInvalidTypeForm, diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.annotationNotSupported(), node.chainedTypeAnnotationComment);
        }
        // If the assignment target base expression is potentially a
        // TypedDict, add the base expression to the flow expressions set
        // to accommodate TypedDict type narrowing.
        if (node.leftExpression.nodeType === 24 /* ParseNodeType.Index */) {
            const target = node.leftExpression;
            if (target.items.length === 1 &&
                !target.trailingComma &&
                target.items[0].valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(target.baseExpression)) {
                    const baseExprReferenceKey = (0, codeFlowTypes_1.createKeyForReference)(target.baseExpression);
                    this._currentScopeCodeFlowExpressions.add(baseExprReferenceKey);
                }
            }
        }
        this.walk(node.rightExpression);
        let isPossibleTypeAlias = true;
        if (ParseTreeUtils.getEnclosingFunction(node)) {
            // We will assume that type aliases are defined only at the module level
            // or as class variables, not as local variables within a function.
            isPossibleTypeAlias = false;
        }
        else if (node.rightExpression.nodeType === 9 /* ParseNodeType.Call */ && this._fileInfo.isTypingStubFile) {
            // Some special built-in types defined in typing.pyi use
            // assignments of the form List = _Alias(). We don't want to
            // treat these as type aliases.
            isPossibleTypeAlias = false;
        }
        else if (ParseTreeUtils.isWithinLoop(node)) {
            // Assume that it's not a type alias if it's within a loop.
            isPossibleTypeAlias = false;
        }
        this._addInferredTypeAssignmentForVariable(node.leftExpression, node.rightExpression, isPossibleTypeAlias);
        // If we didn't create assignment target flow nodes above, do so now.
        this._createAssignmentTargetFlowNodes(node.leftExpression, /* walkTargets */ true, /* unbound */ false);
        // Is this an assignment to dunder all?
        if (this._currentScope.type === 3 /* ScopeType.Module */) {
            if ((node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.leftExpression.value === '__all__') ||
                (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */ &&
                    node.leftExpression.valueExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    node.leftExpression.valueExpression.value === '__all__')) {
                const expr = node.rightExpression;
                this._dunderAllNames = [];
                let emitDunderAllWarning = false;
                if (expr.nodeType === 31 /* ParseNodeType.List */) {
                    expr.entries.forEach((listEntryNode) => {
                        if (listEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                            listEntryNode.strings.length === 1 &&
                            listEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                            this._dunderAllNames.push(listEntryNode.strings[0].value);
                            this._dunderAllStringNodes.push(listEntryNode.strings[0]);
                        }
                        else {
                            emitDunderAllWarning = true;
                        }
                    });
                }
                else if (expr.nodeType === 52 /* ParseNodeType.Tuple */) {
                    expr.expressions.forEach((tupleEntryNode) => {
                        if (tupleEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                            tupleEntryNode.strings.length === 1 &&
                            tupleEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                            this._dunderAllNames.push(tupleEntryNode.strings[0].value);
                            this._dunderAllStringNodes.push(tupleEntryNode.strings[0]);
                        }
                        else {
                            emitDunderAllWarning = true;
                        }
                    });
                }
                else {
                    emitDunderAllWarning = true;
                }
                if (emitDunderAllWarning) {
                    this._usesUnsupportedDunderAllForm = true;
                    this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportUnsupportedDunderAll, diagnosticRules_1.DiagnosticRule.reportUnsupportedDunderAll, localize_1.LocMessage.unsupportedDunderAllOperation(), node);
                }
            }
        }
        // Is this an assignment to dunder slots?
        if (this._currentScope.type === 2 /* ScopeType.Class */) {
            if ((node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.leftExpression.value === '__slots__') ||
                (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */ &&
                    node.leftExpression.valueExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    node.leftExpression.valueExpression.value === '__slots__')) {
                const expr = node.rightExpression;
                this._dunderSlotsEntries = [];
                let isExpressionUnderstood = true;
                if (expr.nodeType === 48 /* ParseNodeType.StringList */) {
                    this._dunderSlotsEntries.push(expr);
                }
                else if (expr.nodeType === 31 /* ParseNodeType.List */) {
                    expr.entries.forEach((listEntryNode) => {
                        if (listEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                            listEntryNode.strings.length === 1 &&
                            listEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                            this._dunderSlotsEntries.push(listEntryNode);
                        }
                        else {
                            isExpressionUnderstood = false;
                        }
                    });
                }
                else if (expr.nodeType === 52 /* ParseNodeType.Tuple */) {
                    expr.expressions.forEach((tupleEntryNode) => {
                        if (tupleEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                            tupleEntryNode.strings.length === 1 &&
                            tupleEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                            this._dunderSlotsEntries.push(tupleEntryNode);
                        }
                        else {
                            isExpressionUnderstood = false;
                        }
                    });
                }
                else {
                    isExpressionUnderstood = false;
                }
                if (!isExpressionUnderstood) {
                    this._dunderSlotsEntries = undefined;
                }
            }
        }
        return false;
    }
    visitAssignmentExpression(node) {
        // Temporarily disable true/false targets in case this assignment
        // expression is located within an if/else conditional.
        this._disableTrueFalseTargets(() => {
            // Evaluate the operand expression.
            this.walk(node.rightExpression);
        });
        const evaluationNode = ParseTreeUtils.getEvaluationNodeForAssignmentExpression(node);
        if (!evaluationNode) {
            this._addSyntaxError(localize_1.LocMessage.assignmentExprContext(), node);
            this.walk(node.name);
        }
        else {
            // Bind the name to the containing scope. This special logic is required
            // because of the behavior defined in PEP 572. Targets of assignment
            // expressions don't bind to a list comprehension's scope but instead
            // bind to its containing scope.
            const containerScope = AnalyzerNodeInfo.getScope(evaluationNode);
            // If we're in a list comprehension (possibly nested), make sure that
            // local for targets don't collide with the target of the assignment
            // expression.
            let curScope = this._currentScope;
            while (curScope && curScope !== containerScope) {
                const localSymbol = curScope.lookUpSymbol(node.name.value);
                if (localSymbol) {
                    this._addSyntaxError(localize_1.LocMessage.assignmentExprComprehension().format({ name: node.name.value }), node.name);
                    break;
                }
                curScope = curScope.parent;
            }
            this._bindNameToScope(containerScope, node.name);
            this._addInferredTypeAssignmentForVariable(node.name, node.rightExpression);
            this._createAssignmentTargetFlowNodes(node.name, /* walkTargets */ true, /* unbound */ false);
        }
        return false;
    }
    visitAugmentedAssignment(node) {
        this.walk(node.leftExpression);
        this.walk(node.rightExpression);
        this._bindPossibleTupleNamedTarget(node.destExpression);
        this._createAssignmentTargetFlowNodes(node.destExpression, /* walkTargets */ false, /* unbound */ false);
        // Is this an assignment to dunder all of the form
        // __all__ += <expression>?
        if (node.operator === 1 /* OperatorType.AddEqual */ &&
            this._currentScope.type === 3 /* ScopeType.Module */ &&
            node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            node.leftExpression.value === '__all__') {
            const expr = node.rightExpression;
            let emitDunderAllWarning = true;
            if (expr.nodeType === 31 /* ParseNodeType.List */) {
                // Is this the form __all__ += ["a", "b"]?
                expr.entries.forEach((listEntryNode) => {
                    var _a;
                    if (listEntryNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                        listEntryNode.strings.length === 1 &&
                        listEntryNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                        (_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.push(listEntryNode.strings[0].value);
                        this._dunderAllStringNodes.push(listEntryNode.strings[0]);
                    }
                });
                emitDunderAllWarning = false;
            }
            else if (expr.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                expr.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                expr.memberName.value === '__all__') {
                // Is this using the form "__all__ += <mod>.__all__"?
                const namesToAdd = this._getDunderAllNamesFromImport(expr.leftExpression.value);
                if (namesToAdd) {
                    namesToAdd.forEach((name) => {
                        var _a;
                        (_a = this._dunderAllNames) === null || _a === void 0 ? void 0 : _a.push(name);
                    });
                    emitDunderAllWarning = false;
                }
            }
            if (emitDunderAllWarning) {
                this._usesUnsupportedDunderAllForm = true;
                this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportUnsupportedDunderAll, diagnosticRules_1.DiagnosticRule.reportUnsupportedDunderAll, localize_1.LocMessage.unsupportedDunderAllOperation(), node);
            }
        }
        return false;
    }
    visitDel(node) {
        node.expressions.forEach((expr) => {
            this._bindPossibleTupleNamedTarget(expr);
            this.walk(expr);
            this._createAssignmentTargetFlowNodes(expr, /* walkTargets */ false, /* unbound */ true);
        });
        return false;
    }
    visitTypeAnnotation(node) {
        var _a;
        if (this._handleTypingStubAssignmentOrAnnotation(node)) {
            return false;
        }
        // If this is an annotated variable assignment within a class body,
        // we need to evaluate the type annotation first.
        const bindVariableBeforeAnnotationEvaluation = ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */ &&
            ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true) !== undefined;
        if (!bindVariableBeforeAnnotationEvaluation) {
            this.walk(node.typeAnnotation);
        }
        this._createVariableAnnotationFlowNode();
        this._bindPossibleTupleNamedTarget(node.valueExpression);
        this._addTypeDeclarationForVariable(node.valueExpression, node.typeAnnotation);
        if (bindVariableBeforeAnnotationEvaluation) {
            this.walk(node.typeAnnotation);
        }
        // For type annotations that are not part of assignments (e.g. simple variable
        // annotations), we need to populate the reference map. Otherwise the type
        // analyzer's code flow engine won't run and detect cases where the variable
        // is unbound.
        const expressionList = [];
        if (this._isNarrowingExpression(node.valueExpression, expressionList)) {
            expressionList.forEach((expr) => {
                const referenceKey = (0, codeFlowTypes_1.createKeyForReference)(expr);
                this._currentScopeCodeFlowExpressions.add(referenceKey);
            });
        }
        this.walk(node.valueExpression);
        return false;
    }
    visitFor(node) {
        this._bindPossibleTupleNamedTarget(node.targetExpression);
        this._addInferredTypeAssignmentForVariable(node.targetExpression, node);
        this.walk(node.iterableExpression);
        const preForLabel = this._createLoopLabel();
        const preElseLabel = this._createBranchLabel();
        const postForLabel = this._createBranchLabel();
        this._addAntecedent(preForLabel, this._currentFlowNode);
        this._currentFlowNode = preForLabel;
        this._addAntecedent(preElseLabel, this._currentFlowNode);
        const targetExpressions = this._trackCodeFlowExpressions(() => {
            this._createAssignmentTargetFlowNodes(node.targetExpression, /* walkTargets */ true, /* unbound */ false);
        });
        this._bindLoopStatement(preForLabel, postForLabel, () => {
            this.walk(node.forSuite);
            this._addAntecedent(preForLabel, this._currentFlowNode);
            // Add any target expressions since they are modified in the loop.
            targetExpressions.forEach((value) => {
                var _a;
                (_a = this._currentScopeCodeFlowExpressions) === null || _a === void 0 ? void 0 : _a.add(value);
            });
        });
        this._currentFlowNode = this._finishFlowLabel(preElseLabel);
        if (node.elseSuite) {
            this.walk(node.elseSuite);
        }
        this._addAntecedent(postForLabel, this._currentFlowNode);
        this._currentFlowNode = this._finishFlowLabel(postForLabel);
        // Async for is not allowed outside of an async function
        // unless we're in ipython mode.
        if (node.asyncToken && !this._fileInfo.ipythonMode) {
            const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node);
            if (!enclosingFunction || !enclosingFunction.isAsync) {
                this._addSyntaxError(localize_1.LocMessage.asyncNotInAsyncFunction(), node.asyncToken);
            }
        }
        return false;
    }
    visitContinue(node) {
        if (this._currentContinueTarget) {
            this._addAntecedent(this._currentContinueTarget, this._currentFlowNode);
        }
        this._currentFlowNode = Binder._unreachableFlowNode;
        // Continue nodes don't have any children.
        return false;
    }
    visitBreak(node) {
        if (this._currentBreakTarget) {
            this._addAntecedent(this._currentBreakTarget, this._currentFlowNode);
        }
        this._currentFlowNode = Binder._unreachableFlowNode;
        // Break nodes don't have any children.
        return false;
    }
    visitReturn(node) {
        if (this._targetFunctionDeclaration) {
            if (!this._targetFunctionDeclaration.returnStatements) {
                this._targetFunctionDeclaration.returnStatements = [];
            }
            this._targetFunctionDeclaration.returnStatements.push(node);
        }
        if (node.returnExpression) {
            this.walk(node.returnExpression);
        }
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        if (this._currentReturnTarget) {
            this._addAntecedent(this._currentReturnTarget, this._currentFlowNode);
        }
        this._finallyTargets.forEach((target) => {
            this._addAntecedent(target, this._currentFlowNode);
        });
        this._currentFlowNode = Binder._unreachableFlowNode;
        return false;
    }
    visitYield(node) {
        if (this._isInListComprehension(node, /* ignoreOutermostIterable */ true)) {
            this._addSyntaxError(localize_1.LocMessage.yieldWithinListCompr(), node);
        }
        this._bindYield(node);
        return false;
    }
    visitYieldFrom(node) {
        if (this._isInListComprehension(node, /* ignoreOutermostIterable */ true)) {
            this._addSyntaxError(localize_1.LocMessage.yieldWithinListCompr(), node);
        }
        this._bindYield(node);
        return false;
    }
    visitMemberAccess(node) {
        this.walk(node.leftExpression);
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        return false;
    }
    visitName(node) {
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        const typeParamSymbol = this._activeTypeParams.get(node.value);
        if (typeParamSymbol) {
            const bindingType = this._currentScope.getBindingType(node.value);
            if (bindingType !== 1 /* NameBindingType.Global */) {
                // See if the type parameter symbol has been shadowed by a
                // variable within an inner scope.
                const nameSymbolWithScope = this._currentScope.lookUpSymbolRecursive(node.value);
                if (!nameSymbolWithScope || !(0, scopeUtils_1.isScopeContainedWithin)(nameSymbolWithScope.scope, typeParamSymbol.scope)) {
                    AnalyzerNodeInfo.setTypeParameterSymbol(node, typeParamSymbol.symbol);
                }
            }
        }
        // Name nodes have no children.
        return false;
    }
    visitIndex(node) {
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        this.walk(node.baseExpression);
        // If we're within an 'Annotated' type annotation, set the flag.
        const wasInAnnotatedAnnotation = this._isInAnnotatedAnnotation;
        if (this._isTypingAnnotation(node.baseExpression, 'Annotated')) {
            this._isInAnnotatedAnnotation = true;
        }
        node.items.forEach((argNode) => {
            this.walk(argNode);
        });
        this._isInAnnotatedAnnotation = wasInAnnotatedAnnotation;
        return false;
    }
    visitIf(node) {
        const preIfFlowNode = this._currentFlowNode;
        const thenLabel = this._createBranchLabel();
        const elseLabel = this._createBranchLabel();
        const postIfLabel = this._createBranchLabel(preIfFlowNode);
        const notTypeCheckingNode = {
            flags: codeFlowTypes_1.FlowFlags.NotTypeChecking | codeFlowTypes_1.FlowFlags.Unreachable,
            id: (0, codeFlowTypes_1.getUniqueFlowNodeId)(),
        };
        const isTypeCheckingNode = (node) => node.nodeType === 38 /* ParseNodeType.Name */ && node.value === 'TYPE_CHECKING';
        postIfLabel.affectedExpressions = this._trackCodeFlowExpressions(() => {
            // Determine if the test condition is always true or always false. If so,
            // we can treat either the then or the else clause as unconditional.
            const constExprValue = StaticExpressions.evaluateStaticBoolLikeExpression(node.testExpression, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, this._typingImportAliases, this._sysImportAliases);
            this._bindConditional(node.testExpression, thenLabel, elseLabel);
            // Handle the if clause.
            if (constExprValue === false) {
                this._currentFlowNode =
                    node.testExpression.nodeType === 55 /* ParseNodeType.UnaryOperation */ &&
                        node.testExpression.operator === 38 /* OperatorType.Not */ &&
                        isTypeCheckingNode(node.testExpression.expression) &&
                        constExprValue === false
                        ? notTypeCheckingNode
                        : Binder._unreachableFlowNode;
            }
            else {
                this._currentFlowNode = this._finishFlowLabel(thenLabel);
            }
            this.walk(node.ifSuite);
            this._addAntecedent(postIfLabel, this._currentFlowNode);
            // Now handle the else clause if it's present. If there
            // are chained "else if" statements, they'll be handled
            // recursively here.
            if (constExprValue === true) {
                this._currentFlowNode = isTypeCheckingNode(node.testExpression)
                    ? notTypeCheckingNode
                    : Binder._unreachableFlowNode;
            }
            else {
                this._currentFlowNode = this._finishFlowLabel(elseLabel);
            }
            if (node.elseSuite) {
                this.walk(node.elseSuite);
            }
            else {
                this._bindNeverCondition(node.testExpression, postIfLabel, /* isPositiveTest */ false);
            }
            this._addAntecedent(postIfLabel, this._currentFlowNode);
            this._currentFlowNode = this._finishFlowLabel(postIfLabel);
        });
        return false;
    }
    visitWhile(node) {
        const thenLabel = this._createBranchLabel();
        const elseLabel = this._createBranchLabel();
        const postWhileLabel = this._createBranchLabel();
        // Determine if the test condition is always true or always false. If so,
        // we can treat either the while or the else clause as unconditional.
        const constExprValue = StaticExpressions.evaluateStaticBoolLikeExpression(node.testExpression, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, this._typingImportAliases, this._sysImportAliases);
        const preLoopLabel = this._createLoopLabel();
        this._addAntecedent(preLoopLabel, this._currentFlowNode);
        this._currentFlowNode = preLoopLabel;
        this._bindConditional(node.testExpression, thenLabel, elseLabel);
        // Handle the while clause.
        this._currentFlowNode =
            constExprValue === false ? Binder._unreachableFlowNode : this._finishFlowLabel(thenLabel);
        this._bindLoopStatement(preLoopLabel, postWhileLabel, () => {
            this.walk(node.whileSuite);
        });
        this._addAntecedent(preLoopLabel, this._currentFlowNode);
        this._currentFlowNode =
            constExprValue === true ? Binder._unreachableFlowNode : this._finishFlowLabel(elseLabel);
        if (node.elseSuite) {
            this.walk(node.elseSuite);
        }
        this._addAntecedent(postWhileLabel, this._currentFlowNode);
        this._currentFlowNode = this._finishFlowLabel(postWhileLabel);
        return false;
    }
    visitAssert(node) {
        const assertTrueLabel = this._createBranchLabel();
        const assertFalseLabel = this._createBranchLabel();
        this._bindConditional(node.testExpression, assertTrueLabel, assertFalseLabel);
        if (node.exceptionExpression) {
            this._currentFlowNode = this._finishFlowLabel(assertFalseLabel);
            this.walk(node.exceptionExpression);
        }
        this._currentFlowNode = this._finishFlowLabel(assertTrueLabel);
        return false;
    }
    visitExcept(node) {
        if (node.typeExpression) {
            this.walk(node.typeExpression);
        }
        if (node.name) {
            this.walk(node.name);
            const symbol = this._bindNameToScope(this._currentScope, node.name);
            this._createAssignmentTargetFlowNodes(node.name, /* walkTargets */ true, /* unbound */ false);
            if (symbol) {
                const declaration = {
                    type: 1 /* DeclarationType.Variable */,
                    node: node.name,
                    isConstant: (0, symbolNameUtils_1.isConstantName)(node.name.value),
                    inferredTypeSource: node,
                    uri: this._fileInfo.fileUri,
                    range: (0, positionUtils_1.convertTextRangeToRange)(node.name, this._fileInfo.lines),
                    moduleName: this._fileInfo.moduleName,
                    isInExceptSuite: this._isInExceptSuite,
                };
                symbol.addDeclaration(declaration);
            }
        }
        const wasInExceptSuite = this._isInExceptSuite;
        this._isInExceptSuite = true;
        this.walk(node.exceptSuite);
        this._isInExceptSuite = wasInExceptSuite;
        if (node.name) {
            // The exception name is implicitly unbound at the end of
            // the except block.
            this._createFlowAssignment(node.name, /* unbound */ true);
        }
        return false;
    }
    visitRaise(node) {
        if (this._currentFlowNode) {
            this._addExceptTargets(this._currentFlowNode);
        }
        if (this._targetFunctionDeclaration) {
            if (!this._targetFunctionDeclaration.raiseStatements) {
                this._targetFunctionDeclaration.raiseStatements = [];
            }
            this._targetFunctionDeclaration.raiseStatements.push(node);
        }
        if (node.typeExpression) {
            this.walk(node.typeExpression);
        }
        if (node.valueExpression) {
            this.walk(node.valueExpression);
        }
        if (node.tracebackExpression) {
            this.walk(node.tracebackExpression);
        }
        this._finallyTargets.forEach((target) => {
            this._addAntecedent(target, this._currentFlowNode);
        });
        this._currentFlowNode = Binder._unreachableFlowNode;
        return false;
    }
    visitTry(node) {
        // The try/except/else/finally statement is tricky to model using static code
        // flow rules because the finally clause is executed regardless of whether an
        // exception is raised or a return statement is executed. Code within the finally
        // clause needs to be reachable always, and we conservatively assume that any
        // statement within the try block can generate an exception, so we assume that its
        // antecedent is the pre-try flow. We implement this with a "gate" node in the
        // control flow graph. If analysis starts within the finally clause, the gate is
        // opened, and all raise/return statements within try/except/else blocks are
        // considered antecedents. If analysis starts outside (after) the finally clause,
        // the gate is closed, and only paths that don't hit a raise/return statement
        // in try/except/else blocks are considered.
        //
        //
        //                               1. PostElse
        //                                    ^
        //                                    |
        // 3. TryExceptElseReturnOrExcept     |
        //       ^                            |
        //       |                            |     2. PostExcept (for each except)
        //       |                            |            ^
        // 4. ReturnOrRaiseLabel              |            |
        //       ^                            |            |
        //       |                            |   |---------
        // 5. PreFinallyGate                  |   |
        //       ^                            |   |
        //       |------------------          |   |
        //                         |          |   |
        //                        6. PreFinallyLabel
        //                                ^
        //                         (finally block)
        //                                ^
        //                        7. PostFinally
        //                                ^    (only if isAfterElseAndExceptsReachable)
        //                         (after finally)
        // Create one flow label for every except clause.
        const preTryFlowNode = this._currentFlowNode;
        const curExceptTargets = node.exceptClauses.map(() => this._createBranchLabel());
        const preFinallyLabel = this._createBranchLabel(preTryFlowNode);
        let isAfterElseAndExceptsReachable = false;
        // Create a label for all of the return or raise labels that are
        // encountered within the try/except/else blocks. This conditionally
        // connects the return/raise statement to the finally clause.
        const preFinallyReturnOrRaiseLabel = this._createBranchLabel(preTryFlowNode);
        const preFinallyGate = {
            flags: codeFlowTypes_1.FlowFlags.PreFinallyGate,
            id: this._getUniqueFlowNodeId(),
            antecedent: preFinallyReturnOrRaiseLabel,
        };
        preFinallyLabel.affectedExpressions = this._trackCodeFlowExpressions(() => {
            if (node.finallySuite) {
                this._addAntecedent(preFinallyLabel, preFinallyGate);
            }
            // Add the finally target as an exception target unless there is
            // a "bare" except clause that accepts all exception types.
            const hasBareExceptClause = node.exceptClauses.some((except) => !except.typeExpression);
            if (!hasBareExceptClause) {
                curExceptTargets.push(preFinallyReturnOrRaiseLabel);
            }
            // An exception may be generated before the first flow node
            // added by the try block, so all of the exception targets
            // must have the pre-try flow node as an antecedent.
            curExceptTargets.forEach((exceptLabel) => {
                this._addAntecedent(exceptLabel, this._currentFlowNode);
            });
            // We don't perfectly handle nested finally clauses, which are not
            // possible to model fully within a static analyzer, but we do handle
            // a single level of finally statements, and we handle most cases
            // involving nesting. Returns or raises within the try/except/raise
            // block will execute the finally target(s).
            if (node.finallySuite) {
                this._finallyTargets.push(preFinallyReturnOrRaiseLabel);
            }
            // Handle the try block.
            this._useExceptTargets(curExceptTargets, () => {
                this.walk(node.trySuite);
            });
            // Handle the else block, which is executed only if
            // execution falls through the try block.
            if (node.elseSuite) {
                this.walk(node.elseSuite);
            }
            this._addAntecedent(preFinallyLabel, this._currentFlowNode);
            if (!this._isCodeUnreachable()) {
                isAfterElseAndExceptsReachable = true;
            }
            // Handle the except blocks.
            node.exceptClauses.forEach((exceptNode, index) => {
                this._currentFlowNode = this._finishFlowLabel(curExceptTargets[index]);
                this.walk(exceptNode);
                this._addAntecedent(preFinallyLabel, this._currentFlowNode);
                if (!this._isCodeUnreachable()) {
                    isAfterElseAndExceptsReachable = true;
                }
            });
            if (node.finallySuite) {
                this._finallyTargets.pop();
            }
            // Handle the finally block.
            this._currentFlowNode = this._finishFlowLabel(preFinallyLabel);
        });
        if (node.finallySuite) {
            this.walk(node.finallySuite);
            // Add a post-finally node at the end. If we traverse this node,
            // we'll set the "ignore" flag in the pre-finally node.
            const postFinallyNode = {
                flags: codeFlowTypes_1.FlowFlags.PostFinally,
                id: this._getUniqueFlowNodeId(),
                finallyNode: node.finallySuite,
                antecedent: this._currentFlowNode,
                preFinallyGate,
            };
            this._currentFlowNode = isAfterElseAndExceptsReachable ? postFinallyNode : Binder._unreachableFlowNode;
        }
        return false;
    }
    visitAwait(node) {
        var _a;
        // Make sure this is within an async lambda or function.
        const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node);
        if (enclosingFunction === undefined || !enclosingFunction.isAsync) {
            if (this._fileInfo.ipythonMode && enclosingFunction === undefined) {
                // Top level await is allowed in ipython mode.
                return true;
            }
            // Allow if it's within a generator expression. Execution of
            // generator expressions is deferred and therefore can be
            // run within the context of an async function later.
            if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 32 /* ParseNodeType.ListComprehension */) {
                this._addSyntaxError(localize_1.LocMessage.awaitNotInAsync(), node);
            }
        }
        return true;
    }
    visitGlobal(node) {
        const globalScope = this._currentScope.getGlobalScope().scope;
        node.nameList.forEach((name) => {
            const nameValue = name.value;
            // Is the binding inconsistent?
            if (this._currentScope.getBindingType(nameValue) === 0 /* NameBindingType.Nonlocal */) {
                this._addSyntaxError(localize_1.LocMessage.nonLocalRedefinition().format({ name: nameValue }), name);
            }
            const valueWithScope = this._currentScope.lookUpSymbolRecursive(nameValue);
            // Was the name already assigned within this scope before it was declared global?
            if (valueWithScope && valueWithScope.scope === this._currentScope) {
                this._addSyntaxError(localize_1.LocMessage.globalReassignment().format({ name: nameValue }), name);
            }
            // Add it to the global scope if it's not already added.
            this._bindNameToScope(globalScope, name);
            if (this._currentScope !== globalScope) {
                this._currentScope.setBindingType(nameValue, 1 /* NameBindingType.Global */);
            }
        });
        return true;
    }
    visitNonlocal(node) {
        const globalScope = this._currentScope.getGlobalScope().scope;
        if (this._currentScope === globalScope) {
            this._addSyntaxError(localize_1.LocMessage.nonLocalInModule(), node);
        }
        else {
            node.nameList.forEach((name) => {
                const nameValue = name.value;
                // Is the binding inconsistent?
                if (this._currentScope.getBindingType(nameValue) === 1 /* NameBindingType.Global */) {
                    this._addSyntaxError(localize_1.LocMessage.globalRedefinition().format({ name: nameValue }), name);
                }
                const valueWithScope = this._currentScope.lookUpSymbolRecursive(nameValue);
                // Was the name already assigned within this scope before it was declared nonlocal?
                if (valueWithScope && valueWithScope.scope === this._currentScope) {
                    this._addSyntaxError(localize_1.LocMessage.nonLocalReassignment().format({ name: nameValue }), name);
                }
                else if (!valueWithScope || valueWithScope.scope === globalScope) {
                    this._addSyntaxError(localize_1.LocMessage.nonLocalNoBinding().format({ name: nameValue }), name);
                }
                if (valueWithScope) {
                    this._currentScope.setBindingType(nameValue, 0 /* NameBindingType.Nonlocal */);
                }
            });
        }
        return true;
    }
    visitImportAs(node) {
        var _a, _b, _c, _d, _e, _f;
        if (node.module.nameParts.length > 0) {
            const firstNamePartValue = node.module.nameParts[0].value;
            let symbolName;
            let symbolNameNode;
            if (node.alias) {
                // The symbol name is defined by the alias.
                symbolName = node.alias.value;
                symbolNameNode = node.alias;
            }
            else {
                // There was no alias, so we need to use the first element of
                // the name parts as the symbol.
                symbolName = firstNamePartValue;
                symbolNameNode = node.module.nameParts[0];
            }
            const symbol = this._bindNameToScope(this._currentScope, symbolNameNode);
            if (symbol &&
                (this._currentScope.type === 3 /* ScopeType.Module */ || this._currentScope.type === 4 /* ScopeType.Builtin */) &&
                (!node.alias ||
                    node.module.nameParts.length !== 1 ||
                    node.module.nameParts[0].value !== node.alias.value)) {
                // PEP 484 indicates that imported symbols should not be
                // considered "reexported" from a type stub file unless
                // they are imported using the "as" form and the aliased
                // name is entirely redundant.
                // in basedpyright, we don't care whether it's a stub file or not. this should
                // apply to regular modules too. this is also consistent with mypy'ss behavior.
                this._potentialHiddenSymbols.set(symbolName, symbol);
            }
            const importInfo = AnalyzerNodeInfo.getImportInfo(node.module);
            (0, debug_1.assert)(importInfo !== undefined);
            if (symbol) {
                this._createAliasDeclarationForMultipartImportName(node, node.alias, importInfo, symbol);
            }
            this._createFlowAssignment(node.alias ? node.alias : node.module.nameParts[0]);
            if (node.module.nameParts.length === 1) {
                if (firstNamePartValue === 'typing' || firstNamePartValue === 'typing_extensions') {
                    this._typingImportAliases.push((_b = (_a = node.alias) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : firstNamePartValue);
                }
                else if (firstNamePartValue === 'sys') {
                    this._sysImportAliases.push((_d = (_c = node.alias) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : firstNamePartValue);
                }
                else if (firstNamePartValue === 'dataclasses') {
                    this._dataclassesImportAliases.push((_f = (_e = node.alias) === null || _e === void 0 ? void 0 : _e.value) !== null && _f !== void 0 ? _f : firstNamePartValue);
                }
            }
        }
        return true;
    }
    visitImportFrom(node) {
        var _a;
        const typingSymbolsOfInterest = ['Final', 'ClassVar', 'Annotated'];
        const dataclassesSymbolsOfInterest = ['InitVar'];
        const importInfo = AnalyzerNodeInfo.getImportInfo(node.module);
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        let resolvedPath = uri_1.Uri.empty();
        if (importInfo && importInfo.isImportFound && !importInfo.isNativeLib) {
            resolvedPath = importInfo.resolvedUris[importInfo.resolvedUris.length - 1];
        }
        // If this file is a module __init__.py(i), relative imports of submodules
        // using the syntax "from .x import y" introduce a symbol x into the
        // module namespace. We do this first (before adding the individual imported
        // symbols below) in case one of the imported symbols is the same name as the
        // submodule. In that case, we want to the symbol to appear later in the
        // declaration list because it should "win" when resolving the alias.
        const fileName = (0, pathUtils_1.stripFileExtension)(this._fileInfo.fileUri.fileName);
        const isModuleInitFile = fileName === '__init__' && node.module.leadingDots === 1 && node.module.nameParts.length === 1;
        let isTypingImport = false;
        let isDataclassesImport = false;
        if (node.module.nameParts.length === 1) {
            const firstNamePartValue = node.module.nameParts[0].value;
            if (firstNamePartValue === 'typing' || firstNamePartValue === 'typing_extensions') {
                isTypingImport = true;
            }
            if (firstNamePartValue === 'dataclasses') {
                isDataclassesImport = true;
            }
        }
        if (node.isWildcardImport) {
            if (ParseTreeUtils.getEnclosingClass(node) || ParseTreeUtils.getEnclosingFunction(node)) {
                this._addSyntaxError(localize_1.LocMessage.wildcardInFunction(), node);
            }
            if (importInfo) {
                const names = [];
                // Note that this scope uses a wildcard import, so we cannot shortcut
                // any code flow checks. All expressions are potentially in play.
                (_a = this._currentScopeCodeFlowExpressions) === null || _a === void 0 ? void 0 : _a.add(codeFlowTypes_1.wildcardImportReferenceKey);
                const lookupInfo = this._fileInfo.importLookup(resolvedPath);
                if (lookupInfo) {
                    const wildcardNames = this._getWildcardImportNames(lookupInfo);
                    if (isModuleInitFile) {
                        // If the symbol is going to be immediately replaced with a same-named
                        // imported symbol, skip this.
                        const isImmediatelyReplaced = wildcardNames.some((name) => {
                            return name === node.module.nameParts[0].value;
                        });
                        if (!isImmediatelyReplaced) {
                            this._addImplicitFromImport(node, importInfo);
                        }
                    }
                    wildcardNames.forEach((name) => {
                        const localSymbol = this._bindNameValueToScope(this._currentScope, name);
                        if (localSymbol) {
                            const importedSymbol = lookupInfo.symbolTable.get(name);
                            // Is the symbol in the target module's symbol table? If so,
                            // alias it.
                            if (importedSymbol) {
                                const aliasDecl = {
                                    type: 8 /* DeclarationType.Alias */,
                                    node,
                                    uri: resolvedPath,
                                    loadSymbolsFromPath: true,
                                    range: (0, textRange_1.getEmptyRange)(),
                                    usesLocalName: false,
                                    symbolName: name,
                                    moduleName: this._fileInfo.moduleName,
                                    isInExceptSuite: this._isInExceptSuite,
                                };
                                localSymbol.addDeclaration(aliasDecl);
                                names.push(name);
                            }
                            else {
                                // The symbol wasn't in the target module's symbol table. It's probably
                                // an implicitly-imported submodule referenced by __all__.
                                if (importInfo && importInfo.filteredImplicitImports) {
                                    const implicitImport = importInfo.filteredImplicitImports.get(name);
                                    if (implicitImport) {
                                        const submoduleFallback = {
                                            type: 8 /* DeclarationType.Alias */,
                                            node,
                                            uri: implicitImport.uri,
                                            loadSymbolsFromPath: true,
                                            range: (0, textRange_1.getEmptyRange)(),
                                            usesLocalName: false,
                                            moduleName: this._fileInfo.moduleName,
                                            isInExceptSuite: this._isInExceptSuite,
                                        };
                                        const aliasDecl = {
                                            type: 8 /* DeclarationType.Alias */,
                                            node,
                                            uri: resolvedPath,
                                            loadSymbolsFromPath: true,
                                            usesLocalName: false,
                                            symbolName: name,
                                            submoduleFallback,
                                            range: (0, textRange_1.getEmptyRange)(),
                                            moduleName: this._fileInfo.moduleName,
                                            isInExceptSuite: this._isInExceptSuite,
                                        };
                                        localSymbol.addDeclaration(aliasDecl);
                                        names.push(name);
                                    }
                                }
                            }
                        }
                    });
                }
                this._createFlowWildcardImport(node, names);
                if (isTypingImport) {
                    typingSymbolsOfInterest.forEach((s) => {
                        this._typingSymbolAliases.set(s, s);
                    });
                }
                if (isDataclassesImport) {
                    dataclassesSymbolsOfInterest.forEach((s) => {
                        this._dataclassesSymbolAliases.set(s, s);
                    });
                }
            }
        }
        else {
            if (isModuleInitFile) {
                this._addImplicitFromImport(node, importInfo);
            }
            node.imports.forEach((importSymbolNode) => {
                const importedName = importSymbolNode.name.value;
                const nameNode = importSymbolNode.alias || importSymbolNode.name;
                AnalyzerNodeInfo.setFlowNode(importSymbolNode, this._currentFlowNode);
                const symbol = this._bindNameToScope(this._currentScope, nameNode);
                if (symbol) {
                    // All import statements of the form `from . import x` treat x
                    // as an externally-visible (not hidden) symbol.
                    if (node.module.nameParts.length > 0) {
                        if (this._currentScope.type === 3 /* ScopeType.Module */ ||
                            this._currentScope.type === 4 /* ScopeType.Builtin */) {
                            if (!importSymbolNode.alias ||
                                importSymbolNode.alias.value !== importSymbolNode.name.value) {
                                // PEP 484 indicates that imported symbols should not be
                                // considered "reexported" from a type stub file unless
                                // they are imported using the "as" form using a redundant form.
                                // Py.typed packages follow the same rule as PEP 484.
                                // in basedpyright, we don't care whether it's a stub file or not. this should
                                // apply to regular modules too. this is also consistent with mypy'ss behavior.
                                this._potentialHiddenSymbols.set(nameNode.value, symbol);
                            }
                        }
                    }
                    // Is the import referring to an implicitly-imported module?
                    let implicitImport;
                    if (importInfo && importInfo.filteredImplicitImports) {
                        implicitImport = importInfo.filteredImplicitImports.get(importedName);
                    }
                    let submoduleFallback;
                    let loadSymbolsFromPath = true;
                    if (implicitImport) {
                        submoduleFallback = {
                            type: 8 /* DeclarationType.Alias */,
                            node: importSymbolNode,
                            uri: implicitImport.uri,
                            loadSymbolsFromPath: true,
                            range: (0, textRange_1.getEmptyRange)(),
                            usesLocalName: false,
                            moduleName: this._formatModuleName(node.module),
                            isInExceptSuite: this._isInExceptSuite,
                        };
                        // Handle the case where this is an __init__.py file and the imported
                        // module name refers to itself. The most common situation where this occurs
                        // is with a "from . import X" form, but it can also occur with
                        // an absolute import (e.g. "from A.B.C import X"). In this case, we want to
                        // always resolve to the submodule rather than the resolved path.
                        if (fileName === '__init__') {
                            if (node.module.leadingDots === 1 && node.module.nameParts.length === 0) {
                                loadSymbolsFromPath = false;
                            }
                            else if (resolvedPath.equals(this._fileInfo.fileUri)) {
                                loadSymbolsFromPath = false;
                            }
                        }
                    }
                    const aliasDecl = {
                        type: 8 /* DeclarationType.Alias */,
                        node: importSymbolNode,
                        uri: resolvedPath,
                        loadSymbolsFromPath,
                        usesLocalName: !!importSymbolNode.alias,
                        symbolName: importedName,
                        submoduleFallback,
                        range: (0, positionUtils_1.convertTextRangeToRange)(nameNode, this._fileInfo.lines),
                        moduleName: this._formatModuleName(node.module),
                        isInExceptSuite: this._isInExceptSuite,
                        isNativeLib: importInfo === null || importInfo === void 0 ? void 0 : importInfo.isNativeLib,
                    };
                    symbol.addDeclaration(aliasDecl);
                    this._createFlowAssignment(importSymbolNode.alias || importSymbolNode.name);
                    if (isTypingImport) {
                        if (typingSymbolsOfInterest.some((s) => s === importSymbolNode.name.value)) {
                            this._typingSymbolAliases.set(nameNode.value, importSymbolNode.name.value);
                        }
                    }
                    if (isDataclassesImport) {
                        if (dataclassesSymbolsOfInterest.some((s) => s === importSymbolNode.name.value)) {
                            this._dataclassesSymbolAliases.set(nameNode.value, importSymbolNode.name.value);
                        }
                    }
                }
            });
        }
        return true;
    }
    visitWith(node) {
        node.withItems.forEach((item) => {
            this.walk(item.expression);
            if (item.target) {
                this._bindPossibleTupleNamedTarget(item.target);
                this._addInferredTypeAssignmentForVariable(item.target, item);
                this._createAssignmentTargetFlowNodes(item.target, /* walkTargets */ true, /* unbound */ false);
            }
        });
        // We need to treat the "with" body as though it is wrapped in a try/except
        // block because some context managers catch and suppress exceptions.
        // We'll make use of a special "context manager label" which acts like
        // a regular branch label in most respects except that it is disabled
        // if none of the context managers support exception suppression. We won't
        // be able to determine whether any context managers support exception
        // processing until the type evaluation phase.
        //
        //  (pre with suite)
        //         ^
        //         |<--------------------|
        //    (with suite)<--------------|
        //         ^                     |
        //         |    ContextManagerSwallowExceptionTarget
        //         |                     ^
        //         |          PostContextManagerLabel
        //         |                     ^
        //         |---------------------|
        //         |
        //   (after with)
        //
        // In addition to the ContextManagerSwallowExceptionTarget, we'll create
        // a second target called ContextManagerForwardExceptionTarget that forwards
        // exceptions to existing exception targets if they exist.
        const contextManagerSwallowExceptionTarget = this._createContextManagerLabel(node.withItems.map((item) => item.expression), !!node.isAsync, 
        /* blockIfSwallowsExceptions */ false);
        this._addAntecedent(contextManagerSwallowExceptionTarget, this._currentFlowNode);
        const contextManagerForwardExceptionTarget = this._createContextManagerLabel(node.withItems.map((item) => item.expression), !!node.isAsync, 
        /* blockIfSwallowsExceptions */ true);
        this._currentExceptTargets.forEach((exceptionTarget) => {
            this._addAntecedent(exceptionTarget, contextManagerForwardExceptionTarget);
        });
        const preWithSuiteNode = this._currentFlowNode;
        const postContextManagerLabel = this._createBranchLabel(preWithSuiteNode);
        this._addAntecedent(postContextManagerLabel, contextManagerSwallowExceptionTarget);
        postContextManagerLabel.affectedExpressions = this._trackCodeFlowExpressions(() => {
            this._useExceptTargets([contextManagerSwallowExceptionTarget, contextManagerForwardExceptionTarget], () => {
                this.walk(node.suite);
            });
            this._addAntecedent(postContextManagerLabel, this._currentFlowNode);
            this._currentFlowNode = postContextManagerLabel;
            // Model the call to `__exit__` as a potential exception generator.
            if (!this._isCodeUnreachable()) {
                this._addExceptTargets(this._currentFlowNode);
            }
            if (node.asyncToken && !this._fileInfo.ipythonMode) {
                // Top level async with is allowed in ipython mode.
                const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node);
                if (!enclosingFunction || !enclosingFunction.isAsync) {
                    this._addSyntaxError(localize_1.LocMessage.asyncNotInAsyncFunction(), node.asyncToken);
                }
            }
        });
        return false;
    }
    visitTernary(node) {
        const preTernaryFlowNode = this._currentFlowNode;
        const trueLabel = this._createBranchLabel();
        const falseLabel = this._createBranchLabel();
        const postExpressionLabel = this._createBranchLabel(preTernaryFlowNode);
        postExpressionLabel.affectedExpressions = this._trackCodeFlowExpressions(() => {
            // Handle the test expression.
            this._bindConditional(node.testExpression, trueLabel, falseLabel);
            // Handle the "true" portion (the "if" expression).
            this._currentFlowNode = this._finishFlowLabel(trueLabel);
            this.walk(node.ifExpression);
            this._addAntecedent(postExpressionLabel, this._currentFlowNode);
            // Handle the "false" portion (the "else" expression).
            this._currentFlowNode = this._finishFlowLabel(falseLabel);
            this.walk(node.elseExpression);
            this._addAntecedent(postExpressionLabel, this._currentFlowNode);
            this._currentFlowNode = this._finishFlowLabel(postExpressionLabel);
        });
        return false;
    }
    visitUnaryOperation(node) {
        if (node.operator === 38 /* OperatorType.Not */ && this._currentFalseTarget && this._currentTrueTarget) {
            // Swap the existing true/false targets.
            this._bindConditional(node.expression, this._currentFalseTarget, this._currentTrueTarget);
        }
        else {
            // Temporarily set the true/false targets to undefined because
            // this unary operation is not part of a chain of logical expressions
            // (AND/OR/NOT subexpressions).
            this._disableTrueFalseTargets(() => {
                // Evaluate the operand expression.
                this.walk(node.expression);
            });
        }
        return false;
    }
    visitBinaryOperation(node) {
        if (node.operator === 36 /* OperatorType.And */ || node.operator === 37 /* OperatorType.Or */) {
            let trueTarget = this._currentTrueTarget;
            let falseTarget = this._currentFalseTarget;
            let postRightLabel;
            if (!trueTarget || !falseTarget) {
                postRightLabel = this._createBranchLabel();
                trueTarget = falseTarget = postRightLabel;
            }
            const preRightLabel = this._createBranchLabel();
            if (node.operator === 36 /* OperatorType.And */) {
                this._bindConditional(node.leftExpression, preRightLabel, falseTarget);
            }
            else {
                this._bindConditional(node.leftExpression, trueTarget, preRightLabel);
            }
            this._currentFlowNode = this._finishFlowLabel(preRightLabel);
            this._bindConditional(node.rightExpression, trueTarget, falseTarget);
            if (postRightLabel) {
                this._currentFlowNode = this._finishFlowLabel(postRightLabel);
            }
        }
        else {
            // Temporarily set the true/false targets to undefined because
            // this binary operation is not part of a chain of logical expressions
            // (AND/OR/NOT subexpressions).
            this._disableTrueFalseTargets(() => {
                this.walk(node.leftExpression);
                this.walk(node.rightExpression);
            });
        }
        return false;
    }
    visitListComprehension(node) {
        const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node);
        // The first iterable is executed outside of the comprehension scope.
        if (node.forIfNodes.length > 0 && node.forIfNodes[0].nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
            this.walk(node.forIfNodes[0].iterableExpression);
        }
        this._createNewScope(0 /* ScopeType.ListComprehension */, this._getNonClassParentScope(), () => {
            var _a;
            AnalyzerNodeInfo.setScope(node, this._currentScope);
            const falseLabel = this._createBranchLabel();
            // We'll walk the forIfNodes list twice. The first time we'll
            // bind targets of for statements. The second time we'll walk
            // expressions and create the control flow graph.
            for (let i = 0; i < node.forIfNodes.length; i++) {
                const compr = node.forIfNodes[i];
                const addedSymbols = new Map();
                if (compr.nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
                    this._bindPossibleTupleNamedTarget(compr.targetExpression, addedSymbols);
                    this._addInferredTypeAssignmentForVariable(compr.targetExpression, compr);
                    // Async for is not allowed outside of an async function
                    // unless we're in ipython mode.
                    if (compr.asyncToken && !this._fileInfo.ipythonMode) {
                        if (!enclosingFunction || !enclosingFunction.isAsync) {
                            // Allow if it's within a generator expression. Execution of
                            // generator expressions is deferred and therefore can be
                            // run within the context of an async function later.
                            if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 31 /* ParseNodeType.List */) {
                                this._addSyntaxError(localize_1.LocMessage.asyncNotInAsyncFunction(), compr.asyncToken);
                            }
                        }
                    }
                }
            }
            for (let i = 0; i < node.forIfNodes.length; i++) {
                const compr = node.forIfNodes[i];
                if (compr.nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
                    // We already walked the first iterable expression above,
                    // so skip it here.
                    if (i !== 0) {
                        this.walk(compr.iterableExpression);
                    }
                    this._createAssignmentTargetFlowNodes(compr.targetExpression, 
                    /* walkTargets */ true, 
                    /* unbound */ false);
                }
                else {
                    const trueLabel = this._createBranchLabel();
                    this._bindConditional(compr.testExpression, trueLabel, falseLabel);
                    this._currentFlowNode = this._finishFlowLabel(trueLabel);
                }
            }
            this.walk(node.expression);
            this._addAntecedent(falseLabel, this._currentFlowNode);
            this._currentFlowNode = this._finishFlowLabel(falseLabel);
        });
        return false;
    }
    visitMatch(node) {
        // Evaluate the subject expression.
        this.walk(node.subjectExpression);
        const expressionList = [];
        const isSubjectNarrowable = this._isNarrowingExpression(node.subjectExpression, expressionList);
        if (isSubjectNarrowable) {
            expressionList.forEach((expr) => {
                const referenceKey = (0, codeFlowTypes_1.createKeyForReference)(expr);
                this._currentScopeCodeFlowExpressions.add(referenceKey);
            });
        }
        const postMatchLabel = this._createBranchLabel();
        let foundIrrefutableCase = false;
        // Model the match statement as a series of if/elif clauses
        // each of which tests for the specified pattern (and optionally
        // for the guard condition).
        node.cases.forEach((caseStatement) => {
            const postCaseLabel = this._createBranchLabel();
            const preGuardLabel = this._createBranchLabel();
            const preSuiteLabel = this._createBranchLabel();
            // Evaluate the pattern.
            this._addAntecedent(preGuardLabel, this._currentFlowNode);
            if (!caseStatement.isIrrefutable) {
                this._addAntecedent(postCaseLabel, this._currentFlowNode);
            }
            else if (!caseStatement.guardExpression) {
                foundIrrefutableCase = true;
            }
            this._currentFlowNode = this._finishFlowLabel(preGuardLabel);
            // Bind the pattern.
            this.walk(caseStatement.pattern);
            this._createFlowNarrowForPattern(node.subjectExpression, caseStatement);
            // Apply the guard expression.
            if (caseStatement.guardExpression) {
                this._bindConditional(caseStatement.guardExpression, preSuiteLabel, postCaseLabel);
            }
            else {
                this._addAntecedent(preSuiteLabel, this._currentFlowNode);
            }
            this._currentFlowNode = this._finishFlowLabel(preSuiteLabel);
            // Bind the body of the case statement.
            this.walk(caseStatement.suite);
            this._addAntecedent(postMatchLabel, this._currentFlowNode);
            this._currentFlowNode = this._finishFlowLabel(postCaseLabel);
        });
        // Add a final narrowing step for the subject expression for the entire
        // match statement. This will compute the narrowed type if no case
        // statements are matched.
        if (isSubjectNarrowable) {
            this._createFlowNarrowForPattern(node.subjectExpression, node);
        }
        // Create an "implied else" to conditionally gate code flow based on
        // whether the narrowed type of the subject expression is Never at this point.
        if (!foundIrrefutableCase) {
            this._createFlowExhaustedMatch(node);
        }
        this._addAntecedent(postMatchLabel, this._currentFlowNode);
        this._currentFlowNode = this._finishFlowLabel(postMatchLabel);
        return false;
    }
    visitPatternAs(node) {
        const postOrLabel = this._createBranchLabel();
        node.orPatterns.forEach((orPattern) => {
            this.walk(orPattern);
            this._addAntecedent(postOrLabel, this._currentFlowNode);
        });
        this._currentFlowNode = this._finishFlowLabel(postOrLabel);
        if (node.target) {
            this.walk(node.target);
            const symbol = this._bindNameToScope(this._currentScope, node.target);
            this._createAssignmentTargetFlowNodes(node.target, /* walkTargets */ false, /* unbound */ false);
            if (symbol) {
                const declaration = {
                    type: 1 /* DeclarationType.Variable */,
                    node: node.target,
                    isConstant: (0, symbolNameUtils_1.isConstantName)(node.target.value),
                    inferredTypeSource: node,
                    uri: this._fileInfo.fileUri,
                    range: (0, positionUtils_1.convertTextRangeToRange)(node.target, this._fileInfo.lines),
                    moduleName: this._fileInfo.moduleName,
                    isInExceptSuite: this._isInExceptSuite,
                };
                symbol.addDeclaration(declaration);
            }
        }
        return false;
    }
    visitPatternCapture(node) {
        if (!node.isWildcard) {
            this._addPatternCaptureTarget(node.target);
        }
        return true;
    }
    visitPatternMappingExpandEntry(node) {
        if (node.target.value !== '_') {
            this._addPatternCaptureTarget(node.target);
        }
        return true;
    }
    _formatModuleName(node) {
        return '.'.repeat(node.leadingDots) + node.nameParts.map((part) => part.value).join('.');
    }
    _removeActiveTypeParameters(node) {
        node.parameters.forEach((typeParamNode) => {
            const entry = this._activeTypeParams.get(typeParamNode.name.value);
            if (entry) {
                const decls = entry.symbol.getDeclarations();
                (0, debug_1.assert)(decls && decls.length === 1 && decls[0].type === 3 /* DeclarationType.TypeParameter */);
                if (decls[0].node === typeParamNode) {
                    this._activeTypeParams.delete(typeParamNode.name.value);
                }
            }
        });
    }
    _getNonClassParentScope() {
        // We may not be able to use the current scope if it's a class scope.
        // Walk up until we find a non-class scope instead.
        let parentScope = this._currentScope;
        while (parentScope.type === 2 /* ScopeType.Class */) {
            parentScope = parentScope.parent;
        }
        return parentScope;
    }
    _addSlotsToCurrentScope(slotNameNodes) {
        (0, debug_1.assert)(this._currentScope.type === 2 /* ScopeType.Class */);
        let slotsContainsDict = false;
        for (const slotNameNode of slotNameNodes) {
            const slotName = slotNameNode.strings[0].value;
            if (slotName === '__dict__') {
                slotsContainsDict = true;
                continue;
            }
            let symbol = this._currentScope.lookUpSymbol(slotName);
            if (!symbol) {
                symbol = this._currentScope.addSymbol(slotName, 1 /* SymbolFlags.InitiallyUnbound */ | 4 /* SymbolFlags.ClassMember */);
                const honorPrivateNaming = this._fileInfo.diagnosticRuleSet.reportPrivateUsage !== 'none';
                if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(slotName) && honorPrivateNaming) {
                    symbol.setIsPrivateMember();
                }
            }
            const declaration = {
                type: 1 /* DeclarationType.Variable */,
                node: slotNameNode,
                isConstant: (0, symbolNameUtils_1.isConstantName)(slotName),
                isDefinedBySlots: true,
                uri: this._fileInfo.fileUri,
                range: (0, positionUtils_1.convertTextRangeToRange)(slotNameNode, this._fileInfo.lines),
                moduleName: this._fileInfo.moduleName,
                isInExceptSuite: this._isInExceptSuite,
            };
            symbol.addDeclaration(declaration);
        }
        if (!slotsContainsDict) {
            this._currentScope.setSlotsNames(slotNameNodes.map((node) => node.strings[0].value));
        }
    }
    _isInListComprehension(node, ignoreOutermostIterable = false) {
        let curNode = node;
        let prevNode;
        let prevPrevNode;
        while (curNode) {
            if (curNode.nodeType === 32 /* ParseNodeType.ListComprehension */) {
                if (ignoreOutermostIterable && curNode.forIfNodes.length > 0) {
                    const outermostCompr = curNode.forIfNodes[0];
                    if (prevNode === outermostCompr && outermostCompr.nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
                        if (prevPrevNode === outermostCompr.iterableExpression) {
                            return false;
                        }
                    }
                }
                return true;
            }
            prevPrevNode = prevNode;
            prevNode = curNode;
            curNode = curNode.parent;
        }
        return false;
    }
    _addPatternCaptureTarget(target) {
        const symbol = this._bindNameToScope(this._currentScope, target);
        this._createAssignmentTargetFlowNodes(target, /* walkTargets */ false, /* unbound */ false);
        if (symbol) {
            const declaration = {
                type: 1 /* DeclarationType.Variable */,
                node: target,
                isConstant: (0, symbolNameUtils_1.isConstantName)(target.value),
                inferredTypeSource: target.parent,
                uri: this._fileInfo.fileUri,
                range: (0, positionUtils_1.convertTextRangeToRange)(target, this._fileInfo.lines),
                moduleName: this._fileInfo.moduleName,
                isInExceptSuite: this._isInExceptSuite,
            };
            symbol.addDeclaration(declaration);
        }
    }
    _useExceptTargets(targets, callback) {
        const prevExceptTargets = this._currentExceptTargets;
        this._currentExceptTargets = targets;
        callback();
        this._currentExceptTargets = prevExceptTargets;
    }
    // Attempts to resolve the module name, import it, and return
    // its __all__ symbols.
    _getDunderAllNamesFromImport(varName) {
        var _a, _b;
        const varSymbol = this._currentScope.lookUpSymbol(varName);
        if (!varSymbol) {
            return undefined;
        }
        // There should be only one declaration for the variable.
        const aliasDecl = varSymbol.getDeclarations().find((decl) => decl.type === 8 /* DeclarationType.Alias */);
        const resolvedUri = (aliasDecl === null || aliasDecl === void 0 ? void 0 : aliasDecl.uri) && !aliasDecl.uri.isEmpty() && aliasDecl.loadSymbolsFromPath
            ? aliasDecl.uri
            : ((_a = aliasDecl === null || aliasDecl === void 0 ? void 0 : aliasDecl.submoduleFallback) === null || _a === void 0 ? void 0 : _a.uri) &&
                !aliasDecl.submoduleFallback.uri.isEmpty() &&
                aliasDecl.submoduleFallback.loadSymbolsFromPath
                ? aliasDecl.submoduleFallback.uri
                : undefined;
        if (!resolvedUri) {
            return undefined;
        }
        let lookupInfo = this._fileInfo.importLookup(resolvedUri);
        if (lookupInfo === null || lookupInfo === void 0 ? void 0 : lookupInfo.dunderAllNames) {
            return lookupInfo.dunderAllNames;
        }
        if (((_b = aliasDecl === null || aliasDecl === void 0 ? void 0 : aliasDecl.submoduleFallback) === null || _b === void 0 ? void 0 : _b.uri) && !aliasDecl.submoduleFallback.uri.isEmpty()) {
            lookupInfo = this._fileInfo.importLookup(aliasDecl.submoduleFallback.uri);
            return lookupInfo === null || lookupInfo === void 0 ? void 0 : lookupInfo.dunderAllNames;
        }
        return undefined;
    }
    _addImplicitFromImport(node, importInfo) {
        const symbolName = node.module.nameParts[0].value;
        const symbol = this._bindNameValueToScope(this._currentScope, symbolName);
        if (symbol) {
            this._createAliasDeclarationForMultipartImportName(node, /* importAlias */ undefined, importInfo, symbol);
        }
        this._createFlowAssignment(node.module.nameParts[0]);
    }
    _createAliasDeclarationForMultipartImportName(node, importAlias, importInfo, symbol) {
        var _a;
        const firstNamePartValue = node.module.nameParts[0].value;
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
        // See if there's already a matching alias declaration for this import.
        // if so, we'll update it rather than creating a new one. This is required
        // to handle cases where multiple import statements target the same
        // starting symbol such as "import a.b.c" and "import a.d". In this case,
        // we'll build a single declaration that describes the combined actions
        // of both import statements, thus reflecting the behavior of the
        // python module loader.
        const existingDecl = symbol
            .getDeclarations()
            .find((decl) => decl.type === 8 /* DeclarationType.Alias */ && decl.firstNamePart === firstNamePartValue);
        let newDecl;
        let uriOfLastSubmodule;
        if (importInfo && importInfo.isImportFound && !importInfo.isNativeLib && importInfo.resolvedUris.length > 0) {
            uriOfLastSubmodule = importInfo.resolvedUris[importInfo.resolvedUris.length - 1];
        }
        else {
            uriOfLastSubmodule = declaration_1.UnresolvedModuleMarker;
        }
        const isResolved = importInfo && importInfo.isImportFound && !importInfo.isNativeLib && importInfo.resolvedUris.length > 0;
        if (existingDecl) {
            newDecl = existingDecl;
        }
        else if (isResolved) {
            newDecl = {
                type: 8 /* DeclarationType.Alias */,
                node,
                uri: uriOfLastSubmodule,
                loadSymbolsFromPath: false,
                range: (0, textRange_1.getEmptyRange)(),
                usesLocalName: !!importAlias,
                moduleName: importAlias
                    ? this._formatModuleName(node.module)
                    : '.'.repeat(node.module.leadingDots) + firstNamePartValue,
                firstNamePart: firstNamePartValue,
                isInExceptSuite: this._isInExceptSuite,
            };
        }
        else {
            // If we couldn't resolve the import, create a dummy declaration with a
            // bogus path so it gets an unknown type (rather than an unbound type) at
            // analysis time.
            newDecl = {
                type: 8 /* DeclarationType.Alias */,
                node,
                uri: uriOfLastSubmodule,
                loadSymbolsFromPath: true,
                range: (0, textRange_1.getEmptyRange)(),
                usesLocalName: !!importAlias,
                moduleName: (_a = importInfo === null || importInfo === void 0 ? void 0 : importInfo.importName) !== null && _a !== void 0 ? _a : '',
                firstNamePart: importAlias
                    ? this._formatModuleName(node.module)
                    : '.'.repeat(node.module.leadingDots) + firstNamePartValue,
                isUnresolved: true,
                isInExceptSuite: this._isInExceptSuite,
            };
        }
        // See if there is import info for this part of the path. This allows us
        // to implicitly import all of the modules in a multi-part module name.
        const implicitImportInfo = AnalyzerNodeInfo.getImportInfo(node.module.nameParts[0]);
        if (implicitImportInfo && implicitImportInfo.resolvedUris.length) {
            newDecl.uri = implicitImportInfo.resolvedUris[0];
            newDecl.loadSymbolsFromPath = true;
            this._addImplicitImportsToLoaderActions(implicitImportInfo, newDecl);
        }
        // Add the implicit imports for this module if it's the last
        // name part we're resolving.
        if (importAlias || node.module.nameParts.length === 1) {
            newDecl.uri = uriOfLastSubmodule;
            newDecl.loadSymbolsFromPath = true;
            newDecl.isUnresolved = false;
            if (importInfo) {
                this._addImplicitImportsToLoaderActions(importInfo, newDecl);
            }
        }
        else {
            // Fill in the remaining name parts.
            let curLoaderActions = newDecl;
            for (let i = 1; i < node.module.nameParts.length; i++) {
                const namePartValue = node.module.nameParts[i].value;
                // Is there an existing loader action for this name?
                let loaderActions = curLoaderActions.implicitImports
                    ? curLoaderActions.implicitImports.get(namePartValue)
                    : undefined;
                if (!loaderActions) {
                    const loaderActionPath = importInfo && i < importInfo.resolvedUris.length
                        ? importInfo.resolvedUris[i]
                        : declaration_1.UnresolvedModuleMarker;
                    // Allocate a new loader action.
                    loaderActions = {
                        uri: loaderActionPath,
                        loadSymbolsFromPath: false,
                        implicitImports: new Map(),
                        isUnresolved: !isResolved,
                    };
                    if (!curLoaderActions.implicitImports) {
                        curLoaderActions.implicitImports = new Map();
                    }
                    curLoaderActions.implicitImports.set(namePartValue, loaderActions);
                }
                if (i === node.module.nameParts.length - 1) {
                    // If this is the last name part we're resolving, add in the
                    // implicit imports as well.
                    if (importInfo && i < importInfo.resolvedUris.length) {
                        loaderActions.uri = importInfo.resolvedUris[i];
                        loaderActions.loadSymbolsFromPath = true;
                        this._addImplicitImportsToLoaderActions(importInfo, loaderActions);
                    }
                }
                else {
                    // If this isn't the last name part we're resolving, see if there
                    // is import info for this part of the path. This allows us to implicitly
                    // import all of the modules in a multi-part module name (e.g. "import a.b.c"
                    // imports "a" and "a.b" and "a.b.c").
                    const implicitImportInfo = AnalyzerNodeInfo.getImportInfo(node.module.nameParts[i]);
                    if (implicitImportInfo && implicitImportInfo.resolvedUris.length) {
                        loaderActions.uri = implicitImportInfo.resolvedUris[i];
                        loaderActions.loadSymbolsFromPath = true;
                        this._addImplicitImportsToLoaderActions(implicitImportInfo, loaderActions);
                    }
                }
                curLoaderActions = loaderActions;
            }
        }
        if (!existingDecl) {
            symbol.addDeclaration(newDecl);
        }
    }
    _getWildcardImportNames(lookupInfo) {
        const namesToImport = [];
        // If a dunder all symbol is defined, it takes precedence.
        if (lookupInfo.dunderAllNames) {
            if (!lookupInfo.usesUnsupportedDunderAllForm) {
                return lookupInfo.dunderAllNames;
            }
            (0, collectionUtils_1.appendArray)(namesToImport, lookupInfo.dunderAllNames);
        }
        lookupInfo.symbolTable.forEach((symbol, name) => {
            if (!symbol.isExternallyHidden() && !name.startsWith('_')) {
                namesToImport.push(name);
            }
        });
        return namesToImport;
    }
    _walkStatementsAndReportUnreachable(statements) {
        let foundUnreachableStatement = false;
        for (const statement of statements) {
            AnalyzerNodeInfo.setFlowNode(statement, this._currentFlowNode);
            if (!foundUnreachableStatement) {
                foundUnreachableStatement = this._isCodeUnreachable();
            }
            if (!foundUnreachableStatement) {
                this.walk(statement);
            }
            else {
                // If we're within a function, we need to look for unreachable yield
                // statements because they affect the behavior of the function (making
                // it a generator) even if they're never executed.
                if (this._targetFunctionDeclaration && !this._targetFunctionDeclaration.isGenerator) {
                    const yieldFinder = new YieldFinder();
                    if (yieldFinder.checkContainsYield(statement)) {
                        this._targetFunctionDeclaration.isGenerator = true;
                    }
                }
                // In case there are any class or function statements within this
                // subtree, we need to create dummy scopes for them. The type analyzer
                // depends on scopes being present.
                if (!this._moduleSymbolOnly) {
                    const dummyScopeGenerator = new DummyScopeGenerator(this._currentScope);
                    dummyScopeGenerator.walk(statement);
                }
            }
        }
        return false;
    }
    _createStartFlowNode() {
        const flowNode = {
            flags: codeFlowTypes_1.FlowFlags.Start,
            id: this._getUniqueFlowNodeId(),
        };
        return flowNode;
    }
    _createBranchLabel(preBranchAntecedent) {
        const flowNode = {
            flags: codeFlowTypes_1.FlowFlags.BranchLabel,
            id: this._getUniqueFlowNodeId(),
            antecedents: [],
            preBranchAntecedent,
            affectedExpressions: undefined,
        };
        return flowNode;
    }
    // Create a flow node that narrows the type of the subject expression for
    // a specified case statement or the entire match statement (if the flow
    // falls through the bottom of all cases).
    _createFlowNarrowForPattern(subjectExpression, statement) {
        const flowNode = {
            flags: codeFlowTypes_1.FlowFlags.NarrowForPattern,
            id: this._getUniqueFlowNodeId(),
            subjectExpression,
            statement,
            antecedent: this._currentFlowNode,
        };
        this._currentFlowNode = flowNode;
    }
    _createContextManagerLabel(expressions, isAsync, blockIfSwallowsExceptions) {
        const flowNode = {
            flags: codeFlowTypes_1.FlowFlags.PostContextManager | codeFlowTypes_1.FlowFlags.BranchLabel,
            id: this._getUniqueFlowNodeId(),
            antecedents: [],
            expressions,
            affectedExpressions: undefined,
            isAsync,
            blockIfSwallowsExceptions,
        };
        return flowNode;
    }
    _createLoopLabel() {
        const flowNode = {
            flags: codeFlowTypes_1.FlowFlags.LoopLabel,
            id: this._getUniqueFlowNodeId(),
            antecedents: [],
            affectedExpressions: undefined,
        };
        return flowNode;
    }
    _finishFlowLabel(node) {
        // If there were no antecedents, this is unreachable.
        if (node.antecedents.length === 0) {
            return Binder._unreachableFlowNode;
        }
        // If there was only one antecedent and this is a simple
        // branch label, there's no need for a label to exist.
        if (node.antecedents.length === 1 && node.flags === codeFlowTypes_1.FlowFlags.BranchLabel) {
            return node.antecedents[0];
        }
        // The cyclomatic complexity is the number of edges minus the
        // number of nodes in the graph. Add n-1 where n is the number
        // of antecedents (edges) and 1 represents the label node.
        this._codeFlowComplexity += node.antecedents.length - 1;
        return node;
    }
    // Creates a node that creates a "gate" that is closed (doesn't allow for code
    // flow) if the specified expression is never once it is narrowed (in either the
    // positive or negative case).
    _bindNeverCondition(node, target, isPositiveTest) {
        const expressionList = [];
        if (node.nodeType === 55 /* ParseNodeType.UnaryOperation */ && node.operator === 38 /* OperatorType.Not */) {
            this._bindNeverCondition(node.expression, target, !isPositiveTest);
        }
        else if (node.nodeType === 7 /* ParseNodeType.BinaryOperation */ &&
            (node.operator === 36 /* OperatorType.And */ || node.operator === 37 /* OperatorType.Or */)) {
            let isAnd = node.operator === 36 /* OperatorType.And */;
            if (isPositiveTest) {
                isAnd = !isAnd;
            }
            if (isAnd) {
                // In the And case, we need to gate the synthesized else clause if both
                // of the operands evaluate to never once they are narrowed.
                const savedCurrentFlowNode = this._currentFlowNode;
                this._bindNeverCondition(node.leftExpression, target, isPositiveTest);
                this._currentFlowNode = savedCurrentFlowNode;
                this._bindNeverCondition(node.rightExpression, target, isPositiveTest);
            }
            else {
                const initialCurrentFlowNode = this._currentFlowNode;
                // In the Or case, we need to gate the synthesized else clause if either
                // of the operands evaluate to never.
                const afterLabel = this._createBranchLabel();
                this._bindNeverCondition(node.leftExpression, afterLabel, isPositiveTest);
                // If the condition didn't result in any new flow nodes, we can skip
                // checking the other condition.
                if (initialCurrentFlowNode !== this._currentFlowNode) {
                    this._currentFlowNode = this._finishFlowLabel(afterLabel);
                    const prevCurrentNode = this._currentFlowNode;
                    this._bindNeverCondition(node.rightExpression, target, isPositiveTest);
                    // If the second condition resulted in no new control flow node, we can
                    // eliminate this entire subgraph.
                    if (prevCurrentNode === this._currentFlowNode) {
                        this._currentFlowNode = initialCurrentFlowNode;
                    }
                }
            }
        }
        else {
            // Limit only to expressions that contain a narrowable subexpression
            // that is a name. This avoids complexities with composite expressions like
            // member access or index expressions.
            if (this._isNarrowingExpression(node, expressionList, /* neverNarrowingExpressions */ true)) {
                const filteredExprList = expressionList.filter((expr) => expr.nodeType === 38 /* ParseNodeType.Name */);
                if (filteredExprList.length > 0) {
                    this._currentFlowNode = this._createFlowConditional(isPositiveTest ? codeFlowTypes_1.FlowFlags.TrueNeverCondition : codeFlowTypes_1.FlowFlags.FalseNeverCondition, this._currentFlowNode, node);
                }
            }
            this._addAntecedent(target, this._currentFlowNode);
        }
    }
    _bindConditional(node, trueTarget, falseTarget) {
        this._setTrueFalseTargets(trueTarget, falseTarget, () => {
            this.walk(node);
        });
        if (!this._isLogicalExpression(node)) {
            this._addAntecedent(trueTarget, this._createFlowConditional(codeFlowTypes_1.FlowFlags.TrueCondition, this._currentFlowNode, node));
            this._addAntecedent(falseTarget, this._createFlowConditional(codeFlowTypes_1.FlowFlags.FalseCondition, this._currentFlowNode, node));
        }
    }
    _disableTrueFalseTargets(callback) {
        this._setTrueFalseTargets(/* trueTarget */ undefined, /* falseTarget */ undefined, callback);
    }
    _setTrueFalseTargets(trueTarget, falseTarget, callback) {
        const savedTrueTarget = this._currentTrueTarget;
        const savedFalseTarget = this._currentFalseTarget;
        this._currentTrueTarget = trueTarget;
        this._currentFalseTarget = falseTarget;
        callback();
        this._currentTrueTarget = savedTrueTarget;
        this._currentFalseTarget = savedFalseTarget;
    }
    _createFlowConditional(flags, antecedent, expression) {
        if (antecedent.flags & codeFlowTypes_1.FlowFlags.Unreachable) {
            return antecedent;
        }
        const staticValue = StaticExpressions.evaluateStaticBoolLikeExpression(expression, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, this._typingImportAliases, this._sysImportAliases);
        if ((staticValue === true && flags & codeFlowTypes_1.FlowFlags.FalseCondition) ||
            (staticValue === false && flags & codeFlowTypes_1.FlowFlags.TrueCondition)) {
            return Binder._unreachableFlowNode;
        }
        const expressionList = [];
        if (!this._isNarrowingExpression(expression, expressionList, 
        /* filterForNeverNarrowing */ (flags &
            (codeFlowTypes_1.FlowFlags.TrueNeverCondition | codeFlowTypes_1.FlowFlags.FalseNeverCondition)) !==
            0)) {
            return antecedent;
        }
        expressionList.forEach((expr) => {
            const referenceKey = (0, codeFlowTypes_1.createKeyForReference)(expr);
            this._currentScopeCodeFlowExpressions.add(referenceKey);
        });
        // Select the first name expression.
        const filteredExprList = expressionList.filter((expr) => expr.nodeType === 38 /* ParseNodeType.Name */);
        const conditionalFlowNode = {
            flags,
            id: this._getUniqueFlowNodeId(),
            reference: filteredExprList.length > 0 ? filteredExprList[0] : undefined,
            expression,
            antecedent,
        };
        this._addExceptTargets(conditionalFlowNode);
        return conditionalFlowNode;
    }
    // Indicates whether the expression is a NOT, AND or OR expression.
    _isLogicalExpression(expression) {
        switch (expression.nodeType) {
            case 55 /* ParseNodeType.UnaryOperation */: {
                return expression.operator === 38 /* OperatorType.Not */;
            }
            case 7 /* ParseNodeType.BinaryOperation */: {
                return expression.operator === 36 /* OperatorType.And */ || expression.operator === 37 /* OperatorType.Or */;
            }
        }
        return false;
    }
    // Determines whether the specified expression can be used for conditional
    // type narrowing. The expression atoms (names, member accesses and index)
    // are provided as an output in the expressionList.
    // If filterForNeverNarrowing is true, we limit some types of narrowing
    // expressions for performance reasons.
    // The isComplexExpression parameter is used internally to determine whether
    // the call is an atom (name, member access, index - plus a "not" form of
    // these) or something more complex (binary operator, call, etc.).
    _isNarrowingExpression(expression, expressionList, filterForNeverNarrowing = false, isComplexExpression = false) {
        switch (expression.nodeType) {
            case 38 /* ParseNodeType.Name */:
            case 35 /* ParseNodeType.MemberAccess */:
            case 24 /* ParseNodeType.Index */: {
                if (filterForNeverNarrowing) {
                    // Never narrowing doesn't support member access or index
                    // expressions.
                    if (expression.nodeType !== 38 /* ParseNodeType.Name */) {
                        return false;
                    }
                    // Never narrowing doesn't support simple names (falsy
                    // or truthy narrowing) because it's too expensive and
                    // provides relatively little utility.
                    if (!isComplexExpression) {
                        return false;
                    }
                }
                if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(expression)) {
                    expressionList.push(expression);
                    if (!filterForNeverNarrowing) {
                        // If the expression is a member access expression, add its
                        // leftExpression to the expression list because that expression
                        // can be narrowed based on the attribute type.
                        if (expression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                            if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(expression.leftExpression)) {
                                expressionList.push(expression.leftExpression);
                            }
                        }
                        // If the expression is an index expression with a supported
                        // subscript, add its baseExpression to the expression list because
                        // that expression can be narrowed.
                        if (expression.nodeType === 24 /* ParseNodeType.Index */ &&
                            expression.items.length === 1 &&
                            !expression.trailingComma &&
                            expression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */) {
                            if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(expression.baseExpression)) {
                                expressionList.push(expression.baseExpression);
                            }
                        }
                    }
                    return true;
                }
                return false;
            }
            case 4 /* ParseNodeType.AssignmentExpression */: {
                expressionList.push(expression.name);
                this._isNarrowingExpression(expression.rightExpression, expressionList, filterForNeverNarrowing, 
                /* isComplexExpression */ true);
                return true;
            }
            case 7 /* ParseNodeType.BinaryOperation */: {
                const isOrIsNotOperator = expression.operator === 39 /* OperatorType.Is */ || expression.operator === 40 /* OperatorType.IsNot */;
                const equalsOrNotEqualsOperator = expression.operator === 12 /* OperatorType.Equals */ || expression.operator === 28 /* OperatorType.NotEquals */;
                if (isOrIsNotOperator || equalsOrNotEqualsOperator) {
                    // Look for "X is None", "X is not None", "X == None", "X != None".
                    // These are commonly-used patterns used in control flow.
                    if (expression.rightExpression.nodeType === 11 /* ParseNodeType.Constant */ &&
                        expression.rightExpression.constType === 26 /* KeywordType.None */) {
                        return this._isNarrowingExpression(expression.leftExpression, expressionList, filterForNeverNarrowing, 
                        /* isComplexExpression */ true);
                    }
                    // Look for "type(X) is Y" or "type(X) is not Y".
                    if (isOrIsNotOperator &&
                        expression.leftExpression.nodeType === 9 /* ParseNodeType.Call */ &&
                        expression.leftExpression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                        expression.leftExpression.leftExpression.value === 'type' &&
                        expression.leftExpression.arguments.length === 1 &&
                        expression.leftExpression.arguments[0].argumentCategory === 0 /* ArgumentCategory.Simple */) {
                        return this._isNarrowingExpression(expression.leftExpression.arguments[0].valueExpression, expressionList, filterForNeverNarrowing, 
                        /* isComplexExpression */ true);
                    }
                    const isLeftNarrowing = this._isNarrowingExpression(expression.leftExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                    // Look for "X is Y" or "X is not Y".
                    // Look for X == <literal> or X != <literal>
                    // Look for len(X) == <literal> or len(X) != <literal>
                    return isLeftNarrowing;
                }
                // Look for len(X) < <literal>, len(X) <= <literal>, len(X) > <literal>, len(X) >= <literal>.
                if (expression.rightExpression.nodeType === 40 /* ParseNodeType.Number */ &&
                    expression.rightExpression.isInteger) {
                    if (expression.operator === 20 /* OperatorType.LessThan */ ||
                        expression.operator === 21 /* OperatorType.LessThanOrEqual */ ||
                        expression.operator === 15 /* OperatorType.GreaterThan */ ||
                        expression.operator === 16 /* OperatorType.GreaterThanOrEqual */) {
                        const isLeftNarrowing = this._isNarrowingExpression(expression.leftExpression, expressionList, filterForNeverNarrowing, 
                        /* isComplexExpression */ true);
                        return isLeftNarrowing;
                    }
                }
                // Look for "<string> in Y" or "<string> not in Y".
                if (expression.operator === 41 /* OperatorType.In */ || expression.operator === 42 /* OperatorType.NotIn */) {
                    if (expression.leftExpression.nodeType === 48 /* ParseNodeType.StringList */ &&
                        this._isNarrowingExpression(expression.rightExpression, expressionList, filterForNeverNarrowing, 
                        /* isComplexExpression */ true)) {
                        return true;
                    }
                }
                // Look for "X in Y" or "X not in Y".
                if (expression.operator === 41 /* OperatorType.In */ || expression.operator === 42 /* OperatorType.NotIn */) {
                    const isLeftNarrowable = this._isNarrowingExpression(expression.leftExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                    const isRightNarrowable = this._isNarrowingExpression(expression.rightExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                    return isLeftNarrowable || isRightNarrowable;
                }
                return false;
            }
            case 55 /* ParseNodeType.UnaryOperation */: {
                return (expression.operator === 38 /* OperatorType.Not */ &&
                    this._isNarrowingExpression(expression.expression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ false));
            }
            case 5 /* ParseNodeType.AugmentedAssignment */: {
                return this._isNarrowingExpression(expression.rightExpression, expressionList, filterForNeverNarrowing, 
                /* isComplexExpression */ true);
            }
            case 9 /* ParseNodeType.Call */: {
                if (expression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    (expression.leftExpression.value === 'isinstance' ||
                        expression.leftExpression.value === 'issubclass') &&
                    expression.arguments.length === 2) {
                    return this._isNarrowingExpression(expression.arguments[0].valueExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                }
                if (expression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    expression.leftExpression.value === 'callable' &&
                    expression.arguments.length === 1) {
                    return this._isNarrowingExpression(expression.arguments[0].valueExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                }
                // Is this potentially a call to a user-defined type guard function?
                if (expression.arguments.length >= 1) {
                    // Never narrowing doesn't support type guards because they do not
                    // offer negative narrowing.
                    if (filterForNeverNarrowing) {
                        return false;
                    }
                    return this._isNarrowingExpression(expression.arguments[0].valueExpression, expressionList, filterForNeverNarrowing, 
                    /* isComplexExpression */ true);
                }
            }
        }
        return false;
    }
    _createAssignmentTargetFlowNodes(target, walkTargets, unbound) {
        switch (target.nodeType) {
            case 38 /* ParseNodeType.Name */:
            case 35 /* ParseNodeType.MemberAccess */: {
                this._createFlowAssignment(target, unbound);
                if (walkTargets) {
                    this.walk(target);
                }
                break;
            }
            case 24 /* ParseNodeType.Index */: {
                this._createFlowAssignment(target, unbound);
                if (walkTargets) {
                    this.walk(target);
                }
                break;
            }
            case 52 /* ParseNodeType.Tuple */: {
                target.expressions.forEach((expr) => {
                    this._createAssignmentTargetFlowNodes(expr, walkTargets, unbound);
                });
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                this._createAssignmentTargetFlowNodes(target.valueExpression, /* walkTargets */ false, unbound);
                if (walkTargets) {
                    this.walk(target);
                }
                break;
            }
            case 56 /* ParseNodeType.Unpack */: {
                this._createAssignmentTargetFlowNodes(target.expression, /* walkTargets */ false, unbound);
                if (walkTargets) {
                    this.walk(target);
                }
                break;
            }
            case 31 /* ParseNodeType.List */: {
                target.entries.forEach((entry) => {
                    this._createAssignmentTargetFlowNodes(entry, walkTargets, unbound);
                });
                break;
            }
            default: {
                if (walkTargets) {
                    this.walk(target);
                }
            }
        }
    }
    _createCallFlowNode(node) {
        if (!this._isCodeUnreachable()) {
            this._addExceptTargets(this._currentFlowNode);
            const flowNode = {
                flags: codeFlowTypes_1.FlowFlags.Call,
                id: this._getUniqueFlowNodeId(),
                node,
                antecedent: this._currentFlowNode,
            };
            this._currentFlowNode = flowNode;
        }
    }
    _createVariableAnnotationFlowNode() {
        if (!this._isCodeUnreachable()) {
            const flowNode = {
                flags: codeFlowTypes_1.FlowFlags.VariableAnnotation,
                id: this._getUniqueFlowNodeId(),
                antecedent: this._currentFlowNode,
            };
            this._currentFlowNode = flowNode;
        }
    }
    _createFlowAssignment(node, unbound = false) {
        let targetSymbolId = symbol_1.indeterminateSymbolId;
        if (node.nodeType === 38 /* ParseNodeType.Name */) {
            const symbolWithScope = this._currentScope.lookUpSymbolRecursive(node.value);
            (0, debug_1.assert)(symbolWithScope !== undefined);
            targetSymbolId = symbolWithScope.symbol.id;
        }
        const prevFlowNode = this._currentFlowNode;
        if (!this._isCodeUnreachable() && (0, codeFlowTypes_1.isCodeFlowSupportedForReference)(node)) {
            const flowNode = {
                flags: codeFlowTypes_1.FlowFlags.Assignment,
                id: this._getUniqueFlowNodeId(),
                node,
                antecedent: this._currentFlowNode,
                targetSymbolId,
            };
            const referenceKey = (0, codeFlowTypes_1.createKeyForReference)(node);
            this._currentScopeCodeFlowExpressions.add(referenceKey);
            if (unbound) {
                flowNode.flags |= codeFlowTypes_1.FlowFlags.Unbind;
            }
            // Assume that an assignment to a member access expression
            // can potentially generate an exception.
            if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                this._addExceptTargets(flowNode);
            }
            this._currentFlowNode = flowNode;
        }
        // If we're marking the node as unbound and there is already a flow node
        // associated with the node, don't replace it. This case applies for symbols
        // introduced in except clauses. If there is no use the previous flow node
        // associated, use the previous flow node (applies in the del case).
        // Otherwise, the node will be evaluated as unbound at this point in the flow.
        if (!unbound || AnalyzerNodeInfo.getFlowNode(node) === undefined) {
            AnalyzerNodeInfo.setFlowNode(node, unbound ? prevFlowNode : this._currentFlowNode);
        }
    }
    _createFlowWildcardImport(node, names) {
        if (!this._isCodeUnreachable()) {
            const flowNode = {
                flags: codeFlowTypes_1.FlowFlags.WildcardImport,
                id: this._getUniqueFlowNodeId(),
                node,
                names,
                antecedent: this._currentFlowNode,
            };
            this._addExceptTargets(flowNode);
            this._currentFlowNode = flowNode;
        }
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
    }
    _createFlowExhaustedMatch(node) {
        if (!this._isCodeUnreachable()) {
            const flowNode = {
                flags: codeFlowTypes_1.FlowFlags.ExhaustedMatch,
                id: this._getUniqueFlowNodeId(),
                node,
                antecedent: this._currentFlowNode,
                subjectExpression: node.subjectExpression,
            };
            this._currentFlowNode = flowNode;
        }
        AnalyzerNodeInfo.setAfterFlowNode(node, this._currentFlowNode);
    }
    _isCodeUnreachable() {
        return !!(this._currentFlowNode.flags & codeFlowTypes_1.FlowFlags.Unreachable);
    }
    _addExceptTargets(flowNode) {
        // If there are any except targets, then we're in a try block, and we
        // have to assume that an exception can be raised after every assignment.
        if (this._currentExceptTargets) {
            this._currentExceptTargets.forEach((label) => {
                this._addAntecedent(label, flowNode);
            });
        }
    }
    _trackCodeFlowExpressions(callback) {
        const savedExpressions = this._currentScopeCodeFlowExpressions;
        this._currentScopeCodeFlowExpressions = new Set();
        callback();
        const scopedExpressions = this._currentScopeCodeFlowExpressions;
        if (savedExpressions) {
            this._currentScopeCodeFlowExpressions.forEach((value) => {
                savedExpressions.add(value);
            });
        }
        this._currentScopeCodeFlowExpressions = savedExpressions;
        return scopedExpressions;
    }
    _bindLoopStatement(preLoopLabel, postLoopLabel, callback) {
        const savedContinueTarget = this._currentContinueTarget;
        const savedBreakTarget = this._currentBreakTarget;
        this._currentContinueTarget = preLoopLabel;
        this._currentBreakTarget = postLoopLabel;
        preLoopLabel.affectedExpressions = this._trackCodeFlowExpressions(callback);
        this._currentContinueTarget = savedContinueTarget;
        this._currentBreakTarget = savedBreakTarget;
    }
    _addAntecedent(label, antecedent) {
        if (!(this._currentFlowNode.flags & codeFlowTypes_1.FlowFlags.Unreachable)) {
            // Don't add the same antecedent twice.
            if (!label.antecedents.some((existing) => existing.id === antecedent.id)) {
                label.antecedents.push(antecedent);
            }
        }
    }
    _bindNameToScope(scope, node, addedSymbols) {
        return this._bindNameValueToScope(scope, node.value, addedSymbols);
    }
    _bindNameValueToScope(scope, name, addedSymbols) {
        // Is this name already bound to a scope other than the local one?
        const bindingType = this._currentScope.getBindingType(name);
        if (bindingType !== undefined) {
            const scopeToUse = bindingType === 0 /* NameBindingType.Nonlocal */
                ? this._currentScope.parent
                : this._currentScope.getGlobalScope().scope;
            const symbolWithScope = scopeToUse.lookUpSymbolRecursive(name);
            if (symbolWithScope) {
                return symbolWithScope.symbol;
            }
        }
        else {
            // Don't overwrite an existing symbol.
            let symbol = scope.lookUpSymbol(name);
            if (!symbol) {
                symbol = scope.addSymbol(name, 1 /* SymbolFlags.InitiallyUnbound */ | 4 /* SymbolFlags.ClassMember */);
                if (this._currentScope.type === 3 /* ScopeType.Module */ || this._currentScope.type === 4 /* ScopeType.Builtin */) {
                    if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(name)) {
                        if ((0, symbolNameUtils_1.isPrivateName)(name)) {
                            // Private names are obscured, so they are always externally hidden.
                            symbol.setIsExternallyHidden();
                        }
                        else if (this._fileInfo.isStubFile || this._fileInfo.isInPyTypedPackage) {
                            if (this._currentScope.type === 4 /* ScopeType.Builtin */) {
                                // Don't include private-named symbols in the builtin scope.
                                symbol.setIsExternallyHidden();
                            }
                            else {
                                this._potentialPrivateSymbols.set(name, symbol);
                            }
                        }
                        else {
                            symbol.setIsPrivateMember();
                        }
                    }
                }
                if (addedSymbols) {
                    addedSymbols.set(name, symbol);
                }
            }
            return symbol;
        }
        return undefined;
    }
    _bindPossibleTupleNamedTarget(target, addedSymbols) {
        switch (target.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                this._bindNameToScope(this._currentScope, target, addedSymbols);
                break;
            }
            case 52 /* ParseNodeType.Tuple */: {
                target.expressions.forEach((expr) => {
                    this._bindPossibleTupleNamedTarget(expr, addedSymbols);
                });
                break;
            }
            case 31 /* ParseNodeType.List */: {
                target.entries.forEach((expr) => {
                    this._bindPossibleTupleNamedTarget(expr, addedSymbols);
                });
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                this._bindPossibleTupleNamedTarget(target.valueExpression, addedSymbols);
                break;
            }
            case 56 /* ParseNodeType.Unpack */: {
                this._bindPossibleTupleNamedTarget(target.expression, addedSymbols);
                break;
            }
        }
    }
    _addImplicitSymbolToCurrentScope(nameValue, node, type) {
        const symbol = this._addSymbolToCurrentScope(nameValue, /* isInitiallyUnbound */ false);
        if (symbol) {
            symbol.addDeclaration({
                type: 0 /* DeclarationType.Intrinsic */,
                node,
                intrinsicType: type,
                uri: this._fileInfo.fileUri,
                range: (0, textRange_1.getEmptyRange)(),
                moduleName: this._fileInfo.moduleName,
                isInExceptSuite: this._isInExceptSuite,
            });
            symbol.setIsIgnoredForProtocolMatch();
        }
    }
    // Adds a new symbol with the specified name if it doesn't already exist.
    _addSymbolToCurrentScope(nameValue, isInitiallyUnbound) {
        let symbol = this._currentScope.lookUpSymbol(nameValue);
        if (!symbol) {
            let symbolFlags = 0 /* SymbolFlags.None */;
            if (isInitiallyUnbound) {
                symbolFlags |= 1 /* SymbolFlags.InitiallyUnbound */;
            }
            if (this._currentScope.type === 2 /* ScopeType.Class */) {
                symbolFlags |= 4 /* SymbolFlags.ClassMember */;
            }
            if (this._fileInfo.isStubFile && (0, symbolNameUtils_1.isPrivateOrProtectedName)(nameValue)) {
                symbolFlags |= 2 /* SymbolFlags.ExternallyHidden */;
            }
            // Add the symbol. Assume that symbols with a default type source ID
            // are "implicit" symbols added to the scope. These are not initially unbound.
            symbol = this._currentScope.addSymbol(nameValue, symbolFlags);
        }
        return symbol;
    }
    _createNewScope(scopeType, parentScope, callback) {
        const prevScope = this._currentScope;
        const newScope = new scope_1.Scope(scopeType, parentScope);
        this._currentScope = newScope;
        // If this scope is an execution scope, allocate a new reference map.
        const isExecutionScope = scopeType === 4 /* ScopeType.Builtin */ || scopeType === 3 /* ScopeType.Module */ || scopeType === 1 /* ScopeType.Function */;
        const prevExpressions = this._currentScopeCodeFlowExpressions;
        if (isExecutionScope) {
            this._currentScopeCodeFlowExpressions = new Set();
        }
        callback();
        this._currentScopeCodeFlowExpressions = prevExpressions;
        this._currentScope = prevScope;
        return newScope;
    }
    _addInferredTypeAssignmentForVariable(target, source, isPossibleTypeAlias = false) {
        switch (target.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                const name = target;
                const symbolWithScope = this._currentScope.lookUpSymbolRecursive(name.value);
                if (symbolWithScope && symbolWithScope.symbol) {
                    const declaration = {
                        type: 1 /* DeclarationType.Variable */,
                        node: target,
                        isConstant: (0, symbolNameUtils_1.isConstantName)(target.value),
                        inferredTypeSource: source,
                        isInferenceAllowedInPyTyped: this._isInferenceAllowedInPyTyped(name.value),
                        typeAliasName: isPossibleTypeAlias ? target : undefined,
                        uri: this._fileInfo.fileUri,
                        range: (0, positionUtils_1.convertTextRangeToRange)(name, this._fileInfo.lines),
                        moduleName: this._fileInfo.moduleName,
                        isInExceptSuite: this._isInExceptSuite,
                        docString: this._getVariableDocString(target),
                    };
                    symbolWithScope.symbol.addDeclaration(declaration);
                }
                break;
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                const memberAccessInfo = this._getMemberAccessInfo(target);
                if (memberAccessInfo) {
                    const name = target.memberName;
                    let symbol = memberAccessInfo.classScope.lookUpSymbol(name.value);
                    if (!symbol) {
                        symbol = memberAccessInfo.classScope.addSymbol(name.value, 1 /* SymbolFlags.InitiallyUnbound */);
                        const honorPrivateNaming = this._fileInfo.diagnosticRuleSet.reportPrivateUsage !== 'none';
                        if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(name.value) && honorPrivateNaming) {
                            symbol.setIsPrivateMember();
                        }
                    }
                    if (memberAccessInfo.isInstanceMember) {
                        // If a method (which has a declared type) is being overwritten
                        // by an expression with no declared type, don't mark it as
                        // an instance member because the type evaluator will think
                        // that it doesn't need to perform object binding.
                        if (!symbol.isClassMember() ||
                            !symbol
                                .getDeclarations()
                                .some((decl) => decl.type === 5 /* DeclarationType.Function */ && decl.isMethod)) {
                            symbol.setIsInstanceMember();
                        }
                    }
                    else {
                        symbol.setIsClassMember();
                    }
                    const declaration = {
                        type: 1 /* DeclarationType.Variable */,
                        node: target.memberName,
                        isConstant: (0, symbolNameUtils_1.isConstantName)(name.value),
                        inferredTypeSource: source,
                        isDefinedByMemberAccess: true,
                        uri: this._fileInfo.fileUri,
                        range: (0, positionUtils_1.convertTextRangeToRange)(target.memberName, this._fileInfo.lines),
                        moduleName: this._fileInfo.moduleName,
                        isInExceptSuite: this._isInExceptSuite,
                        docString: this._getVariableDocString(target),
                    };
                    symbol.addDeclaration(declaration);
                }
                break;
            }
            case 52 /* ParseNodeType.Tuple */: {
                target.expressions.forEach((expr) => {
                    this._addInferredTypeAssignmentForVariable(expr, source);
                });
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                this._addInferredTypeAssignmentForVariable(target.valueExpression, source);
                break;
            }
            case 56 /* ParseNodeType.Unpack */: {
                this._addInferredTypeAssignmentForVariable(target.expression, source);
                break;
            }
            case 31 /* ParseNodeType.List */: {
                target.entries.forEach((entry) => {
                    this._addInferredTypeAssignmentForVariable(entry, source);
                });
                break;
            }
        }
    }
    _isInferenceAllowedInPyTyped(symbolName) {
        const exemptSymbols = ['__match_args__', '__slots__', '__all__'];
        return exemptSymbols.some((name) => name === symbolName);
    }
    _addTypeDeclarationForVariable(target, typeAnnotation) {
        var _a, _b, _c;
        let declarationHandled = false;
        switch (target.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                const name = target;
                const symbolWithScope = this._currentScope.lookUpSymbolRecursive(name.value);
                if (symbolWithScope && symbolWithScope.symbol) {
                    const finalInfo = this._isAnnotationFinal(typeAnnotation);
                    let typeAnnotationNode = typeAnnotation;
                    if (finalInfo.isFinal) {
                        if (!finalInfo.finalTypeNode) {
                            typeAnnotationNode = undefined;
                        }
                    }
                    // Is this annotation indicating that the variable is a "ClassVar"?
                    const classVarInfo = this._isAnnotationClassVar(typeAnnotation);
                    if (classVarInfo.isClassVar) {
                        if (!classVarInfo.classVarTypeNode) {
                            typeAnnotationNode = undefined;
                        }
                    }
                    // PEP 591 indicates that a Final variable initialized within a class
                    // body should also be considered a ClassVar unless it's in a dataclass.
                    // We can't tell at this stage whether it's a dataclass, so we'll simply
                    // record whether it's a Final assigned in a class body.
                    let isFinalAssignedInClassBody = false;
                    if (finalInfo.isFinal) {
                        const containingClass = ParseTreeUtils.getEnclosingClassOrFunction(target);
                        if (containingClass && containingClass.nodeType === 10 /* ParseNodeType.Class */) {
                            // Make sure it's part of an assignment.
                            if (((_a = target.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */ ||
                                ((_c = (_b = target.parent) === null || _b === void 0 ? void 0 : _b.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 3 /* ParseNodeType.Assignment */) {
                                isFinalAssignedInClassBody = true;
                            }
                        }
                    }
                    const declaration = {
                        type: 1 /* DeclarationType.Variable */,
                        node: target,
                        isConstant: (0, symbolNameUtils_1.isConstantName)(name.value),
                        isFinal: finalInfo.isFinal,
                        typeAliasName: target,
                        uri: this._fileInfo.fileUri,
                        typeAnnotationNode,
                        range: (0, positionUtils_1.convertTextRangeToRange)(name, this._fileInfo.lines),
                        moduleName: this._fileInfo.moduleName,
                        isInExceptSuite: this._isInExceptSuite,
                        docString: this._getVariableDocString(target),
                    };
                    symbolWithScope.symbol.addDeclaration(declaration);
                    if (isFinalAssignedInClassBody) {
                        symbolWithScope.symbol.setIsFinalVarInClassBody();
                    }
                    if (classVarInfo.isClassVar) {
                        symbolWithScope.symbol.setIsClassVar();
                    }
                    else if (!isFinalAssignedInClassBody) {
                        symbolWithScope.symbol.setIsInstanceMember();
                    }
                    // Look for an 'InitVar' either by itself or wrapped in an 'Annotated'.
                    if (typeAnnotation.nodeType === 24 /* ParseNodeType.Index */) {
                        if (this._isDataclassesAnnotation(typeAnnotation.baseExpression, 'InitVar')) {
                            symbolWithScope.symbol.setIsInitVar();
                        }
                        else if (this._isTypingAnnotation(typeAnnotation.baseExpression, 'Annotated') &&
                            typeAnnotation.items.length > 0) {
                            const item0Expr = typeAnnotation.items[0].valueExpression;
                            if (item0Expr.nodeType === 24 /* ParseNodeType.Index */ &&
                                this._isDataclassesAnnotation(item0Expr.baseExpression, 'InitVar')) {
                                symbolWithScope.symbol.setIsInitVar();
                            }
                        }
                    }
                }
                declarationHandled = true;
                break;
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                // We need to determine whether this expression is declaring a class or
                // instance variable. This is difficult because python doesn't provide
                // a keyword for accessing "this". Instead, it uses naming conventions
                // of "cls" and "self", but we don't want to rely on these naming
                // conventions here. Instead, we'll apply some heuristics to determine
                // whether the symbol on the LHS is a reference to the current class
                // or an instance of the current class.
                const memberAccessInfo = this._getMemberAccessInfo(target);
                if (memberAccessInfo) {
                    const name = target.memberName;
                    let symbol = memberAccessInfo.classScope.lookUpSymbol(name.value);
                    if (!symbol) {
                        symbol = memberAccessInfo.classScope.addSymbol(name.value, 1 /* SymbolFlags.InitiallyUnbound */);
                        const honorPrivateNaming = this._fileInfo.diagnosticRuleSet.reportPrivateUsage !== 'none';
                        if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(name.value) && honorPrivateNaming) {
                            symbol.setIsPrivateMember();
                        }
                    }
                    if (memberAccessInfo.isInstanceMember) {
                        symbol.setIsInstanceMember();
                    }
                    else {
                        symbol.setIsClassMember();
                    }
                    const finalInfo = this._isAnnotationFinal(typeAnnotation);
                    const declaration = {
                        type: 1 /* DeclarationType.Variable */,
                        node: target.memberName,
                        isConstant: (0, symbolNameUtils_1.isConstantName)(name.value),
                        isDefinedByMemberAccess: true,
                        isFinal: finalInfo.isFinal,
                        uri: this._fileInfo.fileUri,
                        typeAnnotationNode: finalInfo.isFinal && !finalInfo.finalTypeNode ? undefined : typeAnnotation,
                        range: (0, positionUtils_1.convertTextRangeToRange)(target.memberName, this._fileInfo.lines),
                        moduleName: this._fileInfo.moduleName,
                        isInExceptSuite: this._isInExceptSuite,
                        docString: this._getVariableDocString(target),
                    };
                    symbol.addDeclaration(declaration);
                    declarationHandled = true;
                }
                break;
            }
        }
        if (!declarationHandled) {
            this._addDiagnostic(this._fileInfo.diagnosticRuleSet.reportInvalidTypeForm, diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.annotationNotSupported(), typeAnnotation);
        }
    }
    // Determines whether the expression refers to a type exported by the typing
    // or typing_extensions modules. We can directly evaluate the types at binding
    // time. We assume here that the code isn't making use of some custom type alias
    // to refer to the typing types.
    _isTypingAnnotation(typeAnnotation, name) {
        return this._isKnownAnnotation(typeAnnotation, name, this._typingImportAliases, this._typingSymbolAliases);
    }
    _isDataclassesAnnotation(typeAnnotation, name) {
        return this._isKnownAnnotation(typeAnnotation, name, this._dataclassesImportAliases, this._dataclassesSymbolAliases);
    }
    _isKnownAnnotation(typeAnnotation, name, importAliases, symbolAliases) {
        let annotationNode = typeAnnotation;
        // Is this a quoted annotation?
        if (annotationNode.nodeType === 48 /* ParseNodeType.StringList */ && annotationNode.typeAnnotation) {
            annotationNode = annotationNode.typeAnnotation;
        }
        if (annotationNode.nodeType === 38 /* ParseNodeType.Name */) {
            const alias = symbolAliases.get(annotationNode.value);
            if (alias === name) {
                return true;
            }
        }
        else if (annotationNode.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            if (annotationNode.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                annotationNode.memberName.value === name) {
                const baseName = annotationNode.leftExpression.value;
                return importAliases.some((alias) => alias === baseName);
            }
        }
        return false;
    }
    _getVariableDocString(node) {
        const docNode = ParseTreeUtils.getVariableDocStringNode(node);
        if (!docNode) {
            return undefined;
        }
        // A docstring can consist of multiple joined strings in a single expression.
        const strings = docNode.strings;
        if (strings.length === 1) {
            // Common case.
            return strings[0].value;
        }
        return strings.map((s) => s.value).join('');
    }
    // Determines if the specified type annotation expression is a "Final".
    // It returns a value indicating whether the expression is a "Final"
    // expression and whether it's a "raw" Final with no type arguments.
    _isAnnotationFinal(typeAnnotation) {
        let isFinal = false;
        let finalTypeNode;
        if (typeAnnotation) {
            if (this._isTypingAnnotation(typeAnnotation, 'Final')) {
                isFinal = true;
            }
            else if (typeAnnotation.nodeType === 24 /* ParseNodeType.Index */ && typeAnnotation.items.length === 1) {
                // Recursively call to see if the base expression is "Final".
                const finalInfo = this._isAnnotationFinal(typeAnnotation.baseExpression);
                if (finalInfo.isFinal &&
                    typeAnnotation.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                    !typeAnnotation.items[0].name &&
                    !typeAnnotation.trailingComma) {
                    isFinal = true;
                    finalTypeNode = typeAnnotation.items[0].valueExpression;
                }
            }
        }
        return { isFinal, finalTypeNode };
    }
    // Determines if the specified type annotation expression is a "ClassVar".
    // It returns a value indicating whether the expression is a "ClassVar"
    // expression and whether it's a "raw" ClassVar with no type arguments.
    _isAnnotationClassVar(typeAnnotation) {
        let isClassVar = false;
        let classVarTypeNode;
        while (typeAnnotation) {
            // Is this a quoted annotation?
            if (typeAnnotation.nodeType === 48 /* ParseNodeType.StringList */ && typeAnnotation.typeAnnotation) {
                typeAnnotation = typeAnnotation.typeAnnotation;
            }
            if (typeAnnotation.nodeType === 24 /* ParseNodeType.Index */ &&
                typeAnnotation.items.length > 0 &&
                this._isTypingAnnotation(typeAnnotation.baseExpression, 'Annotated')) {
                typeAnnotation = typeAnnotation.items[0].valueExpression;
            }
            else if (this._isTypingAnnotation(typeAnnotation, 'ClassVar')) {
                isClassVar = true;
                break;
            }
            else if (typeAnnotation.nodeType === 24 /* ParseNodeType.Index */ && typeAnnotation.items.length === 1) {
                // Recursively call to see if the base expression is "ClassVar".
                const finalInfo = this._isAnnotationClassVar(typeAnnotation.baseExpression);
                if (finalInfo.isClassVar &&
                    typeAnnotation.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                    !typeAnnotation.items[0].name &&
                    !typeAnnotation.trailingComma) {
                    isClassVar = true;
                    classVarTypeNode = typeAnnotation.items[0].valueExpression;
                }
                break;
            }
            else {
                break;
            }
        }
        return { isClassVar, classVarTypeNode };
    }
    // Determines whether a member access expression is referring to a
    // member of a class (either a class or instance member). This will
    // typically take the form "self.x" or "cls.x".
    _getMemberAccessInfo(node) {
        // We handle only simple names on the left-hand side of the expression,
        // not calls, nested member accesses, index expressions, etc.
        if (node.leftExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            return undefined;
        }
        const leftSymbolName = node.leftExpression.value;
        // Make sure the expression is within a function (i.e. a method) that's
        // within a class definition.
        const methodNode = ParseTreeUtils.getEnclosingFunction(node);
        if (!methodNode) {
            return undefined;
        }
        const classNode = ParseTreeUtils.getEnclosingClass(methodNode, /* stopAtFunction */ true);
        if (!classNode) {
            return undefined;
        }
        // Determine whether the left-hand side indicates a class or
        // instance member.
        let isInstanceMember = false;
        if (methodNode.parameters.length < 1 || !methodNode.parameters[0].name) {
            return undefined;
        }
        const className = classNode.name.value;
        const firstParamName = methodNode.parameters[0].name.value;
        if (leftSymbolName === className) {
            isInstanceMember = false;
        }
        else {
            if (leftSymbolName !== firstParamName) {
                return undefined;
            }
            // To determine whether the first parameter of the method
            // refers to the class or the instance, we need to apply
            // some heuristics.
            if (methodNode.name.value === '__new__') {
                // The __new__ method is special. It acts as a classmethod even
                // though it doesn't have a @classmethod decorator.
                isInstanceMember = false;
            }
            else {
                // Assume that it's an instance member unless we find
                // a decorator that tells us otherwise.
                isInstanceMember = true;
                for (const decorator of methodNode.decorators) {
                    if (decorator.expression.nodeType === 38 /* ParseNodeType.Name */) {
                        const decoratorName = decorator.expression.value;
                        if (decoratorName === 'staticmethod') {
                            // A static method doesn't have a "self" or "cls" parameter.
                            return undefined;
                        }
                        else if (decoratorName === 'classmethod') {
                            // A classmethod implies that the first parameter is "cls".
                            isInstanceMember = false;
                            break;
                        }
                    }
                }
            }
        }
        const classScope = AnalyzerNodeInfo.getScope(classNode);
        (0, debug_1.assert)(classScope !== undefined);
        return {
            classNode,
            methodNode,
            classScope,
            isInstanceMember,
        };
    }
    _addImplicitImportsToLoaderActions(importResult, loaderActions) {
        importResult.filteredImplicitImports.forEach((implicitImport) => {
            const existingLoaderAction = loaderActions.implicitImports
                ? loaderActions.implicitImports.get(implicitImport.name)
                : undefined;
            if (existingLoaderAction) {
                existingLoaderAction.uri = implicitImport.uri;
                existingLoaderAction.loadSymbolsFromPath = true;
            }
            else {
                if (!loaderActions.implicitImports) {
                    loaderActions.implicitImports = new Map();
                }
                loaderActions.implicitImports.set(implicitImport.name, {
                    uri: implicitImport.uri,
                    loadSymbolsFromPath: true,
                    implicitImports: new Map(),
                });
            }
        });
    }
    // Handles some special-case assignment statements that are found
    // within the typings.pyi file.
    _handleTypingStubAssignmentOrAnnotation(node) {
        if (!this._fileInfo.isTypingStubFile) {
            return false;
        }
        let annotationNode;
        if (node.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            annotationNode = node;
        }
        else {
            if (node.leftExpression.nodeType !== 54 /* ParseNodeType.TypeAnnotation */) {
                return false;
            }
            annotationNode = node.leftExpression;
        }
        if (annotationNode.valueExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            return false;
        }
        const assignedNameNode = annotationNode.valueExpression;
        const specialTypes = new Set([
            'Tuple',
            'Generic',
            'Protocol',
            'Callable',
            'Type',
            'ClassVar',
            'Final',
            'Literal',
            'TypedDict',
            'Union',
            'Optional',
            'Annotated',
            'TypeAlias',
            'Concatenate',
            'TypeGuard',
            'Unpack',
            'Self',
            'NoReturn',
            'Never',
            'LiteralString',
            'OrderedDict',
            'TypeIs',
        ]);
        const assignedName = assignedNameNode.value;
        if (!specialTypes.has(assignedName)) {
            return false;
        }
        const specialBuiltInClassDeclaration = {
            type: 7 /* DeclarationType.SpecialBuiltInClass */,
            node: annotationNode,
            uri: this._fileInfo.fileUri,
            range: (0, positionUtils_1.convertTextRangeToRange)(annotationNode, this._fileInfo.lines),
            moduleName: this._fileInfo.moduleName,
            isInExceptSuite: this._isInExceptSuite,
        };
        const symbol = this._bindNameToScope(this._currentScope, annotationNode.valueExpression);
        if (symbol) {
            symbol.addDeclaration(specialBuiltInClassDeclaration);
        }
        AnalyzerNodeInfo.setDeclaration(node, specialBuiltInClassDeclaration);
        return true;
    }
    _deferBinding(callback) {
        if (this._moduleSymbolOnly) {
            return;
        }
        this._deferredBindingTasks.push({
            scope: this._currentScope,
            codeFlowExpressions: this._currentScopeCodeFlowExpressions,
            activeTypeParams: new Map(this._activeTypeParams),
            callback,
        });
    }
    _bindDeferred() {
        while (this._deferredBindingTasks.length > 0) {
            const nextItem = this._deferredBindingTasks.shift();
            // Reset the state
            this._currentScope = nextItem.scope;
            this._currentScopeCodeFlowExpressions = nextItem.codeFlowExpressions;
            this._activeTypeParams = nextItem.activeTypeParams;
            nextItem.callback();
        }
    }
    _bindYield(node) {
        const functionNode = ParseTreeUtils.getEnclosingFunction(node);
        if (!functionNode) {
            if (!ParseTreeUtils.getEnclosingLambda(node)) {
                this._addSyntaxError(localize_1.LocMessage.yieldOutsideFunction(), node);
            }
        }
        else if (functionNode.isAsync && node.nodeType === 61 /* ParseNodeType.YieldFrom */) {
            // PEP 525 indicates that 'yield from' is not allowed in an
            // async function.
            this._addSyntaxError(localize_1.LocMessage.yieldFromOutsideAsync(), node);
        }
        if (this._targetFunctionDeclaration) {
            if (!this._targetFunctionDeclaration.yieldStatements) {
                this._targetFunctionDeclaration.yieldStatements = [];
            }
            this._targetFunctionDeclaration.yieldStatements.push(node);
            this._targetFunctionDeclaration.isGenerator = true;
        }
        if (node.expression) {
            this.walk(node.expression);
        }
        AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode);
    }
    _getUniqueFlowNodeId() {
        this._codeFlowComplexity += flowNodeComplexityContribution;
        return (0, codeFlowTypes_1.getUniqueFlowNodeId)();
    }
    _addDiagnostic(diagLevel, rule, message, textRange) {
        let diagnostic;
        switch (diagLevel) {
            case 'error':
            case 'warning':
            case 'information':
                diagnostic = this._fileInfo.diagnosticSink.addDiagnosticWithTextRange(diagLevel, message, textRange);
                break;
            case 'none':
                break;
            default:
                return (0, debug_1.assertNever)(diagLevel, `${diagLevel} is not expected`);
        }
        if (diagnostic) {
            diagnostic.setRule(rule);
        }
        return diagnostic;
    }
    _addSyntaxError(message, textRange) {
        return this._fileInfo.diagnosticSink.addDiagnosticWithTextRange('error', message, textRange);
    }
}
exports.Binder = Binder;
// Flow node that is used for unreachable code.
Binder._unreachableFlowNode = {
    flags: codeFlowTypes_1.FlowFlags.Unreachable,
    id: (0, codeFlowTypes_1.getUniqueFlowNodeId)(),
};
class YieldFinder extends parseTreeWalker_1.ParseTreeWalker {
    constructor() {
        super(...arguments);
        this._containsYield = false;
    }
    checkContainsYield(node) {
        this.walk(node);
        return this._containsYield;
    }
    visitYield(node) {
        this._containsYield = true;
        return false;
    }
    visitYieldFrom(node) {
        this._containsYield = true;
        return false;
    }
}
exports.YieldFinder = YieldFinder;
class ReturnFinder extends parseTreeWalker_1.ParseTreeWalker {
    constructor() {
        super(...arguments);
        this._containsReturn = false;
    }
    checkContainsReturn(node) {
        this.walk(node);
        return this._containsReturn;
    }
    visitReturn(node) {
        this._containsReturn = true;
        return false;
    }
}
exports.ReturnFinder = ReturnFinder;
// Creates dummy scopes for classes or functions within a parse tree.
// This is needed in cases where the parse tree has been determined
// to be unreachable. There are code paths where the type evaluator
// will still evaluate these types, and it depends on the presence
// of a scope.
class DummyScopeGenerator extends parseTreeWalker_1.ParseTreeWalker {
    constructor(currentScope) {
        super();
        this._currentScope = currentScope;
    }
    visitClass(node) {
        const newScope = this._createNewScope(2 /* ScopeType.Class */, () => {
            this.walk(node.suite);
        });
        if (!AnalyzerNodeInfo.getScope(node)) {
            AnalyzerNodeInfo.setScope(node, newScope);
        }
        return false;
    }
    visitFunction(node) {
        const newScope = this._createNewScope(1 /* ScopeType.Function */, () => {
            this.walk(node.suite);
        });
        if (!AnalyzerNodeInfo.getScope(node)) {
            AnalyzerNodeInfo.setScope(node, newScope);
        }
        return false;
    }
    _createNewScope(scopeType, callback) {
        const prevScope = this._currentScope;
        const newScope = new scope_1.Scope(scopeType, this._currentScope);
        this._currentScope = newScope;
        callback();
        this._currentScope = prevScope;
        return newScope;
    }
}
exports.DummyScopeGenerator = DummyScopeGenerator;


/***/ }),

/***/ "../pyright-internal/src/analyzer/cacheManager.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/cacheManager.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * cacheManager.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A singleton that tracks the size of caches and empties them
 * if memory usage approaches the max heap space.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CacheManager = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const memUtils_1 = __webpack_require__(/*! ../common/memUtils */ "../pyright-internal/src/common/memUtils.ts");
class CacheManager {
    constructor(_maxWorkers = 0) {
        this._maxWorkers = _maxWorkers;
        this._pausedCount = 0;
        this._cacheOwners = [];
        this._sharedUsagePosition = 0;
        this._lastHeapStats = Date.now();
    }
    registerCacheOwner(provider) {
        this._cacheOwners.push(provider);
    }
    addWorker(index, worker) {
        // Send the sharedArrayBuffer to the worker so it can be used
        // to keep track of heap usage on all threads.
        const buffer = this._getSharedUsageBuffer();
        if (buffer) {
            // The SharedArrayBuffer needs to be separate from data in order for it
            // to be marshalled correctly.
            worker.postMessage({ requestType: 'cacheUsageBuffer', sharedUsageBuffer: buffer, data: index.toString() });
            worker.on('exit', () => {
                const view = new Float64Array(buffer);
                view[index] = 0;
            });
        }
    }
    handleCachedUsageBufferMessage(msg) {
        if (msg.requestType === 'cacheUsageBuffer') {
            const index = parseInt(msg.data || '0');
            const buffer = msg.sharedUsageBuffer;
            // Index of zero is reserved for the main thread so if
            // the index isn't passed, don't save the shared buffer.
            if (buffer && index) {
                this._sharedUsageBuffer = buffer;
                this._sharedUsagePosition = index;
            }
        }
    }
    unregisterCacheOwner(provider) {
        const index = this._cacheOwners.findIndex((p) => p === provider);
        if (index < 0) {
            (0, debug_1.fail)('Specified cache provider not found');
        }
        else {
            this._cacheOwners.splice(index, 1);
        }
    }
    pauseTracking() {
        const local = this;
        local._pausedCount++;
        return {
            dispose() {
                local._pausedCount--;
            },
        };
    }
    getCacheUsage() {
        if (this._pausedCount > 0) {
            return -1;
        }
        let totalUsage = 0;
        this._cacheOwners.forEach((p) => {
            totalUsage += p.getCacheUsage();
        });
        return totalUsage;
    }
    emptyCache(console) {
        if (console) {
            const heapStats = (0, memUtils_1.getHeapStatistics)();
            console.info(`Emptying type cache to avoid heap overflow. Used ${this._convertToMB(heapStats.used_heap_size)} out of ${this._convertToMB(heapStats.heap_size_limit)}.`);
        }
        this._cacheOwners.forEach((p) => {
            p.emptyCache();
        });
    }
    // Returns a ratio of used bytes to total bytes.
    getUsedHeapRatio(console) {
        const heapStats = (0, memUtils_1.getHeapStatistics)();
        let usage = this._getTotalHeapUsage(heapStats);
        if (console && Date.now() - this._lastHeapStats > 1000) {
            // This can fill up the user's console, so we only do it once per second.
            this._lastHeapStats = Date.now();
            console.info(`Heap stats: ` +
                `total_heap_size=${this._convertToMB(heapStats.total_heap_size)}, ` +
                `used_heap_size=${this._convertToMB(heapStats.used_heap_size)}, ` +
                `cross_worker_used_heap_size=${this._convertToMB(usage)}, ` +
                `total_physical_size=${this._convertToMB(heapStats.total_physical_size)}, ` +
                `total_available_size=${this._convertToMB(heapStats.total_available_size)}, ` +
                `heap_size_limit=${this._convertToMB(heapStats.heap_size_limit)}`);
        }
        // Total usage seems to be off by about 5%, so we'll add that back in
        // to make the ratio more accurate. (200MB at 4GB)
        usage += usage * 0.05;
        return usage / heapStats.heap_size_limit;
    }
    _convertToMB(bytes) {
        return `${Math.round(bytes / (1024 * 1024))}MB`;
    }
    _getSharedUsageBuffer() {
        try {
            if (!this._sharedUsageBuffer && this._maxWorkers > 0) {
                // Allocate enough space for the workers and the main thread.
                this._sharedUsageBuffer = new SharedArrayBuffer(8 * (this._maxWorkers + 1));
            }
            return this._sharedUsageBuffer;
        }
        catch {
            // SharedArrayBuffer is not supported.
            return undefined;
        }
    }
    _getTotalHeapUsage(heapStats) {
        // If the SharedArrayBuffer is supported, we'll use it to to get usage
        // from other threads and add that to our own
        const buffer = this._getSharedUsageBuffer();
        if (buffer) {
            const view = new Float64Array(buffer);
            view[this._sharedUsagePosition] = heapStats.used_heap_size;
            return view.reduce((a, b) => a + b, 0);
        }
        return heapStats.used_heap_size;
    }
}
exports.CacheManager = CacheManager;
(function (CacheManager) {
    function is(obj) {
        return (obj.registerCacheOwner !== undefined &&
            obj.unregisterCacheOwner !== undefined &&
            obj.pauseTracking !== undefined &&
            obj.getCacheUsage !== undefined &&
            obj.emptyCache !== undefined &&
            obj.getUsedHeapRatio !== undefined);
    }
    CacheManager.is = is;
})(CacheManager || (exports.CacheManager = CacheManager = {}));


/***/ }),

/***/ "../pyright-internal/src/analyzer/checker.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/analyzer/checker.ts ***!
  \***************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * checker.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A parse tree walker that performs static type checking for
 * a source file. Most of its work is performed by the type
 * evaluator, but this module touches every node in the file
 * to ensure that all statements and expressions are evaluated
 * and checked. It also performs some additional checks that
 * cannot (or should not be) performed lazily.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Checker = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const definitionProvider_1 = __webpack_require__(/*! ../languageService/definitionProvider */ "../pyright-internal/src/languageService/definitionProvider.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const stringTokenUtils_1 = __webpack_require__(/*! ../parser/stringTokenUtils */ "../pyright-internal/src/parser/stringTokenUtils.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const constructors_1 = __webpack_require__(/*! ./constructors */ "../pyright-internal/src/analyzer/constructors.ts");
const declaration_1 = __webpack_require__(/*! ./declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const declarationUtils_1 = __webpack_require__(/*! ./declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
const deprecatedSymbols_1 = __webpack_require__(/*! ./deprecatedSymbols */ "../pyright-internal/src/analyzer/deprecatedSymbols.ts");
const enums_1 = __webpack_require__(/*! ./enums */ "../pyright-internal/src/analyzer/enums.ts");
const importResolver_1 = __webpack_require__(/*! ./importResolver */ "../pyright-internal/src/analyzer/importResolver.ts");
const importStatementUtils_1 = __webpack_require__(/*! ./importStatementUtils */ "../pyright-internal/src/analyzer/importStatementUtils.ts");
const parameterUtils_1 = __webpack_require__(/*! ./parameterUtils */ "../pyright-internal/src/analyzer/parameterUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const patternMatching_1 = __webpack_require__(/*! ./patternMatching */ "../pyright-internal/src/analyzer/patternMatching.ts");
const protocols_1 = __webpack_require__(/*! ./protocols */ "../pyright-internal/src/analyzer/protocols.ts");
const scopeUtils_1 = __webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const sourceFile_1 = __webpack_require__(/*! ./sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const sourceMapper_1 = __webpack_require__(/*! ./sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const staticExpressions_1 = __webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts");
const SymbolNameUtils = __importStar(__webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
const symbolUtils_1 = __webpack_require__(/*! ./symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const typeEvaluator_1 = __webpack_require__(/*! ./typeEvaluator */ "../pyright-internal/src/analyzer/typeEvaluator.ts");
const typeGuards_1 = __webpack_require__(/*! ./typeGuards */ "../pyright-internal/src/analyzer/typeGuards.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
const typedDicts_1 = __webpack_require__(/*! ./typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// When enabled, this debug flag causes the code complexity of
// functions to be emitted.
const isPrintCodeComplexityEnabled = false;
class Checker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_importResolver, _evaluator, parseResults, _sourceMapper, _dependentFiles) {
        super();
        this._importResolver = _importResolver;
        this._evaluator = _evaluator;
        this._sourceMapper = _sourceMapper;
        this._dependentFiles = _dependentFiles;
        this._isUnboundCheckSuppressed = false;
        // A list of all nodes that are defined within the module that
        // have their own scopes.
        this._scopedNodes = [];
        // A list of all visited type parameter lists.
        this._typeParameterLists = [];
        this._moduleNode = parseResults.parseTree;
        this._fileInfo = AnalyzerNodeInfo.getFileInfo(this._moduleNode);
    }
    check() {
        this._scopedNodes.push(this._moduleNode);
        this._conditionallyReportShadowedModule();
        // Report code complexity issues for the module.
        const codeComplexity = AnalyzerNodeInfo.getCodeFlowComplexity(this._moduleNode);
        if (isPrintCodeComplexityEnabled) {
            console.log(`Code complexity of module ${this._fileInfo.fileUri.toUserVisibleString()} is ${codeComplexity.toString()}`);
        }
        if (codeComplexity > typeEvaluator_1.maxCodeComplexity) {
            this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.codeTooComplexToAnalyze(), { start: 0, length: 0 });
        }
        this._walkStatementsAndReportUnreachable(this._moduleNode.statements);
        // Mark symbols accessed by __all__ as accessed.
        const dunderAllInfo = AnalyzerNodeInfo.getDunderAllInfo(this._moduleNode);
        if (dunderAllInfo) {
            this._evaluator.markNamesAccessed(this._moduleNode, dunderAllInfo.names);
            this._reportUnusedDunderAllSymbols(dunderAllInfo.stringNodes);
        }
        // Perform a one-time validation of symbols in all scopes
        // defined in this module for things like unaccessed variables.
        this._validateSymbolTables();
        this._reportDuplicateImports();
    }
    walk(node) {
        if (!AnalyzerNodeInfo.isCodeUnreachable(node)) {
            super.walk(node);
        }
        else {
            this._evaluator.suppressDiagnostics(node, () => {
                super.walk(node);
            });
        }
    }
    visitSuite(node) {
        this._walkStatementsAndReportUnreachable(node.statements);
        return false;
    }
    visitStatementList(node) {
        node.statements.forEach((statement) => {
            if ((0, parseNodes_1.isExpressionNode)(statement)) {
                // Evaluate the expression in case it wasn't otherwise evaluated
                // through lazy analysis. This will mark referenced symbols as
                // accessed and report any errors associated with it.
                this._evaluator.getType(statement);
                this._reportUnusedExpression(statement);
            }
        });
        return true;
    }
    visitClass(node) {
        const classTypeResult = this._evaluator.getTypeOfClass(node);
        if (node.typeParameters) {
            this.walk(node.typeParameters);
        }
        this.walk(node.suite);
        this.walkMultiple(node.decorators);
        this.walkMultiple(node.arguments);
        if (classTypeResult) {
            // Protocol classes cannot derive from non-protocol classes.
            if (types_1.ClassType.isProtocolClass(classTypeResult.classType)) {
                node.arguments.forEach((arg) => {
                    if (!arg.name) {
                        const baseClassType = this._evaluator.getType(arg.valueExpression);
                        if (baseClassType &&
                            (0, types_1.isInstantiableClass)(baseClassType) &&
                            !types_1.ClassType.isBuiltIn(baseClassType, 'Protocol') &&
                            !types_1.ClassType.isBuiltIn(baseClassType, 'Generic')) {
                            if (!types_1.ClassType.isProtocolClass(baseClassType)) {
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.protocolBaseClass().format({
                                    classType: classTypeResult.classType.details.name,
                                    baseType: baseClassType.details.name,
                                }), arg.valueExpression);
                            }
                        }
                    }
                });
                // If this is a generic protocol class, verify that its type variables
                // have the proper variance.
                this._validateProtocolTypeParamVariance(node, classTypeResult.classType);
            }
            // Skip the slots check because class variables declared in a stub
            // file are interpreted as instance variables.
            if (!this._fileInfo.isStubFile) {
                this._validateSlotsClassVarConflict(classTypeResult.classType);
            }
            this._validateBaseClassOverrides(classTypeResult.classType);
            this._validateTypedDictOverrides(classTypeResult.classType);
            this._validateOverloadDecoratorConsistency(classTypeResult.classType);
            this._validateMultipleInheritanceBaseClasses(classTypeResult.classType, node.name);
            this._validateMultipleInheritanceCompatibility(classTypeResult.classType, node.name);
            this._validateConstructorConsistency(classTypeResult.classType, node.name);
            this._validateFinalMemberOverrides(classTypeResult.classType);
            this._validateInstanceVariableInitialization(node, classTypeResult.classType);
            this._validateFinalClassNotAbstract(classTypeResult.classType, node);
            this._validateDataClassPostInit(classTypeResult.classType, node);
            this._validateEnumMembers(classTypeResult.classType, node);
            if (types_1.ClassType.isTypedDictClass(classTypeResult.classType)) {
                this._validateTypedDictClassSuite(node.suite);
            }
            if (types_1.ClassType.isEnumClass(classTypeResult.classType)) {
                this._validateEnumClassOverride(node, classTypeResult.classType);
            }
            this._evaluator.validateInitSubclassArgs(node, classTypeResult.classType);
        }
        this._scopedNodes.push(node);
        return false;
    }
    visitFunction(node) {
        var _a, _b;
        if (node.typeParameters) {
            this.walk(node.typeParameters);
        }
        if (!this._fileInfo.diagnosticRuleSet.analyzeUnannotatedFunctions && !this._fileInfo.isStubFile) {
            if (ParseTreeUtils.isUnannotatedFunction(node)) {
                this._evaluator.addInformation(localize_1.LocMessage.unannotatedFunctionSkipped().format({ name: node.name.value }), node.name);
            }
        }
        const functionTypeResult = this._evaluator.getTypeOfFunction(node);
        const containingClassNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true);
        if (functionTypeResult) {
            // Track whether we have seen a *args: P.args parameter. Named
            // parameters after this need to be flagged as an error.
            let sawParamSpecArgs = false;
            const keywordNames = new Set();
            const paramDetails = (0, parameterUtils_1.getParameterListDetails)(functionTypeResult.functionType);
            // Report any unknown or missing parameter types.
            node.parameters.forEach((param, index) => {
                if (param.name) {
                    if (param.category === 0 /* ParameterCategory.Simple */ && index >= paramDetails.positionOnlyParamCount) {
                        keywordNames.add(param.name.value);
                    }
                    // Determine whether this is a P.args parameter.
                    if (param.category === 1 /* ParameterCategory.ArgsList */) {
                        const annotationExpr = param.typeAnnotation || param.typeAnnotationComment;
                        if (annotationExpr &&
                            annotationExpr.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                            annotationExpr.memberName.value === 'args') {
                            const baseType = this._evaluator.getType(annotationExpr.leftExpression);
                            if (baseType && (0, types_1.isTypeVar)(baseType) && baseType.details.isParamSpec) {
                                sawParamSpecArgs = true;
                            }
                        }
                    }
                    else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                        sawParamSpecArgs = false;
                    }
                }
                if (param.name && param.category === 0 /* ParameterCategory.Simple */ && sawParamSpecArgs) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.namedParamAfterParamSpecArgs().format({ name: param.name.value }), param.name);
                }
                // Allow unknown and missing param types if the param is named '_'.
                if (param.name && param.name.value !== '_') {
                    const functionTypeParam = functionTypeResult.functionType.details.parameters.find((p) => { var _a; return p.name === ((_a = param.name) === null || _a === void 0 ? void 0 : _a.value); });
                    if (functionTypeParam) {
                        const paramType = functionTypeParam.type;
                        if (this._fileInfo.diagnosticRuleSet.reportUnknownParameterType !== 'none' ||
                            this._fileInfo.diagnosticRuleSet.reportAny !== 'none') {
                            if ((0, types_1.isUnknown)(paramType) ||
                                ((0, types_1.isTypeVar)(paramType) &&
                                    paramType.details.isSynthesized &&
                                    !paramType.details.isSynthesizedSelf)) {
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownParameterType, localize_1.LocMessage.paramTypeUnknown().format({ paramName: param.name.value }), param.name);
                            }
                            else if ((0, typeUtils_1.isPartlyUnknown)(paramType)) {
                                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                                diagAddendum.addMessage(localize_1.LocAddendum.paramType().format({
                                    paramType: this._evaluator.printType(paramType, { expandTypeAlias: true }),
                                }));
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownParameterType, localize_1.LocMessage.paramTypePartiallyUnknown().format({
                                    paramName: param.name.value,
                                }) + diagAddendum.getString(), param.name);
                            }
                            else if ((0, types_1.isAny)(paramType)) {
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.paramTypeAny().format({ paramName: param.name.value }), param.name);
                            }
                        }
                        let hasAnnotation = false;
                        if (functionTypeParam.typeAnnotation) {
                            hasAnnotation = true;
                        }
                        else {
                            // See if this is a "self" and "cls" parameter. They are exempt from this rule.
                            if ((0, types_1.isTypeVar)(paramType) && paramType.details.isSynthesizedSelf) {
                                hasAnnotation = true;
                            }
                        }
                        if (!hasAnnotation && this._fileInfo.diagnosticRuleSet.reportMissingParameterType !== 'none') {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingParameterType, localize_1.LocMessage.paramAnnotationMissing().format({ name: param.name.value }), param.name);
                        }
                    }
                }
            });
            // Verify that an unpacked TypedDict doesn't overlap any keyword parameters.
            if (paramDetails.hasUnpackedTypedDict) {
                const kwargsIndex = functionTypeResult.functionType.details.parameters.length - 1;
                const kwargsType = types_1.FunctionType.getEffectiveParameterType(functionTypeResult.functionType, kwargsIndex);
                if ((0, types_1.isClass)(kwargsType) && kwargsType.details.typedDictEntries) {
                    const overlappingEntries = new Set();
                    kwargsType.details.typedDictEntries.knownItems.forEach((_, name) => {
                        if (keywordNames.has(name)) {
                            overlappingEntries.add(name);
                        }
                    });
                    if (overlappingEntries.size > 0) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.overlappingKeywordArgs().format({
                            names: [...overlappingEntries.values()].join(', '),
                        }), (_a = node.parameters[kwargsIndex].typeAnnotation) !== null && _a !== void 0 ? _a : node.parameters[kwargsIndex]);
                    }
                }
            }
            // Check for invalid use of ParamSpec P.args and P.kwargs.
            const paramSpecParams = functionTypeResult.functionType.details.parameters.filter((param) => {
                if (param.typeAnnotation && (0, types_1.isTypeVar)(param.type) && (0, types_1.isParamSpec)(param.type)) {
                    if (param.category !== 0 /* ParameterCategory.Simple */ && param.name && param.type.paramSpecAccess) {
                        return true;
                    }
                }
                return false;
            });
            if (paramSpecParams.length === 1 && paramSpecParams[0].typeAnnotation) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramSpecArgsKwargsUsage(), paramSpecParams[0].typeAnnotation);
            }
            // If this is a stub, ensure that the return type is specified.
            if (this._fileInfo.isStubFile) {
                const returnAnnotation = node.returnTypeAnnotation || ((_b = node.functionAnnotationComment) === null || _b === void 0 ? void 0 : _b.returnTypeAnnotation);
                if (!returnAnnotation) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownParameterType, localize_1.LocMessage.returnTypeUnknown(), node.name);
                }
            }
            if (containingClassNode) {
                this._validateMethod(node, functionTypeResult.functionType, containingClassNode);
            }
        }
        node.parameters.forEach((param, index) => {
            if (param.defaultValue) {
                this.walk(param.defaultValue);
            }
            if (param.typeAnnotation) {
                this.walk(param.typeAnnotation);
            }
            if (param.typeAnnotationComment) {
                this.walk(param.typeAnnotationComment);
            }
            // Look for method parameters that are typed with TypeVars that have the wrong variance.
            if (functionTypeResult) {
                const annotationNode = param.typeAnnotation || param.typeAnnotationComment;
                if (annotationNode && index < functionTypeResult.functionType.details.parameters.length) {
                    const paramType = functionTypeResult.functionType.details.parameters[index].type;
                    const exemptMethods = ['__init__', '__new__'];
                    if (containingClassNode &&
                        (0, types_1.isTypeVar)(paramType) &&
                        paramType.details.declaredVariance === 3 /* Variance.Covariant */ &&
                        !paramType.details.isSynthesized &&
                        !exemptMethods.some((name) => name === functionTypeResult.functionType.details.name)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramTypeCovariant(), annotationNode);
                    }
                }
            }
        });
        if (node.returnTypeAnnotation) {
            this.walk(node.returnTypeAnnotation);
        }
        if (node.functionAnnotationComment) {
            this.walk(node.functionAnnotationComment);
            if (this._fileInfo.diagnosticRuleSet.reportTypeCommentUsage !== 'none' &&
                this._fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_5)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportTypeCommentUsage, localize_1.LocMessage.typeCommentDeprecated(), node.functionAnnotationComment);
            }
        }
        this.walkMultiple(node.decorators);
        node.parameters.forEach((param) => {
            if (param.name) {
                this.walk(param.name);
            }
        });
        const codeComplexity = AnalyzerNodeInfo.getCodeFlowComplexity(node);
        const isTooComplexToAnalyze = codeComplexity > typeEvaluator_1.maxCodeComplexity;
        if (isPrintCodeComplexityEnabled) {
            console.log(`Code complexity of function ${node.name.value} is ${codeComplexity.toString()}`);
        }
        if (isTooComplexToAnalyze) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.codeTooComplexToAnalyze(), node.name);
        }
        else {
            this.walk(node.suite);
        }
        if (functionTypeResult) {
            // Validate that the function returns the declared type.
            if (!isTooComplexToAnalyze) {
                this._validateFunctionReturn(node, functionTypeResult.functionType);
            }
            // Verify common dunder signatures.
            this._validateDunderSignatures(node, functionTypeResult.functionType, containingClassNode !== undefined);
            // Verify TypeGuard and TypeIs functions.
            this._validateTypeGuardFunction(node, functionTypeResult.functionType, containingClassNode !== undefined);
            this._validateFunctionTypeVarUsage(node, functionTypeResult);
            this._validateGeneratorReturnType(node, functionTypeResult.functionType);
            this._reportDeprecatedClassProperty(node, functionTypeResult);
            // If this is not a method, @final is disallowed.
            if (!containingClassNode && types_1.FunctionType.isFinal(functionTypeResult.functionType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalNonMethod().format({ name: node.name.value }), node.name);
            }
        }
        // If we're at the module level within a stub file, report a diagnostic
        // if there is a '__getattr__' function defined when in strict mode.
        // This signifies an incomplete stub file that obscures type errors.
        if (this._fileInfo.isStubFile && node.name.value === '__getattr__') {
            const scope = (0, scopeUtils_1.getScopeForNode)(node);
            if ((scope === null || scope === void 0 ? void 0 : scope.type) === 3 /* ScopeType.Module */) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompleteStub, localize_1.LocMessage.stubUsesGetAttr(), node.name);
            }
        }
        this._scopedNodes.push(node);
        if (functionTypeResult && (0, types_1.isOverloadedFunction)(functionTypeResult.decoratedType)) {
            // If this is the implementation for the overloaded function, skip
            // overload consistency checks.
            if (types_1.OverloadedFunctionType.getImplementation(functionTypeResult.decoratedType) !==
                functionTypeResult.functionType) {
                const overloads = types_1.OverloadedFunctionType.getOverloads(functionTypeResult.decoratedType);
                if (overloads.length > 1) {
                    const maxOverloadConsistencyCheckLength = 100;
                    // The check is n^2 in time, so if the number of overloads
                    // is very large (which can happen for some generated code),
                    // skip this check to avoid quadratic analysis time.
                    if (overloads.length < maxOverloadConsistencyCheckLength) {
                        this._validateOverloadConsistency(node, overloads[overloads.length - 1], overloads.slice(0, overloads.length - 1));
                    }
                }
            }
            this._validateOverloadAttributeConsistency(node, functionTypeResult.decoratedType);
        }
        return false;
    }
    visitLambda(node) {
        this._evaluator.getType(node);
        // Walk the children.
        this.walkMultiple([...node.parameters, node.expression]);
        node.parameters.forEach((param) => {
            if (param.name) {
                const paramType = this._evaluator.getType(param.name);
                if (paramType) {
                    if ((0, types_1.isUnknown)(paramType)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownLambdaType, localize_1.LocMessage.paramTypeUnknown().format({ paramName: param.name.value }), param.name);
                    }
                    else if ((0, typeUtils_1.isPartlyUnknown)(paramType)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownLambdaType, localize_1.LocMessage.paramTypePartiallyUnknown().format({ paramName: param.name.value }), param.name);
                    }
                    else if ((0, types_1.isAny)(paramType)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.paramTypeAny().format({ paramName: param.name.value }), param.name);
                    }
                }
            }
        });
        const returnType = this._evaluator.getType(node.expression);
        if (returnType) {
            if ((0, types_1.isUnknown)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownLambdaType, localize_1.LocMessage.lambdaReturnTypeUnknown(), node.expression);
            }
            else if ((0, typeUtils_1.isPartlyUnknown)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownLambdaType, localize_1.LocMessage.lambdaReturnTypePartiallyUnknown().format({
                    returnType: this._evaluator.printType(returnType, { expandTypeAlias: true }),
                }), node.expression);
            }
            else if ((0, types_1.isAny)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.lambdaReturnTypeAny(), node.expression);
            }
        }
        this._scopedNodes.push(node);
        return false;
    }
    visitCall(node) {
        var _a;
        this._validateIsInstanceCall(node);
        this._validateIllegalDefaultParamInitializer(node);
        this._validateStandardCollectionInstantiation(node);
        if (this._fileInfo.diagnosticRuleSet.reportUnusedCallResult !== 'none' ||
            this._fileInfo.diagnosticRuleSet.reportUnusedCoroutine !== 'none') {
            if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 47 /* ParseNodeType.StatementList */) {
                const isRevealTypeCall = node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.leftExpression.value === 'reveal_type';
                const returnType = this._evaluator.getType(node);
                if (!isRevealTypeCall && returnType && this._isTypeValidForUnusedValueTest(returnType)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnusedCallResult, localize_1.LocMessage.unusedCallResult().format({
                        type: this._evaluator.printType(returnType),
                    }), node);
                    if ((0, types_1.isClassInstance)(returnType) && types_1.ClassType.isBuiltIn(returnType, 'Coroutine')) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnusedCoroutine, localize_1.LocMessage.unusedCoroutine(), node);
                    }
                }
            }
        }
        return true;
    }
    visitAwait(node) {
        var _a;
        if (this._fileInfo.diagnosticRuleSet.reportUnusedCallResult !== 'none') {
            if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 47 /* ParseNodeType.StatementList */ &&
                node.expression.nodeType === 9 /* ParseNodeType.Call */) {
                const returnType = this._evaluator.getType(node);
                if (returnType && this._isTypeValidForUnusedValueTest(returnType)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnusedCallResult, localize_1.LocMessage.unusedCallResult().format({
                        type: this._evaluator.printType(returnType),
                    }), node);
                }
            }
        }
        return true;
    }
    visitFor(node) {
        this._evaluator.evaluateTypesForStatement(node);
        if (node.typeComment) {
            this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportInvalidTypeForm, diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.annotationNotSupported(), node.typeComment);
        }
        return true;
    }
    visitList(node) {
        this._validateIllegalDefaultParamInitializer(node);
        return true;
    }
    visitSet(node) {
        this._validateIllegalDefaultParamInitializer(node);
        return true;
    }
    visitDictionary(node) {
        this._validateIllegalDefaultParamInitializer(node);
        return true;
    }
    visitListComprehension(node) {
        this._scopedNodes.push(node);
        return true;
    }
    visitListComprehensionIf(node) {
        this._validateConditionalIsBool(node.testExpression);
        this._reportUnnecessaryConditionExpression(node.testExpression);
        return true;
    }
    visitIf(node) {
        this._validateConditionalIsBool(node.testExpression);
        this._reportUnnecessaryConditionExpression(node.testExpression);
        return true;
    }
    visitWhile(node) {
        this._validateConditionalIsBool(node.testExpression);
        this._reportUnnecessaryConditionExpression(node.testExpression);
        return true;
    }
    visitWith(node) {
        node.withItems.forEach((item) => {
            this._evaluator.evaluateTypesForStatement(item);
        });
        if (node.typeComment) {
            this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportInvalidTypeForm, diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.annotationNotSupported(), node.typeComment);
        }
        return true;
    }
    visitReturn(node) {
        var _a, _b, _c, _d, _e, _f;
        let returnTypeResult;
        let returnType;
        const enclosingFunctionNode = ParseTreeUtils.getEnclosingFunction(node);
        const declaredReturnType = enclosingFunctionNode
            ? this._evaluator.getFunctionDeclaredReturnType(enclosingFunctionNode)
            : undefined;
        if (node.returnExpression) {
            returnTypeResult = (_a = this._evaluator.getTypeResult(node.returnExpression)) !== null && _a !== void 0 ? _a : { type: types_1.UnknownType.create() };
        }
        else {
            // There is no return expression, so "None" is assumed.
            returnTypeResult = { type: this._evaluator.getNoneType() };
        }
        returnType = returnTypeResult.type;
        // If this type is a special form, use the special form instead.
        if (returnType.specialForm) {
            returnType = returnType.specialForm;
        }
        // If the enclosing function is async and a generator, the return
        // statement is not allowed to have an argument. A syntax error occurs
        // at runtime in this case.
        if ((enclosingFunctionNode === null || enclosingFunctionNode === void 0 ? void 0 : enclosingFunctionNode.isAsync) && node.returnExpression) {
            const functionDecl = AnalyzerNodeInfo.getDeclaration(enclosingFunctionNode);
            if ((functionDecl === null || functionDecl === void 0 ? void 0 : functionDecl.type) === 5 /* DeclarationType.Function */ && functionDecl.isGenerator) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.returnInAsyncGenerator(), node.returnExpression);
            }
        }
        if (this._evaluator.isNodeReachable(node, /* sourceNode */ undefined) && enclosingFunctionNode) {
            if (declaredReturnType) {
                if ((0, types_1.isNever)(declaredReturnType)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.noReturnContainsReturn(), node);
                }
                else {
                    let diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    let returnTypeMatches = false;
                    if (this._evaluator.assignType(declaredReturnType, returnType, diagAddendum, new typeVarContext_1.TypeVarContext(), 
                    /* srcTypeVarContext */ undefined, 128 /* AssignTypeFlags.AllowBoolTypeGuard */)) {
                        returnTypeMatches = true;
                    }
                    else {
                        // See if the declared return type includes one or more constrained TypeVars. If so,
                        // try to narrow these TypeVars to a single type.
                        const uniqueTypeVars = (0, typeUtils_1.getTypeVarArgumentsRecursive)(declaredReturnType);
                        if (uniqueTypeVars &&
                            uniqueTypeVars.some((typeVar) => typeVar.details.constraints.length > 0)) {
                            const typeVarContext = new typeVarContext_1.TypeVarContext();
                            for (const typeVar of uniqueTypeVars) {
                                if (typeVar.details.constraints.length > 0) {
                                    const narrowedType = this._evaluator.narrowConstrainedTypeVar(node, typeVar);
                                    if (narrowedType) {
                                        typeVarContext.setTypeVarType(typeVar, narrowedType);
                                        typeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(typeVar));
                                    }
                                }
                            }
                            if (!typeVarContext.isEmpty()) {
                                const adjustedReturnType = (0, typeUtils_1.applySolvedTypeVars)(declaredReturnType, typeVarContext);
                                if (this._evaluator.assignType(adjustedReturnType, returnType, diagAddendum, 
                                /* destTypeVarContext */ undefined, 
                                /* srcTypeVarContext */ undefined, 128 /* AssignTypeFlags.AllowBoolTypeGuard */)) {
                                    returnTypeMatches = true;
                                }
                            }
                        }
                    }
                    if (!returnTypeMatches) {
                        // If we have more detailed diagnostic information from
                        // bidirectional type inference, use that.
                        if (returnTypeResult.expectedTypeDiagAddendum) {
                            diagAddendum = returnTypeResult.expectedTypeDiagAddendum;
                        }
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportReturnType, localize_1.LocMessage.returnTypeMismatch().format({
                            exprType: this._evaluator.printType(returnType),
                            returnType: this._evaluator.printType(declaredReturnType),
                        }) + diagAddendum.getString(), (_b = node.returnExpression) !== null && _b !== void 0 ? _b : node, (_c = returnTypeResult.expectedTypeDiagAddendum) === null || _c === void 0 ? void 0 : _c.getEffectiveTextRange());
                    }
                }
            }
            if ((0, types_1.isUnknown)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, localize_1.LocMessage.returnTypeUnknown(), (_d = node.returnExpression) !== null && _d !== void 0 ? _d : node);
            }
            else if ((0, typeUtils_1.isPartlyUnknown)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, localize_1.LocMessage.returnTypePartiallyUnknown().format({
                    returnType: this._evaluator.printType(returnType, { expandTypeAlias: true }),
                }), (_e = node.returnExpression) !== null && _e !== void 0 ? _e : node);
            }
            else if ((0, types_1.isAny)(returnType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.returnTypeAny(), (_f = node.returnExpression) !== null && _f !== void 0 ? _f : node);
            }
        }
        return true;
    }
    visitYield(node) {
        var _a;
        const yieldTypeResult = node.expression
            ? this._evaluator.getTypeResult(node.expression)
            : { type: this._evaluator.getNoneType() };
        this._validateYieldType(node, (_a = yieldTypeResult === null || yieldTypeResult === void 0 ? void 0 : yieldTypeResult.type) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(), yieldTypeResult === null || yieldTypeResult === void 0 ? void 0 : yieldTypeResult.expectedTypeDiagAddendum);
        return true;
    }
    visitYieldFrom(node) {
        var _a, _b, _c, _d;
        const yieldFromType = this._evaluator.getType(node.expression) || types_1.UnknownType.create();
        let yieldType;
        let sendType;
        if ((0, types_1.isClassInstance)(yieldFromType) && types_1.ClassType.isBuiltIn(yieldFromType, 'Coroutine')) {
            // Handle the case of old-style (pre-await) coroutines.
            yieldType = types_1.UnknownType.create();
        }
        else {
            yieldType =
                (_b = (_a = this._evaluator.getTypeOfIterable({ type: yieldFromType }, /* isAsync */ false, node)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
            // Does the iterator return a Generator? If so, get the yield type from it.
            // If the iterator doesn't return a Generator, use the iterator return type
            // directly.
            const generatorTypeArgs = (0, typeUtils_1.getGeneratorTypeArgs)(yieldType);
            if (generatorTypeArgs) {
                yieldType = generatorTypeArgs.length >= 1 ? generatorTypeArgs[0] : types_1.UnknownType.create();
                sendType = generatorTypeArgs.length >= 2 ? generatorTypeArgs[1] : undefined;
            }
            else {
                yieldType =
                    (_d = (_c = this._evaluator.getTypeOfIterator({ type: yieldFromType }, /* isAsync */ false, node)) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : types_1.UnknownType.create();
            }
        }
        this._validateYieldType(node, yieldType, /* expectedDiagAddendum */ undefined, sendType);
        return true;
    }
    visitRaise(node) {
        this._evaluator.verifyRaiseExceptionType(node);
        if (node.valueExpression) {
            const baseExceptionType = this._evaluator.getBuiltInType(node, 'BaseException');
            const exceptionType = this._evaluator.getType(node.valueExpression);
            // Validate that the argument of "raise" is an exception object or None.
            if (exceptionType && baseExceptionType && (0, types_1.isInstantiableClass)(baseExceptionType)) {
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                (0, typeUtils_1.doForEachSubtype)(exceptionType, (subtype) => {
                    subtype = this._evaluator.makeTopLevelTypeVarsConcrete(subtype);
                    if (!(0, types_1.isAnyOrUnknown)(subtype) && !(0, typeUtils_1.isNoneInstance)(subtype)) {
                        if ((0, types_1.isClass)(subtype)) {
                            if (!(0, typeUtils_1.derivesFromClassRecursive)(subtype, baseExceptionType, /* ignoreUnknown */ false)) {
                                diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                                    type: this._evaluator.printType(subtype),
                                }));
                            }
                        }
                        else {
                            diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                                type: this._evaluator.printType(subtype),
                            }));
                        }
                    }
                });
                if (!diagAddendum.isEmpty()) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.expectedExceptionObj() + diagAddendum.getString(), node.valueExpression);
                }
            }
        }
        return true;
    }
    visitExcept(node) {
        if (node.typeExpression) {
            this._evaluator.evaluateTypesForStatement(node);
            const exceptionType = this._evaluator.getType(node.typeExpression);
            if (exceptionType) {
                this._validateExceptionType(exceptionType, node.typeExpression);
            }
        }
        return true;
    }
    visitAssert(node) {
        if (node.exceptionExpression) {
            this._evaluator.getType(node.exceptionExpression);
        }
        this._validateConditionalIsBool(node.testExpression);
        // Specifically look for a common programming error where the two arguments
        // to an assert are enclosed in parens and interpreted as a two-element tuple.
        //   assert (x > 3, "bad value x")
        const type = this._evaluator.getType(node.testExpression);
        if (type && (0, types_1.isClassInstance)(type)) {
            if ((0, typeUtils_1.isTupleClass)(type) && type.tupleTypeArguments) {
                if (type.tupleTypeArguments.length > 0) {
                    if (!(0, typeUtils_1.isUnboundedTupleClass)(type)) {
                        this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportAssertAlwaysTrue, diagnosticRules_1.DiagnosticRule.reportAssertAlwaysTrue, localize_1.LocMessage.assertAlwaysTrue(), node.testExpression);
                    }
                }
            }
        }
        return true;
    }
    visitAssignment(node) {
        this._evaluator.evaluateTypesForStatement(node);
        if (node.typeAnnotationComment) {
            this._evaluator.getType(node.typeAnnotationComment);
            if (this._fileInfo.diagnosticRuleSet.reportTypeCommentUsage !== 'none' &&
                this._fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_6)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportTypeCommentUsage, localize_1.LocMessage.typeCommentDeprecated(), node.typeAnnotationComment);
            }
        }
        // If this isn't a class or global scope, explicit type aliases are not allowed.
        if (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            const annotationType = this._evaluator.getTypeOfAnnotation(node.leftExpression.typeAnnotation);
            if ((0, types_1.isClassInstance)(annotationType) && types_1.ClassType.isBuiltIn(annotationType, 'TypeAlias')) {
                const scope = (0, scopeUtils_1.getScopeForNode)(node);
                if (scope) {
                    if (scope.type !== 2 /* ScopeType.Class */ &&
                        scope.type !== 3 /* ScopeType.Module */ &&
                        scope.type !== 4 /* ScopeType.Builtin */) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasNotInModuleOrClass(), node.leftExpression.typeAnnotation);
                    }
                }
            }
        }
        return true;
    }
    visitAssignmentExpression(node) {
        this._evaluator.getType(node);
        return true;
    }
    visitAugmentedAssignment(node) {
        this._evaluator.evaluateTypesForStatement(node);
        return true;
    }
    visitIndex(node) {
        this._evaluator.getType(node);
        // If the index is a literal integer, see if this is a tuple with
        // a known length and the integer value exceeds the length.
        const baseType = this._evaluator.getType(node.baseExpression);
        if (baseType) {
            (0, typeUtils_1.doForEachSubtype)(baseType, (subtype) => {
                const tupleType = (0, typeUtils_1.getSpecializedTupleType)(subtype);
                if ((0, types_1.isClassInstance)(subtype) &&
                    (tupleType === null || tupleType === void 0 ? void 0 : tupleType.tupleTypeArguments) &&
                    !(0, typeUtils_1.isUnboundedTupleClass)(tupleType) &&
                    !this._evaluator.isTypeSubsumedByOtherType(tupleType, baseType, /* allowAnyToSubsume */ false)) {
                    const tupleLength = tupleType.tupleTypeArguments.length;
                    if (node.items.length === 1 &&
                        !node.trailingComma &&
                        node.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                        !node.items[0].name) {
                        const subscriptType = this._evaluator.getType(node.items[0].valueExpression);
                        if (subscriptType &&
                            (0, types_1.isClassInstance)(subscriptType) &&
                            types_1.ClassType.isBuiltIn(subscriptType, 'int') &&
                            (0, typeUtils_1.isLiteralType)(subscriptType) &&
                            typeof subscriptType.literalValue === 'number') {
                            if ((subscriptType.literalValue >= 0 && subscriptType.literalValue >= tupleLength) ||
                                (subscriptType.literalValue < 0 && subscriptType.literalValue + tupleLength < 0)) {
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.tupleIndexOutOfRange().format({
                                    index: subscriptType.literalValue,
                                    type: this._evaluator.printType(subtype),
                                }), node);
                            }
                        }
                    }
                }
            });
        }
        return true;
    }
    visitBinaryOperation(node) {
        if (node.operator === 36 /* OperatorType.And */ || node.operator === 37 /* OperatorType.Or */) {
            this._validateConditionalIsBool(node.leftExpression);
            this._validateConditionalIsBool(node.rightExpression);
        }
        if (node.operator === 12 /* OperatorType.Equals */ || node.operator === 28 /* OperatorType.NotEquals */) {
            // Don't apply this rule if it's within an assert.
            if (!ParseTreeUtils.isWithinAssertExpression(node)) {
                this._validateComparisonTypes(node);
            }
        }
        else if (node.operator === 39 /* OperatorType.Is */ || node.operator === 40 /* OperatorType.IsNot */) {
            // Don't apply this rule if it's within an assert.
            if (!ParseTreeUtils.isWithinAssertExpression(node)) {
                this._validateComparisonTypesForIsOperator(node);
            }
        }
        else if (node.operator === 41 /* OperatorType.In */ || node.operator === 42 /* OperatorType.NotIn */) {
            // Don't apply this rule if it's within an assert.
            if (!ParseTreeUtils.isWithinAssertExpression(node)) {
                this._validateContainmentTypes(node);
            }
        }
        this._evaluator.getType(node);
        return true;
    }
    visitSlice(node) {
        this._evaluator.getType(node);
        return true;
    }
    visitUnpack(node) {
        this._evaluator.getType(node);
        return true;
    }
    visitTuple(node) {
        this._evaluator.getType(node);
        return true;
    }
    visitUnaryOperation(node) {
        if (node.operator === 38 /* OperatorType.Not */) {
            this._validateConditionalIsBool(node.expression);
        }
        this._evaluator.getType(node);
        return true;
    }
    visitTernary(node) {
        this._evaluator.getType(node);
        this._validateConditionalIsBool(node.testExpression);
        this._reportUnnecessaryConditionExpression(node.testExpression);
        return true;
    }
    visitStringList(node) {
        // If this is Python 3.11 or older, there are several restrictions
        // associated with f-strings that we need to validate. Determine whether
        // we're within an f-string (or multiple f-strings if nesting is used).
        const fStringContainers = [];
        if (this._fileInfo.executionEnvironment.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_12)) {
            let curNode = node;
            while (curNode) {
                if (curNode.nodeType === 27 /* ParseNodeType.FormatString */) {
                    fStringContainers.push(curNode);
                }
                curNode = curNode.parent;
            }
        }
        for (const stringNode of node.strings) {
            const stringTokens = stringNode.nodeType === 49 /* ParseNodeType.String */ ? [stringNode.token] : stringNode.middleTokens;
            stringTokens.forEach((token) => {
                const unescapedResult = (0, stringTokenUtils_1.getUnescapedString)(token);
                let start = token.start;
                if (token.type === 5 /* TokenType.String */) {
                    start += token.prefixLength + token.quoteMarkLength;
                }
                unescapedResult.unescapeErrors.forEach((error) => {
                    if (error.errorType === 0 /* UnescapeErrorType.InvalidEscapeSequence */) {
                        this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportInvalidStringEscapeSequence, diagnosticRules_1.DiagnosticRule.reportInvalidStringEscapeSequence, localize_1.LocMessage.stringUnsupportedEscape(), { start: start + error.offset, length: error.length });
                    }
                });
                // Prior to Python 3.12, it was not allowed to include a slash in an f-string.
                if (fStringContainers.length > 0) {
                    const escapeOffset = token.escapedValue.indexOf('\\');
                    if (escapeOffset >= 0) {
                        this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.formatStringEscape(), { start, length: 1 });
                    }
                }
            });
            // Prior to Python 3.12, it was not allowed to nest strings that
            // used the same quote scheme within an f-string.
            if (fStringContainers.length > 0) {
                const quoteTypeMask = 1 /* StringTokenFlags.SingleQuote */ | 2 /* StringTokenFlags.DoubleQuote */ | 4 /* StringTokenFlags.Triplicate */;
                if (fStringContainers.some((fStringContainer) => (fStringContainer.token.flags & quoteTypeMask) === (stringNode.token.flags & quoteTypeMask))) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.formatStringNestedQuote(), stringNode);
                }
            }
        }
        if (node.typeAnnotation) {
            this._evaluator.getType(node);
        }
        if (node.strings.length > 1 && !node.isParenthesized) {
            this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportImplicitStringConcatenation, diagnosticRules_1.DiagnosticRule.reportImplicitStringConcatenation, localize_1.LocMessage.implicitStringConcat(), node);
        }
        return true;
    }
    visitFormatString(node) {
        node.fieldExpressions.forEach((expr) => {
            this._evaluator.getType(expr);
        });
        node.formatExpressions.forEach((expr) => {
            this._evaluator.getType(expr);
        });
        return true;
    }
    visitGlobal(node) {
        this._suppressUnboundCheck(() => {
            node.nameList.forEach((name) => {
                this._evaluator.getType(name);
                this.walk(name);
            });
        });
        return false;
    }
    visitNonlocal(node) {
        this._suppressUnboundCheck(() => {
            node.nameList.forEach((name) => {
                this._evaluator.getType(name);
                this.walk(name);
            });
        });
        return false;
    }
    visitName(node) {
        // Determine if we should log information about private usage.
        this._conditionallyReportPrivateUsage(node);
        // Determine if the name is possibly unbound.
        if (!this._isUnboundCheckSuppressed) {
            this._reportUnboundName(node);
        }
        // Report the use of a deprecated symbol.
        const type = this._evaluator.getType(node);
        this._reportDeprecatedUseForType(node, type);
        return true;
    }
    visitDel(node) {
        node.expressions.forEach((expr) => {
            this._evaluator.verifyDeleteExpression(expr);
            this.walk(expr);
        });
        return false;
    }
    visitMemberAccess(node) {
        var _a;
        const typeResult = this._evaluator.getTypeResult(node);
        const type = (_a = typeResult === null || typeResult === void 0 ? void 0 : typeResult.type) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        const leftExprType = this._evaluator.getType(node.leftExpression);
        this._reportDeprecatedUseForType(node.memberName, type, leftExprType && (0, types_1.isModule)(leftExprType) && leftExprType.moduleName === 'typing');
        if (typeResult === null || typeResult === void 0 ? void 0 : typeResult.memberAccessDeprecationInfo) {
            this._reportDeprecatedUseForMemberAccess(node.memberName, typeResult.memberAccessDeprecationInfo);
        }
        this._conditionallyReportPrivateUsage(node.memberName);
        // Walk the leftExpression but not the memberName.
        this.walk(node.leftExpression);
        return false;
    }
    visitImportAs(node) {
        this._conditionallyReportShadowedImport(node);
        this._evaluator.evaluateTypesForStatement(node);
        return true;
    }
    visitImportFrom(node) {
        // Verify that any "__future__" import occurs at the top of the file.
        if (node.module.leadingDots === 0 &&
            node.module.nameParts.length === 1 &&
            node.module.nameParts[0].value === '__future__') {
            if (!ParseTreeUtils.isValidLocationForFutureImport(node)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.futureImportLocationNotAllowed(), node);
            }
        }
        this._conditionallyReportShadowedImport(node);
        if (!node.isWildcardImport) {
            node.imports.forEach((importAs) => {
                this._evaluator.evaluateTypesForStatement(importAs);
            });
        }
        else {
            this._evaluator.evaluateTypesForStatement(node);
            const importInfo = AnalyzerNodeInfo.getImportInfo(node.module);
            if (importInfo &&
                importInfo.isImportFound &&
                importInfo.importType !== 2 /* ImportType.Local */ &&
                !this._fileInfo.isStubFile) {
                this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportWildcardImportFromLibrary, diagnosticRules_1.DiagnosticRule.reportWildcardImportFromLibrary, localize_1.LocMessage.wildcardLibraryImport(), node.wildcardToken || node);
            }
        }
        return true;
    }
    visitImportFromAs(node) {
        var _a, _b;
        if (this._fileInfo.isStubFile) {
            return false;
        }
        const decls = this._evaluator.getDeclarationsForNameNode(node.name);
        if (!decls) {
            return false;
        }
        for (const decl of decls) {
            if (!(0, declaration_1.isAliasDeclaration)(decl) || !decl.submoduleFallback || decl.node !== node) {
                // If it is not implicitly imported module, move to next.
                continue;
            }
            const resolvedAlias = this._evaluator.resolveAliasDeclaration(decl, /* resolveLocalNames */ true);
            const resolvedAliasUri = resolvedAlias === null || resolvedAlias === void 0 ? void 0 : resolvedAlias.uri;
            if (!resolvedAliasUri || !(0, sourceMapper_1.isStubFile)(resolvedAliasUri)) {
                continue;
            }
            const importResult = this._getImportResult(node, resolvedAliasUri);
            if (!importResult) {
                continue;
            }
            this._addMissingModuleSourceDiagnosticIfNeeded(importResult, node.name);
            break;
        }
        let isImportFromTyping = false;
        if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 22 /* ParseNodeType.ImportFrom */) {
            if (node.parent.module.leadingDots === 0 && node.parent.module.nameParts.length === 1) {
                if (node.parent.module.nameParts[0].value === 'typing') {
                    isImportFromTyping = true;
                }
            }
        }
        const type = this._evaluator.getType((_b = node.alias) !== null && _b !== void 0 ? _b : node.name);
        this._reportDeprecatedUseForType(node.name, type, isImportFromTyping);
        return false;
    }
    visitModuleName(node) {
        if (this._fileInfo.isStubFile) {
            return false;
        }
        const importResult = AnalyzerNodeInfo.getImportInfo(node);
        (0, debug_1.assert)(importResult !== undefined);
        this._addMissingModuleSourceDiagnosticIfNeeded(importResult, node);
        return false;
    }
    visitTypeParameterList(node) {
        this._typeParameterLists.push(node);
        return true;
    }
    visitTypeParameter(node) {
        return false;
    }
    visitTypeAlias(node) {
        const scope = (0, scopeUtils_1.getScopeForNode)(node);
        if (scope) {
            if (scope.type !== 2 /* ScopeType.Class */ && scope.type !== 3 /* ScopeType.Module */ && scope.type !== 4 /* ScopeType.Builtin */) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasStatementBadScope(), node.name);
            }
        }
        return true;
    }
    visitTypeAnnotation(node) {
        this._evaluator.getType(node.typeAnnotation);
        return true;
    }
    visitMatch(node) {
        this._evaluator.getType(node.subjectExpression);
        this._validateExhaustiveMatch(node);
        return true;
    }
    visitCase(node) {
        if (node.guardExpression) {
            this._validateConditionalIsBool(node.guardExpression);
        }
        this._evaluator.evaluateTypesForStatement(node.pattern);
        return true;
    }
    visitPatternClass(node) {
        (0, patternMatching_1.validateClassPattern)(this._evaluator, node);
        return true;
    }
    visitTry(node) {
        this._reportUnusedExceptStatements(node);
        return true;
    }
    visitError(node) {
        // Get the type of the child so it's available to
        // the completion provider.
        if (node.child) {
            this._evaluator.getType(node.child);
        }
        // Don't explore further.
        return false;
    }
    _getImportResult(node, uri) {
        const execEnv = this._importResolver.getConfigOptions().findExecEnvironment(uri);
        const moduleNameNode = node.parent.module;
        // Handle both absolute and relative imports.
        const moduleName = moduleNameNode.leadingDots === 0
            ? this._importResolver.getModuleNameForImport(uri, execEnv).moduleName
            : (0, importStatementUtils_1.getRelativeModuleName)(this._importResolver.fileSystem, this._fileInfo.fileUri, uri, this._importResolver.getConfigOptions());
        if (!moduleName) {
            return undefined;
        }
        return this._importResolver.resolveImport(this._fileInfo.fileUri, execEnv, (0, importResolver_1.createImportedModuleDescriptor)(moduleName));
    }
    _addMissingModuleSourceDiagnosticIfNeeded(importResult, node) {
        if (importResult.isNativeLib ||
            !importResult.isStubFile ||
            importResult.importType === 0 /* ImportType.BuiltIn */ ||
            !importResult.nonStubImportResult ||
            importResult.nonStubImportResult.isImportFound) {
            return;
        }
        // Type stub found, but source is missing.
        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingModuleSource, localize_1.LocMessage.importSourceResolveFailure().format({
            importName: importResult.importName,
            venv: this._fileInfo.executionEnvironment.name,
        }), node);
    }
    _validateConditionalIsBool(node) {
        const operandType = this._evaluator.getType(node);
        if (!operandType) {
            return;
        }
        let isTypeBool = true;
        const diag = new diagnostic_1.DiagnosticAddendum();
        this._evaluator.mapSubtypesExpandTypeVars(operandType, /* options */ undefined, (expandedSubtype) => {
            if ((0, types_1.isAnyOrUnknown)(expandedSubtype)) {
                return undefined;
            }
            // If it's a bool (the common case), we're good.
            if ((0, types_1.isClassInstance)(expandedSubtype) && types_1.ClassType.isBuiltIn(expandedSubtype, 'bool')) {
                return undefined;
            }
            // Invoke the __bool__ method on the type.
            const boolReturnType = this._evaluator.getTypeOfMagicMethodCall(expandedSubtype, '__bool__', [], node, 
            /* inferenceContext */ undefined);
            if (!boolReturnType || (0, types_1.isAnyOrUnknown)(boolReturnType)) {
                return undefined;
            }
            if ((0, types_1.isClassInstance)(boolReturnType) && types_1.ClassType.isBuiltIn(boolReturnType, 'bool')) {
                return undefined;
            }
            // All other types are problematic.
            isTypeBool = false;
            diag.addMessage(localize_1.LocAddendum.conditionalRequiresBool().format({
                operandType: this._evaluator.printType(expandedSubtype),
                boolReturnType: this._evaluator.printType(boolReturnType),
            }));
            return undefined;
        });
        if (!isTypeBool) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.conditionalOperandInvalid().format({
                type: this._evaluator.printType(operandType),
            }) + diag.getString(), node);
        }
    }
    _reportUnnecessaryConditionExpression(expression) {
        if (expression.nodeType === 7 /* ParseNodeType.BinaryOperation */) {
            if (expression.operator === 36 /* OperatorType.And */ || expression.operator === 37 /* OperatorType.Or */) {
                this._reportUnnecessaryConditionExpression(expression.leftExpression);
                this._reportUnnecessaryConditionExpression(expression.rightExpression);
            }
            return;
        }
        else if (expression.nodeType === 55 /* ParseNodeType.UnaryOperation */) {
            if (expression.operator === 38 /* OperatorType.Not */) {
                this._reportUnnecessaryConditionExpression(expression.expression);
            }
            return;
        }
        const exprTypeResult = this._evaluator.getTypeOfExpression(expression);
        let isExprFunction = true;
        let isCoroutine = false;
        (0, typeUtils_1.doForEachSubtype)(exprTypeResult.type, (subtype) => {
            subtype = this._evaluator.makeTopLevelTypeVarsConcrete(subtype);
            if (!(0, types_1.isFunction)(subtype) && !(0, types_1.isOverloadedFunction)(subtype)) {
                isExprFunction = false;
            }
            if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'Coroutine')) {
                isCoroutine = true;
            }
        });
        if (isExprFunction) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, localize_1.LocMessage.functionInConditionalExpression(), expression);
        }
        if (isCoroutine) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, localize_1.LocMessage.coroutineInConditionalExpression(), expression);
        }
    }
    _reportUnusedExpression(node) {
        var _a, _b;
        if (this._fileInfo.diagnosticRuleSet.reportUnusedExpression === 'none') {
            return;
        }
        const simpleExpressionTypes = [
            55 /* ParseNodeType.UnaryOperation */,
            7 /* ParseNodeType.BinaryOperation */,
            40 /* ParseNodeType.Number */,
            11 /* ParseNodeType.Constant */,
            38 /* ParseNodeType.Name */,
            52 /* ParseNodeType.Tuple */,
        ];
        let reportAsUnused = false;
        if (simpleExpressionTypes.some((nodeType) => nodeType === node.nodeType)) {
            reportAsUnused = true;
        }
        else if (node.nodeType === 31 /* ParseNodeType.List */ ||
            node.nodeType === 45 /* ParseNodeType.Set */ ||
            node.nodeType === 15 /* ParseNodeType.Dictionary */) {
            // Exclude comprehensions.
            if (!node.entries.some((entry) => entry.nodeType === 32 /* ParseNodeType.ListComprehension */)) {
                reportAsUnused = true;
            }
        }
        if (reportAsUnused &&
            this._fileInfo.ipythonMode === sourceFile_1.IPythonMode.CellDocs &&
            ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 47 /* ParseNodeType.StatementList */ &&
            node.parent.statements[node.parent.statements.length - 1] === node &&
            ((_b = node.parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 36 /* ParseNodeType.Module */ &&
            node.parent.parent.statements[node.parent.parent.statements.length - 1] === node.parent) {
            // Exclude an expression at the end of a notebook cell, as that is treated as
            // the cell's value.
            reportAsUnused = false;
        }
        if (reportAsUnused) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnusedExpression, localize_1.LocMessage.unusedExpression(), node);
        }
    }
    _validateExhaustiveMatch(node) {
        // This check can be expensive, so skip it if it's disabled.
        if (this._fileInfo.diagnosticRuleSet.reportMatchNotExhaustive === 'none') {
            return;
        }
        const narrowedTypeResult = this._evaluator.evaluateTypeForSubnode(node, () => {
            this._evaluator.evaluateTypesForMatchStatement(node);
        });
        if (narrowedTypeResult && !(0, types_1.isNever)(narrowedTypeResult.type)) {
            const diagAddendum = new diagnostic_1.DiagnosticAddendum();
            diagAddendum.addMessage(localize_1.LocAddendum.matchIsNotExhaustiveType().format({
                type: this._evaluator.printType(narrowedTypeResult.type),
            }));
            diagAddendum.addMessage(localize_1.LocAddendum.matchIsNotExhaustiveHint());
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMatchNotExhaustive, localize_1.LocMessage.matchIsNotExhaustive() + diagAddendum.getString(), node.subjectExpression);
        }
    }
    _suppressUnboundCheck(callback) {
        const wasSuppressed = this._isUnboundCheckSuppressed;
        this._isUnboundCheckSuppressed = true;
        try {
            callback();
        }
        finally {
            this._isUnboundCheckSuppressed = wasSuppressed;
        }
    }
    _validateIllegalDefaultParamInitializer(node) {
        if (this._fileInfo.diagnosticRuleSet.reportCallInDefaultInitializer !== 'none') {
            if (ParseTreeUtils.isWithinDefaultParamInitializer(node) && !this._fileInfo.isStubFile) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallInDefaultInitializer, localize_1.LocMessage.defaultValueContainsCall(), node);
            }
        }
    }
    _validateStandardCollectionInstantiation(node) {
        const leftType = this._evaluator.getType(node.leftExpression);
        if (leftType &&
            (0, types_1.isInstantiableClass)(leftType) &&
            types_1.ClassType.isBuiltIn(leftType) &&
            !leftType.includeSubclasses &&
            leftType.aliasName) {
            const nonInstantiable = ['List', 'Set', 'Dict', 'Tuple'];
            if (nonInstantiable.some((name) => name === leftType.aliasName)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.collectionAliasInstantiation().format({
                    type: leftType.aliasName,
                    alias: leftType.details.name,
                }), node.leftExpression);
            }
        }
    }
    _validateContainmentTypes(node) {
        const leftType = this._evaluator.getType(node.leftExpression);
        const containerType = this._evaluator.getType(node.rightExpression);
        if (!leftType || !containerType) {
            return;
        }
        if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(containerType)) {
            return;
        }
        // Use the common narrowing logic for containment.
        const elementType = (0, typeGuards_1.getElementTypeForContainerNarrowing)(containerType);
        if (!elementType) {
            return;
        }
        const narrowedType = (0, typeGuards_1.narrowTypeForContainerElementType)(this._evaluator, leftType, this._evaluator.makeTopLevelTypeVarsConcrete(elementType));
        if ((0, types_1.isNever)(narrowedType)) {
            const getMessage = () => {
                return node.operator === 41 /* OperatorType.In */
                    ? localize_1.LocMessage.containmentAlwaysFalse()
                    : localize_1.LocMessage.containmentAlwaysTrue();
            };
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryContains, getMessage().format({
                leftType: this._evaluator.printType(leftType, { expandTypeAlias: true }),
                rightType: this._evaluator.printType(elementType, { expandTypeAlias: true }),
            }), node);
        }
    }
    // Determines whether the types of the two operands for an "is" or "is not"
    // operation have overlapping types.
    _validateComparisonTypesForIsOperator(node) {
        const rightType = this._evaluator.getType(node.rightExpression);
        if (!rightType || !(0, typeUtils_1.isNoneInstance)(rightType)) {
            return;
        }
        const leftType = this._evaluator.getType(node.leftExpression);
        if (!leftType) {
            return;
        }
        let foundMatchForNone = false;
        (0, typeUtils_1.doForEachSubtype)(leftType, (subtype) => {
            subtype = this._evaluator.makeTopLevelTypeVarsConcrete(subtype);
            if (this._evaluator.assignType(subtype, this._evaluator.getNoneType())) {
                foundMatchForNone = true;
            }
        });
        const getMessage = () => {
            return node.operator === 39 /* OperatorType.Is */
                ? localize_1.LocMessage.comparisonAlwaysFalse()
                : localize_1.LocMessage.comparisonAlwaysTrue();
        };
        if (!foundMatchForNone) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, getMessage().format({
                leftType: this._evaluator.printType(leftType, { expandTypeAlias: true }),
                rightType: this._evaluator.printType(rightType),
            }), node);
        }
    }
    // Determines whether the types of the two operands for an == or != operation
    // have overlapping types.
    _validateComparisonTypes(node) {
        let rightExpression = node.rightExpression;
        // Check for chained comparisons.
        if (rightExpression.nodeType === 7 /* ParseNodeType.BinaryOperation */ &&
            !rightExpression.parenthesized &&
            ParseTreeUtils.operatorSupportsChaining(rightExpression.operator)) {
            // Use the left side of the right expression for comparison purposes.
            rightExpression = rightExpression.leftExpression;
        }
        const leftType = this._evaluator.getType(node.leftExpression);
        const rightType = this._evaluator.getType(rightExpression);
        if (!leftType || !rightType) {
            return;
        }
        const getMessage = () => {
            return node.operator === 12 /* OperatorType.Equals */
                ? localize_1.LocMessage.comparisonAlwaysFalse()
                : localize_1.LocMessage.comparisonAlwaysTrue();
        };
        // Check for the special case where the LHS and RHS are both literals.
        if ((0, typeUtils_1.isLiteralTypeOrUnion)(rightType) && (0, typeUtils_1.isLiteralTypeOrUnion)(leftType)) {
            if ((0, staticExpressions_1.evaluateStaticBoolExpression)(node, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants) === undefined) {
                let isPossiblyTrue = false;
                (0, typeUtils_1.doForEachSubtype)(leftType, (leftSubtype) => {
                    if (this._evaluator.assignType(rightType, leftSubtype)) {
                        isPossiblyTrue = true;
                    }
                });
                if (!isPossiblyTrue) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, getMessage().format({
                        leftType: this._evaluator.printType(leftType, { expandTypeAlias: true }),
                        rightType: this._evaluator.printType(rightType, { expandTypeAlias: true }),
                    }), node);
                }
            }
        }
        else {
            if (!this._evaluator.typesOverlap(leftType, rightType, /* checkEq */ true)) {
                const leftTypeText = this._evaluator.printType(leftType, { expandTypeAlias: true });
                const rightTypeText = this._evaluator.printType(rightType, { expandTypeAlias: true });
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, getMessage().format({
                    leftType: leftTypeText,
                    rightType: rightTypeText,
                }), node);
            }
        }
    }
    // If the function is a generator, validates that its annotated return type
    // is appropriate for a generator.
    _validateGeneratorReturnType(node, functionType) {
        var _a;
        if (!types_1.FunctionType.isGenerator(functionType)) {
            return;
        }
        const declaredReturnType = functionType.details.declaredReturnType;
        if (!declaredReturnType) {
            return;
        }
        if ((0, types_1.isNever)(declaredReturnType)) {
            return;
        }
        const functionDecl = functionType.details.declaration;
        if (!functionDecl || !functionDecl.yieldStatements || functionDecl.yieldStatements.length === 0) {
            return;
        }
        let generatorType;
        if (!node.isAsync &&
            (0, types_1.isClassInstance)(declaredReturnType) &&
            types_1.ClassType.isBuiltIn(declaredReturnType, 'AwaitableGenerator')) {
            // Handle the old-style (pre-await) generator case
            // if the return type explicitly uses AwaitableGenerator.
            generatorType = this._evaluator.getTypingType(node, 'AwaitableGenerator');
        }
        else {
            generatorType = this._evaluator.getTypingType(node, node.isAsync ? 'AsyncGenerator' : 'Generator');
        }
        if (!generatorType || !(0, types_1.isInstantiableClass)(generatorType)) {
            return;
        }
        const specializedGenerator = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(generatorType, [types_1.AnyType.create(), types_1.AnyType.create(), types_1.AnyType.create()], 
        /* isTypeArgumentExplicit */ true));
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        if (!this._evaluator.assignType(declaredReturnType, specializedGenerator, diagAddendum)) {
            const errorMessage = node.isAsync
                ? localize_1.LocMessage.generatorAsyncReturnType()
                : localize_1.LocMessage.generatorSyncReturnType();
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, errorMessage.format({ yieldType: this._evaluator.printType(types_1.AnyType.create()) }) +
                diagAddendum.getString(), (_a = node.returnTypeAnnotation) !== null && _a !== void 0 ? _a : node.name);
        }
    }
    // Determines whether the specified type is one that should trigger
    // an "unused" value diagnostic.
    _isTypeValidForUnusedValueTest(type) {
        return !(0, typeUtils_1.isNoneInstance)(type) && !(0, types_1.isNever)(type) && !(0, types_1.isAnyOrUnknown)(type);
    }
    // Verifies that each local type variable is used more than once.
    _validateFunctionTypeVarUsage(node, functionTypeResult) {
        // Skip this check entirely if it's disabled.
        if (this._fileInfo.diagnosticRuleSet.reportInvalidTypeVarUse === 'none') {
            return;
        }
        const type = functionTypeResult.functionType;
        const localTypeVarUsage = new Map();
        const classTypeVarUsage = new Map();
        let exemptBoundTypeVar = true;
        let curParamNode;
        // Is this a constructor (an __init__ method) for a generic class?
        let constructorClass;
        if (types_1.FunctionType.isInstanceMethod(type) && node.name.value === '__init__') {
            const containingClassNode = ParseTreeUtils.getEnclosingClassOrFunction(node);
            if (containingClassNode && containingClassNode.nodeType === 10 /* ParseNodeType.Class */) {
                const classType = this._evaluator.getTypeOfClass(containingClassNode);
                if (classType && (0, types_1.isClass)(classType.classType)) {
                    constructorClass = classType.classType;
                }
            }
        }
        const nameWalker = new ParseTreeUtils.NameNodeWalker((nameNode, subscriptIndex, baseExpression) => {
            var _a, _b, _c, _d, _e, _f;
            const nameType = this._evaluator.getType(nameNode);
            ``;
            if (nameType && (0, types_1.isTypeVar)(nameType) && !nameType.details.isSynthesizedSelf) {
                // Does this name refer to a TypeVar that is scoped to this function?
                if (nameType.scopeId === ParseTreeUtils.getScopeIdForNode(node)) {
                    // We exempt constrained TypeVars, TypeVars that are type arguments of
                    // other types, and ParamSpecs. There are legitimate uses for singleton
                    // instances in these particular cases.
                    let isExempt = nameType.details.constraints.length > 0 ||
                        nameType.details.isDefaultExplicit ||
                        (exemptBoundTypeVar && subscriptIndex !== undefined) ||
                        (0, types_1.isParamSpec)(nameType);
                    if (!isExempt && baseExpression && subscriptIndex !== undefined) {
                        // Is this a type argument for a generic type alias? If so,
                        // exempt it from the check because the type alias may repeat
                        // the TypeVar multiple times.
                        const baseType = this._evaluator.getType(baseExpression);
                        if ((baseType === null || baseType === void 0 ? void 0 : baseType.typeAliasInfo) &&
                            baseType.typeAliasInfo.typeParameters &&
                            subscriptIndex < baseType.typeAliasInfo.typeParameters.length) {
                            isExempt = true;
                        }
                    }
                    const existingEntry = localTypeVarUsage.get(nameType.details.name);
                    const isParamTypeWithEllipsisUsage = ((_a = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.defaultValue) === null || _a === void 0 ? void 0 : _a.nodeType) === 18 /* ParseNodeType.Ellipsis */;
                    if (!existingEntry) {
                        localTypeVarUsage.set(nameType.details.name, {
                            nodes: [nameNode],
                            typeVar: nameType,
                            paramTypeUsageCount: curParamNode !== undefined ? 1 : 0,
                            paramTypeWithEllipsisUsageCount: isParamTypeWithEllipsisUsage ? 1 : 0,
                            returnTypeUsageCount: curParamNode === undefined ? 1 : 0,
                            paramWithEllipsis: isParamTypeWithEllipsisUsage ? (_b = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.name) === null || _b === void 0 ? void 0 : _b.value : undefined,
                            isExempt,
                        });
                    }
                    else {
                        existingEntry.nodes.push(nameNode);
                        if (curParamNode !== undefined) {
                            existingEntry.paramTypeUsageCount += 1;
                            if (isParamTypeWithEllipsisUsage) {
                                existingEntry.paramTypeWithEllipsisUsageCount += 1;
                                if (!existingEntry.paramWithEllipsis) {
                                    existingEntry.paramWithEllipsis = (_c = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.name) === null || _c === void 0 ? void 0 : _c.value;
                                }
                            }
                        }
                        else {
                            existingEntry.returnTypeUsageCount += 1;
                        }
                    }
                }
                // Does this name refer to a TypeVar that is scoped to the class associated with
                // this constructor method?
                if (constructorClass && nameType.scopeId === constructorClass.details.typeVarScopeId) {
                    const existingEntry = classTypeVarUsage.get(nameType.details.name);
                    const isParamTypeWithEllipsisUsage = ((_d = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.defaultValue) === null || _d === void 0 ? void 0 : _d.nodeType) === 18 /* ParseNodeType.Ellipsis */;
                    const isExempt = !!nameType.details.isDefaultExplicit;
                    if (!existingEntry) {
                        classTypeVarUsage.set(nameType.details.name, {
                            typeVar: nameType,
                            nodes: [nameNode],
                            paramTypeUsageCount: curParamNode !== undefined ? 1 : 0,
                            paramTypeWithEllipsisUsageCount: isParamTypeWithEllipsisUsage ? 1 : 0,
                            returnTypeUsageCount: 0,
                            paramWithEllipsis: isParamTypeWithEllipsisUsage ? (_e = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.name) === null || _e === void 0 ? void 0 : _e.value : undefined,
                            isExempt,
                        });
                    }
                    else {
                        existingEntry.nodes.push(nameNode);
                        if (curParamNode !== undefined) {
                            existingEntry.paramTypeUsageCount += 1;
                            if (isParamTypeWithEllipsisUsage) {
                                existingEntry.paramTypeWithEllipsisUsageCount += 1;
                                if (!existingEntry.paramWithEllipsis) {
                                    existingEntry.paramWithEllipsis = (_f = curParamNode === null || curParamNode === void 0 ? void 0 : curParamNode.name) === null || _f === void 0 ? void 0 : _f.value;
                                }
                            }
                        }
                    }
                }
            }
        });
        // Find all of the local type variables in signature.
        node.parameters.forEach((param) => {
            const annotation = param.typeAnnotation || param.typeAnnotationComment;
            if (annotation) {
                curParamNode = param;
                nameWalker.walk(annotation);
            }
        });
        curParamNode = undefined;
        if (node.returnTypeAnnotation) {
            // Don't exempt the use of a bound TypeVar when used as a type argument
            // within a return type. This exemption applies only to input parameter
            // annotations.
            exemptBoundTypeVar = false;
            nameWalker.walk(node.returnTypeAnnotation);
        }
        localTypeVarUsage.forEach((usage) => {
            var _a;
            // Report error for local type variable that appears only once.
            if (usage.nodes.length === 1 && !usage.isExempt) {
                let altTypeText;
                if (usage.typeVar.details.isVariadic) {
                    altTypeText = '"tuple[object, ...]"';
                }
                else if (usage.typeVar.details.boundType) {
                    altTypeText = `"${this._evaluator.printType((0, typeUtils_1.convertToInstance)(usage.typeVar.details.boundType))}"`;
                }
                else {
                    altTypeText = '"object"';
                }
                const diag = new diagnostic_1.DiagnosticAddendum();
                diag.addMessage(localize_1.LocAddendum.typeVarUnnecessarySuggestion().format({
                    type: altTypeText,
                }));
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeVarUse, localize_1.LocMessage.typeVarUsedOnlyOnce().format({
                    name: usage.nodes[0].value,
                }) + diag.getString(), usage.nodes[0]);
            }
            // Report error for local type variable that appears in return type
            // (but not as a top-level TypeVar within a union) and appears only
            // within parameters that have default values. These may go unsolved.
            let isUsedInReturnType = usage.returnTypeUsageCount > 0;
            if (usage.returnTypeUsageCount === 1 && type.details.declaredReturnType) {
                // If the TypeVar appears only once in the return type and it's a top-level
                // TypeVar within a union, exempt it from this check. Although these
                // TypeVars may go unsolved, they can be safely eliminated from the union
                // without generating an Unknown type.
                const returnType = type.details.declaredReturnType;
                if ((0, types_1.isUnion)(returnType) &&
                    returnType.subtypes.some((subtype) => (0, types_1.isTypeVar)(subtype) && subtype.details.name === usage.nodes[0].value)) {
                    isUsedInReturnType = false;
                }
            }
            // Skip this check if the function is overloaded because the TypeVar
            // will be solved in terms of the overload signatures.
            const skipUnsolvableTypeVarCheck = (0, types_1.isOverloadedFunction)(functionTypeResult.decoratedType) &&
                !types_1.FunctionType.isOverloaded(functionTypeResult.functionType);
            if (isUsedInReturnType &&
                usage.paramTypeWithEllipsisUsageCount > 0 &&
                usage.paramTypeUsageCount === usage.paramTypeWithEllipsisUsageCount &&
                !skipUnsolvableTypeVarCheck) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                diag.addMessage(localize_1.LocAddendum.typeVarUnsolvableRemedy());
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeVarUse, localize_1.LocMessage.typeVarPossiblyUnsolvable().format({
                    name: usage.nodes[0].value,
                    param: (_a = usage.paramWithEllipsis) !== null && _a !== void 0 ? _a : '',
                }) + diag.getString(), usage.nodes[0]);
            }
        });
        // Report error for a class type variable that appears only within
        // constructor parameters that have default values. These may go unsolved.
        classTypeVarUsage.forEach((usage) => {
            var _a;
            if (usage.paramTypeWithEllipsisUsageCount > 0 &&
                usage.paramTypeUsageCount === usage.paramTypeWithEllipsisUsageCount &&
                !usage.isExempt) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                diag.addMessage(localize_1.LocAddendum.typeVarUnsolvableRemedy());
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeVarUse, localize_1.LocMessage.typeVarPossiblyUnsolvable().format({
                    name: usage.nodes[0].value,
                    param: (_a = usage.paramWithEllipsis) !== null && _a !== void 0 ? _a : '',
                }) + diag.getString(), usage.nodes[0]);
            }
        });
    }
    // Validates that overloads use @staticmethod and @classmethod consistently.
    _validateOverloadAttributeConsistency(node, functionType) {
        var _a, _b, _c, _d, _e, _f;
        let staticMethodCount = 0;
        let classMethodCount = 0;
        functionType.overloads.forEach((overload) => {
            if (types_1.FunctionType.isStaticMethod(overload)) {
                staticMethodCount++;
            }
            if (types_1.FunctionType.isClassMethod(overload)) {
                classMethodCount++;
            }
        });
        if (staticMethodCount > 0 && staticMethodCount < functionType.overloads.length) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadStaticMethodInconsistent().format({
                name: node.name.value,
            }), (_c = (_b = (_a = functionType.overloads[0]) === null || _a === void 0 ? void 0 : _a.details.declaration) === null || _b === void 0 ? void 0 : _b.node.name) !== null && _c !== void 0 ? _c : node.name);
        }
        if (classMethodCount > 0 && classMethodCount < functionType.overloads.length) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadClassMethodInconsistent().format({
                name: node.name.value,
            }), (_f = (_e = (_d = functionType.overloads[0]) === null || _d === void 0 ? void 0 : _d.details.declaration) === null || _e === void 0 ? void 0 : _e.node.name) !== null && _f !== void 0 ? _f : node.name);
        }
    }
    // Validates that overloads do not overlap with inconsistent return results.
    _validateOverloadConsistency(node, functionType, prevOverloads) {
        for (let i = 0; i < prevOverloads.length; i++) {
            const prevOverload = prevOverloads[i];
            if (this._isOverlappingOverload(functionType, prevOverload, /* partialOverlap */ false)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOverlappingOverload, localize_1.LocMessage.overlappingOverload().format({
                    name: node.name.value,
                    obscured: prevOverloads.length + 1,
                    obscuredBy: i + 1,
                }), node.name);
                break;
            }
        }
        for (let i = 0; i < prevOverloads.length; i++) {
            const prevOverload = prevOverloads[i];
            if (this._isOverlappingOverload(prevOverload, functionType, /* partialOverlap */ true)) {
                const prevReturnType = types_1.FunctionType.getSpecializedReturnType(prevOverload);
                const returnType = types_1.FunctionType.getSpecializedReturnType(functionType);
                if (prevReturnType &&
                    returnType &&
                    !this._evaluator.assignType(returnType, prevReturnType, 
                    /* diag */ undefined, new typeVarContext_1.TypeVarContext(), 
                    /* srcTypeVarContext */ undefined, 8 /* AssignTypeFlags.SkipSolveTypeVars */ | 1024 /* AssignTypeFlags.IgnoreTypeVarScope */)) {
                    const altNode = this._findNodeForOverload(node, prevOverload);
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOverlappingOverload, localize_1.LocMessage.overloadReturnTypeMismatch().format({
                        name: node.name.value,
                        newIndex: prevOverloads.length + 1,
                        prevIndex: i + 1,
                    }), (altNode || node).name);
                    break;
                }
            }
        }
    }
    // Mypy reports overlapping overload errors on the line that contains the
    // earlier overload. Typeshed stubs contain type: ignore comments on these
    // lines, so it is important for us to report them in the same manner.
    _findNodeForOverload(functionNode, overloadType) {
        const decls = this._evaluator.getDeclarationsForNameNode(functionNode.name);
        if (!decls) {
            return undefined;
        }
        for (const decl of decls) {
            if (decl.type === 5 /* DeclarationType.Function */) {
                const functionType = this._evaluator.getTypeOfFunction(decl.node);
                if ((functionType === null || functionType === void 0 ? void 0 : functionType.functionType) === overloadType) {
                    return decl.node;
                }
            }
        }
        return undefined;
    }
    _isOverlappingOverload(functionType, prevOverload, partialOverlap) {
        // According to precedent, the __get__ method is special-cased and is
        // exempt from overlapping overload checks. It's not clear why this is
        // the case, but for consistency with other type checkers, we'll honor
        // this rule. See https://github.com/python/typing/issues/253#issuecomment-389262904
        // for details.
        if (types_1.FunctionType.isInstanceMethod(functionType) && functionType.details.name === '__get__') {
            return false;
        }
        let flags = 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */ | 16 /* AssignTypeFlags.OverloadOverlapCheck */;
        if (partialOverlap) {
            flags |= 32 /* AssignTypeFlags.PartialOverloadOverlapCheck */;
        }
        return this._evaluator.assignType(functionType, prevOverload, 
        /* diag */ undefined, new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(functionType)), 
        /* srcTypeVarContext */ undefined, flags);
    }
    _isLegalOverloadImplementation(overload, implementation, diag) {
        var _a;
        const implTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(implementation));
        const overloadTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overload));
        // First check the parameters to see if they are assignable.
        let isLegal = this._evaluator.assignType(overload, implementation, diag, overloadTypeVarContext, implTypeVarContext, 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */ |
            2 /* AssignTypeFlags.ReverseTypeVarMatching */ |
            512 /* AssignTypeFlags.SkipSelfClsTypeCheck */);
        // Now check the return types.
        const overloadReturnType = (_a = overload.details.declaredReturnType) !== null && _a !== void 0 ? _a : this._evaluator.getFunctionInferredReturnType(overload);
        const implementationReturnType = (0, typeUtils_1.applySolvedTypeVars)(implementation.details.declaredReturnType || this._evaluator.getFunctionInferredReturnType(implementation), implTypeVarContext);
        const returnDiag = new diagnostic_1.DiagnosticAddendum();
        if (!(0, types_1.isNever)(overloadReturnType) &&
            !this._evaluator.assignType(implementationReturnType, overloadReturnType, returnDiag.createAddendum(), implTypeVarContext, overloadTypeVarContext, 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
            returnDiag.addMessage(localize_1.LocAddendum.functionReturnTypeMismatch().format({
                sourceType: this._evaluator.printType(overloadReturnType),
                destType: this._evaluator.printType(implementationReturnType),
            }));
            diag === null || diag === void 0 ? void 0 : diag.addAddendum(returnDiag);
            isLegal = false;
        }
        return isLegal;
    }
    _walkStatementsAndReportUnreachable(statements) {
        let reportedUnreachable = false;
        let prevStatement;
        for (const statement of statements) {
            // No need to report unreachable more than once since the first time
            // covers all remaining statements in the statement list.
            if (!reportedUnreachable) {
                if (!this._evaluator.isNodeReachable(statement, prevStatement)) {
                    // Create a text range that covers the next statement through
                    // the end of the statement list.
                    const start = statement.start;
                    const lastStatement = statements[statements.length - 1];
                    const end = textRange_1.TextRange.getEnd(lastStatement);
                    this._evaluator.addUnreachableCode(statement, { start, length: end - start });
                    reportedUnreachable = true;
                }
            }
            if (!reportedUnreachable && this._fileInfo.isStubFile) {
                this._validateStubStatement(statement);
            }
            this.walk(statement);
            prevStatement = statement;
        }
    }
    _validateStubStatement(statement) {
        switch (statement.nodeType) {
            case 19 /* ParseNodeType.If */:
            case 28 /* ParseNodeType.Function */:
            case 10 /* ParseNodeType.Class */:
            case 0 /* ParseNodeType.Error */: {
                // These are allowed in a stub file.
                break;
            }
            case 57 /* ParseNodeType.While */:
            case 26 /* ParseNodeType.For */:
            case 53 /* ParseNodeType.Try */:
            case 58 /* ParseNodeType.With */: {
                // These are not allowed.
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidStubStatement, localize_1.LocMessage.invalidStubStatement(), statement);
                break;
            }
            case 47 /* ParseNodeType.StatementList */: {
                for (const substatement of statement.statements) {
                    let isValid = true;
                    switch (substatement.nodeType) {
                        case 2 /* ParseNodeType.Assert */:
                        case 4 /* ParseNodeType.AssignmentExpression */:
                        case 6 /* ParseNodeType.Await */:
                        case 7 /* ParseNodeType.BinaryOperation */:
                        case 11 /* ParseNodeType.Constant */:
                        case 14 /* ParseNodeType.Del */:
                        case 15 /* ParseNodeType.Dictionary */:
                        case 24 /* ParseNodeType.Index */:
                        case 26 /* ParseNodeType.For */:
                        case 27 /* ParseNodeType.FormatString */:
                        case 29 /* ParseNodeType.Global */:
                        case 30 /* ParseNodeType.Lambda */:
                        case 31 /* ParseNodeType.List */:
                        case 35 /* ParseNodeType.MemberAccess */:
                        case 38 /* ParseNodeType.Name */:
                        case 39 /* ParseNodeType.Nonlocal */:
                        case 40 /* ParseNodeType.Number */:
                        case 43 /* ParseNodeType.Raise */:
                        case 44 /* ParseNodeType.Return */:
                        case 45 /* ParseNodeType.Set */:
                        case 46 /* ParseNodeType.Slice */:
                        case 51 /* ParseNodeType.Ternary */:
                        case 52 /* ParseNodeType.Tuple */:
                        case 53 /* ParseNodeType.Try */:
                        case 55 /* ParseNodeType.UnaryOperation */:
                        case 56 /* ParseNodeType.Unpack */:
                        case 57 /* ParseNodeType.While */:
                        case 58 /* ParseNodeType.With */:
                        case 59 /* ParseNodeType.WithItem */:
                        case 60 /* ParseNodeType.Yield */:
                        case 61 /* ParseNodeType.YieldFrom */: {
                            isValid = false;
                            break;
                        }
                        case 5 /* ParseNodeType.AugmentedAssignment */: {
                            // Exempt __all__ manipulations.
                            isValid =
                                substatement.operator === 1 /* OperatorType.AddEqual */ &&
                                    substatement.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                                    substatement.leftExpression.value === '__all__';
                            break;
                        }
                        case 9 /* ParseNodeType.Call */: {
                            // Exempt __all__ manipulations.
                            isValid =
                                substatement.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                                    substatement.leftExpression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                                    substatement.leftExpression.leftExpression.value === '__all__';
                            break;
                        }
                    }
                    if (!isValid) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidStubStatement, localize_1.LocMessage.invalidStubStatement(), substatement);
                    }
                }
            }
        }
    }
    _validateExceptionTypeRecursive(exceptionType, diag, baseExceptionType, allowTuple) {
        const derivesFromBaseException = (classType) => {
            if (!baseExceptionType || !(0, types_1.isInstantiableClass)(baseExceptionType)) {
                return true;
            }
            return (0, typeUtils_1.derivesFromClassRecursive)(classType, baseExceptionType, /* ignoreUnknown */ false);
        };
        (0, typeUtils_1.doForEachSubtype)(exceptionType, (exceptionSubtype) => {
            if ((0, types_1.isAnyOrUnknown)(exceptionSubtype)) {
                return;
            }
            if ((0, types_1.isClass)(exceptionSubtype)) {
                if (types_1.TypeBase.isInstantiable(exceptionSubtype)) {
                    if (!derivesFromBaseException(exceptionSubtype)) {
                        diag.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                            type: this._evaluator.printType(exceptionSubtype),
                        }));
                    }
                    return;
                }
                if (allowTuple && exceptionSubtype.tupleTypeArguments) {
                    exceptionSubtype.tupleTypeArguments.forEach((typeArg) => {
                        this._validateExceptionTypeRecursive(typeArg.type, diag, baseExceptionType, 
                        /* allowTuple */ false);
                    });
                    return;
                }
                diag.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                    type: this._evaluator.printType(exceptionSubtype),
                }));
            }
        });
    }
    _validateExceptionType(exceptionType, errorNode) {
        const baseExceptionType = this._evaluator.getBuiltInType(errorNode, 'BaseException');
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        this._validateExceptionTypeRecursive(exceptionType, diagAddendum, baseExceptionType, /* allowTuple */ true);
        if (!diagAddendum.isEmpty()) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.exceptionTypeNotClass().format({
                type: this._evaluator.printType(exceptionType),
            }), errorNode);
        }
    }
    _reportUnusedDunderAllSymbols(nodes) {
        // If this rule is disabled, don't bother doing the work.
        if (this._fileInfo.diagnosticRuleSet.reportUnsupportedDunderAll === 'none') {
            return;
        }
        const moduleScope = AnalyzerNodeInfo.getScope(this._moduleNode);
        if (!moduleScope) {
            return;
        }
        nodes.forEach((node) => {
            if (!moduleScope.symbolTable.has(node.value)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnsupportedDunderAll, localize_1.LocMessage.dunderAllSymbolNotPresent().format({ name: node.value }), node);
            }
        });
    }
    _validateSymbolTables() {
        var _a;
        const dependentFileInfo = (_a = this._dependentFiles) === null || _a === void 0 ? void 0 : _a.map((p) => AnalyzerNodeInfo.getFileInfo(p.parseTree));
        for (const scopedNode of this._scopedNodes) {
            const scope = AnalyzerNodeInfo.getScope(scopedNode);
            if (scope) {
                scope.symbolTable.forEach((symbol, name) => {
                    this._conditionallyReportUnusedSymbol(name, symbol, scope.type, dependentFileInfo);
                    this._reportIncompatibleDeclarations(name, symbol);
                    this._reportMultipleFinalDeclarations(name, symbol, scope.type);
                    this._reportMultipleTypeAliasDeclarations(name, symbol);
                    this._reportInvalidOverload(name, symbol);
                });
            }
        }
        // Report unaccessed type parameters.
        const accessedSymbolSet = this._fileInfo.accessedSymbolSet;
        for (const paramList of this._typeParameterLists) {
            for (const param of paramList.parameters) {
                const symbol = AnalyzerNodeInfo.getTypeParameterSymbol(param.name);
                if (!symbol) {
                    // This can happen if the code is unreachable.
                    return;
                }
                if (!accessedSymbolSet.has(symbol.id)) {
                    const decls = symbol.getDeclarations();
                    decls.forEach((decl) => {
                        this._conditionallyReportUnusedDeclaration(decl, /* isPrivate */ false);
                    });
                }
            }
        }
    }
    _reportInvalidOverload(name, symbol) {
        const typedDecls = symbol.getTypedDeclarations();
        if (typedDecls.length >= 1) {
            const primaryDecl = typedDecls[0];
            if (primaryDecl.type === 5 /* DeclarationType.Function */) {
                const type = this._evaluator.getEffectiveTypeOfSymbol(symbol);
                const overloadedFunctions = (0, types_1.isOverloadedFunction)(type)
                    ? types_1.OverloadedFunctionType.getOverloads(type)
                    : (0, types_1.isFunction)(type) && types_1.FunctionType.isOverloaded(type)
                        ? [type]
                        : [];
                if (overloadedFunctions.length === 1) {
                    // There should never be a single overload.
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.singleOverload().format({ name }), primaryDecl.node.name);
                }
                // If the file is not a stub and this is the first overload,
                // verify that there is an implementation.
                if (!this._fileInfo.isStubFile && overloadedFunctions.length > 0) {
                    let implementationFunction;
                    let exemptMissingImplementation = false;
                    if ((0, types_1.isOverloadedFunction)(type)) {
                        implementationFunction = types_1.OverloadedFunctionType.getImplementation(type);
                        // If the implementation has no name, it was synthesized probably by a
                        // decorator that used a callable with a ParamSpec that captured the
                        // overloaded signature. We'll exempt it from this check.
                        const overloads = types_1.OverloadedFunctionType.getOverloads(type);
                        if (overloads.length > 0 && overloads[0].details.name === '') {
                            exemptMissingImplementation = true;
                        }
                    }
                    else if ((0, types_1.isFunction)(type) && !types_1.FunctionType.isOverloaded(type)) {
                        implementationFunction = type;
                    }
                    if (!implementationFunction) {
                        const containingClassNode = ParseTreeUtils.getEnclosingClassOrFunction(primaryDecl.node);
                        if (containingClassNode && containingClassNode.nodeType === 10 /* ParseNodeType.Class */) {
                            const classType = this._evaluator.getTypeOfClass(containingClassNode);
                            if (classType) {
                                if (types_1.ClassType.isProtocolClass(classType.classType)) {
                                    exemptMissingImplementation = true;
                                }
                                else if (types_1.ClassType.supportsAbstractMethods(classType.classType)) {
                                    if ((0, types_1.isOverloadedFunction)(type) &&
                                        types_1.OverloadedFunctionType.getOverloads(type).every((overload) => types_1.FunctionType.isAbstractMethod(overload))) {
                                        exemptMissingImplementation = true;
                                    }
                                }
                            }
                        }
                        // If this is a method within a protocol class, don't require that
                        // there is an implementation.
                        if (!exemptMissingImplementation) {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportNoOverloadImplementation, localize_1.LocMessage.overloadWithoutImplementation().format({
                                name: primaryDecl.node.name.value,
                            }), primaryDecl.node.name);
                        }
                    }
                    else if ((0, types_1.isOverloadedFunction)(type)) {
                        // Verify that all overload signatures are assignable to implementation signature.
                        types_1.OverloadedFunctionType.getOverloads(type).forEach((overload, index) => {
                            var _a, _b, _c, _d;
                            const diag = new diagnostic_1.DiagnosticAddendum();
                            if (!this._isLegalOverloadImplementation(overload, implementationFunction, diag)) {
                                if (implementationFunction.details.declaration) {
                                    const diagnostic = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadImplementationMismatch().format({
                                        name,
                                        index: index + 1,
                                    }) + diag.getString(), implementationFunction.details.declaration.node.name);
                                    if (diagnostic && overload.details.declaration) {
                                        diagnostic.addRelatedInfo(localize_1.LocAddendum.overloadSignature(), (_b = (_a = overload.details.declaration) === null || _a === void 0 ? void 0 : _a.uri) !== null && _b !== void 0 ? _b : primaryDecl.uri, (_d = (_c = overload.details.declaration) === null || _c === void 0 ? void 0 : _c.range) !== null && _d !== void 0 ? _d : primaryDecl.range);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
    }
    _reportMultipleFinalDeclarations(name, symbol, scopeType) {
        if (!this._evaluator.isFinalVariable(symbol)) {
            return;
        }
        const decls = symbol.getDeclarations();
        let sawFinal = false;
        let sawAssignment = false;
        decls.forEach((decl) => {
            var _a;
            if (this._evaluator.isFinalVariableDeclaration(decl)) {
                if (sawFinal) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalRedeclaration().format({ name }), decl.node);
                }
                sawFinal = true;
            }
            let reportRedeclaration = false;
            if (decl.type === 1 /* DeclarationType.Variable */) {
                if (decl.inferredTypeSource) {
                    if (sawAssignment) {
                        // We check for assignment of Final instance and class variables
                        // the type evaluator because we need to take into account whether
                        // the assignment is within an `__init__` method, so ignore class
                        // scopes here.
                        if (scopeType !== 2 /* ScopeType.Class */) {
                            reportRedeclaration = true;
                        }
                    }
                    sawAssignment = true;
                }
            }
            else {
                reportRedeclaration = true;
            }
            if (reportRedeclaration) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalReassigned().format({ name }), (_a = (0, declarationUtils_1.getNameNodeForDeclaration)(decl)) !== null && _a !== void 0 ? _a : decl.node);
            }
        });
        // If it's not a stub file, an assignment must be provided.
        if (!sawAssignment && !this._fileInfo.isStubFile) {
            const firstDecl = decls.find((decl) => decl.type === 1 /* DeclarationType.Variable */ && decl.isFinal);
            if (firstDecl) {
                // Is this an instance variable declared within a dataclass? If so, it
                // is implicitly initialized by the synthesized `__init__` method and
                // therefore has an implied assignment.
                let isImplicitlyAssigned = false;
                // Is this a class variable within a protocol class? If so, it can
                // be marked final without providing a value.
                let isProtocolClass = false;
                if (symbol.isClassMember() && !symbol.isClassVar()) {
                    const containingClass = ParseTreeUtils.getEnclosingClass(firstDecl.node, /* stopAtFunction */ true);
                    if (containingClass) {
                        const classType = this._evaluator.getTypeOfClass(containingClass);
                        if (classType && (0, types_1.isClass)(classType.decoratedType)) {
                            if (types_1.ClassType.isDataClass(classType.decoratedType)) {
                                isImplicitlyAssigned = true;
                            }
                            if (types_1.ClassType.isProtocolClass(classType.decoratedType)) {
                                isProtocolClass = true;
                            }
                        }
                    }
                }
                if (!isImplicitlyAssigned && !isProtocolClass) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalUnassigned().format({ name }), firstDecl.node);
                }
            }
        }
    }
    _reportMultipleTypeAliasDeclarations(name, symbol) {
        const decls = symbol.getDeclarations();
        const typeAliasDecl = decls.find((decl) => this._evaluator.isExplicitTypeAliasDeclaration(decl));
        // If this is a type alias, there should be only one declaration.
        if (typeAliasDecl && decls.length > 1) {
            decls.forEach((decl) => {
                if (decl !== typeAliasDecl) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, localize_1.LocMessage.typeAliasRedeclared().format({ name }), decl.node);
                }
            });
        }
    }
    _reportIncompatibleDeclarations(name, symbol) {
        var _a, _b;
        // If there's one or more declaration with a declared type,
        // all other declarations should match. The only exception is
        // for functions that have an overload.
        const primaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
        // If there's no declaration with a declared type, we're done.
        if (!primaryDecl) {
            return;
        }
        // Special case the '_' symbol, which is used in single dispatch
        // code and other cases where the name does not matter.
        if (name === '_') {
            return;
        }
        let otherDecls = symbol.getDeclarations().filter((decl) => decl !== primaryDecl);
        // If it's a function, we can skip any other declarations
        // that are overloads or property setters/deleters.
        if (primaryDecl.type === 5 /* DeclarationType.Function */) {
            const primaryDeclTypeInfo = this._evaluator.getTypeOfFunction(primaryDecl.node);
            otherDecls = otherDecls.filter((decl) => {
                if (decl.type !== 5 /* DeclarationType.Function */) {
                    return true;
                }
                const funcTypeInfo = this._evaluator.getTypeOfFunction(decl.node);
                if (!funcTypeInfo) {
                    return true;
                }
                const decoratedType = primaryDeclTypeInfo
                    ? this._evaluator.makeTopLevelTypeVarsConcrete(primaryDeclTypeInfo.decoratedType)
                    : undefined;
                // We need to handle properties in a careful manner because of
                // the way that setters and deleters are often defined using multiple
                // methods with the same name.
                if (decoratedType &&
                    (0, types_1.isClassInstance)(decoratedType) &&
                    types_1.ClassType.isPropertyClass(decoratedType) &&
                    (0, types_1.isClassInstance)(funcTypeInfo.decoratedType) &&
                    types_1.ClassType.isPropertyClass(funcTypeInfo.decoratedType)) {
                    return funcTypeInfo.decoratedType.details.typeSourceId !== decoratedType.details.typeSourceId;
                }
                return !types_1.FunctionType.isOverloaded(funcTypeInfo.functionType);
            });
        }
        // If there are no other declarations to consider, we're done.
        if (otherDecls.length === 0) {
            return;
        }
        let primaryDeclInfo;
        if (primaryDecl.type === 5 /* DeclarationType.Function */) {
            if (primaryDecl.isMethod) {
                primaryDeclInfo = localize_1.LocAddendum.seeMethodDeclaration();
            }
            else {
                primaryDeclInfo = localize_1.LocAddendum.seeFunctionDeclaration();
            }
        }
        else if (primaryDecl.type === 6 /* DeclarationType.Class */) {
            primaryDeclInfo = localize_1.LocAddendum.seeClassDeclaration();
        }
        else if (primaryDecl.type === 2 /* DeclarationType.Parameter */) {
            primaryDeclInfo = localize_1.LocAddendum.seeParameterDeclaration();
        }
        else if (primaryDecl.type === 1 /* DeclarationType.Variable */) {
            primaryDeclInfo = localize_1.LocAddendum.seeVariableDeclaration();
        }
        else if (primaryDecl.type === 4 /* DeclarationType.TypeAlias */) {
            primaryDeclInfo = localize_1.LocAddendum.seeTypeAliasDeclaration();
        }
        else {
            primaryDeclInfo = localize_1.LocAddendum.seeDeclaration();
        }
        const addPrimaryDeclInfo = (diag) => {
            if (diag) {
                let primaryDeclNode;
                if (primaryDecl.type === 5 /* DeclarationType.Function */ || primaryDecl.type === 6 /* DeclarationType.Class */) {
                    primaryDeclNode = primaryDecl.node.name;
                }
                else if (primaryDecl.type === 1 /* DeclarationType.Variable */) {
                    if (primaryDecl.node.nodeType === 38 /* ParseNodeType.Name */) {
                        primaryDeclNode = primaryDecl.node;
                    }
                }
                else if (primaryDecl.type === 2 /* DeclarationType.Parameter */ ||
                    primaryDecl.type === 3 /* DeclarationType.TypeParameter */) {
                    if (primaryDecl.node.name) {
                        primaryDeclNode = primaryDecl.node.name;
                    }
                }
                if (primaryDeclNode) {
                    diag.addRelatedInfo(primaryDeclInfo, primaryDecl.uri, primaryDecl.range);
                }
            }
        };
        for (const otherDecl of otherDecls) {
            if (otherDecl.type === 6 /* DeclarationType.Class */) {
                let duplicateIsOk = false;
                if (primaryDecl.type === 3 /* DeclarationType.TypeParameter */) {
                    // The error will be reported elsewhere if a type parameter is
                    // involved, so don't report it here.
                    duplicateIsOk = true;
                }
                if (!duplicateIsOk) {
                    const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, localize_1.LocMessage.obscuredClassDeclaration().format({ name }), otherDecl.node.name);
                    addPrimaryDeclInfo(diag);
                }
            }
            else if (otherDecl.type === 5 /* DeclarationType.Function */) {
                const primaryType = (_a = this._evaluator.getTypeForDeclaration(primaryDecl)) === null || _a === void 0 ? void 0 : _a.type;
                let duplicateIsOk = false;
                // If the return type has not yet been inferred, do so now.
                if (primaryType && (0, types_1.isFunction)(primaryType)) {
                    this._evaluator.getFunctionInferredReturnType(primaryType);
                }
                const otherType = (_b = this._evaluator.getTypeForDeclaration(otherDecl)) === null || _b === void 0 ? void 0 : _b.type;
                const suite1 = ParseTreeUtils.getEnclosingSuite(primaryDecl.node);
                const suite2 = ParseTreeUtils.getEnclosingSuite(otherDecl.node);
                // Allow same-signature overrides in cases where the declarations
                // are not within the same statement suite (e.g. one in the "if"
                // and another in the "else").
                const isInSameStatementList = suite1 === suite2;
                // If the return type has not yet been inferred, do so now.
                if (otherType && (0, types_1.isFunction)(otherType)) {
                    this._evaluator.getFunctionInferredReturnType(otherType);
                }
                // If both declarations are functions, it's OK if they
                // both have the same signatures.
                if (!isInSameStatementList && primaryType && otherType && (0, types_1.isTypeSame)(primaryType, otherType)) {
                    duplicateIsOk = true;
                }
                if (primaryDecl.type === 3 /* DeclarationType.TypeParameter */) {
                    // The error will be reported elsewhere if a type parameter is
                    // involved, so don't report it here.
                    duplicateIsOk = true;
                }
                if (!duplicateIsOk) {
                    const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, otherDecl.isMethod
                        ? localize_1.LocMessage.obscuredMethodDeclaration().format({ name })
                        : localize_1.LocMessage.obscuredFunctionDeclaration().format({ name }), otherDecl.node.name);
                    addPrimaryDeclInfo(diag);
                }
            }
            else if (otherDecl.type === 2 /* DeclarationType.Parameter */) {
                if (otherDecl.node.name) {
                    let duplicateIsOk = false;
                    if (primaryDecl.type === 3 /* DeclarationType.TypeParameter */) {
                        // The error will be reported elsewhere if a type parameter is
                        // involved, so don't report it here.
                        duplicateIsOk = true;
                    }
                    if (!duplicateIsOk) {
                        const message = localize_1.LocMessage.obscuredParameterDeclaration();
                        const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, message.format({ name }), otherDecl.node.name);
                        addPrimaryDeclInfo(diag);
                    }
                }
            }
            else if (otherDecl.type === 1 /* DeclarationType.Variable */) {
                if (otherDecl.typeAnnotationNode) {
                    if (otherDecl.node.nodeType === 38 /* ParseNodeType.Name */) {
                        let duplicateIsOk = false;
                        if (primaryDecl.type === 3 /* DeclarationType.TypeParameter */) {
                            // The error will be reported elsewhere if a type parameter is
                            // involved, so don't report it here.
                            duplicateIsOk = true;
                        }
                        if (!duplicateIsOk) {
                            const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, localize_1.LocMessage.obscuredVariableDeclaration().format({ name }), otherDecl.node);
                            addPrimaryDeclInfo(diag);
                        }
                    }
                }
            }
            else if (otherDecl.type === 4 /* DeclarationType.TypeAlias */) {
                const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportRedeclaration, localize_1.LocMessage.obscuredTypeAliasDeclaration().format({ name }), otherDecl.node.name);
                addPrimaryDeclInfo(diag);
            }
        }
    }
    _conditionallyReportUnusedSymbol(name, symbol, scopeType, dependentFileInfo) {
        const accessedSymbolSet = this._fileInfo.accessedSymbolSet;
        if (symbol.isIgnoredForProtocolMatch() || accessedSymbolSet.has(symbol.id)) {
            return;
        }
        // If this file is implicitly imported by other files, we need to make sure the symbol defined in
        // the current file is not accessed from those other files.
        if (dependentFileInfo && dependentFileInfo.some((i) => i.accessedSymbolSet.has(symbol.id))) {
            return;
        }
        // A name of "_" means "I know this symbol isn't used", so
        // don't report it as unused.
        if (name === '_') {
            return;
        }
        if (SymbolNameUtils.isDunderName(name)) {
            return;
        }
        const decls = symbol.getDeclarations();
        decls.forEach((decl) => {
            this._conditionallyReportUnusedDeclaration(decl, this._isSymbolPrivate(name, scopeType));
        });
    }
    _conditionallyReportUnusedDeclaration(decl, isPrivate) {
        var _a;
        let diagnosticLevel;
        let nameNode;
        let message;
        let rule;
        switch (decl.type) {
            case 8 /* DeclarationType.Alias */:
                diagnosticLevel = this._fileInfo.diagnosticRuleSet.reportUnusedImport;
                rule = diagnosticRules_1.DiagnosticRule.reportUnusedImport;
                if (decl.node.nodeType === 21 /* ParseNodeType.ImportAs */) {
                    if (decl.node.alias) {
                        // For statements of the form "import x as x", don't mark "x" as unaccessed
                        // because it's assumed to be re-exported.
                        // See https://typing.readthedocs.io/en/latest/source/stubs.html#imports.
                        if (decl.node.alias.value !== decl.moduleName) {
                            nameNode = decl.node.alias;
                        }
                    }
                    else {
                        // Handle multi-part names specially.
                        const nameParts = decl.node.module.nameParts;
                        if (nameParts.length > 0) {
                            const multipartName = nameParts.map((np) => np.value).join('.');
                            let textRange = { start: nameParts[0].start, length: nameParts[0].length };
                            textRange = textRange_1.TextRange.extend(textRange, nameParts[nameParts.length - 1]);
                            this._fileInfo.diagnosticSink.addUnusedCodeWithTextRange(localize_1.LocMessage.unaccessedSymbol().format({ name: multipartName }), textRange, { action: "basedpyright.unusedImport" /* Commands.unusedImport */ });
                            this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportUnusedImport, diagnosticRules_1.DiagnosticRule.reportUnusedImport, localize_1.LocMessage.unaccessedImport().format({ name: multipartName }), textRange);
                            return;
                        }
                    }
                }
                else if (decl.node.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
                    const importFrom = decl.node.parent;
                    // For statements of the form "from y import x as x", don't mark "x" as
                    // unaccessed because it's assumed to be re-exported.
                    const isReexport = ((_a = decl.node.alias) === null || _a === void 0 ? void 0 : _a.value) === decl.node.name.value;
                    // If this is a __future__ import, it's OK for the import symbol to be unaccessed.
                    const isFuture = importFrom.module.nameParts.length === 1 &&
                        importFrom.module.nameParts[0].value === '__future__';
                    if (!isReexport && !isFuture) {
                        nameNode = decl.node.alias || decl.node.name;
                    }
                }
                if (nameNode) {
                    message = localize_1.LocMessage.unaccessedImport().format({ name: nameNode.value });
                }
                break;
            case 4 /* DeclarationType.TypeAlias */:
            case 1 /* DeclarationType.Variable */:
            case 2 /* DeclarationType.Parameter */:
                if (!isPrivate) {
                    return;
                }
                if (this._fileInfo.isStubFile) {
                    // Don't mark variables or parameters as unaccessed in
                    // stub files. It's typical for them to be unaccessed here.
                    return;
                }
                diagnosticLevel = this._fileInfo.diagnosticRuleSet.reportUnusedVariable;
                if (decl.node.nodeType === 38 /* ParseNodeType.Name */) {
                    nameNode = decl.node;
                    // Don't emit a diagnostic if the name starts with an underscore.
                    // This indicates that the variable is unused.
                    if (nameNode.value.startsWith('_')) {
                        diagnosticLevel = 'none';
                    }
                }
                else if (decl.node.nodeType === 41 /* ParseNodeType.Parameter */) {
                    nameNode = decl.node.name;
                    // Don't emit a diagnostic for unused parameters or type parameters.
                    diagnosticLevel = 'none';
                }
                if (nameNode) {
                    rule = diagnosticRules_1.DiagnosticRule.reportUnusedVariable;
                    message = localize_1.LocMessage.unaccessedVariable().format({ name: nameNode.value });
                }
                break;
            case 6 /* DeclarationType.Class */:
                if (!isPrivate) {
                    return;
                }
                // If a stub is exporting a private type, we'll assume that the author
                // knows what he or she is doing.
                if (this._fileInfo.isStubFile) {
                    return;
                }
                diagnosticLevel = this._fileInfo.diagnosticRuleSet.reportUnusedClass;
                nameNode = decl.node.name;
                rule = diagnosticRules_1.DiagnosticRule.reportUnusedClass;
                message = localize_1.LocMessage.unaccessedClass().format({ name: nameNode.value });
                break;
            case 5 /* DeclarationType.Function */:
                if (!isPrivate) {
                    return;
                }
                // If a stub is exporting a private type, we'll assume that the author
                // knows what he or she is doing.
                if (this._fileInfo.isStubFile) {
                    return;
                }
                diagnosticLevel = this._fileInfo.diagnosticRuleSet.reportUnusedFunction;
                nameNode = decl.node.name;
                rule = diagnosticRules_1.DiagnosticRule.reportUnusedFunction;
                message = localize_1.LocMessage.unaccessedFunction().format({ name: nameNode.value });
                break;
            case 3 /* DeclarationType.TypeParameter */:
                // Never report a diagnostic for an unused TypeParameter.
                diagnosticLevel = 'none';
                nameNode = decl.node.name;
                break;
            case 0 /* DeclarationType.Intrinsic */:
            case 7 /* DeclarationType.SpecialBuiltInClass */:
                return;
            default:
                (0, debug_1.assertNever)(decl);
        }
        const action = rule === diagnosticRules_1.DiagnosticRule.reportUnusedImport ? { action: "basedpyright.unusedImport" /* Commands.unusedImport */ } : undefined;
        if (nameNode) {
            this._fileInfo.diagnosticSink.addUnusedCodeWithTextRange(localize_1.LocMessage.unaccessedSymbol().format({ name: nameNode.value }), nameNode, action);
            if (rule !== undefined && message && diagnosticLevel !== 'none') {
                this._evaluator.addDiagnostic(rule, message, nameNode);
            }
        }
    }
    // Validates that a call to isinstance or issubclass are necessary. This is a
    // common source of programming errors. Also validates that arguments passed
    // to isinstance or issubclass won't generate exceptions.
    _validateIsInstanceCall(node) {
        if (node.leftExpression.nodeType !== 38 /* ParseNodeType.Name */ ||
            (node.leftExpression.value !== 'isinstance' && node.leftExpression.value !== 'issubclass') ||
            node.arguments.length !== 2) {
            return;
        }
        const callName = node.leftExpression.value;
        const isInstanceCheck = callName === 'isinstance';
        let arg0Type = this._evaluator.getType(node.arguments[0].valueExpression);
        if (!arg0Type) {
            return;
        }
        arg0Type = (0, typeUtils_1.mapSubtypes)(arg0Type, (subtype) => {
            return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
        });
        arg0Type = this._evaluator.expandPromotionTypes(node, arg0Type);
        const arg1Type = this._evaluator.getType(node.arguments[1].valueExpression);
        if (!arg1Type) {
            return;
        }
        let isValidType = true;
        const diag = new diagnostic_1.DiagnosticAddendum();
        (0, typeUtils_1.doForEachSubtype)(arg1Type, (arg1Subtype) => {
            if ((0, types_1.isClassInstance)(arg1Subtype) && types_1.ClassType.isTupleClass(arg1Subtype) && arg1Subtype.tupleTypeArguments) {
                if (arg1Subtype.tupleTypeArguments.some((typeArg) => !this._isTypeSupportedTypeForIsInstance(typeArg.type, isInstanceCheck, diag))) {
                    isValidType = false;
                }
            }
            else {
                if (!this._isTypeSupportedTypeForIsInstance(arg1Subtype, isInstanceCheck, diag)) {
                    isValidType = false;
                }
            }
        });
        if (!isValidType) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, isInstanceCheck
                ? localize_1.LocMessage.isInstanceInvalidType().format({
                    type: this._evaluator.printType(arg1Type),
                }) + diag.getString()
                : localize_1.LocMessage.isSubclassInvalidType().format({
                    type: this._evaluator.printType(arg1Type),
                }) + diag.getString(), node.arguments[1]);
        }
        // If this call is an issubclass, check for the use of a "data protocol",
        // which PEP 544 says cannot be used in issubclass.
        if (!isInstanceCheck) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            (0, typeUtils_1.doForEachSubtype)(arg1Type, (arg1Subtype) => {
                if ((0, types_1.isClassInstance)(arg1Subtype) &&
                    types_1.ClassType.isTupleClass(arg1Subtype) &&
                    arg1Subtype.tupleTypeArguments) {
                    arg1Subtype.tupleTypeArguments.forEach((typeArg) => {
                        this._validateNotDataProtocol(typeArg.type, diag);
                    });
                }
                else {
                    this._validateNotDataProtocol(arg1Subtype, diag);
                }
            });
            if (!diag.isEmpty()) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataProtocolInSubclassCheck(), node.arguments[1]);
            }
        }
        // If this call is within an assert statement, we won't check whether
        // it's unnecessary.
        let curNode = node;
        while (curNode) {
            if (curNode.nodeType === 2 /* ParseNodeType.Assert */) {
                return;
            }
            curNode = curNode.parent;
        }
        // Several built-in classes don't follow the normal class hierarchy
        // rules, so we'll avoid emitting false-positive diagnostics if these
        // are used.
        const nonstandardClassTypes = [
            'FunctionType',
            'LambdaType',
            'BuiltinFunctionType',
            'BuiltinMethodType',
            'type',
            'Type',
        ];
        const classTypeList = [];
        let arg1IncludesSubclasses = false;
        (0, typeUtils_1.doForEachSubtype)(arg1Type, (arg1Subtype) => {
            if ((0, types_1.isClass)(arg1Subtype)) {
                if (types_1.TypeBase.isInstantiable(arg1Subtype)) {
                    if (arg1Subtype.literalValue === undefined) {
                        classTypeList.push(arg1Subtype);
                        if (types_1.ClassType.isBuiltIn(arg1Subtype) &&
                            nonstandardClassTypes.some((name) => name === arg1Subtype.details.name)) {
                            isValidType = false;
                        }
                        if (arg1Subtype.includeSubclasses) {
                            arg1IncludesSubclasses = true;
                        }
                    }
                    if (arg0Type) {
                        this._validateUnsafeProtocolOverlap(node.arguments[0].valueExpression, (0, typeUtils_1.convertToInstance)(arg1Subtype), isInstanceCheck ? arg0Type : (0, typeUtils_1.convertToInstance)(arg0Type));
                    }
                }
                else {
                    // The isinstance and issubclass call supports a variation where the second
                    // parameter is a tuple of classes.
                    if ((0, typeUtils_1.isTupleClass)(arg1Subtype)) {
                        if (arg1Subtype.tupleTypeArguments) {
                            arg1Subtype.tupleTypeArguments.forEach((typeArg) => {
                                if ((0, types_1.isInstantiableClass)(typeArg.type)) {
                                    classTypeList.push(typeArg.type);
                                    if (typeArg.type.includeSubclasses) {
                                        arg1IncludesSubclasses = true;
                                    }
                                    if (arg0Type) {
                                        this._validateUnsafeProtocolOverlap(node.arguments[0].valueExpression, (0, typeUtils_1.convertToInstance)(typeArg.type), isInstanceCheck ? arg0Type : (0, typeUtils_1.convertToInstance)(arg0Type));
                                    }
                                }
                                else {
                                    isValidType = false;
                                }
                            });
                        }
                    }
                    else {
                        if (arg1Subtype.includeSubclasses) {
                            arg1IncludesSubclasses = true;
                        }
                    }
                    if (types_1.ClassType.isBuiltIn(arg1Subtype) &&
                        nonstandardClassTypes.some((name) => name === arg1Subtype.details.name)) {
                        isValidType = false;
                    }
                }
            }
            else {
                isValidType = false;
            }
        });
        if (!isValidType) {
            return;
        }
        if ((0, typeUtils_1.derivesFromAnyOrUnknown)(arg0Type)) {
            return;
        }
        const finalizeFilteredTypeList = (types) => {
            return (0, types_1.combineTypes)(types);
        };
        const filterType = (varType) => {
            const filteredTypes = [];
            for (const filterType of classTypeList) {
                const filterIsSuperclass = (0, typeGuards_1.isIsinstanceFilterSuperclass)(this._evaluator, varType, varType, filterType, filterType, isInstanceCheck);
                const filterIsSubclass = (0, typeGuards_1.isIsinstanceFilterSubclass)(this._evaluator, varType, filterType, isInstanceCheck);
                // Normally, a class should never be both a subclass and a
                // superclass. However, this can happen if one of the classes
                // derives from an unknown type. In this case, we'll add an
                // unknown type into the filtered type list to avoid any
                // false positives.
                const isClassRelationshipIndeterminate = filterIsSuperclass && filterIsSubclass && !types_1.ClassType.isSameGenericClass(varType, filterType);
                if (isClassRelationshipIndeterminate) {
                    filteredTypes.push(types_1.UnknownType.create());
                }
                else if (filterIsSuperclass) {
                    // If the variable type is a subclass of the isinstance
                    // filter, we haven't learned anything new about the
                    // variable type.
                    filteredTypes.push(varType);
                }
                else if (filterIsSubclass) {
                    // If the variable type is a superclass of the isinstance
                    // filter, we can narrow the type to the subclass.
                    filteredTypes.push(filterType);
                }
            }
            if (!isInstanceCheck) {
                return filteredTypes;
            }
            // Make all instantiable classes into instances before returning them.
            return filteredTypes.map((t) => ((0, types_1.isInstantiableClass)(t) ? types_1.ClassType.cloneAsInstance(t) : t));
        };
        let filteredType;
        if (isInstanceCheck && (0, types_1.isClassInstance)(arg0Type)) {
            const remainingTypes = filterType(types_1.ClassType.cloneAsInstantiable(arg0Type));
            filteredType = finalizeFilteredTypeList(remainingTypes);
        }
        else if (!isInstanceCheck && (0, types_1.isInstantiableClass)(arg0Type)) {
            const remainingTypes = filterType(arg0Type);
            filteredType = finalizeFilteredTypeList(remainingTypes);
        }
        else if ((0, types_1.isUnion)(arg0Type)) {
            let remainingTypes = [];
            let foundAnyType = false;
            (0, typeUtils_1.doForEachSubtype)(arg0Type, (subtype) => {
                if ((0, types_1.isAnyOrUnknown)(subtype)) {
                    foundAnyType = true;
                }
                if (isInstanceCheck && (0, types_1.isClassInstance)(subtype)) {
                    remainingTypes = remainingTypes.concat(filterType(types_1.ClassType.cloneAsInstantiable(subtype)));
                }
                else if (!isInstanceCheck && (0, types_1.isInstantiableClass)(subtype)) {
                    remainingTypes = remainingTypes.concat(filterType(subtype));
                }
            });
            filteredType = finalizeFilteredTypeList(remainingTypes);
            // If we found an any or unknown type, all bets are off.
            if (foundAnyType) {
                return;
            }
        }
        else {
            return;
        }
        const getTestType = () => {
            const objTypeList = classTypeList.map((t) => types_1.ClassType.cloneAsInstance(t));
            return (0, types_1.combineTypes)(objTypeList);
        };
        // If arg1IncludesSubclasses is true, it contains a Type[X] class rather than X. A Type[X]
        // could be a subclass of X, so the "unnecessary isinstance check" may be legit.
        if (!arg1IncludesSubclasses && (0, types_1.isTypeSame)(filteredType, arg0Type, { ignorePseudoGeneric: true })) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryIsInstance, isInstanceCheck
                ? localize_1.LocMessage.unnecessaryIsInstanceAlways().format({
                    testType: this._evaluator.printType(arg0Type),
                    classType: this._evaluator.printType(getTestType()),
                })
                : localize_1.LocMessage.unnecessaryIsSubclassAlways().format({
                    testType: this._evaluator.printType(arg0Type),
                    classType: this._evaluator.printType(getTestType()),
                }), node);
        }
    }
    _validateUnsafeProtocolOverlap(errorNode, protocol, testType) {
        // If this is a protocol class, check for an "unsafe overlap"
        // with the arg0 type.
        if (types_1.ClassType.isProtocolClass(protocol)) {
            let isUnsafeOverlap = false;
            const diag = new diagnostic_1.DiagnosticAddendum();
            (0, typeUtils_1.doForEachSubtype)(testType, (testSubtype) => {
                if ((0, types_1.isClassInstance)(testSubtype)) {
                    if ((0, protocols_1.isProtocolUnsafeOverlap)(this._evaluator, protocol, testSubtype)) {
                        isUnsafeOverlap = true;
                        diag.addMessage(localize_1.LocAddendum.protocolUnsafeOverlap().format({
                            name: testSubtype.details.name,
                        }));
                    }
                }
            });
            if (isUnsafeOverlap) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.protocolUnsafeOverlap().format({
                    name: protocol.details.name,
                }) + diag.getString(), errorNode);
            }
        }
    }
    // Determines whether the specified type is allowed as the second argument
    // to an isinstance or issubclass check.
    _isTypeSupportedTypeForIsInstance(type, isInstanceCheck, diag) {
        let isSupported = true;
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            subtype = this._evaluator.makeTopLevelTypeVarsConcrete(subtype);
            subtype = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
            if (subtype.specialForm && types_1.ClassType.isBuiltIn(subtype.specialForm, 'TypeAliasType')) {
                diag.addMessage(localize_1.LocAddendum.typeAliasInstanceCheck());
                isSupported = false;
                return;
            }
            switch (subtype.category) {
                case 2 /* TypeCategory.Any */:
                case 1 /* TypeCategory.Unknown */:
                case 0 /* TypeCategory.Unbound */:
                    break;
                case 6 /* TypeCategory.Class */:
                    if (types_1.ClassType.isBuiltIn(subtype, 'TypedDict')) {
                        diag.addMessage(localize_1.LocAddendum.typedDictNotAllowed());
                        isSupported = false;
                    }
                    else if (types_1.ClassType.isBuiltIn(subtype, 'NamedTuple')) {
                        diag.addMessage(localize_1.LocAddendum.namedTupleNotAllowed());
                        isSupported = false;
                    }
                    else if ((0, typeUtils_1.isNoneInstance)(subtype)) {
                        diag.addMessage(localize_1.LocAddendum.noneNotAllowed());
                        isSupported = false;
                    }
                    else if (types_1.ClassType.isTypedDictClass(subtype)) {
                        diag.addMessage(localize_1.LocAddendum.typedDictClassNotAllowed());
                        isSupported = false;
                    }
                    else if (subtype.isTypeArgumentExplicit && !subtype.includeSubclasses) {
                        // If it's a class, make sure that it has not been given explicit
                        // type arguments. This will result in a TypeError exception.
                        diag.addMessage(localize_1.LocAddendum.genericClassNotAllowed());
                        isSupported = false;
                    }
                    else if (types_1.ClassType.isProtocolClass(subtype) &&
                        !types_1.ClassType.isRuntimeCheckable(subtype) &&
                        !subtype.includeSubclasses) {
                        // According to PEP 544, protocol classes cannot be used as the right-hand
                        // argument to isinstance or issubclass unless they are annotated as
                        // "runtime checkable".
                        diag.addMessage(localize_1.LocAddendum.protocolRequiresRuntimeCheckable());
                        isSupported = false;
                    }
                    else if (types_1.ClassType.isNewTypeClass(subtype)) {
                        diag.addMessage(localize_1.LocAddendum.newTypeClassNotAllowed());
                        isSupported = false;
                    }
                    else if (subtype.specialForm &&
                        (0, types_1.isInstantiableClass)(subtype.specialForm) &&
                        types_1.ClassType.isBuiltIn(subtype.specialForm, 'Annotated')) {
                        diag.addMessage(localize_1.LocAddendum.annotatedNotAllowed());
                        isSupported = false;
                    }
                    break;
                case 4 /* TypeCategory.Function */:
                    if (!types_1.TypeBase.isInstantiable(subtype) || subtype.isCallableWithTypeArgs) {
                        diag.addMessage(localize_1.LocAddendum.genericClassNotAllowed());
                        isSupported = false;
                    }
                    break;
                case 9 /* TypeCategory.TypeVar */:
                    diag.addMessage(localize_1.LocAddendum.typeVarNotAllowed());
                    isSupported = false;
                    break;
            }
        });
        return isSupported;
    }
    _validateNotDataProtocol(type, diag) {
        if ((0, types_1.isInstantiableClass)(type) && types_1.ClassType.isProtocolClass(type) && !(0, protocols_1.isMethodOnlyProtocol)(type)) {
            diag.addMessage(localize_1.LocAddendum.dataProtocolUnsupported().format({
                name: type.details.name,
            }));
        }
    }
    _isSymbolPrivate(nameValue, scopeType) {
        // All variables within the scope of a function or a list
        // comprehension are considered private.
        if (scopeType === 1 /* ScopeType.Function */ || scopeType === 0 /* ScopeType.ListComprehension */) {
            return true;
        }
        // See if the symbol is private.
        if (SymbolNameUtils.isPrivateName(nameValue)) {
            return true;
        }
        if (SymbolNameUtils.isProtectedName(nameValue)) {
            // Protected names outside of a class scope are considered private.
            const isClassScope = scopeType === 2 /* ScopeType.Class */;
            return !isClassScope;
        }
        return false;
    }
    _reportDeprecatedClassProperty(node, functionTypeResult) {
        if (!(0, types_1.isClassInstance)(functionTypeResult.decoratedType) ||
            !types_1.ClassType.isClassProperty(functionTypeResult.decoratedType)) {
            return;
        }
        this._reportDeprecatedDiagnostic(node.name, localize_1.LocMessage.classPropertyDeprecated());
    }
    _reportDeprecatedUseForMemberAccess(node, info) {
        let errorMessage;
        if (info.accessType === 'property') {
            if (info.accessMethod === 'get') {
                errorMessage = localize_1.LocMessage.deprecatedPropertyGetter().format({ name: node.value });
            }
            else if (info.accessMethod === 'set') {
                errorMessage = localize_1.LocMessage.deprecatedPropertySetter().format({ name: node.value });
            }
            else {
                errorMessage = localize_1.LocMessage.deprecatedPropertyDeleter().format({ name: node.value });
            }
        }
        else if (info.accessType === 'descriptor') {
            if (info.accessMethod === 'get') {
                errorMessage = localize_1.LocMessage.deprecatedDescriptorGetter().format({ name: node.value });
            }
            else if (info.accessMethod === 'set') {
                errorMessage = localize_1.LocMessage.deprecatedDescriptorSetter().format({ name: node.value });
            }
            else {
                errorMessage = localize_1.LocMessage.deprecatedDescriptorDeleter().format({ name: node.value });
            }
        }
        if (errorMessage) {
            this._reportDeprecatedDiagnostic(node, errorMessage, info.deprecationMessage);
        }
    }
    _reportDeprecatedUseForType(node, type, isImportFromTyping = false) {
        var _a, _b;
        if (!type) {
            return;
        }
        let errorMessage;
        let deprecatedMessage;
        function getDeprecatedMessageForFunction(functionType) {
            if (functionType.details.declaration &&
                functionType.details.declaration.node.nodeType === 28 /* ParseNodeType.Function */) {
                const containingClass = ParseTreeUtils.getEnclosingClass(functionType.details.declaration.node, 
                /* stopAtFunction */ true);
                if (containingClass) {
                    return localize_1.LocMessage.deprecatedMethod().format({
                        name: functionType.details.name || '<anonymous>',
                        className: containingClass.name.value,
                    });
                }
            }
            return localize_1.LocMessage.deprecatedFunction().format({
                name: functionType.details.name,
            });
        }
        function getDeprecatedMessageForOverloadedCall(evaluator, type) {
            // Determine if the node is part of a call expression. If so,
            // we can determine which overload(s) were used to satisfy
            // the call expression and determine whether any of them
            // are deprecated.
            let callTypeResult;
            const callNode = ParseTreeUtils.getCallForName(node);
            if (callNode) {
                callTypeResult = evaluator.getTypeResult(callNode);
            }
            else {
                const decoratorNode = ParseTreeUtils.getDecoratorForName(node);
                if (decoratorNode) {
                    callTypeResult = evaluator.getTypeResultForDecorator(decoratorNode);
                }
            }
            if (callTypeResult &&
                callTypeResult.overloadsUsedForCall &&
                callTypeResult.overloadsUsedForCall.length > 0) {
                callTypeResult.overloadsUsedForCall.forEach((overload) => {
                    if (overload.details.deprecatedMessage !== undefined) {
                        if (node.value === overload.details.name) {
                            deprecatedMessage = overload.details.deprecatedMessage;
                            errorMessage = getDeprecatedMessageForFunction(overload);
                        }
                        else if ((0, types_1.isInstantiableClass)(type) && overload.details.name === '__init__') {
                            deprecatedMessage = overload.details.deprecatedMessage;
                            errorMessage = localize_1.LocMessage.deprecatedConstructor().format({
                                name: type.details.name,
                            });
                        }
                    }
                });
            }
        }
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if ((0, types_1.isClass)(subtype)) {
                if (!subtype.includeSubclasses &&
                    subtype.details.deprecatedMessage !== undefined &&
                    node.value === subtype.details.name) {
                    deprecatedMessage = subtype.details.deprecatedMessage;
                    errorMessage = localize_1.LocMessage.deprecatedClass().format({ name: subtype.details.name });
                }
                else {
                    // See if this is part of a call to a constructor.
                    getDeprecatedMessageForOverloadedCall(this._evaluator, subtype);
                }
            }
            else if ((0, types_1.isFunction)(subtype)) {
                if (subtype.details.deprecatedMessage !== undefined) {
                    if (!subtype.details.name || node.value === subtype.details.name) {
                        deprecatedMessage = subtype.details.deprecatedMessage;
                        errorMessage = getDeprecatedMessageForFunction(subtype);
                    }
                }
            }
            else if ((0, types_1.isOverloadedFunction)(subtype)) {
                // Determine if the node is part of a call expression. If so,
                // we can determine which overload(s) were used to satisfy
                // the call expression and determine whether any of them
                // are deprecated.
                getDeprecatedMessageForOverloadedCall(this._evaluator, subtype);
                // If there the implementation itself is deprecated, assume it
                // is deprecated even if it's outside of a call expression.
                const overloadImpl = types_1.OverloadedFunctionType.getImplementation(subtype);
                if ((overloadImpl === null || overloadImpl === void 0 ? void 0 : overloadImpl.details.deprecatedMessage) !== undefined) {
                    if (!overloadImpl.details.name || node.value === overloadImpl.details.name) {
                        deprecatedMessage = overloadImpl.details.deprecatedMessage;
                        errorMessage = getDeprecatedMessageForFunction(overloadImpl);
                    }
                }
            }
        });
        if (errorMessage) {
            this._reportDeprecatedDiagnostic(node, errorMessage, deprecatedMessage);
        }
        if (this._fileInfo.diagnosticRuleSet.deprecateTypingAliases) {
            const deprecatedForm = (_a = deprecatedSymbols_1.deprecatedAliases.get(node.value)) !== null && _a !== void 0 ? _a : deprecatedSymbols_1.deprecatedSpecialForms.get(node.value);
            if (deprecatedForm) {
                if (((0, types_1.isInstantiableClass)(type) && type.details.fullName === deprecatedForm.fullName) ||
                    ((_b = type.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.fullName) === deprecatedForm.fullName) {
                    if (this._fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(deprecatedForm.version)) {
                        if (!deprecatedForm.typingImportOnly || isImportFromTyping) {
                            if (this._fileInfo.diagnosticRuleSet.reportDeprecated === 'none') {
                                this._evaluator.addDeprecated(localize_1.LocMessage.deprecatedType().format({
                                    version: deprecatedForm.version.toString(),
                                    replacement: deprecatedForm.replacementText,
                                }), node);
                            }
                            else {
                                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportDeprecated, localize_1.LocMessage.deprecatedType().format({
                                    version: deprecatedForm.version.toString(),
                                    replacement: deprecatedForm.replacementText,
                                }), node);
                            }
                        }
                    }
                }
            }
        }
    }
    _reportDeprecatedDiagnostic(node, diagnosticMessage, deprecatedMessage) {
        const diag = new diagnostic_1.DiagnosticAddendum();
        if (deprecatedMessage) {
            diag.addMessage(deprecatedMessage);
        }
        if (this._fileInfo.diagnosticRuleSet.reportDeprecated === 'none') {
            this._evaluator.addDeprecated(diagnosticMessage + diag.getString(), node);
        }
        else {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportDeprecated, diagnosticMessage + diag.getString(), node);
        }
    }
    _reportUnboundName(node) {
        if (this._fileInfo.diagnosticRuleSet.reportUnboundVariable === 'none') {
            return;
        }
        if (!AnalyzerNodeInfo.isCodeUnreachable(node)) {
            const type = this._evaluator.getType(node);
            if (type) {
                if ((0, types_1.isUnbound)(type)) {
                    if (this._evaluator.isNodeReachable(node)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnboundVariable, localize_1.LocMessage.symbolIsUnbound().format({ name: node.value }), node);
                    }
                }
                else if ((0, types_1.isPossiblyUnbound)(type)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPossiblyUnboundVariable, localize_1.LocMessage.symbolIsPossiblyUnbound().format({ name: node.value }), node);
                }
            }
        }
    }
    _conditionallyReportShadowedModule() {
        if (this._fileInfo.diagnosticRuleSet.reportShadowedImports === 'none') {
            return;
        }
        // Check the module we're in.
        const moduleName = this._fileInfo.moduleName;
        const desc = {
            nameParts: moduleName.split('.'),
            leadingDots: 0,
            importedSymbols: new Set(),
        };
        const stdlibPath = this._importResolver.getTypeshedStdLibPath(this._fileInfo.executionEnvironment);
        if (stdlibPath &&
            this._importResolver.isStdlibModule(desc, this._fileInfo.executionEnvironment) &&
            this._sourceMapper.isUserCode(this._fileInfo.fileUri)) {
            // This means the user has a module that is overwriting the stdlib module.
            const diag = this._evaluator.addDiagnosticForTextRange(this._fileInfo, this._fileInfo.diagnosticRuleSet.reportShadowedImports, diagnosticRules_1.DiagnosticRule.reportShadowedImports, localize_1.LocMessage.stdlibModuleOverridden().format({
                name: moduleName,
                path: this._fileInfo.fileUri.toUserVisibleString(),
            }), this._moduleNode);
            // Add a quick action that renames the file.
            if (diag) {
                const renameAction = {
                    action: "renameShadowedFile" /* ActionKind.RenameShadowedFileAction */,
                    oldUri: this._fileInfo.fileUri,
                    newUri: this._sourceMapper.getNextFileName(this._fileInfo.fileUri),
                };
                diag.addAction(renameAction);
            }
        }
    }
    _conditionallyReportShadowedImport(node) {
        var _a, _b;
        if (this._fileInfo.diagnosticRuleSet.reportShadowedImports === 'none') {
            return;
        }
        // Skip this check for relative imports.
        const nodeModule = node.nodeType === 23 /* ParseNodeType.ImportFromAs */
            ? ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 22 /* ParseNodeType.ImportFrom */
                ? (_b = node.parent) === null || _b === void 0 ? void 0 : _b.module
                : undefined
            : node.module;
        if (nodeModule === null || nodeModule === void 0 ? void 0 : nodeModule.leadingDots) {
            return;
        }
        // Otherwise use the name to determine if a match for a stdlib module.
        const namePartNodes = node.nodeType === 21 /* ParseNodeType.ImportAs */
            ? node.module.nameParts
            : node.nodeType === 23 /* ParseNodeType.ImportFromAs */
                ? [node.name]
                : node.module.nameParts;
        const nameParts = namePartNodes.map((n) => n.value);
        const module = {
            nameParts,
            leadingDots: 0,
            importedSymbols: new Set(),
        };
        // Make sure the module is a potential stdlib one so we don't spend the time
        // searching for the definition.
        const stdlibPath = this._importResolver.getTypeshedStdLibPath(this._fileInfo.executionEnvironment);
        if (stdlibPath && this._importResolver.isStdlibModule(module, this._fileInfo.executionEnvironment)) {
            // If the definition for this name is in 'user' module, it is overwriting the stdlib module.
            const definitions = definitionProvider_1.DefinitionProvider.getDefinitionsForNode(this._sourceMapper, this._evaluator, namePartNodes[namePartNodes.length - 1], namePartNodes[namePartNodes.length - 1].start, vscode_languageserver_1.CancellationToken.None);
            const paths = definitions ? definitions.map((d) => d.uri) : [];
            paths.forEach((p) => {
                if (!p.startsWith(stdlibPath) && !(0, sourceMapper_1.isStubFile)(p) && this._sourceMapper.isUserCode(p)) {
                    // This means the user has a module that is overwriting the stdlib module.
                    const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportShadowedImports, localize_1.LocMessage.stdlibModuleOverridden().format({
                        name: nameParts.join('.'),
                        path: p.toUserVisibleString(),
                    }), node);
                    // Add a quick action that renames the file.
                    if (diag) {
                        const renameAction = {
                            action: "renameShadowedFile" /* ActionKind.RenameShadowedFileAction */,
                            oldUri: p,
                            newUri: this._sourceMapper.getNextFileName(p),
                        };
                        diag.addAction(renameAction);
                    }
                }
            });
        }
    }
    _conditionallyReportPrivateUsage(node) {
        var _a;
        if (this._fileInfo.diagnosticRuleSet.reportPrivateUsage === 'none') {
            return;
        }
        // Ignore privates in type stubs.
        if (this._fileInfo.isStubFile) {
            return;
        }
        // Ignore privates in named arguments.
        if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 1 /* ParseNodeType.Argument */ && node.parent.name === node) {
            return;
        }
        const nameValue = node.value;
        const isPrivateName = SymbolNameUtils.isPrivateName(nameValue);
        const isProtectedName = SymbolNameUtils.isProtectedName(nameValue);
        // If it's not a protected or private name, don't bother with
        // any further checks.
        if (!isPrivateName && !isProtectedName) {
            return;
        }
        const declarations = this._evaluator.getDeclarationsForNameNode(node);
        let primaryDeclaration = declarations && declarations.length > 0 ? declarations[declarations.length - 1] : undefined;
        if (!primaryDeclaration || primaryDeclaration.node === node) {
            return;
        }
        if (primaryDeclaration.type === 8 /* DeclarationType.Alias */) {
            // If this symbol is an import alias (i.e. it's a local name rather than the
            // original imported name), skip the private check.
            if (primaryDeclaration.usesLocalName) {
                return;
            }
            const resolvedAliasInfo = this._evaluator.resolveAliasDeclarationWithInfo(primaryDeclaration, 
            /* resolveLocalNames */ true);
            if (!resolvedAliasInfo) {
                return;
            }
            primaryDeclaration = resolvedAliasInfo.declaration;
            // If the alias resolved to a stub file or py.typed source file
            // and the declaration is marked "externally visible", it is
            // exempt from private usage checks.
            if (!resolvedAliasInfo.isPrivate) {
                return;
            }
        }
        if (!primaryDeclaration || primaryDeclaration.node === node) {
            return;
        }
        let classNode;
        if (primaryDeclaration.node) {
            classNode = ParseTreeUtils.getEnclosingClass(primaryDeclaration.node);
        }
        // If this is the name of a class, find the class that contains it rather
        // than constraining the use of the class name within the class itself.
        if (primaryDeclaration.node && primaryDeclaration.node.parent && primaryDeclaration.node.parent === classNode) {
            classNode = ParseTreeUtils.getEnclosingClass(classNode);
        }
        // If it's a class member, check whether it's a legal protected access.
        let isProtectedAccess = false;
        if (classNode) {
            if (isProtectedName) {
                const declClassTypeInfo = this._evaluator.getTypeOfClass(classNode);
                if (declClassTypeInfo && (0, types_1.isInstantiableClass)(declClassTypeInfo.decoratedType)) {
                    // If it's a member defined in a stub file, we'll assume that it's part
                    // of the public contract even if it's named as though it's private.
                    if (types_1.ClassType.isDefinedInStub(declClassTypeInfo.decoratedType)) {
                        return;
                    }
                    // Note that the access is to a protected class member.
                    isProtectedAccess = true;
                    const enclosingClassNode = ParseTreeUtils.getEnclosingClass(node);
                    if (enclosingClassNode) {
                        const enclosingClassTypeInfo = this._evaluator.getTypeOfClass(enclosingClassNode);
                        // If the referencing class is a subclass of the declaring class, it's
                        // allowed to access a protected name.
                        if (enclosingClassTypeInfo && (0, types_1.isInstantiableClass)(enclosingClassTypeInfo.decoratedType)) {
                            if ((0, typeUtils_1.derivesFromClassRecursive)(enclosingClassTypeInfo.decoratedType, declClassTypeInfo.decoratedType, 
                            /* ignoreUnknown */ true)) {
                                return;
                            }
                        }
                    }
                }
            }
        }
        if (classNode && !ParseTreeUtils.isNodeContainedWithin(node, classNode)) {
            if (isProtectedAccess) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateUsage, localize_1.LocMessage.protectedUsedOutsideOfClass().format({ name: nameValue }), node);
            }
            else {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateUsage, localize_1.LocMessage.privateUsedOutsideOfClass().format({ name: nameValue }), node);
            }
        }
    }
    // Validates that an enum class does not attempt to override another
    // enum class that has already defined values.
    _validateEnumClassOverride(node, classType) {
        classType.details.baseClasses.forEach((baseClass, index) => {
            if ((0, types_1.isClass)(baseClass) && (0, enums_1.isEnumClassWithMembers)(this._evaluator, baseClass)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.enumClassOverride().format({ name: baseClass.details.name }), node.arguments[index]);
            }
        });
    }
    // Verifies the rules specified in PEP 589 about TypedDict classes.
    // They cannot have statements other than type annotations, doc
    // strings, and "pass" statements or ellipses.
    _validateTypedDictClassSuite(suiteNode) {
        const emitBadStatementError = (node) => {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictBadVar(), node);
        };
        suiteNode.statements.forEach((statement) => {
            if (!AnalyzerNodeInfo.isCodeUnreachable(statement)) {
                if (statement.nodeType === 47 /* ParseNodeType.StatementList */) {
                    for (const substatement of statement.statements) {
                        if (substatement.nodeType !== 54 /* ParseNodeType.TypeAnnotation */ &&
                            substatement.nodeType !== 18 /* ParseNodeType.Ellipsis */ &&
                            substatement.nodeType !== 48 /* ParseNodeType.StringList */ &&
                            substatement.nodeType !== 42 /* ParseNodeType.Pass */) {
                            emitBadStatementError(substatement);
                        }
                    }
                }
                else {
                    emitBadStatementError(statement);
                }
            }
        });
    }
    _validateTypeGuardFunction(node, functionType, isMethod) {
        var _a;
        const returnType = functionType.details.declaredReturnType;
        if (!returnType) {
            return;
        }
        if (!(0, types_1.isClassInstance)(returnType) || !returnType.typeArguments || returnType.typeArguments.length < 1) {
            return;
        }
        const isTypeGuard = types_1.ClassType.isBuiltIn(returnType, 'TypeGuard');
        const isTypeIs = types_1.ClassType.isBuiltIn(returnType, 'TypeIs');
        if (!isTypeGuard && !isTypeIs) {
            return;
        }
        // Make sure there's at least one input parameter provided.
        let paramCount = functionType.details.parameters.length;
        if (isMethod) {
            if (types_1.FunctionType.isInstanceMethod(functionType) ||
                types_1.FunctionType.isConstructorMethod(functionType) ||
                types_1.FunctionType.isClassMethod(functionType)) {
                paramCount--;
            }
        }
        if (paramCount < 1) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeGuardParamCount(), node.name);
        }
        if (isTypeIs) {
            const typeGuardType = returnType.typeArguments[0];
            // Determine the type of the first parameter.
            const paramIndex = isMethod && !types_1.FunctionType.isStaticMethod(functionType) ? 1 : 0;
            if (paramIndex >= functionType.details.parameters.length) {
                return;
            }
            const paramType = types_1.FunctionType.getEffectiveParameterType(functionType, paramIndex);
            // Verify that the typeGuardType is a narrower type than the paramType.
            if (!this._evaluator.assignType(paramType, typeGuardType)) {
                const returnAnnotation = node.returnTypeAnnotation || ((_a = node.functionAnnotationComment) === null || _a === void 0 ? void 0 : _a.returnTypeAnnotation);
                if (returnAnnotation) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeIsReturnType().format({
                        type: this._evaluator.printType(paramType),
                        returnType: this._evaluator.printType(typeGuardType),
                    }), returnAnnotation);
                }
            }
        }
    }
    _validateDunderSignatures(node, functionType, isMethod) {
        var _a;
        const functionName = functionType.details.name;
        // Is this an '__init__' method? Verify that it returns None.
        if (isMethod && functionName === '__init__') {
            const returnAnnotation = node.returnTypeAnnotation || ((_a = node.functionAnnotationComment) === null || _a === void 0 ? void 0 : _a.returnTypeAnnotation);
            const declaredReturnType = functionType.details.declaredReturnType;
            if (returnAnnotation && declaredReturnType) {
                if (!(0, typeUtils_1.isNoneInstance)(declaredReturnType) && !(0, types_1.isNever)(declaredReturnType)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.initMustReturnNone(), returnAnnotation);
                }
            }
            else {
                const inferredReturnType = this._evaluator.getFunctionInferredReturnType(functionType);
                if (!(0, types_1.isNever)(inferredReturnType) &&
                    !(0, typeUtils_1.isNoneInstance)(inferredReturnType) &&
                    !(0, types_1.isAnyOrUnknown)(inferredReturnType)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.initMustReturnNone(), node.name);
                }
            }
        }
    }
    _validateFunctionReturn(node, functionType) {
        var _a;
        // Stub files are allowed not to return an actual value,
        // so skip this if it's a stub file.
        if (this._fileInfo.isStubFile) {
            return;
        }
        const returnAnnotation = node.returnTypeAnnotation || ((_a = node.functionAnnotationComment) === null || _a === void 0 ? void 0 : _a.returnTypeAnnotation);
        if (returnAnnotation) {
            const functionNeverReturns = !this._evaluator.isAfterNodeReachable(node);
            const implicitlyReturnsNone = this._evaluator.isAfterNodeReachable(node.suite);
            let declaredReturnType = functionType.details.declaredReturnType;
            if (declaredReturnType) {
                this._reportUnknownReturnResult(node, declaredReturnType);
                this._validateReturnTypeIsNotContravariant(declaredReturnType, returnAnnotation);
            }
            // Wrap the declared type in a generator type if the function is a generator.
            if (types_1.FunctionType.isGenerator(functionType)) {
                declaredReturnType = (0, typeUtils_1.getDeclaredGeneratorReturnType)(functionType);
            }
            // The types of all return statement expressions were already checked
            // against the declared type, but we need to verify the implicit None
            // at the end of the function.
            if (declaredReturnType && !functionNeverReturns && implicitlyReturnsNone) {
                if ((0, types_1.isNever)(declaredReturnType)) {
                    // If the function consists entirely of "...", assume that it's
                    // an abstract method or a protocol method and don't require that
                    // the return type matches. This check can also be skipped for an overload.
                    if (!ParseTreeUtils.isSuiteEmpty(node.suite) &&
                        !types_1.FunctionType.isOverloaded(functionType) &&
                        !types_1.FunctionType.isAsync(functionType)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportReturnType, localize_1.LocMessage.noReturnReturnsNone(), returnAnnotation);
                    }
                }
                else if (!types_1.FunctionType.isAbstractMethod(functionType)) {
                    // Make sure that the function doesn't implicitly return None if the declared
                    // type doesn't allow it. Skip this check for abstract methods.
                    const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    // If the declared type isn't compatible with 'None', flag an error.
                    if (!this._evaluator.assignType(declaredReturnType, this._evaluator.getNoneType(), diagAddendum)) {
                        // If the function consists entirely of "...", assume that it's
                        // an abstract method or a protocol method and don't require that
                        // the return type matches. This check can also be skipped for an overload.
                        if (!ParseTreeUtils.isSuiteEmpty(node.suite) && !types_1.FunctionType.isOverloaded(functionType)) {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportReturnType, localize_1.LocMessage.returnMissing().format({
                                returnType: this._evaluator.printType(declaredReturnType),
                            }) + diagAddendum.getString(), returnAnnotation);
                        }
                    }
                }
            }
        }
        else {
            const inferredReturnType = this._evaluator.getFunctionInferredReturnType(functionType);
            this._reportUnknownReturnResult(node, inferredReturnType);
            this._validateReturnTypeIsNotContravariant(inferredReturnType, node.name);
        }
    }
    _validateReturnTypeIsNotContravariant(returnType, errorNode) {
        let isContraTypeVar = false;
        (0, typeUtils_1.doForEachSubtype)(returnType, (subtype) => {
            if ((0, types_1.isTypeVar)(subtype) &&
                subtype.details.declaredVariance === 4 /* Variance.Contravariant */ &&
                subtype.scopeType === 0 /* TypeVarScopeType.Class */) {
                isContraTypeVar = true;
            }
        });
        if (isContraTypeVar) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.returnTypeContravariant(), errorNode);
        }
    }
    _reportUnknownReturnResult(node, returnType) {
        if ((0, types_1.isUnknown)(returnType)) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownParameterType, localize_1.LocMessage.returnTypeUnknown(), node.name);
        }
        else if ((0, typeUtils_1.isPartlyUnknown)(returnType)) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownParameterType, localize_1.LocMessage.returnTypePartiallyUnknown().format({
                returnType: this._evaluator.printType(returnType, { expandTypeAlias: true }),
            }), node.name);
        }
        else if ((0, types_1.isAny)(returnType)) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.returnTypeAny(), node.name);
        }
    }
    // Validates that any overridden member variables are not marked
    // as Final in parent classes.
    _validateFinalMemberOverrides(classType) {
        types_1.ClassType.getSymbolTable(classType).forEach((localSymbol, name) => {
            const parentSymbol = (0, typeUtils_1.lookUpClassMember)(classType, name, 1 /* MemberAccessFlags.SkipOriginalClass */);
            if (parentSymbol && (0, types_1.isInstantiableClass)(parentSymbol.classType) && !SymbolNameUtils.isPrivateName(name)) {
                // Did the parent class explicitly declare the variable as final?
                if (this._evaluator.isFinalVariable(parentSymbol.symbol)) {
                    const decl = localSymbol.getDeclarations()[0];
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalRedeclarationBySubclass().format({
                        name,
                        className: parentSymbol.classType.details.name,
                    }), decl.node);
                }
                else if (types_1.ClassType.isReadOnlyInstanceVariables(parentSymbol.classType) &&
                    !SymbolNameUtils.isDunderName(name)) {
                    // If the parent class is a named tuple, all instance variables
                    // (other than dundered ones) are implicitly final.
                    const decl = localSymbol.getDeclarations()[0];
                    if (decl.type === 1 /* DeclarationType.Variable */) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.namedTupleEntryRedeclared().format({
                            name,
                            className: parentSymbol.classType.details.name,
                        }), decl.node);
                    }
                }
            }
        });
    }
    // Validates that the values associated with enum members are type compatible.
    // Also looks for duplicate values.
    _validateEnumMembers(classType, node) {
        if (!types_1.ClassType.isEnumClass(classType) || types_1.ClassType.isBuiltIn(classType)) {
            return;
        }
        // Does the "_value_" field have a declared type? If so, we'll enforce it.
        const declaredValueType = (0, enums_1.getEnumDeclaredValueType)(this._evaluator, classType, /* declaredTypesOnly */ true);
        // Is there a custom "__new__" and/or "__init__" method? If so, we'll
        // verify that the signature of these calls is compatible with the values.
        let newMemberTypeResult = (0, constructors_1.getBoundNewMethod)(this._evaluator, node.name, classType, 
        /* diag */ undefined, 4 /* MemberAccessFlags.SkipObjectBaseClass */);
        // If this __new__ comes from a built-in class like Enum, we'll ignore it.
        if (newMemberTypeResult === null || newMemberTypeResult === void 0 ? void 0 : newMemberTypeResult.classType) {
            if ((0, types_1.isClass)(newMemberTypeResult.classType) && types_1.ClassType.isBuiltIn(newMemberTypeResult.classType)) {
                newMemberTypeResult = undefined;
            }
        }
        let initMemberTypeResult = (0, constructors_1.getBoundInitMethod)(this._evaluator, node.name, types_1.ClassType.cloneAsInstance(classType), 
        /* diag */ undefined, 4 /* MemberAccessFlags.SkipObjectBaseClass */);
        // If this __init__ comes from a built-in class like Enum, we'll ignore it.
        if (initMemberTypeResult === null || initMemberTypeResult === void 0 ? void 0 : initMemberTypeResult.classType) {
            if ((0, types_1.isClass)(initMemberTypeResult.classType) && types_1.ClassType.isBuiltIn(initMemberTypeResult.classType)) {
                initMemberTypeResult = undefined;
            }
        }
        types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
            var _a;
            // Enum members don't have type annotations.
            if (symbol.getTypedDeclarations().length > 0) {
                return;
            }
            const symbolType = this._evaluator.getEffectiveTypeOfSymbol(symbol);
            // Is this symbol a literal instance of the enum class?
            if (!(0, types_1.isClassInstance)(symbolType) ||
                !types_1.ClassType.isSameGenericClass(symbolType, classType) ||
                !(symbolType.literalValue instanceof types_1.EnumLiteral)) {
                return;
            }
            // Look for a duplicate assignment.
            const decls = symbol.getDeclarations();
            if (decls.length >= 2 && decls[0].type === 1 /* DeclarationType.Variable */) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.duplicateEnumMember().format({ name }), decls[1].node);
                return;
            }
            if (decls[0].type !== 1 /* DeclarationType.Variable */) {
                return;
            }
            const declNode = decls[0].node;
            const assignedValueType = symbolType.literalValue.itemType;
            const assignmentNode = ParseTreeUtils.getParentNodeOfType(declNode, 3 /* ParseNodeType.Assignment */);
            const errorNode = (_a = assignmentNode === null || assignmentNode === void 0 ? void 0 : assignmentNode.rightExpression) !== null && _a !== void 0 ? _a : declNode;
            // Validate the __new__ and __init__ methods if present.
            if (newMemberTypeResult || initMemberTypeResult) {
                if (!(0, types_1.isAnyOrUnknown)(assignedValueType)) {
                    // Construct an argument list. If the assigned type is a tuple, we'll
                    // unpack it. Otherwise, only one argument is passed.
                    const argList = [
                        {
                            argumentCategory: (0, types_1.isClassInstance)(assignedValueType) && (0, typeUtils_1.isTupleClass)(assignedValueType)
                                ? 1 /* ArgumentCategory.UnpackedList */
                                : 0 /* ArgumentCategory.Simple */,
                            typeResult: { type: assignedValueType },
                        },
                    ];
                    if (newMemberTypeResult) {
                        this._evaluator.validateCallArguments(errorNode, argList, newMemberTypeResult);
                    }
                    if (initMemberTypeResult) {
                        this._evaluator.validateCallArguments(errorNode, argList, initMemberTypeResult);
                    }
                }
            }
            else if (declaredValueType) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                // If the assigned value is already an instance of this enum class, skip this check.
                if (!(0, types_1.isClassInstance)(assignedValueType) ||
                    !types_1.ClassType.isSameGenericClass(assignedValueType, classType)) {
                    if (!this._evaluator.assignType(declaredValueType, assignedValueType, diag)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAssignmentType, localize_1.LocMessage.typeAssignmentMismatch().format(this._evaluator.printSrcDestTypes(assignedValueType, declaredValueType)) + diag.getString(), errorNode);
                    }
                }
            }
        });
    }
    // If a class is a dataclass with a `__post_init__` method, verify that its
    // signature is correct.
    _validateDataClassPostInit(classType, errorNode) {
        if (!types_1.ClassType.isDataClass(classType)) {
            return;
        }
        const postInitMember = (0, typeUtils_1.lookUpClassMember)(classType, '__post_init__', 2 /* MemberAccessFlags.SkipBaseClasses */ | 64 /* MemberAccessFlags.DeclaredTypesOnly */);
        // If there's no __post_init__ method, there's nothing to check.
        if (!postInitMember) {
            return;
        }
        // If the class derives from Any, we can't reliably apply the check.
        if (types_1.ClassType.derivesFromAnyOrUnknown(classType)) {
            return;
        }
        // Collect the list of init-only variables in the order they were declared.
        const initOnlySymbolMap = new Map();
        types_1.ClassType.getReverseMro(classType).forEach((mroClass) => {
            if ((0, types_1.isClass)(mroClass) && types_1.ClassType.isDataClass(mroClass)) {
                types_1.ClassType.getSymbolTable(mroClass).forEach((symbol, name) => {
                    if (symbol.isInitVar()) {
                        initOnlySymbolMap.set(name, symbol);
                    }
                });
            }
        });
        const postInitType = this._evaluator.getTypeOfMember(postInitMember);
        if (!(0, types_1.isFunction)(postInitType) ||
            !types_1.FunctionType.isInstanceMethod(postInitType) ||
            !postInitType.details.declaration) {
            return;
        }
        const paramListDetails = (0, parameterUtils_1.getParameterListDetails)(postInitType);
        // If there is an *args or **kwargs parameter or a keyword-only separator,
        // don't bother checking.
        if (paramListDetails.argsIndex !== undefined ||
            paramListDetails.kwargsIndex !== undefined ||
            paramListDetails.firstKeywordOnlyIndex !== undefined) {
            return;
        }
        // Verify that the parameter count matches.
        const nonDefaultParams = paramListDetails.params.filter((paramInfo) => !paramInfo.param.hasDefault);
        // We expect to see one param for "self" plus one for each of the InitVars.
        const expectedParamCount = initOnlySymbolMap.size + 1;
        if (expectedParamCount < nonDefaultParams.length || expectedParamCount > paramListDetails.params.length) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassPostInitParamCount().format({ expected: initOnlySymbolMap.size }), postInitType.details.declaration.node.name);
        }
        // Verify that the parameter types match.
        let paramIndex = 1;
        initOnlySymbolMap.forEach((symbol, fieldName) => {
            var _a;
            if (paramIndex >= paramListDetails.params.length) {
                return;
            }
            const param = paramListDetails.params[paramIndex].param;
            if (param.hasDeclaredType && param.typeAnnotation) {
                const fieldType = (_a = this._evaluator.getDeclaredTypeOfSymbol(symbol)) === null || _a === void 0 ? void 0 : _a.type;
                const paramType = types_1.FunctionType.getEffectiveParameterType(postInitType, paramListDetails.params[paramIndex].index);
                const assignTypeDiag = new diagnostic_1.DiagnosticAddendum();
                if (fieldType && !this._evaluator.assignType(paramType, fieldType, assignTypeDiag)) {
                    const diagnostic = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassPostInitType().format({ fieldName }) + assignTypeDiag.getString(), param.typeAnnotation);
                    if (diagnostic) {
                        const fieldDecls = symbol.getTypedDeclarations();
                        if (fieldDecls.length > 0) {
                            diagnostic.addRelatedInfo(localize_1.LocAddendum.dataClassFieldLocation(), fieldDecls[0].uri, fieldDecls[0].range);
                        }
                    }
                }
            }
            paramIndex++;
        });
    }
    // If a class is marked final, it must implement all abstract methods,
    // otherwise it is of no use.
    _validateFinalClassNotAbstract(classType, errorNode) {
        if (!types_1.ClassType.isFinal(classType)) {
            return;
        }
        if (!types_1.ClassType.supportsAbstractMethods(classType)) {
            return;
        }
        const abstractSymbols = this._evaluator.getAbstractSymbols(classType);
        if (abstractSymbols.length === 0) {
            return;
        }
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        const errorsToDisplay = 2;
        abstractSymbols.forEach((abstractMethod, index) => {
            if (index === errorsToDisplay) {
                diagAddendum.addMessage(localize_1.LocAddendum.memberIsAbstractMore().format({
                    count: abstractSymbols.length - errorsToDisplay,
                }));
            }
            else if (index < errorsToDisplay) {
                if ((0, types_1.isInstantiableClass)(abstractMethod.classType)) {
                    const className = abstractMethod.classType.details.name;
                    diagAddendum.addMessage(localize_1.LocAddendum.memberIsAbstract().format({
                        type: className,
                        name: abstractMethod.symbolName,
                    }));
                }
            }
        });
        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalClassIsAbstract().format({
            type: classType.details.name,
        }) + diagAddendum.getString(), errorNode.name);
    }
    // Reports the case where an instance variable is not declared or initialized
    // within the class body or constructor method.
    _validateInstanceVariableInitialization(node, classType) {
        // This check doesn't apply to stub files.
        if (this._fileInfo.isStubFile) {
            return;
        }
        // This check can be expensive, so don't perform it if the corresponding
        // rule is disabled.
        if (this._fileInfo.diagnosticRuleSet.reportUninitializedInstanceVariable === 'none') {
            return;
        }
        // Protocol classes and ABCs are exempted from this check unless they are
        // marked @final.
        if (types_1.ClassType.isProtocolClass(classType) ||
            (types_1.ClassType.supportsAbstractMethods(classType) && !types_1.ClassType.isFinal(classType))) {
            return;
        }
        // If the class is final, see if it has any abstract base classes that define
        // variables. We need to make sure these are initialized.
        const abstractSymbols = new Map();
        if (types_1.ClassType.isFinal(classType)) {
            (0, typeUtils_1.getProtocolSymbolsRecursive)(classType, abstractSymbols, 2048 /* ClassTypeFlags.SupportsAbstractMethods */);
        }
        types_1.ClassType.getSymbolTable(classType).forEach((localSymbol, name) => {
            abstractSymbols.delete(name);
            // This applies only to instance members.
            if (!localSymbol.isInstanceMember()) {
                return;
            }
            const decls = localSymbol.getDeclarations();
            // If the symbol is assigned (or at least declared) within the
            // class body or within the __init__ method, it can be ignored.
            if (decls.find((decl) => {
                var _a, _b, _c;
                const containingClass = ParseTreeUtils.getEnclosingClassOrFunction(decl.node);
                if (!containingClass) {
                    return true;
                }
                if (containingClass.nodeType === 10 /* ParseNodeType.Class */) {
                    // If this is part of an assignment statement, assume it has been
                    // initialized as a class variable.
                    if (((_a = decl.node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */) {
                        return true;
                    }
                    if (((_b = decl.node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 54 /* ParseNodeType.TypeAnnotation */ &&
                        ((_c = decl.node.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 3 /* ParseNodeType.Assignment */) {
                        return true;
                    }
                    // If this is part of a dataclass or a class handled by a dataclass_transform,
                    // exempt it because the class variable will be transformed into an instance
                    // variable in this case.
                    if (types_1.ClassType.isDataClass(classType)) {
                        return true;
                    }
                    // If this is part of a TypedDict, exempt it because the class variables
                    // are not actually class variables in a TypedDict.
                    if (types_1.ClassType.isTypedDictClass(classType)) {
                        return true;
                    }
                }
                if (containingClass.name.value === '__init__') {
                    return true;
                }
                return false;
            })) {
                return;
            }
            // If the symbol is declared by its parent, we can assume it
            // is initialized there.
            const parentSymbol = (0, typeUtils_1.lookUpClassMember)(classType, name, 1 /* MemberAccessFlags.SkipOriginalClass */);
            if (parentSymbol) {
                return;
            }
            // Report the variable as uninitialized only on the first decl.
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUninitializedInstanceVariable, localize_1.LocMessage.uninitializedInstanceVariable().format({ name: name }), decls[0].node);
        });
        // See if there are any variables from abstract base classes
        // that are not initialized.
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        abstractSymbols.forEach((member, name) => {
            const decls = member.symbol.getDeclarations();
            if (decls.length === 0 || !(0, types_1.isClass)(member.classType)) {
                return;
            }
            if (decls[0].type === 1 /* DeclarationType.Variable */) {
                // If none of the declarations involve assignments, assume it's
                // not implemented in the protocol.
                if (!decls.some((decl) => decl.type === 1 /* DeclarationType.Variable */ && !!decl.inferredTypeSource)) {
                    // This is a variable declaration that is not implemented in the
                    // protocol base class. Make sure it's implemented in the derived class.
                    diagAddendum.addMessage(localize_1.LocAddendum.uninitializedAbstractVariable().format({
                        name,
                        classType: member.classType.details.name,
                    }));
                }
            }
        });
        if (!diagAddendum.isEmpty()) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUninitializedInstanceVariable, localize_1.LocMessage.uninitializedAbstractVariables().format({ classType: classType.details.name }) +
                diagAddendum.getString(), node.name);
        }
    }
    // Validates that the type variables used in a generic protocol class have
    // the proper variance (invariant, covariant, contravariant). See PEP 544
    // for an explanation for why this is important to enforce.
    _validateProtocolTypeParamVariance(errorNode, classType) {
        // If this protocol has no TypeVars with specified variance, there's nothing to do here.
        if (classType.details.typeParameters.length === 0) {
            return;
        }
        const objectType = this._evaluator.getBuiltInType(errorNode, 'object');
        if (!(0, types_1.isInstantiableClass)(objectType)) {
            return;
        }
        const objectObject = types_1.ClassType.cloneAsInstance(objectType);
        const dummyTypeObject = types_1.ClassType.createInstantiable('__varianceDummy', '', '', uri_1.Uri.empty(), 0, 0, undefined, undefined);
        classType.details.typeParameters.forEach((param, paramIndex) => {
            // Skip variadics and ParamSpecs.
            if (param.details.isVariadic || param.details.isParamSpec) {
                return;
            }
            // Skip type variables with auto-variance.
            if (param.details.declaredVariance === 0 /* Variance.Auto */) {
                return;
            }
            // Replace all type arguments with a dummy type except for the
            // TypeVar of interest, which is replaced with an object instance.
            const srcTypeArgs = classType.details.typeParameters.map((p, i) => {
                if (p.details.isVariadic) {
                    return p;
                }
                return i === paramIndex ? objectObject : dummyTypeObject;
            });
            // Replace all type arguments with a dummy type except for the
            // TypeVar of interest, which is replaced with itself.
            const destTypeArgs = classType.details.typeParameters.map((p, i) => {
                return i === paramIndex || p.details.isVariadic ? p : dummyTypeObject;
            });
            const srcType = types_1.ClassType.cloneForSpecialization(classType, srcTypeArgs, /* isTypeArgumentExplicit */ true);
            const destType = types_1.ClassType.cloneForSpecialization(classType, destTypeArgs, 
            /* isTypeArgumentExplicit */ true);
            const isDestSubtypeOfSrc = this._evaluator.assignClassToSelf(srcType, destType, 3 /* Variance.Covariant */);
            let expectedVariance;
            if (isDestSubtypeOfSrc) {
                expectedVariance = 3 /* Variance.Covariant */;
            }
            else {
                const isSrcSubtypeOfDest = this._evaluator.assignClassToSelf(destType, srcType, 4 /* Variance.Contravariant */);
                if (isSrcSubtypeOfDest) {
                    expectedVariance = 4 /* Variance.Contravariant */;
                }
                else {
                    expectedVariance = 2 /* Variance.Invariant */;
                }
            }
            if (expectedVariance !== classType.details.typeParameters[paramIndex].details.declaredVariance) {
                let message;
                if (expectedVariance === 3 /* Variance.Covariant */) {
                    message = localize_1.LocMessage.protocolVarianceCovariant().format({
                        variable: param.details.name,
                        class: classType.details.name,
                    });
                }
                else if (expectedVariance === 4 /* Variance.Contravariant */) {
                    message = localize_1.LocMessage.protocolVarianceContravariant().format({
                        variable: param.details.name,
                        class: classType.details.name,
                    });
                }
                else {
                    message = localize_1.LocMessage.protocolVarianceInvariant().format({
                        variable: param.details.name,
                        class: classType.details.name,
                    });
                }
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeVarUse, message, errorNode.name);
            }
        });
    }
    // Validates that a class variable doesn't conflict with a __slots__
    // name. This will generate a runtime exception.
    _validateSlotsClassVarConflict(classType) {
        if (!classType.details.localSlotsNames) {
            // Nothing to check, since this class doesn't use __slots__.
            return;
        }
        // Don't apply this for dataclasses because their class variables
        // are transformed into instance variables.
        if (types_1.ClassType.isDataClass(classType)) {
            return;
        }
        types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
            const decls = symbol.getDeclarations();
            const isDefinedBySlots = decls.some((decl) => decl.type === 1 /* DeclarationType.Variable */ && decl.isDefinedBySlots);
            if (isDefinedBySlots) {
                decls.forEach((decl) => {
                    if (decl.type === 1 /* DeclarationType.Variable */ &&
                        !decl.isDefinedBySlots &&
                        !decl.isDefinedByMemberAccess) {
                        if (decl.node.nodeType === 38 /* ParseNodeType.Name */ && ParseTreeUtils.isWriteAccess(decl.node)) {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.slotsClassVarConflict().format({ name }), decl.node);
                        }
                    }
                });
            }
        });
    }
    // Validates that the __init__ and __new__ method signatures are consistent.
    _validateConstructorConsistency(classType, errorNode) {
        // If the class has a custom metaclass with a __call__ method, skip this check.
        const callMethodResult = (0, constructors_1.getBoundCallMethod)(this._evaluator, errorNode, classType);
        if (callMethodResult) {
            return;
        }
        const newMethodResult = (0, constructors_1.getBoundNewMethod)(this._evaluator, errorNode, classType);
        if (!newMethodResult ||
            newMethodResult.typeErrors ||
            !newMethodResult.classType ||
            !(0, types_1.isClass)(newMethodResult.classType)) {
            return;
        }
        const initMethodResult = (0, constructors_1.getBoundInitMethod)(this._evaluator, errorNode, types_1.ClassType.cloneAsInstance(classType));
        if (!initMethodResult ||
            initMethodResult.typeErrors ||
            !initMethodResult.classType ||
            !(0, types_1.isClass)(initMethodResult.classType)) {
            return;
        }
        // If both the __new__ and __init__ come from subclasses, don't bother
        // checking for this class.
        if (!types_1.ClassType.isSameGenericClass(initMethodResult.classType, classType) &&
            !types_1.ClassType.isSameGenericClass(newMethodResult.classType, classType)) {
            return;
        }
        let newMemberType = newMethodResult.type;
        if (!(0, types_1.isFunction)(newMemberType) && !(0, types_1.isOverloadedFunction)(newMemberType)) {
            return;
        }
        if ((0, types_1.isOverloadedFunction)(newMemberType)) {
            // Find the implementation, not the overloaded signatures.
            newMemberType = types_1.OverloadedFunctionType.getImplementation(newMemberType);
            if (!newMemberType) {
                return;
            }
        }
        let initMemberType = initMethodResult.type;
        if (!(0, types_1.isFunction)(initMemberType) && !(0, types_1.isOverloadedFunction)(initMemberType)) {
            return;
        }
        if ((0, types_1.isOverloadedFunction)(initMemberType)) {
            // Find the implementation, not the overloaded signatures.
            initMemberType = types_1.OverloadedFunctionType.getImplementation(initMemberType);
            if (!initMemberType) {
                return;
            }
        }
        // If either of the functions has a default parameter signature
        // (* args: Any, ** kwargs: Any), don't proceed with the check.
        if (types_1.FunctionType.hasDefaultParameters(initMemberType) || types_1.FunctionType.hasDefaultParameters(newMemberType)) {
            return;
        }
        // We'll set the "SkipArgsKwargs" flag for pragmatic reasons since __new__
        // often has an *args and/or **kwargs. We'll also set the ParamSpecValue
        // because we don't care about the return type for this check.
        initMemberType = types_1.FunctionType.cloneWithNewFlags(initMemberType, initMemberType.details.flags |
            32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */ |
            65536 /* FunctionTypeFlags.ParamSpecValue */);
        newMemberType = types_1.FunctionType.cloneWithNewFlags(newMemberType, initMemberType.details.flags |
            32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */ |
            65536 /* FunctionTypeFlags.ParamSpecValue */);
        if (!this._evaluator.assignType(newMemberType, initMemberType, 
        /* diag */ undefined, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */) ||
            !this._evaluator.assignType(initMemberType, newMemberType, 
            /* diag */ undefined, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */)) {
            const displayOnInit = types_1.ClassType.isSameGenericClass(initMethodResult.classType, classType);
            const initDecl = initMemberType.details.declaration;
            const newDecl = newMemberType.details.declaration;
            if (initDecl && newDecl) {
                const mainDecl = displayOnInit ? initDecl : newDecl;
                const mainDeclNode = mainDecl.node.nodeType === 28 /* ParseNodeType.Function */ ? mainDecl.node.name : mainDecl.node;
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                const initSignature = this._evaluator.printType(initMemberType);
                const newSignature = this._evaluator.printType(newMemberType);
                diagAddendum.addMessage(localize_1.LocAddendum.initMethodSignature().format({
                    type: initSignature,
                }));
                diagAddendum.addMessage(localize_1.LocAddendum.newMethodSignature().format({
                    type: newSignature,
                }));
                const diagnostic = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentConstructor, localize_1.LocMessage.constructorParametersMismatch().format({
                    classType: this._evaluator.printType(types_1.ClassType.cloneAsInstance(displayOnInit ? initMethodResult.classType : newMethodResult.classType)),
                }) + diagAddendum.getString(), mainDeclNode);
                if (diagnostic) {
                    const secondaryDecl = displayOnInit ? newDecl : initDecl;
                    diagnostic.addRelatedInfo((displayOnInit ? localize_1.LocAddendum.newMethodLocation() : localize_1.LocAddendum.initMethodLocation()).format({
                        type: this._evaluator.printType(types_1.ClassType.cloneAsInstance(displayOnInit ? newMethodResult.classType : initMethodResult.classType)),
                    }), secondaryDecl.uri, secondaryDecl.range);
                }
            }
        }
    }
    // Verifies that classes that have more than one base class do not have
    // have conflicting type arguments.
    _validateMultipleInheritanceBaseClasses(classType, errorNode) {
        // Skip this check if the class has only one base class or one or more
        // of the base classes are Any.
        const filteredBaseClasses = [];
        for (const baseClass of classType.details.baseClasses) {
            if (!(0, types_1.isClass)(baseClass)) {
                return;
            }
            if (!types_1.ClassType.isBuiltIn(baseClass, ['Generic', 'Protocol', 'object'])) {
                filteredBaseClasses.push(baseClass);
            }
        }
        if (filteredBaseClasses.length < 2) {
            return;
        }
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        for (const baseClass of filteredBaseClasses) {
            const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(baseClass);
            for (const baseClassMroClass of baseClass.details.mro) {
                // There's no need to check for conflicts if this class isn't generic.
                if ((0, types_1.isClass)(baseClassMroClass) && baseClassMroClass.details.typeParameters.length > 0) {
                    const specializedBaseClassMroClass = (0, typeUtils_1.applySolvedTypeVars)(baseClassMroClass, typeVarContext);
                    // Find the corresponding class in the derived class's MRO list.
                    const matchingMroClass = classType.details.mro.find((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isSameGenericClass(mroClass, specializedBaseClassMroClass));
                    if (matchingMroClass && (0, types_1.isInstantiableClass)(matchingMroClass)) {
                        const matchingMroObject = types_1.ClassType.cloneAsInstance(matchingMroClass);
                        const baseClassMroObject = types_1.ClassType.cloneAsInstance(specializedBaseClassMroClass);
                        if (!this._evaluator.assignType(matchingMroObject, baseClassMroObject)) {
                            const diag = new diagnostic_1.DiagnosticAddendum();
                            const baseClassObject = (0, typeUtils_1.convertToInstance)(baseClass);
                            if ((0, types_1.isTypeSame)(baseClassObject, baseClassMroObject)) {
                                diag.addMessage(localize_1.LocAddendum.baseClassIncompatible().format({
                                    baseClass: this._evaluator.printType(baseClassObject),
                                    type: this._evaluator.printType(matchingMroObject),
                                }));
                            }
                            else {
                                diag.addMessage(localize_1.LocAddendum.baseClassIncompatibleSubclass().format({
                                    baseClass: this._evaluator.printType(baseClassObject),
                                    subclass: this._evaluator.printType(baseClassMroObject),
                                    type: this._evaluator.printType(matchingMroObject),
                                }));
                            }
                            diagAddendum.addAddendum(diag);
                            // Break out of the inner loop so we don't report any redundant errors for this base class.
                            break;
                        }
                    }
                }
            }
        }
        if (!diagAddendum.isEmpty()) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.baseClassIncompatible().format({ type: classType.details.name }) + diagAddendum.getString(), errorNode);
        }
    }
    // Validates that any methods and variables in multiple base classes are
    // compatible with each other.
    _validateMultipleInheritanceCompatibility(classType, errorNode) {
        // Skip this check if reportIncompatibleMethodOverride and reportIncompatibleVariableOverride
        // are disabled because it's a relatively expensive check.
        if (this._fileInfo.diagnosticRuleSet.reportIncompatibleMethodOverride === 'none' &&
            this._fileInfo.diagnosticRuleSet.reportIncompatibleVariableOverride === 'none') {
            return;
        }
        const baseClasses = [];
        // Filter any unknown base classes. Also remove Generic and Protocol
        // base classes.
        classType.details.baseClasses.forEach((baseClass) => {
            if ((0, types_1.isClass)(baseClass) &&
                !types_1.ClassType.isBuiltIn(baseClass, 'Generic') &&
                !types_1.ClassType.isBuiltIn(baseClass, 'Protocol')) {
                baseClasses.push(baseClass);
            }
        });
        // If there is only one base class, there's nothing to do.
        if (baseClasses.length < 2) {
            return;
        }
        // Build maps of symbols for each of the base classes.
        const baseClassSymbolMaps = baseClasses.map((baseClass) => {
            const specializedBaseClass = classType.details.mro.find((c) => (0, types_1.isClass)(c) && types_1.ClassType.isSameGenericClass(c, baseClass));
            if (!specializedBaseClass || !(0, types_1.isClass)(specializedBaseClass)) {
                return new Map();
            }
            // Retrieve all of the specialized symbols from the base class and its ancestors.
            return (0, typeUtils_1.getClassFieldsRecursive)(specializedBaseClass);
        });
        const childClassSymbolMap = (0, typeUtils_1.getClassFieldsRecursive)(classType);
        for (let symbolMapBaseIndex = 1; symbolMapBaseIndex < baseClassSymbolMaps.length; symbolMapBaseIndex++) {
            const baseSymbolMap = baseClassSymbolMaps[symbolMapBaseIndex];
            for (const [name, overriddenClassAndSymbol] of baseSymbolMap) {
                // Special-case dundered methods, which can differ in signature. Also
                // exempt private symbols.
                if (SymbolNameUtils.isDunderName(name) || SymbolNameUtils.isPrivateName(name)) {
                    continue;
                }
                const overriddenClassType = overriddenClassAndSymbol.classType;
                if (!(0, types_1.isClass)(overriddenClassType)) {
                    continue;
                }
                const overrideClassAndSymbol = childClassSymbolMap.get(name);
                if (overrideClassAndSymbol) {
                    const overrideClassType = overrideClassAndSymbol.classType;
                    // If the override is the same as the overridden, then there's nothing
                    // to check. If the override is the child class, then we can also skip
                    // the check because the normal override checks will report the error.
                    if (!(0, types_1.isClass)(overrideClassType) ||
                        types_1.ClassType.isSameGenericClass(overrideClassType, overriddenClassType) ||
                        types_1.ClassType.isSameGenericClass(overrideClassType, classType)) {
                        continue;
                    }
                    this._validateMultipleInheritanceOverride(overriddenClassAndSymbol, overrideClassAndSymbol, classType, name, errorNode);
                }
            }
        }
    }
    _validateMultipleInheritanceOverride(overriddenClassAndSymbol, overrideClassAndSymbol, childClassType, memberName, errorNode) {
        var _a, _b, _c, _d;
        if (!(0, types_1.isClass)(overriddenClassAndSymbol.classType) || !(0, types_1.isClass)(overrideClassAndSymbol.classType)) {
            return;
        }
        // Special case the '_' symbol, which is used in single dispatch
        // code and other cases where the name does not matter.
        if (memberName === '_') {
            return;
        }
        let overriddenType = this._evaluator.getEffectiveTypeOfSymbol(overriddenClassAndSymbol.symbol);
        overriddenType = (0, typeUtils_1.partiallySpecializeType)(overriddenType, overriddenClassAndSymbol.classType);
        const overrideSymbol = overrideClassAndSymbol.symbol;
        let overrideType = this._evaluator.getEffectiveTypeOfSymbol(overrideSymbol);
        overrideType = (0, typeUtils_1.partiallySpecializeType)(overrideType, overrideClassAndSymbol.classType);
        const childOverrideSymbol = types_1.ClassType.getSymbolTable(childClassType).get(memberName);
        const childOverrideType = childOverrideSymbol
            ? this._evaluator.getEffectiveTypeOfSymbol(childOverrideSymbol)
            : undefined;
        let diag;
        const overrideDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(overrideClassAndSymbol.symbol);
        const overriddenDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(overriddenClassAndSymbol.symbol);
        if ((0, types_1.isFunction)(overriddenType) || (0, types_1.isOverloadedFunction)(overriddenType)) {
            const diagAddendum = new diagnostic_1.DiagnosticAddendum();
            let overrideFunction;
            if ((0, types_1.isFunction)(overrideType)) {
                overrideFunction = overrideType;
            }
            else if ((0, types_1.isOverloadedFunction)(overrideType)) {
                // Use the last overload.
                overrideFunction = types_1.OverloadedFunctionType.getImplementation(overrideType);
                // If the last overload isn't an implementation, skip the check for this symbol.
                if (!overrideFunction) {
                    return;
                }
            }
            if (overrideFunction) {
                if (!this._evaluator.validateOverrideMethod(overriddenType, overrideFunction, 
                /* baseClass */ undefined, diagAddendum, 
                /* enforceParamNameMatch */ true)) {
                    const decl = overrideFunction.details.declaration;
                    if (decl && decl.type === 5 /* DeclarationType.Function */) {
                        diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.baseClassMethodTypeIncompatible().format({
                            classType: childClassType.details.name,
                            name: memberName,
                        }) + diagAddendum.getString(), errorNode);
                    }
                }
            }
        }
        else if ((0, typeUtils_1.isProperty)(overriddenType)) {
            // Handle properties specially.
            if (!(0, typeUtils_1.isProperty)(overrideType) && !(0, types_1.isAnyOrUnknown)(overrideType)) {
                const decls = overrideSymbol.getDeclarations();
                if (decls.length > 0) {
                    diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.baseClassVariableTypeIncompatible().format({
                        classType: childClassType.details.name,
                        name: memberName,
                    }), errorNode);
                }
            }
            else {
                // TODO - check types of property methods fget, fset, fdel.
            }
        }
        else {
            // This check can be expensive, so don't perform it if the corresponding
            // rule is disabled.
            if (this._fileInfo.diagnosticRuleSet.reportIncompatibleVariableOverride !== 'none') {
                const primaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(overriddenClassAndSymbol.symbol);
                let isInvariant = (primaryDecl === null || primaryDecl === void 0 ? void 0 : primaryDecl.type) === 1 /* DeclarationType.Variable */ && !primaryDecl.isFinal;
                // If the entry is a member of a frozen dataclass, it is immutable,
                // so it does not need to be invariant.
                if (types_1.ClassType.isFrozenDataClass(overriddenClassAndSymbol.classType) &&
                    overriddenClassAndSymbol.classType.details.dataClassEntries) {
                    const dataclassEntry = overriddenClassAndSymbol.classType.details.dataClassEntries.find((entry) => entry.name === memberName);
                    if (dataclassEntry) {
                        isInvariant = false;
                    }
                }
                let overriddenTDEntry;
                if (overriddenClassAndSymbol.classType.details.typedDictEntries) {
                    overriddenTDEntry =
                        (_b = (_a = overriddenClassAndSymbol.classType.details.typedDictEntries.knownItems.get(memberName)) !== null && _a !== void 0 ? _a : overriddenClassAndSymbol.classType.details.typedDictEntries.extraItems) !== null && _b !== void 0 ? _b : (0, typedDicts_1.getEffectiveExtraItemsEntryType)(this._evaluator, overriddenClassAndSymbol.classType);
                    if (overriddenTDEntry === null || overriddenTDEntry === void 0 ? void 0 : overriddenTDEntry.isReadOnly) {
                        isInvariant = false;
                    }
                }
                let overrideTDEntry;
                if (overrideClassAndSymbol.classType.details.typedDictEntries) {
                    overrideTDEntry =
                        (_d = (_c = overrideClassAndSymbol.classType.details.typedDictEntries.knownItems.get(memberName)) !== null && _c !== void 0 ? _c : overrideClassAndSymbol.classType.details.typedDictEntries.extraItems) !== null && _d !== void 0 ? _d : (0, typedDicts_1.getEffectiveExtraItemsEntryType)(this._evaluator, overrideClassAndSymbol.classType);
                }
                if (!this._evaluator.assignType(overriddenType, childOverrideType !== null && childOverrideType !== void 0 ? childOverrideType : overrideType, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, isInvariant ? 1 /* AssignTypeFlags.EnforceInvariance */ : 0 /* AssignTypeFlags.Default */)) {
                    diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.baseClassVariableTypeIncompatible().format({
                        classType: childClassType.details.name,
                        name: memberName,
                    }), errorNode);
                }
                else if (overriddenTDEntry && overrideTDEntry) {
                    let isRequiredCompatible;
                    let isReadOnlyCompatible = true;
                    // If both classes are TypedDicts and they both define this field,
                    // make sure the attributes are compatible.
                    if (overriddenTDEntry.isReadOnly) {
                        isRequiredCompatible = overrideTDEntry.isRequired || !overriddenTDEntry.isRequired;
                    }
                    else {
                        isReadOnlyCompatible = !overrideTDEntry.isReadOnly;
                        isRequiredCompatible = overrideTDEntry.isRequired === overriddenTDEntry.isRequired;
                    }
                    if (!isRequiredCompatible) {
                        const message = overrideTDEntry.isRequired
                            ? localize_1.LocMessage.typedDictFieldRequiredRedefinition
                            : localize_1.LocMessage.typedDictFieldNotRequiredRedefinition;
                        diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, message().format({ name: memberName }), errorNode);
                    }
                    else if (!isReadOnlyCompatible) {
                        diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.typedDictFieldReadOnlyRedefinition().format({
                            name: memberName,
                        }), errorNode);
                    }
                }
            }
        }
        if (diag && overrideDecl && overriddenDecl) {
            diag.addRelatedInfo(localize_1.LocAddendum.baseClassOverriddenType().format({
                baseClass: this._evaluator.printType((0, typeUtils_1.convertToInstance)(overriddenClassAndSymbol.classType)),
                type: this._evaluator.printType(overriddenType),
            }), overriddenDecl.uri, overriddenDecl.range);
            diag.addRelatedInfo(localize_1.LocAddendum.baseClassOverridesType().format({
                baseClass: this._evaluator.printType((0, typeUtils_1.convertToInstance)(overrideClassAndSymbol.classType)),
                type: this._evaluator.printType(overrideType),
            }), overrideDecl.uri, overrideDecl.range);
        }
    }
    // Validates that any overloaded methods are consistent in how they
    // are decorated. For example, if the first overload is not marked @final
    // but subsequent ones are, an error should be reported.
    _validateOverloadDecoratorConsistency(classType) {
        types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
            const primaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
            if (!primaryDecl || primaryDecl.type !== 5 /* DeclarationType.Function */) {
                return;
            }
            const typeOfSymbol = this._evaluator.getEffectiveTypeOfSymbol(symbol);
            if (!(0, types_1.isOverloadedFunction)(typeOfSymbol)) {
                return;
            }
            const overloads = types_1.OverloadedFunctionType.getOverloads(typeOfSymbol);
            // If there's an implementation, it will determine whether the
            // function is @final.
            const implementation = types_1.OverloadedFunctionType.getImplementation(typeOfSymbol);
            if (implementation) {
                // If one or more of the overloads is marked @final but the
                // implementation is not, report an error.
                if (!types_1.FunctionType.isFinal(implementation)) {
                    overloads.forEach((overload) => {
                        var _a, _b;
                        if (types_1.FunctionType.isFinal(overload) && ((_a = overload.details.declaration) === null || _a === void 0 ? void 0 : _a.node)) {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadFinalInconsistencyImpl().format({
                                name: overload.details.name,
                            }), (_b = (0, declarationUtils_1.getNameNodeForDeclaration)(overload.details.declaration)) !== null && _b !== void 0 ? _b : overload.details.declaration.node);
                        }
                    });
                }
                return;
            }
            if (!types_1.FunctionType.isFinal(overloads[0])) {
                overloads.slice(1).forEach((overload, index) => {
                    var _a, _b;
                    if (types_1.FunctionType.isFinal(overload) && ((_a = overload.details.declaration) === null || _a === void 0 ? void 0 : _a.node)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadFinalInconsistencyNoImpl().format({
                            name: overload.details.name,
                            index: index + 2,
                        }), (_b = (0, declarationUtils_1.getNameNodeForDeclaration)(overload.details.declaration)) !== null && _b !== void 0 ? _b : overload.details.declaration.node);
                    }
                });
            }
        });
    }
    // For a TypedDict class that derives from another TypedDict class
    // that is closed, verify that any new keys are compatible with the
    // base class.
    _validateTypedDictOverrides(classType) {
        if (!types_1.ClassType.isTypedDictClass(classType)) {
            return;
        }
        const typedDictEntries = (0, typedDicts_1.getTypedDictMembersForClass)(this._evaluator, classType, /* allowNarrowed */ false);
        for (const baseClass of classType.details.baseClasses) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            if (!(0, types_1.isClass)(baseClass) ||
                !types_1.ClassType.isTypedDictClass(baseClass) ||
                !types_1.ClassType.isTypedDictEffectivelyClosed(baseClass)) {
                continue;
            }
            const baseTypedDictEntries = (0, typedDicts_1.getTypedDictMembersForClass)(this._evaluator, baseClass, 
            /* allowNarrowed */ false);
            const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(baseClass);
            const baseExtraItemsType = baseTypedDictEntries.extraItems
                ? (0, typeUtils_1.applySolvedTypeVars)(baseTypedDictEntries.extraItems.valueType, typeVarContext)
                : types_1.UnknownType.create();
            for (const [name, entry] of typedDictEntries.knownItems) {
                const baseEntry = baseTypedDictEntries.knownItems.get(name);
                if (!baseEntry) {
                    if (!baseTypedDictEntries.extraItems || (0, types_1.isNever)(baseTypedDictEntries.extraItems.valueType)) {
                        diag.addMessage(localize_1.LocAddendum.typedDictClosedExtraNotAllowed().format({
                            name,
                        }));
                    }
                    else if (!this._evaluator.assignType(baseExtraItemsType, entry.valueType, 
                    /* diag */ undefined, 
                    /* destTypeVarContext */ undefined, 
                    /* srcTypeVarContext */ undefined, !baseTypedDictEntries.extraItems.isReadOnly
                        ? 1 /* AssignTypeFlags.EnforceInvariance */
                        : 0 /* AssignTypeFlags.Default */)) {
                        diag.addMessage(localize_1.LocAddendum.typedDictClosedExtraTypeMismatch().format({
                            name,
                            type: this._evaluator.printType(entry.valueType),
                        }));
                    }
                    else if (!baseTypedDictEntries.extraItems.isReadOnly && entry.isRequired) {
                        diag.addMessage(localize_1.LocAddendum.typedDictClosedFieldNotRequired().format({
                            name,
                        }));
                    }
                }
            }
            if (typedDictEntries.extraItems && baseTypedDictEntries.extraItems) {
                if (!this._evaluator.assignType(baseExtraItemsType, typedDictEntries.extraItems.valueType, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, !baseTypedDictEntries.extraItems.isReadOnly
                    ? 1 /* AssignTypeFlags.EnforceInvariance */
                    : 0 /* AssignTypeFlags.Default */)) {
                    diag.addMessage(localize_1.LocAddendum.typedDictClosedExtraTypeMismatch().format({
                        name: '__extra_items__',
                        type: this._evaluator.printType(typedDictEntries.extraItems.valueType),
                    }));
                }
            }
            if (!diag.isEmpty() && classType.details.declaration) {
                const declNode = (0, declarationUtils_1.getNameNodeForDeclaration)(classType.details.declaration);
                if (declNode) {
                    if (baseTypedDictEntries.extraItems) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.typedDictClosedExtras().format({
                            name: baseClass.details.name,
                            type: this._evaluator.printType(baseExtraItemsType),
                        }) + diag.getString(), declNode);
                    }
                    else {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.typedDictClosedNoExtras().format({
                            name: baseClass.details.name,
                        }) + diag.getString(), declNode);
                    }
                }
            }
        }
    }
    // Validates that any overridden methods or variables contain the same
    // types as the original method. Also marks the class as abstract if one
    // or more abstract methods are not overridden.
    _validateBaseClassOverrides(classType) {
        types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
            // Private symbols do not need to match in type since their
            // names are mangled, and subclasses can't access the value in
            // the parent class.
            if (SymbolNameUtils.isPrivateName(name)) {
                return;
            }
            // If the symbol has no declaration, and the type is inferred,
            // skip the type validation but still check for other issues like
            // Final overrides and class/instance variable mismatches.
            let validateType = true;
            if (!symbol.hasTypedDeclarations()) {
                validateType = false;
            }
            // Get the symbol type defined in this class.
            const typeOfSymbol = this._evaluator.getEffectiveTypeOfSymbol(symbol);
            // If the type of the override symbol isn't known, stop here.
            if ((0, types_1.isAnyOrUnknown)(typeOfSymbol)) {
                return;
            }
            let firstOverride;
            for (const baseClass of classType.details.baseClasses) {
                if (!(0, types_1.isClass)(baseClass)) {
                    continue;
                }
                // Look up the base class in the MRO list. It's the same generic class
                // but has already been specialized using the type variables of the classType.
                const mroBaseClass = classType.details.mro.find((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isSameGenericClass(mroClass, baseClass));
                if (!mroBaseClass) {
                    continue;
                }
                (0, debug_1.assert)((0, types_1.isClass)(mroBaseClass));
                const baseClassAndSymbol = (0, typeUtils_1.lookUpClassMember)(mroBaseClass, name, 0 /* MemberAccessFlags.Default */);
                if (!baseClassAndSymbol) {
                    continue;
                }
                firstOverride = firstOverride !== null && firstOverride !== void 0 ? firstOverride : baseClassAndSymbol;
                this._validateBaseClassOverride(baseClassAndSymbol, symbol, validateType ? typeOfSymbol : types_1.AnyType.create(), classType, name);
            }
            if (!firstOverride) {
                // If this is a method decorated with @override, validate that there
                // is a base class method of the same name.
                this._validateOverrideDecoratorNotPresent(symbol, typeOfSymbol);
            }
            else {
                this._validateOverrideDecoratorPresent(symbol, typeOfSymbol, firstOverride);
            }
        });
    }
    _validateOverrideDecoratorPresent(symbol, overrideType, baseMember) {
        // Skip this check if disabled.
        if (this._fileInfo.diagnosticRuleSet.reportImplicitOverride === 'none') {
            return;
        }
        let overrideFunction;
        if ((0, types_1.isFunction)(overrideType)) {
            overrideFunction = overrideType;
        }
        else if ((0, types_1.isOverloadedFunction)(overrideType)) {
            overrideFunction = types_1.OverloadedFunctionType.getImplementation(overrideType);
        }
        else if ((0, types_1.isClassInstance)(overrideType) && types_1.ClassType.isPropertyClass(overrideType)) {
            if (overrideType.fgetInfo) {
                overrideFunction = overrideType.fgetInfo.methodType;
            }
        }
        if (!(overrideFunction === null || overrideFunction === void 0 ? void 0 : overrideFunction.details.declaration) || types_1.FunctionType.isOverridden(overrideFunction)) {
            return;
        }
        // Constructors are exempt.
        if (this._isMethodExemptFromLsp(overrideFunction.details.name)) {
            return;
        }
        // If the declaration for the override function is not the same as the
        // declaration for the symbol, the function was probably replaced by a decorator.
        if (!symbol.getDeclarations().some((decl) => decl === overrideFunction.details.declaration)) {
            return;
        }
        // If the base class is unknown, don't report a missing decorator.
        if ((0, types_1.isAnyOrUnknown)(baseMember.classType)) {
            return;
        }
        const funcNode = overrideFunction.details.declaration.node;
        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportImplicitOverride, localize_1.LocMessage.overrideDecoratorMissing().format({
            name: funcNode.name.value,
            className: this._evaluator.printType((0, typeUtils_1.convertToInstance)(baseMember.classType)),
        }), funcNode.name);
    }
    // Determines whether the name is exempt from Liskov Substitution Principle rules.
    _isMethodExemptFromLsp(name) {
        const exemptMethods = ['__init__', '__new__', '__init_subclass__', '__post_init__'];
        return exemptMethods.some((n) => n === name);
    }
    // Determines whether the type is a function or overloaded function with an @override
    // decorator. In this case, an error is reported because no base class has declared
    // a method of the same name.
    _validateOverrideDecoratorNotPresent(symbol, overrideType) {
        let overrideFunction;
        if ((0, types_1.isFunction)(overrideType)) {
            overrideFunction = overrideType;
        }
        else if ((0, types_1.isOverloadedFunction)(overrideType)) {
            overrideFunction = types_1.OverloadedFunctionType.getImplementation(overrideType);
        }
        else if ((0, types_1.isClassInstance)(overrideType) && types_1.ClassType.isPropertyClass(overrideType)) {
            if (overrideType.fgetInfo) {
                overrideFunction = overrideType.fgetInfo.methodType;
            }
        }
        if (!(overrideFunction === null || overrideFunction === void 0 ? void 0 : overrideFunction.details.declaration) || !types_1.FunctionType.isOverridden(overrideFunction)) {
            return;
        }
        // If the declaration for the override function is not the same as the
        // declaration for the symbol, the function was probably replaced by a decorator.
        if (!symbol.getDeclarations().some((decl) => decl === overrideFunction.details.declaration)) {
            return;
        }
        const funcNode = overrideFunction.details.declaration.node;
        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.overriddenMethodNotFound().format({ name: funcNode.name.value }), funcNode.name);
    }
    _validateBaseClassOverride(baseClassAndSymbol, overrideSymbol, overrideType, childClassType, memberName) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        if (!(0, types_1.isInstantiableClass)(baseClassAndSymbol.classType)) {
            return;
        }
        if (baseClassAndSymbol.symbol.isIgnoredForOverrideChecks() || overrideSymbol.isIgnoredForOverrideChecks()) {
            return;
        }
        // If the base class doesn't provide a type declaration, we won't bother
        // proceeding with additional checks. Type inference is too inaccurate
        // in this case, plus it would be very slow.
        if (!baseClassAndSymbol.symbol.hasTypedDeclarations()) {
            return;
        }
        // Special case the '_' symbol, which is used in single dispatch
        // code and other cases where the name does not matter.
        if (memberName === '_') {
            return;
        }
        const baseClass = baseClassAndSymbol.classType;
        const childClassSelf = types_1.ClassType.cloneAsInstance((0, typeUtils_1.selfSpecializeClass)(childClassType));
        const baseType = (0, typeUtils_1.partiallySpecializeType)(this._evaluator.getEffectiveTypeOfSymbol(baseClassAndSymbol.symbol), baseClass, childClassSelf);
        overrideType = (0, typeUtils_1.partiallySpecializeType)(overrideType, childClassType, childClassSelf);
        if ((0, types_1.isFunction)(baseType) || (0, types_1.isOverloadedFunction)(baseType)) {
            const diagAddendum = new diagnostic_1.DiagnosticAddendum();
            // Determine whether this is an attempt to override a method marked @final.
            let reportFinalMethodOverride = false;
            // Private names (starting with double underscore) are exempt from this check.
            if (!SymbolNameUtils.isPrivateName(memberName)) {
                if ((0, types_1.isFunction)(baseType) && types_1.FunctionType.isFinal(baseType)) {
                    reportFinalMethodOverride = true;
                }
                else if ((0, types_1.isOverloadedFunction)(baseType) &&
                    baseType.overloads.some((overload) => types_1.FunctionType.isFinal(overload))) {
                    reportFinalMethodOverride = true;
                }
            }
            if (reportFinalMethodOverride) {
                const decl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(overrideSymbol);
                if (decl && decl.type === 5 /* DeclarationType.Function */) {
                    const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.finalMethodOverride().format({
                        name: memberName,
                        className: baseClass.details.name,
                    }), decl.node.name);
                    const origDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(baseClassAndSymbol.symbol);
                    if (diag && origDecl) {
                        diag.addRelatedInfo(localize_1.LocAddendum.finalMethod(), origDecl.uri, origDecl.range);
                    }
                }
            }
            if ((0, types_1.isFunction)(overrideType) || (0, types_1.isOverloadedFunction)(overrideType)) {
                // Don't enforce parameter names for dundered methods. Many of them
                // are misnamed in typeshed stubs, so this would result in many
                // false positives.
                const enforceParamNameMatch = !SymbolNameUtils.isDunderName(memberName);
                // Don't check certain magic functions or private symbols.
                // Also, skip this check if the class is a TypedDict. The methods for a TypedDict
                // are synthesized, and they can result in many overloads. We assume they
                // are correct and will not produce any errors.
                if (!this._isMethodExemptFromLsp(memberName) &&
                    !SymbolNameUtils.isPrivateName(memberName) &&
                    !types_1.ClassType.isTypedDictClass(childClassType)) {
                    if (!this._evaluator.validateOverrideMethod(baseType, overrideType, childClassType, diagAddendum, enforceParamNameMatch)) {
                        const decl = (0, types_1.isFunction)(overrideType) && overrideType.details.declaration
                            ? overrideType.details.declaration
                            : (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(overrideSymbol);
                        if (decl) {
                            const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.incompatibleMethodOverride().format({
                                name: memberName,
                                className: baseClass.details.name,
                            }) + diagAddendum.getString(), (_a = (0, declarationUtils_1.getNameNodeForDeclaration)(decl)) !== null && _a !== void 0 ? _a : decl.node);
                            const origDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(baseClassAndSymbol.symbol);
                            if (diag && origDecl) {
                                diag.addRelatedInfo(localize_1.LocAddendum.overriddenMethod(), origDecl.uri, origDecl.range);
                            }
                        }
                    }
                }
            }
            else if (!(0, types_1.isAnyOrUnknown)(overrideType)) {
                // Special-case overrides of methods in '_TypedDict', since
                // TypedDict attributes aren't manifest as attributes but rather
                // as named keys.
                if (!types_1.ClassType.isBuiltIn(baseClass, '_TypedDict')) {
                    const decls = overrideSymbol.getDeclarations();
                    if (decls.length > 0) {
                        const lastDecl = decls[decls.length - 1];
                        const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.methodOverridden().format({
                            name: memberName,
                            className: baseClass.details.name,
                            type: this._evaluator.printType(overrideType),
                        }), (_b = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _b !== void 0 ? _b : lastDecl.node);
                        const origDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(baseClassAndSymbol.symbol);
                        if (diag && origDecl) {
                            diag.addRelatedInfo(localize_1.LocAddendum.overriddenMethod(), origDecl.uri, origDecl.range);
                        }
                    }
                }
            }
        }
        else if ((0, typeUtils_1.isProperty)(baseType)) {
            // Handle properties specially.
            if (!(0, typeUtils_1.isProperty)(overrideType)) {
                const decls = overrideSymbol.getDeclarations();
                if (decls.length > 0 && overrideSymbol.isClassMember()) {
                    const lastDecl = decls[decls.length - 1];
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.propertyOverridden().format({
                        name: memberName,
                        className: baseClass.details.name,
                    }), (_c = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _c !== void 0 ? _c : lastDecl.node);
                }
            }
            else {
                const baseClassType = baseClass;
                const propMethodInfo = [
                    ['fget', (c) => { var _a; return (_a = c.fgetInfo) === null || _a === void 0 ? void 0 : _a.methodType; }],
                    ['fset', (c) => { var _a; return (_a = c.fsetInfo) === null || _a === void 0 ? void 0 : _a.methodType; }],
                    ['fdel', (c) => { var _a; return (_a = c.fdelInfo) === null || _a === void 0 ? void 0 : _a.methodType; }],
                ];
                propMethodInfo.forEach((info) => {
                    var _a;
                    const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    const [methodName, methodAccessor] = info;
                    const baseClassPropMethod = methodAccessor(baseType);
                    const subclassPropMethod = methodAccessor(overrideType);
                    // Is the method present on the base class but missing in the subclass?
                    if (baseClassPropMethod) {
                        const baseClassMethodType = (0, typeUtils_1.partiallySpecializeType)(baseClassPropMethod, baseClassType);
                        if ((0, types_1.isFunction)(baseClassMethodType)) {
                            if (!subclassPropMethod) {
                                // The method is missing.
                                diagAddendum.addMessage(localize_1.LocAddendum.propertyMethodMissing().format({
                                    name: methodName,
                                }));
                                const decls = overrideSymbol.getDeclarations();
                                if (decls.length > 0) {
                                    const lastDecl = decls[decls.length - 1];
                                    const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.propertyOverridden().format({
                                        name: memberName,
                                        className: baseClassType.details.name,
                                    }) + diagAddendum.getString(), (_a = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _a !== void 0 ? _a : lastDecl.node);
                                    const origDecl = baseClassMethodType.details.declaration;
                                    if (diag && origDecl) {
                                        diag.addRelatedInfo(localize_1.LocAddendum.overriddenMethod(), origDecl.uri, origDecl.range);
                                    }
                                }
                            }
                            else {
                                const subclassMethodType = (0, typeUtils_1.partiallySpecializeType)(subclassPropMethod, childClassType);
                                if ((0, types_1.isFunction)(subclassMethodType)) {
                                    if (!this._evaluator.validateOverrideMethod(baseClassMethodType, subclassMethodType, childClassType, diagAddendum.createAddendum())) {
                                        diagAddendum.addMessage(localize_1.LocAddendum.propertyMethodIncompatible().format({
                                            name: methodName,
                                        }));
                                        const decl = subclassMethodType.details.declaration;
                                        if (decl && decl.type === 5 /* DeclarationType.Function */) {
                                            const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride, localize_1.LocMessage.propertyOverridden().format({
                                                name: memberName,
                                                className: baseClassType.details.name,
                                            }) + diagAddendum.getString(), decl.node.name);
                                            const origDecl = baseClassMethodType.details.declaration;
                                            if (diag && origDecl) {
                                                diag.addRelatedInfo(localize_1.LocAddendum.overriddenMethod(), origDecl.uri, origDecl.range);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
        else {
            // This check can be expensive, so don't perform it if the corresponding
            // rule is disabled.
            if (this._fileInfo.diagnosticRuleSet.reportIncompatibleVariableOverride !== 'none') {
                const decls = overrideSymbol.getDeclarations();
                if (decls.length > 0) {
                    const lastDecl = decls[decls.length - 1];
                    const primaryDecl = decls[0];
                    // Verify that the override type is assignable to (same or narrower than)
                    // the declared type of the base symbol.
                    let isInvariant = (primaryDecl === null || primaryDecl === void 0 ? void 0 : primaryDecl.type) === 1 /* DeclarationType.Variable */ && !primaryDecl.isFinal;
                    // If the entry is a member of a frozen dataclass, it is immutable,
                    // so it does not need to be invariant.
                    if (types_1.ClassType.isFrozenDataClass(baseClass) && baseClass.details.dataClassEntries) {
                        const dataclassEntry = baseClass.details.dataClassEntries.find((entry) => entry.name === memberName);
                        if (dataclassEntry) {
                            isInvariant = false;
                        }
                    }
                    let overriddenTDEntry;
                    let overrideTDEntry;
                    if (!overrideSymbol.isIgnoredForProtocolMatch()) {
                        if (baseClass.details.typedDictEntries) {
                            overriddenTDEntry =
                                (_e = (_d = baseClass.details.typedDictEntries.knownItems.get(memberName)) !== null && _d !== void 0 ? _d : baseClass.details.typedDictEntries.extraItems) !== null && _e !== void 0 ? _e : (0, typedDicts_1.getEffectiveExtraItemsEntryType)(this._evaluator, baseClass);
                            if (overriddenTDEntry === null || overriddenTDEntry === void 0 ? void 0 : overriddenTDEntry.isReadOnly) {
                                isInvariant = false;
                            }
                        }
                        if (childClassType.details.typedDictEntries) {
                            // Exempt __extra_items__ here. We'll check this separately
                            // in _validateTypedDictOverrides. If we don't skip it here,
                            // redundant errors will be produced.
                            if (types_1.ClassType.isTypedDictMarkedClosed(childClassType) && memberName === '__extra_items__') {
                                overrideTDEntry = overriddenTDEntry;
                                overrideType = baseType;
                            }
                            else {
                                overrideTDEntry =
                                    (_g = (_f = childClassType.details.typedDictEntries.knownItems.get(memberName)) !== null && _f !== void 0 ? _f : childClassType.details.typedDictEntries.extraItems) !== null && _g !== void 0 ? _g : (0, typedDicts_1.getEffectiveExtraItemsEntryType)(this._evaluator, childClassType);
                            }
                        }
                    }
                    let diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    if (!this._evaluator.assignType(baseType, overrideType, diagAddendum, 
                    /* destTypeVarContext */ undefined, 
                    /* srcTypeVarContext */ undefined, isInvariant ? 1 /* AssignTypeFlags.EnforceInvariance */ : 0 /* AssignTypeFlags.Default */)) {
                        if (isInvariant) {
                            diagAddendum = new diagnostic_1.DiagnosticAddendum();
                            diagAddendum.addMessage(localize_1.LocAddendum.overrideIsInvariant());
                            diagAddendum.createAddendum().addMessage(localize_1.LocAddendum.overrideInvariantMismatch().format({
                                overrideType: this._evaluator.printType(overrideType),
                                baseType: this._evaluator.printType(baseType),
                            }));
                        }
                        const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.symbolOverridden().format({
                            name: memberName,
                            className: baseClass.details.name,
                        }) + diagAddendum.getString(), (_h = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _h !== void 0 ? _h : lastDecl.node);
                        const origDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(baseClassAndSymbol.symbol);
                        if (diag && origDecl) {
                            diag.addRelatedInfo(localize_1.LocAddendum.overriddenSymbol(), origDecl.uri, origDecl.range);
                        }
                    }
                    else if (overriddenTDEntry && overrideTDEntry) {
                        // Make sure the required/not-required attribute is compatible.
                        let isRequiredCompatible = true;
                        if (overriddenTDEntry.isReadOnly) {
                            // If the read-only flag is set, a not-required field can be overridden
                            // by a required field, but not vice versa.
                            isRequiredCompatible = overrideTDEntry.isRequired || !overriddenTDEntry.isRequired;
                        }
                        else {
                            isRequiredCompatible = overrideTDEntry.isRequired === overriddenTDEntry.isRequired;
                        }
                        if (!isRequiredCompatible) {
                            const message = overrideTDEntry.isRequired
                                ? localize_1.LocMessage.typedDictFieldRequiredRedefinition
                                : localize_1.LocMessage.typedDictFieldNotRequiredRedefinition;
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, message().format({ name: memberName }), (_j = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _j !== void 0 ? _j : lastDecl.node);
                        }
                        // Make sure that the derived class isn't marking a previously writable
                        // entry as read-only.
                        if (!overriddenTDEntry.isReadOnly && overrideTDEntry.isReadOnly) {
                            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictFieldReadOnlyRedefinition().format({
                                name: memberName,
                            }), (_k = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _k !== void 0 ? _k : lastDecl.node);
                        }
                    }
                    // Verify that there is not a Final mismatch.
                    const isBaseVarFinal = this._evaluator.isFinalVariable(baseClassAndSymbol.symbol);
                    const overrideFinalVarDecl = decls.find((d) => this._evaluator.isFinalVariableDeclaration(d));
                    if (!isBaseVarFinal && overrideFinalVarDecl) {
                        const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, localize_1.LocMessage.variableFinalOverride().format({
                            name: memberName,
                            className: baseClass.details.name,
                        }), (_l = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _l !== void 0 ? _l : lastDecl.node);
                        if (diag) {
                            diag.addRelatedInfo(localize_1.LocAddendum.overriddenSymbol(), overrideFinalVarDecl.uri, overrideFinalVarDecl.range);
                        }
                    }
                    // Verify that a class variable isn't overriding an instance
                    // variable or vice versa.
                    const isBaseClassVar = baseClassAndSymbol.symbol.isClassVar();
                    let isClassVar = overrideSymbol.isClassVar();
                    if (isBaseClassVar && !isClassVar) {
                        // If the subclass doesn't redeclare the type but simply assigns
                        // it without declaring its type, we won't consider it an instance
                        // variable.
                        if (!overrideSymbol.hasTypedDeclarations()) {
                            isClassVar = true;
                        }
                        // If the subclass is declaring an inner class, we'll consider that
                        // to be a ClassVar.
                        if (overrideSymbol.getTypedDeclarations().every((decl) => decl.type === 6 /* DeclarationType.Class */)) {
                            isClassVar = true;
                        }
                    }
                    if (isBaseClassVar !== isClassVar) {
                        const unformattedMessage = overrideSymbol.isClassVar()
                            ? localize_1.LocMessage.classVarOverridesInstanceVar()
                            : localize_1.LocMessage.instanceVarOverridesClassVar();
                        const diag = this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride, unformattedMessage.format({
                            name: memberName,
                            className: baseClass.details.name,
                        }), (_m = (0, declarationUtils_1.getNameNodeForDeclaration)(lastDecl)) !== null && _m !== void 0 ? _m : lastDecl.node);
                        const origDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(baseClassAndSymbol.symbol);
                        if (diag && origDecl) {
                            diag.addRelatedInfo(localize_1.LocAddendum.overriddenSymbol(), origDecl.uri, origDecl.range);
                        }
                    }
                }
            }
        }
    }
    // Performs checks on a function that is located within a class
    // and has been determined not to be a property accessor.
    _validateMethod(node, functionType, classNode) {
        var _a, _b;
        const classTypeInfo = this._evaluator.getTypeOfClass(classNode);
        const classType = classTypeInfo === null || classTypeInfo === void 0 ? void 0 : classTypeInfo.classType;
        if (node.name && classType) {
            const superCheckMethods = ['__init__', '__init_subclass__', '__enter__', '__exit__'];
            if (superCheckMethods.some((name) => name === node.name.value)) {
                if (!types_1.FunctionType.isAbstractMethod(functionType) &&
                    !types_1.FunctionType.isOverloaded(functionType) &&
                    !this._fileInfo.isStubFile) {
                    this._validateSuperCallForMethod(node, functionType, classType);
                }
            }
        }
        if (((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) === '__new__') {
            // __new__ overrides should have a "cls" parameter.
            if (node.parameters.length === 0 ||
                !node.parameters[0].name ||
                !['cls', '_cls', '__cls', '__mcls', 'mcls', 'mcs', 'metacls'].some((name) => node.parameters[0].name.value === name)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportSelfClsParameterName, localize_1.LocMessage.newClsParam(), node.parameters.length > 0 ? node.parameters[0] : node.name);
            }
            if (classType) {
                this._validateClsSelfParameterType(functionType, classType, /* isCls */ true);
            }
        }
        else if (((_b = node.name) === null || _b === void 0 ? void 0 : _b.value) === '_generate_next_value_') {
            // Skip this check for _generate_next_value_.
        }
        else if (types_1.FunctionType.isStaticMethod(functionType)) {
            // Static methods should not have "self" or "cls" parameters.
            if (node.parameters.length > 0 && node.parameters[0].name) {
                const paramName = node.parameters[0].name.value;
                if (paramName === 'self' || paramName === 'cls') {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportSelfClsParameterName, localize_1.LocMessage.staticClsSelfParam(), node.parameters[0].name);
                }
            }
        }
        else if (types_1.FunctionType.isClassMethod(functionType)) {
            let paramName = '';
            if (node.parameters.length > 0 && node.parameters[0].name) {
                paramName = node.parameters[0].name.value;
            }
            // Class methods should have a "cls" parameter. We'll exempt parameter
            // names that start with an underscore since those are used in a few
            // cases in the stdlib pyi files.
            if (paramName !== 'cls') {
                if (!this._fileInfo.isStubFile || (!paramName.startsWith('_') && paramName !== 'metacls')) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportSelfClsParameterName, localize_1.LocMessage.classMethodClsParam(), node.parameters.length > 0 ? node.parameters[0] : node.name);
                }
            }
            if (classType) {
                this._validateClsSelfParameterType(functionType, classType, /* isCls */ true);
            }
        }
        else {
            const decoratorIsPresent = node.decorators.length > 0;
            const isOverloaded = types_1.FunctionType.isOverloaded(functionType);
            // The presence of a decorator can change the behavior, so we need
            // to back off from this check if a decorator is present. An overload
            // is a decorator, but we'll ignore that here.
            if (isOverloaded || !decoratorIsPresent) {
                let paramName = '';
                let firstParamIsSimple = true;
                if (node.parameters.length > 0) {
                    if (node.parameters[0].name) {
                        paramName = node.parameters[0].name.value;
                    }
                    if (node.parameters[0].category !== 0 /* ParameterCategory.Simple */) {
                        firstParamIsSimple = false;
                    }
                }
                // Instance methods should have a "self" parameter.
                if (firstParamIsSimple && paramName !== 'self') {
                    // Special-case metaclasses, which can use "cls" or several variants.
                    let isLegalMetaclassName = false;
                    if (['cls', 'mcls', 'mcs'].some((name) => name === paramName)) {
                        const classTypeInfo = this._evaluator.getTypeOfClass(classNode);
                        const typeType = this._evaluator.getBuiltInType(classNode, 'type');
                        if (typeType &&
                            (0, types_1.isInstantiableClass)(typeType) &&
                            classTypeInfo &&
                            (0, types_1.isInstantiableClass)(classTypeInfo.classType)) {
                            if ((0, typeUtils_1.derivesFromClassRecursive)(classTypeInfo.classType, typeType, /* ignoreUnknown */ true)) {
                                isLegalMetaclassName = true;
                            }
                        }
                    }
                    // Some typeshed stubs use a name that starts with an underscore to designate
                    // a parameter that cannot be positional.
                    const isPrivateName = SymbolNameUtils.isPrivateOrProtectedName(paramName);
                    if (!isLegalMetaclassName && !isPrivateName) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportSelfClsParameterName, localize_1.LocMessage.instanceMethodSelfParam(), node.parameters.length > 0 ? node.parameters[0] : node.name);
                    }
                }
            }
            if (classType) {
                this._validateClsSelfParameterType(functionType, classType, /* isCls */ false);
            }
        }
    }
    // Determines whether the method properly calls through to the same method in all
    // parent classes that expose a same-named method.
    _validateSuperCallForMethod(node, methodType, classType) {
        // This is an expensive test, so if it's not enabled, don't do any work.
        if (this._fileInfo.diagnosticRuleSet.reportMissingSuperCall === 'none') {
            return;
        }
        // If the class is marked final, we can skip the "object" base class
        // because we know that the `__init__` method in `object` doesn't do
        // anything. It's not safe to do this if the class isn't final because
        // it could be combined with other classes in a multi-inheritance
        // situation that effectively adds new superclasses that we don't know
        // about statically.
        let effectiveFlags = 16 /* MemberAccessFlags.SkipInstanceMembers */ | 1 /* MemberAccessFlags.SkipOriginalClass */;
        if (types_1.ClassType.isFinal(classType)) {
            effectiveFlags |= 4 /* MemberAccessFlags.SkipObjectBaseClass */;
        }
        const methodMember = (0, typeUtils_1.lookUpClassMember)(classType, methodType.details.name, effectiveFlags);
        if (!methodMember) {
            return;
        }
        let foundCallOfMember = false;
        // Now scan the implementation of the method to determine whether
        // super().<method> has been called for all of the required base classes.
        const callNodeWalker = new ParseTreeUtils.CallNodeWalker((node) => {
            if (node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                // Is it accessing the method by the same name?
                if (node.leftExpression.memberName.value === methodType.details.name) {
                    const memberBaseExpr = node.leftExpression.leftExpression;
                    // Is it a "super" call?
                    if (memberBaseExpr.nodeType === 9 /* ParseNodeType.Call */ &&
                        memberBaseExpr.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                        memberBaseExpr.leftExpression.value === 'super') {
                        foundCallOfMember = true;
                    }
                    else {
                        // Is it an X.<method> direct call?
                        const baseType = this._evaluator.getType(memberBaseExpr);
                        if (baseType && (0, types_1.isInstantiableClass)(baseType)) {
                            foundCallOfMember = true;
                        }
                    }
                }
            }
        });
        callNodeWalker.walk(node.suite);
        // If we didn't find a call to at least one base class, report the problem.
        if (!foundCallOfMember) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingSuperCall, localize_1.LocMessage.missingSuperCall().format({
                methodName: methodType.details.name,
            }), node.name);
        }
    }
    // Validates that the annotated type of a "self" or "cls" parameter is
    // compatible with the type of the class that contains it.
    _validateClsSelfParameterType(functionType, classType, isCls) {
        if (functionType.details.parameters.length < 1) {
            return;
        }
        // If there is no type annotation, there's nothing to check because
        // the type will be inferred.
        const paramInfo = functionType.details.parameters[0];
        if (!paramInfo.typeAnnotation || !paramInfo.name) {
            return;
        }
        // If this is an __init__ method, we need to specifically check for the
        // use of class-scoped TypeVars, which are not allowed in this context
        // according to the typing spec.
        if (functionType.details.name === '__init__' && functionType.details.methodClass) {
            const typeVars = (0, typeUtils_1.getTypeVarArgumentsRecursive)(paramInfo.type);
            if (typeVars.some((typeVar) => { var _a; return typeVar.scopeId === ((_a = functionType.details.methodClass) === null || _a === void 0 ? void 0 : _a.details.typeVarScopeId); })) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.initMethodSelfParamTypeVar(), paramInfo.typeAnnotation);
            }
        }
        // If this is a protocol class, the self and cls parameters can be bound
        // to something other than the class.
        if (types_1.ClassType.isProtocolClass(classType)) {
            return;
        }
        const paramType = this._evaluator.makeTopLevelTypeVarsConcrete(paramInfo.type);
        const expectedType = isCls ? classType : (0, typeUtils_1.convertToInstance)(classType);
        // If the declared type is a protocol class or instance, skip
        // the check. This has legitimate uses for mix-in classes.
        if ((0, types_1.isInstantiableClass)(paramType) && types_1.ClassType.isProtocolClass(paramType)) {
            return;
        }
        if ((0, types_1.isClassInstance)(paramType) && types_1.ClassType.isProtocolClass(paramType)) {
            return;
        }
        // If the method starts with a `*args: P.args`, skip the check.
        if (paramInfo.category === 1 /* ParameterCategory.ArgsList */ &&
            (0, types_1.isParamSpec)(paramInfo.type) &&
            paramInfo.type.paramSpecAccess === 'args') {
            return;
        }
        // Don't enforce this for an overloaded method because the "self" param
        // annotation can be used as a filter for the overload. This differs from
        // mypy, which enforces this check for overloads, but there are legitimate
        // uses for this in an overloaded method.
        if (types_1.FunctionType.isOverloaded(functionType)) {
            return;
        }
        // If the declared type is LiteralString and the class is str, exempt this case.
        // It's used in the typeshed stubs.
        if ((0, types_1.isClassInstance)(paramType) &&
            types_1.ClassType.isBuiltIn(paramType, 'LiteralString') &&
            types_1.ClassType.isBuiltIn(classType, 'str')) {
            return;
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(functionType));
        if (!this._evaluator.assignType(paramType, expectedType, /* diag */ undefined, typeVarContext)) {
            // We exempt Never from this check because it has a legitimate use in this case.
            if (!(0, types_1.isNever)(paramType)) {
                this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.clsSelfParamTypeMismatch().format({
                    name: paramInfo.name,
                    classType: this._evaluator.printType(expectedType),
                }), paramInfo.typeAnnotation);
            }
        }
    }
    // Determines whether a yield or yield from node is compatible with the
    // return type annotation of the containing function.
    _validateYieldType(node, yieldType, expectedDiagAddendum, sendType) {
        var _a, _b, _c, _d;
        const enclosingFunctionNode = ParseTreeUtils.getEnclosingFunction(node);
        if (!enclosingFunctionNode || !enclosingFunctionNode.returnTypeAnnotation) {
            return;
        }
        const functionTypeResult = this._evaluator.getTypeOfFunction(enclosingFunctionNode);
        if (!functionTypeResult) {
            return;
        }
        const declaredReturnType = types_1.FunctionType.getSpecializedReturnType(functionTypeResult.functionType);
        if (!declaredReturnType) {
            return;
        }
        let generatorType;
        if (!enclosingFunctionNode.isAsync &&
            (0, types_1.isClassInstance)(declaredReturnType) &&
            types_1.ClassType.isBuiltIn(declaredReturnType, 'AwaitableGenerator')) {
            // Handle the old-style (pre-await) generator case
            // if the return type explicitly uses AwaitableGenerator.
            generatorType = this._evaluator.getTypingType(node, 'AwaitableGenerator');
        }
        else {
            generatorType = this._evaluator.getTypingType(node, enclosingFunctionNode.isAsync ? 'AsyncGenerator' : 'Generator');
        }
        if (!generatorType || !(0, types_1.isInstantiableClass)(generatorType)) {
            return;
        }
        if (!this._evaluator.isNodeReachable(node, /* sourceNode */ undefined)) {
            return;
        }
        if ((0, types_1.isNever)(declaredReturnType)) {
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.noReturnContainsYield(), node);
            return;
        }
        const generatorTypeArgs = [yieldType, sendType !== null && sendType !== void 0 ? sendType : types_1.UnknownType.create(), types_1.UnknownType.create()];
        const specializedGenerator = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(generatorType, generatorTypeArgs, /* isTypeArgumentExplicit */ true));
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        if (!this._evaluator.assignType(declaredReturnType, specializedGenerator, diagAddendum)) {
            const errorMessage = enclosingFunctionNode.isAsync
                ? localize_1.LocMessage.generatorAsyncReturnType()
                : localize_1.LocMessage.generatorSyncReturnType();
            this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportReturnType, errorMessage.format({ yieldType: this._evaluator.printType(yieldType) }) +
                ((_a = expectedDiagAddendum === null || expectedDiagAddendum === void 0 ? void 0 : expectedDiagAddendum.getString()) !== null && _a !== void 0 ? _a : diagAddendum.getString()), (_b = node.expression) !== null && _b !== void 0 ? _b : node, (_d = (_c = expectedDiagAddendum === null || expectedDiagAddendum === void 0 ? void 0 : expectedDiagAddendum.getEffectiveTextRange()) !== null && _c !== void 0 ? _c : node.expression) !== null && _d !== void 0 ? _d : node);
        }
    }
    // Determines whether any of the except statements are unreachable because
    // they are redundant.
    _reportUnusedExceptStatements(node) {
        let sawUnknownExceptionType = false;
        const exceptionTypesSoFar = [];
        node.exceptClauses.forEach((except) => {
            var _a, _b;
            if (sawUnknownExceptionType || except.isExceptGroup || !except.typeExpression) {
                return;
            }
            const exceptionType = this._evaluator.getType(except.typeExpression);
            if (!exceptionType || (0, types_1.isAnyOrUnknown)(exceptionType)) {
                sawUnknownExceptionType = true;
                return;
            }
            const typesOfThisExcept = [];
            if ((0, types_1.isInstantiableClass)(exceptionType)) {
                // If the exception type is a variable whose type could represent
                // subclasses, the actual exception type is statically unknown.
                if (exceptionType.includeSubclasses) {
                    sawUnknownExceptionType = true;
                }
                typesOfThisExcept.push(exceptionType);
            }
            else if ((0, types_1.isClassInstance)(exceptionType)) {
                const iterableType = (_b = (_a = this._evaluator.getTypeOfIterator({ type: exceptionType }, 
                /* isAsync */ false, 
                /* errorNode */ except.typeExpression, 
                /* emitNotIterableError */ false)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
                (0, typeUtils_1.doForEachSubtype)(iterableType, (subtype) => {
                    if ((0, types_1.isAnyOrUnknown)(subtype)) {
                        sawUnknownExceptionType = true;
                    }
                    if ((0, types_1.isInstantiableClass)(subtype)) {
                        // If the exception type is a variable whose type could represent
                        // subclasses, the actual exception type is statically unknown.
                        if (subtype.includeSubclasses) {
                            sawUnknownExceptionType = true;
                        }
                        typesOfThisExcept.push(subtype);
                    }
                });
            }
            else {
                sawUnknownExceptionType = true;
            }
            if (exceptionTypesSoFar.length > 0 && !sawUnknownExceptionType) {
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                let overriddenExceptionCount = 0;
                typesOfThisExcept.forEach((thisExceptType) => {
                    const subtype = exceptionTypesSoFar.find((previousExceptType) => {
                        return (0, typeUtils_1.derivesFromClassRecursive)(thisExceptType, previousExceptType, /* ignoreUnknown */ true);
                    });
                    if (subtype) {
                        diagAddendum.addMessage(localize_1.LocAddendum.unreachableExcept().format({
                            exceptionType: this._evaluator.printType((0, typeUtils_1.convertToInstance)(thisExceptType)),
                            parentType: this._evaluator.printType((0, typeUtils_1.convertToInstance)(subtype)),
                        }));
                        overriddenExceptionCount++;
                    }
                });
                // Were all of the exception types overridden?
                if (typesOfThisExcept.length > 0 && typesOfThisExcept.length === overriddenExceptionCount) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnusedExcept, localize_1.LocMessage.unreachableExcept() + diagAddendum.getString(), except.typeExpression);
                    this._evaluator.addUnreachableCode(except, except.exceptSuite);
                }
            }
            (0, collectionUtils_1.appendArray)(exceptionTypesSoFar, typesOfThisExcept);
        });
    }
    _reportDuplicateImports() {
        const importedNames = [];
        (0, importStatementUtils_1.getTopLevelImports)(this._moduleNode).orderedImports.forEach((importStatement) => {
            if (importStatement.node.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                importStatement.node.imports.forEach((importFromAs) => {
                    var _a;
                    const node = (_a = importFromAs.alias) !== null && _a !== void 0 ? _a : importFromAs.name;
                    const name = node.value;
                    if (importedNames.includes(name)) {
                        this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportDuplicateImport, localize_1.LocMessage.duplicateImport().format({ importName: name }), node);
                    }
                    importedNames.push(name);
                });
            }
            else if (importStatement.subnode) {
                let node;
                let name;
                if (importStatement.subnode.alias) {
                    node = importStatement.subnode.alias;
                    name = node.value;
                }
                else {
                    node = importStatement.node;
                    name = importStatement.moduleName;
                }
                if (importedNames.includes(name)) {
                    this._evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportDuplicateImport, localize_1.LocMessage.duplicateImport().format({ importName: name }), node);
                }
                importedNames.push(name);
            }
        });
    }
}
exports.Checker = Checker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/circularDependency.ts":
/*!**************************************************************!*\
  !*** ../pyright-internal/src/analyzer/circularDependency.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * circularDependency.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A list of file paths that are part of a circular dependency
 * chain (i.e. a chain of imports). Since these are circular, there
 * no defined "start", but this module helps normalize the start
 * by picking the alphabetically-first module in the cycle.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CircularDependency = void 0;
class CircularDependency {
    constructor() {
        this._paths = [];
    }
    appendPath(path) {
        this._paths.push(path);
    }
    getPaths() {
        return this._paths;
    }
    normalizeOrder() {
        // Find the path that is alphabetically first and reorder
        // based on that.
        let firstIndex = 0;
        this._paths.forEach((path, index) => {
            if (path < this._paths[firstIndex]) {
                firstIndex = index;
            }
        });
        if (firstIndex !== 0) {
            this._paths = this._paths.slice(firstIndex).concat(this._paths.slice(0, firstIndex));
        }
    }
    isEqual(circDependency) {
        if (circDependency._paths.length !== this._paths.length) {
            return false;
        }
        for (let i = 0; i < this._paths.length; i++) {
            if (this._paths[i] !== circDependency._paths[i]) {
                return false;
            }
        }
        return true;
    }
}
exports.CircularDependency = CircularDependency;


/***/ }),

/***/ "../pyright-internal/src/analyzer/codeFlowEngine.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/codeFlowEngine.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * codeFlowEngine.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Code that traverses the code flow graph to determine the (narrowed)
 * type of a variable or expression or the reachability of a statement.
 *
 * This is largely based on the code flow engine in the
 * TypeScript compiler.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCodeFlowEngine = exports.isIncompleteType = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const codeFlowTypes_1 = __webpack_require__(/*! ./codeFlowTypes */ "../pyright-internal/src/analyzer/codeFlowTypes.ts");
const codeFlowUtils_1 = __webpack_require__(/*! ./codeFlowUtils */ "../pyright-internal/src/analyzer/codeFlowUtils.ts");
const constructors_1 = __webpack_require__(/*! ./constructors */ "../pyright-internal/src/analyzer/constructors.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const patternMatching_1 = __webpack_require__(/*! ./patternMatching */ "../pyright-internal/src/analyzer/patternMatching.ts");
const typedDicts_1 = __webpack_require__(/*! ./typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const typeGuards_1 = __webpack_require__(/*! ./typeGuards */ "../pyright-internal/src/analyzer/typeGuards.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
// Define a user type guard function for IncompleteType.
function isIncompleteType(cachedType) {
    return !!cachedType.isIncompleteType;
}
exports.isIncompleteType = isIncompleteType;
// This debugging option prints the control flow graph when getTypeFromCodeFlow is called.
const enablePrintControlFlowGraph = false;
// This debugging option prints the results of calls to isCallNoReturn.
const enablePrintCallNoReturn = false;
// Should the code flow engine assume that an unannotated function does not have
// an inferred return type of `NoReturn`, or should it perform code flow analysis
// to determine whether it is `NoReturn`? Enabling this produces more consistent
// and complete results, but it can be very expensive.
const inferNoReturnForUnannotatedFunctions = false;
function getCodeFlowEngine(evaluator, speculativeTypeTracker) {
    const isReachableRecursionSet = new Set();
    const callIsNoReturnCache = new Map();
    const isExceptionContextManagerCache = new Map();
    let flowIncompleteGeneration = 1;
    let noReturnAnalysisDepth = 0;
    let contextManagerAnalysisDepth = 0;
    // Creates a new code flow analyzer that can be used to narrow the types
    // of the expressions within an execution context. Each code flow analyzer
    // instance maintains a cache of types it has already determined.
    // The caller should pass a typeAtStart value because the code flow
    // analyzer may cache types based on this value, but the typeAtStart
    // may vary depending on the context in which the code flow analysis
    // is performed.
    function createCodeFlowAnalyzer(typeAtStart) {
        const flowNodeTypeCacheSet = new Map();
        function getFlowNodeTypeCacheForReference(referenceKey) {
            let flowNodeTypeCache = flowNodeTypeCacheSet.get(referenceKey);
            if (!flowNodeTypeCache) {
                flowNodeTypeCache = {
                    cache: new Map(),
                    pendingNodes: new Set(),
                    closedFinallyGateNodes: new Set(),
                };
                flowNodeTypeCacheSet.set(referenceKey, flowNodeTypeCache);
            }
            return flowNodeTypeCache;
        }
        // This function has two primary modes. The first is used to determine
        // the narrowed type of a reference expression based on code flow analysis.
        // The second (when reference is undefined) is used to determine whether
        // the specified flowNode is reachable when "never narrowing" is applied.
        function getTypeFromCodeFlow(flowNode, reference, options) {
            var _a, _b;
            if (enablePrintControlFlowGraph) {
                printControlFlowGraph(flowNode, reference, 'getTypeFromCodeFlow');
            }
            const referenceKey = reference !== undefined ? (0, codeFlowTypes_1.createKeyForReference)(reference) : undefined;
            let subexpressionReferenceKeys;
            const referenceKeyWithSymbolId = referenceKey !== undefined && (options === null || options === void 0 ? void 0 : options.targetSymbolId) !== undefined
                ? referenceKey + `.${options === null || options === void 0 ? void 0 : options.targetSymbolId.toString()}`
                : '.';
            const flowNodeTypeCache = getFlowNodeTypeCacheForReference(referenceKeyWithSymbolId);
            // Caches the type of the flow node in our local cache, keyed by the flow node ID.
            function setCacheEntry(flowNode, type, isIncomplete) {
                if (!isIncomplete) {
                    flowIncompleteGeneration++;
                }
                else if (type) {
                    const prevEntry = flowNodeTypeCache.cache.get(flowNode.id);
                    if (prevEntry) {
                        const prevIncompleteType = prevEntry;
                        if (prevIncompleteType.isIncompleteType &&
                            prevIncompleteType.type &&
                            !(0, types_1.isTypeSame)(prevIncompleteType.type, type)) {
                            flowIncompleteGeneration++;
                        }
                    }
                }
                // For speculative or incomplete types, we'll create a separate
                // object. For non-speculative and complete types, we'll store
                // the type directly.
                const entry = isIncomplete
                    ? {
                        isIncompleteType: true,
                        type,
                        incompleteSubtypes: [],
                        generationCount: flowIncompleteGeneration,
                    }
                    : type;
                flowNodeTypeCache.cache.set(flowNode.id, entry);
                speculativeTypeTracker.trackEntry(flowNodeTypeCache.cache, flowNode.id);
                return {
                    type,
                    isIncomplete,
                    generationCount: flowIncompleteGeneration,
                    incompleteSubtypes: isIncomplete ? [] : undefined,
                };
            }
            function setIncompleteSubtype(flowNode, index, type, isIncomplete, isPending, evaluationCount) {
                const cachedEntry = flowNodeTypeCache.cache.get(flowNode.id);
                if (cachedEntry === undefined || !isIncompleteType(cachedEntry)) {
                    (0, debug_1.fail)('setIncompleteSubtype can be called only on a valid incomplete cache entry: ' +
                        `prev cache entry?: ${!cachedEntry} ` +
                        `index=${index} ` +
                        `isPending=${isPending} ` +
                        `evaluationCount=${evaluationCount}`);
                }
                const incompleteEntries = cachedEntry.incompleteSubtypes;
                if (index < incompleteEntries.length) {
                    const oldEntry = incompleteEntries[index];
                    if (oldEntry.isIncomplete !== isIncomplete || !(0, types_1.isTypeSame)(oldEntry.type, type)) {
                        incompleteEntries[index] = { type, isIncomplete, isPending, evaluationCount };
                        flowIncompleteGeneration++;
                    }
                    else if (oldEntry.isPending !== isPending) {
                        incompleteEntries[index] = { type, isIncomplete, isPending, evaluationCount };
                    }
                }
                else {
                    (0, debug_1.assert)(incompleteEntries.length === index);
                    incompleteEntries.push({ type, isIncomplete, isPending, evaluationCount });
                    flowIncompleteGeneration++;
                }
                let combinedType;
                if (cachedEntry.incompleteSubtypes.length > 0) {
                    // Recompute the effective type based on all of the incomplete
                    // types we've accumulated so far.
                    const typesToCombine = [];
                    cachedEntry.incompleteSubtypes.forEach((t) => {
                        if (t.type) {
                            typesToCombine.push(t.type);
                        }
                    });
                    combinedType = typesToCombine.length > 0 ? (0, types_1.combineTypes)(typesToCombine) : undefined;
                }
                cachedEntry.type = combinedType;
                cachedEntry.generationCount = flowIncompleteGeneration;
                return getCacheEntry(flowNode);
            }
            // Cache either contains a type or an object that represents an incomplete type.
            // Incomplete types are types that haven't gone through all flow nodes yet.
            // Incomplete only happens for branch and loop nodes.
            function getCacheEntry(flowNode) {
                if (!flowNodeTypeCache.cache.has(flowNode.id)) {
                    return undefined;
                }
                const cachedEntry = flowNodeTypeCache.cache.get(flowNode.id);
                if (cachedEntry === undefined) {
                    return { type: undefined, isIncomplete: false };
                }
                if (!isIncompleteType(cachedEntry)) {
                    return { type: cachedEntry, isIncomplete: false };
                }
                return {
                    type: cachedEntry.type,
                    isIncomplete: true,
                    incompleteSubtypes: cachedEntry.incompleteSubtypes,
                    generationCount: cachedEntry.generationCount,
                };
            }
            function deleteCacheEntry(flowNode) {
                flowNodeTypeCache.cache.delete(flowNode.id);
            }
            function evaluateAssignmentFlowNode(flowNode) {
                // For function and class nodes, the reference node is the name
                // node, but we need to use the parent node (the FunctionNode or ClassNode)
                // to access the decorated type in the type cache.
                let nodeForCacheLookup = flowNode.node;
                const parentNode = flowNode.node.parent;
                if (parentNode) {
                    if (parentNode.nodeType === 28 /* ParseNodeType.Function */ || parentNode.nodeType === 10 /* ParseNodeType.Class */) {
                        nodeForCacheLookup = parentNode;
                    }
                }
                return evaluator.evaluateTypeForSubnode(nodeForCacheLookup, () => {
                    evaluator.evaluateTypesForStatement(flowNode.node);
                });
            }
            function preventRecursion(flowNode, callback) {
                flowNodeTypeCache.pendingNodes.add(flowNode.id);
                try {
                    const result = callback();
                    flowNodeTypeCache.pendingNodes.delete(flowNode.id);
                    return result;
                }
                catch (e) {
                    // Don't use a "finally" clause here because the TypeScript
                    // debugger doesn't handle "step out" well with finally clauses.
                    flowNodeTypeCache.pendingNodes.delete(flowNode.id);
                    throw e;
                }
            }
            // If this flow has no knowledge of the target expression, it returns undefined.
            // If the start flow node for this scope is reachable, the typeAtStart value is
            // returned.
            function getTypeFromFlowNode(flowNode) {
                var _a, _b, _c, _d, _e, _f;
                let curFlowNode = flowNode;
                // This is a frequently-called routine, so it's a good place to call
                // the cancellation check. If the operation is canceled, an exception
                // will be thrown at this point.
                evaluator.checkForCancellation();
                while (true) {
                    // Have we already been here? If so, use the cached value.
                    const cachedEntry = getCacheEntry(curFlowNode);
                    if (cachedEntry) {
                        if (!cachedEntry.isIncomplete) {
                            return cachedEntry;
                        }
                        // If the cached entry is incomplete, we can use it only if nothing
                        // has changed that may cause the previously-reported incomplete type to change.
                        if (cachedEntry.generationCount === flowIncompleteGeneration) {
                            return {
                                type: cachedEntry.type ? (0, typeUtils_1.cleanIncompleteUnknown)(cachedEntry.type) : undefined,
                                isIncomplete: true,
                            };
                        }
                    }
                    // Check for recursion.
                    if (flowNodeTypeCache.pendingNodes.has(curFlowNode.id)) {
                        return {
                            type: (_a = cachedEntry === null || cachedEntry === void 0 ? void 0 : cachedEntry.type) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(/* isIncomplete */ true),
                            isIncomplete: true,
                        };
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Unreachable) {
                        // We can get here if there are nodes in a compound logical expression
                        // (e.g. "False and x") that are never executed but are evaluated.
                        return setCacheEntry(curFlowNode, types_1.NeverType.createNever(), /* isIncomplete */ false);
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.VariableAnnotation) {
                        const varAnnotationNode = curFlowNode;
                        curFlowNode = varAnnotationNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Call) {
                        const callFlowNode = curFlowNode;
                        // If this function returns a "NoReturn" type, that means
                        // it always raises an exception or otherwise doesn't return,
                        // so we can assume that the code before this is unreachable.
                        if (isCallNoReturn(evaluator, callFlowNode)) {
                            return setCacheEntry(curFlowNode, /* type */ undefined, /* isIncomplete */ false);
                        }
                        curFlowNode = callFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Assignment) {
                        const assignmentFlowNode = curFlowNode;
                        const targetNode = assignmentFlowNode.node;
                        // Are we targeting the same symbol? We need to do this extra check because the same
                        // symbol name might refer to different symbols in different scopes (e.g. a list
                        // comprehension introduces a new scope).
                        if (reference) {
                            if ((options === null || options === void 0 ? void 0 : options.targetSymbolId) === assignmentFlowNode.targetSymbolId &&
                                (0, parseTreeUtils_1.isMatchingExpression)(reference, targetNode)) {
                                // Is this a special "unbind" assignment? If so,
                                // we can handle it immediately without any further evaluation.
                                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Unbind) {
                                    // Don't treat unbound assignments to indexed expressions (i.e. "del x[0]")
                                    // as true deletions. The most common use case for "del x[0]" is in a list,
                                    // and the list class treats this as an element deletion, not an assignment.
                                    if (reference.nodeType === 24 /* ParseNodeType.Index */) {
                                        // No need to explore further.
                                        return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
                                    }
                                    // Don't treat unbound assignments to member access expressions (i.e. "del a.x")
                                    // as true deletions either. These may go through a descriptor object __delete__
                                    // method or a __delattr__ method on the class.
                                    if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                                        // No need to explore further.
                                        return setCacheEntry(curFlowNode, undefined, /* isIncomplete */ false);
                                    }
                                    return setCacheEntry(curFlowNode, types_1.UnboundType.create(), /* isIncomplete */ false);
                                }
                                let flowTypeResult = preventRecursion(curFlowNode, () => evaluateAssignmentFlowNode(assignmentFlowNode));
                                if (flowTypeResult) {
                                    if ((0, typeUtils_1.isTypeAliasPlaceholder)(flowTypeResult.type)) {
                                        // Don't cache a recursive type alias placeholder.
                                        return {
                                            type: flowTypeResult.type,
                                            isIncomplete: true,
                                        };
                                    }
                                    else if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                                        evaluator.isAsymmetricAccessorAssignment(targetNode)) {
                                        flowTypeResult = undefined;
                                    }
                                }
                                if (flowTypeResult && !isFlowNodeReachable(flowNode)) {
                                    flowTypeResult = undefined;
                                }
                                return setCacheEntry(curFlowNode, flowTypeResult === null || flowTypeResult === void 0 ? void 0 : flowTypeResult.type, !!(flowTypeResult === null || flowTypeResult === void 0 ? void 0 : flowTypeResult.isIncomplete));
                            }
                            // Is this a simple assignment to an index expression? If so, it could
                            // be assigning to a TypedDict, which requires narrowing of the expression's
                            // base type.
                            if (targetNode.nodeType === 24 /* ParseNodeType.Index */ &&
                                (0, parseTreeUtils_1.isMatchingExpression)(reference, targetNode.baseExpression)) {
                                if (((_b = targetNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 3 /* ParseNodeType.Assignment */ &&
                                    targetNode.items.length === 1 &&
                                    !targetNode.trailingComma &&
                                    !targetNode.items[0].name &&
                                    targetNode.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                                    targetNode.items[0].valueExpression.nodeType === 48 /* ParseNodeType.StringList */ &&
                                    targetNode.items[0].valueExpression.strings.length === 1 &&
                                    targetNode.items[0].valueExpression.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                                    const keyValue = targetNode.items[0].valueExpression.strings[0].value;
                                    const narrowedResult = preventRecursion(assignmentFlowNode, () => {
                                        const flowTypeResult = getTypeFromFlowNode(assignmentFlowNode.antecedent);
                                        if (flowTypeResult.type) {
                                            flowTypeResult.type = (0, typeUtils_1.mapSubtypes)(flowTypeResult.type, (subtype) => {
                                                if ((0, types_1.isClass)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
                                                    return (0, typedDicts_1.narrowForKeyAssignment)(subtype, keyValue);
                                                }
                                                return subtype;
                                            });
                                        }
                                        return flowTypeResult;
                                    });
                                    return setCacheEntry(curFlowNode, narrowedResult === null || narrowedResult === void 0 ? void 0 : narrowedResult.type, !!(narrowedResult === null || narrowedResult === void 0 ? void 0 : narrowedResult.isIncomplete));
                                }
                            }
                            if ((0, parseTreeUtils_1.isPartialMatchingExpression)(reference, targetNode)) {
                                // If the node partially matches the reference, we need to "kill" any narrowed
                                // types further above this point. For example, if we see the sequence
                                //    a.b = 3
                                //    a = Foo()
                                //    x = a.b
                                // The type of "a.b" can no longer be assumed to be Literal[3].
                                return {
                                    type: (_c = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _c === void 0 ? void 0 : _c.type,
                                    isIncomplete: !!((_d = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _d === void 0 ? void 0 : _d.isIncomplete),
                                };
                            }
                        }
                        curFlowNode = assignmentFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.BranchLabel) {
                        const branchFlowNode = curFlowNode;
                        if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PostContextManager) {
                            // Determine whether any of the context managers support exception
                            // suppression. If not, none of its antecedents are reachable.
                            const contextMgrNode = curFlowNode;
                            const contextManagerSwallowsExceptions = contextMgrNode.expressions.some((expr) => isExceptionContextManager(evaluator, expr, contextMgrNode.isAsync));
                            if (contextManagerSwallowsExceptions === contextMgrNode.blockIfSwallowsExceptions) {
                                // Do not explore any further along this code flow path.
                                return setCacheEntry(curFlowNode, /* type */ undefined, /* isIncomplete */ false);
                            }
                        }
                        // Is the current symbol modified in any way within the scope of the branch?
                        // If not, we can skip all processing within the branch scope.
                        if (reference && branchFlowNode.preBranchAntecedent && branchFlowNode.affectedExpressions) {
                            if (!subexpressionReferenceKeys) {
                                subexpressionReferenceKeys = (0, codeFlowTypes_1.createKeysForReferenceSubexpressions)(reference);
                            }
                            if (!subexpressionReferenceKeys.some((key) => branchFlowNode.affectedExpressions.has(key)) &&
                                isFlowNodeReachable(curFlowNode, branchFlowNode.preBranchAntecedent)) {
                                curFlowNode = branchFlowNode.preBranchAntecedent;
                                continue;
                            }
                        }
                        return getTypeFromBranchFlowNode(curFlowNode);
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.LoopLabel) {
                        const loopNode = curFlowNode;
                        // Is the current symbol modified in any way within the loop? If not, we can skip all
                        // processing within the loop and assume that the type comes from the first antecedent,
                        // which feeds the loop.
                        if (reference) {
                            if (!subexpressionReferenceKeys) {
                                subexpressionReferenceKeys = (0, codeFlowTypes_1.createKeysForReferenceSubexpressions)(reference);
                            }
                            if (!subexpressionReferenceKeys.some((key) => loopNode.affectedExpressions.has(key))) {
                                curFlowNode = loopNode.antecedents[0];
                                continue;
                            }
                        }
                        return getTypeFromLoopFlowNode(loopNode, cachedEntry);
                    }
                    if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.FalseCondition)) {
                        const conditionalFlowNode = curFlowNode;
                        if (!(options === null || options === void 0 ? void 0 : options.skipConditionalNarrowing) && reference) {
                            const narrowedResult = preventRecursion(curFlowNode, () => {
                                const typeNarrowingCallback = (0, typeGuards_1.getTypeNarrowingCallback)(evaluator, reference, conditionalFlowNode.expression, !!(conditionalFlowNode.flags &
                                    (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.TrueNeverCondition)));
                                if (typeNarrowingCallback) {
                                    const flowTypeResult = getTypeFromFlowNode(conditionalFlowNode.antecedent);
                                    let flowType = flowTypeResult.type;
                                    let isIncomplete = flowTypeResult.isIncomplete;
                                    if (flowType) {
                                        const flowTypeResult = typeNarrowingCallback(flowType);
                                        if (flowTypeResult) {
                                            flowType = flowTypeResult.type;
                                            if (flowTypeResult.isIncomplete) {
                                                isIncomplete = true;
                                            }
                                        }
                                    }
                                    return setCacheEntry(curFlowNode, flowType, isIncomplete);
                                }
                                return undefined;
                            });
                            if (narrowedResult) {
                                return narrowedResult;
                            }
                        }
                        curFlowNode = conditionalFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.TrueNeverCondition | codeFlowTypes_1.FlowFlags.FalseNeverCondition)) {
                        const conditionalFlowNode = curFlowNode;
                        if (!(options === null || options === void 0 ? void 0 : options.skipConditionalNarrowing) && conditionalFlowNode.reference) {
                            // Don't allow apply if the conditional expression references the expression
                            // we're already narrowing. This case will be handled by the TrueCondition
                            // or FalseCondition node.
                            if ((0, codeFlowTypes_1.createKeyForReference)(conditionalFlowNode.reference) !== referenceKey) {
                                // Make sure the reference type has a declared type. If not,
                                // don't bother trying to infer its type because that would be
                                // too expensive.
                                const symbolWithScope = evaluator.lookUpSymbolRecursive(conditionalFlowNode.reference, conditionalFlowNode.reference.value, 
                                /* honorCodeFlow */ false);
                                if (symbolWithScope && symbolWithScope.symbol.hasTypedDeclarations()) {
                                    const result = preventRecursion(curFlowNode, () => {
                                        const typeNarrowingCallback = (0, typeGuards_1.getTypeNarrowingCallback)(evaluator, conditionalFlowNode.reference, conditionalFlowNode.expression, !!(conditionalFlowNode.flags &
                                            (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.TrueNeverCondition)));
                                        if (typeNarrowingCallback) {
                                            const refTypeInfo = evaluator.getTypeOfExpression(conditionalFlowNode.reference);
                                            let narrowedType = refTypeInfo.type;
                                            let isIncomplete = !!refTypeInfo.isIncomplete;
                                            const narrowedTypeResult = typeNarrowingCallback(refTypeInfo.type);
                                            if (narrowedTypeResult) {
                                                narrowedType = narrowedTypeResult.type;
                                                if (narrowedTypeResult.isIncomplete) {
                                                    isIncomplete = true;
                                                }
                                            }
                                            // If the narrowed type is "never", don't allow further exploration.
                                            if ((0, types_1.isNever)(narrowedType)) {
                                                return setCacheEntry(curFlowNode, undefined, isIncomplete);
                                            }
                                        }
                                        return undefined;
                                    });
                                    if (result) {
                                        return result;
                                    }
                                }
                            }
                        }
                        curFlowNode = conditionalFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.ExhaustedMatch) {
                        const exhaustedMatchFlowNode = curFlowNode;
                        const narrowedTypeResult = evaluator.evaluateTypeForSubnode(exhaustedMatchFlowNode.node, () => {
                            evaluator.evaluateTypesForMatchStatement(exhaustedMatchFlowNode.node);
                        });
                        // If the narrowed type is "never", don't allow further exploration.
                        if (narrowedTypeResult) {
                            if ((0, types_1.isNever)(narrowedTypeResult.type)) {
                                return setCacheEntry(curFlowNode, narrowedTypeResult.type, !!narrowedTypeResult.isIncomplete);
                            }
                            if (reference) {
                                // See if the reference is a subexpression within the subject expression.
                                const typeNarrowingCallback = (0, patternMatching_1.getPatternSubtypeNarrowingCallback)(evaluator, reference, exhaustedMatchFlowNode.subjectExpression);
                                if (typeNarrowingCallback) {
                                    const subexpressionTypeResult = typeNarrowingCallback(narrowedTypeResult.type);
                                    if (subexpressionTypeResult) {
                                        return setCacheEntry(curFlowNode, subexpressionTypeResult.type, !!narrowedTypeResult.isIncomplete || !!subexpressionTypeResult.isIncomplete);
                                    }
                                }
                            }
                        }
                        curFlowNode = exhaustedMatchFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.NarrowForPattern) {
                        const patternFlowNode = curFlowNode;
                        if (!reference || (0, parseTreeUtils_1.isMatchingExpression)(reference, patternFlowNode.subjectExpression)) {
                            const typeResult = evaluator.evaluateTypeForSubnode(patternFlowNode.statement, () => {
                                if (patternFlowNode.statement.nodeType === 64 /* ParseNodeType.Case */) {
                                    evaluator.evaluateTypesForCaseStatement(patternFlowNode.statement);
                                }
                                else {
                                    evaluator.evaluateTypesForMatchStatement(patternFlowNode.statement);
                                }
                            });
                            if (typeResult) {
                                if (!reference) {
                                    if ((0, types_1.isNever)(typeResult.type)) {
                                        return setCacheEntry(curFlowNode, 
                                        /* type */ undefined, !!typeResult.isIncomplete);
                                    }
                                }
                                else {
                                    return setCacheEntry(curFlowNode, typeResult.type, !!typeResult.isIncomplete);
                                }
                            }
                        }
                        else if (patternFlowNode.statement.nodeType === 64 /* ParseNodeType.Case */) {
                            const caseStatement = patternFlowNode.statement;
                            // See if the reference is a subexpression within the subject expression.
                            const typeNarrowingCallback = (0, patternMatching_1.getPatternSubtypeNarrowingCallback)(evaluator, reference, patternFlowNode.subjectExpression);
                            if (typeNarrowingCallback) {
                                const typeResult = evaluator.evaluateTypeForSubnode(caseStatement, () => {
                                    evaluator.evaluateTypesForCaseStatement(caseStatement);
                                });
                                if (typeResult) {
                                    const narrowedTypeResult = typeNarrowingCallback(typeResult.type);
                                    if (narrowedTypeResult) {
                                        return setCacheEntry(curFlowNode, narrowedTypeResult.type, !!typeResult.isIncomplete || !!narrowedTypeResult.isIncomplete);
                                    }
                                }
                            }
                        }
                        curFlowNode = patternFlowNode.antecedent;
                        continue;
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PreFinallyGate) {
                        return getTypeFromPreFinallyGateFlowNode(curFlowNode);
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PostFinally) {
                        return getTypeFromPostFinallyFlowNode(curFlowNode);
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Start) {
                        return setCacheEntry(curFlowNode, (_e = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _e === void 0 ? void 0 : _e.type, !!((_f = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _f === void 0 ? void 0 : _f.isIncomplete));
                    }
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.WildcardImport) {
                        const wildcardImportFlowNode = curFlowNode;
                        if (reference && reference.nodeType === 38 /* ParseNodeType.Name */) {
                            const nameValue = reference.value;
                            if (wildcardImportFlowNode.names.some((name) => name === nameValue)) {
                                return preventRecursion(curFlowNode, () => {
                                    const type = getTypeFromWildcardImport(wildcardImportFlowNode, nameValue);
                                    return setCacheEntry(curFlowNode, type, /* isIncomplete */ false);
                                });
                            }
                        }
                        curFlowNode = wildcardImportFlowNode.antecedent;
                        continue;
                    }
                    // We shouldn't get here.
                    (0, debug_1.fail)('Unexpected flow node flags');
                }
            }
            function getTypeFromBranchFlowNode(branchNode) {
                const typesToCombine = [];
                let sawIncomplete = false;
                for (const antecedent of branchNode.antecedents) {
                    const flowTypeResult = getTypeFromFlowNode(antecedent);
                    if (reference === undefined && flowTypeResult.type && !(0, types_1.isNever)(flowTypeResult.type)) {
                        // If we're solving for "reachability", and we have now proven
                        // reachability, there's no reason to do more work. The type we
                        // return here doesn't matter as long as it's not undefined.
                        return setCacheEntry(branchNode, types_1.UnknownType.create(), /* isIncomplete */ false);
                    }
                    if (flowTypeResult.isIncomplete) {
                        sawIncomplete = true;
                    }
                    if (flowTypeResult.type) {
                        typesToCombine.push(flowTypeResult.type);
                    }
                }
                const effectiveType = typesToCombine.length > 0 ? (0, types_1.combineTypes)(typesToCombine) : undefined;
                return setCacheEntry(branchNode, effectiveType, sawIncomplete);
            }
            function getTypeFromLoopFlowNode(loopNode, cacheEntry) {
                var _a;
                // The type result from one antecedent may depend on the type
                // result from another, so loop up to one time for each
                // antecedent in the loop.
                const maxAttemptCount = loopNode.antecedents.length;
                if (cacheEntry === undefined) {
                    // We haven't been here before, so create a new incomplete cache entry.
                    cacheEntry = setCacheEntry(loopNode, reference ? undefined : types_1.UnknownType.create(), 
                    /* isIncomplete */ true);
                }
                else if (cacheEntry.incompleteSubtypes &&
                    cacheEntry.incompleteSubtypes.length === loopNode.antecedents.length &&
                    cacheEntry.incompleteSubtypes.some((subtype) => subtype.isPending)) {
                    // If entries have been added for all antecedents and there are pending entries
                    // that have not been evaluated even once, treat it as incomplete. We clean
                    // any incomplete unknowns from the type here to assist with type convergence.
                    return {
                        type: cacheEntry.type ? (0, typeUtils_1.cleanIncompleteUnknown)(cacheEntry.type) : undefined,
                        isIncomplete: true,
                    };
                }
                let attemptCount = 0;
                while (true) {
                    let sawIncomplete = false;
                    let sawPending = false;
                    let isProvenReachable = reference === undefined &&
                        ((_a = cacheEntry.incompleteSubtypes) === null || _a === void 0 ? void 0 : _a.some((subtype) => subtype.type !== undefined));
                    let firstAntecedentTypeIsIncomplete = false;
                    let firstAntecedentTypeIsPending = false;
                    loopNode.antecedents.forEach((antecedent, index) => {
                        var _a, _b;
                        // If we've trying to determine reachability and we've already proven
                        // reachability, then we're done.
                        if (reference === undefined && isProvenReachable) {
                            return;
                        }
                        if (firstAntecedentTypeIsPending && index > 0) {
                            return;
                        }
                        cacheEntry = getCacheEntry(loopNode);
                        // Is this entry marked "pending"? If so, we have recursed and there
                        // is another call on the stack that is actively evaluating this
                        // antecedent. Skip it here to avoid infinite recursion but note that
                        // we skipped a "pending" antecedent.
                        if (cacheEntry.incompleteSubtypes &&
                            index < cacheEntry.incompleteSubtypes.length &&
                            cacheEntry.incompleteSubtypes[index].isPending) {
                            // In rare circumstances, it's possible for a code flow graph with
                            // nested loops to hit the case where the first antecedent is marked
                            // as pending. In this case, we'll evaluate only the first antecedent
                            // again even though it's pending. We're guaranteed to make forward
                            // progress with the first antecedent, and that will allow us to establish
                            // an initial type for this expression, but we don't want to evaluate
                            // any other antecedents in this case because this could result in
                            // infinite recursion.
                            if (index === 0) {
                                firstAntecedentTypeIsPending = true;
                            }
                            else {
                                sawIncomplete = true;
                                sawPending = true;
                                return;
                            }
                        }
                        // Have we already been here (i.e. does the entry exist and is
                        // not marked "pending")? If so, we can use the type that was already
                        // computed if it is complete.
                        const subtypeEntry = cacheEntry.incompleteSubtypes !== undefined && index < cacheEntry.incompleteSubtypes.length
                            ? cacheEntry.incompleteSubtypes[index]
                            : undefined;
                        if (subtypeEntry === undefined || (!(subtypeEntry === null || subtypeEntry === void 0 ? void 0 : subtypeEntry.isPending) && (subtypeEntry === null || subtypeEntry === void 0 ? void 0 : subtypeEntry.isIncomplete))) {
                            const entryEvaluationCount = subtypeEntry === undefined ? 0 : subtypeEntry.evaluationCount;
                            // Set this entry to "pending" to prevent infinite recursion.
                            // We'll mark it "not pending" below.
                            cacheEntry = setIncompleteSubtype(loopNode, index, (_a = subtypeEntry === null || subtypeEntry === void 0 ? void 0 : subtypeEntry.type) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(/* isIncomplete */ true), 
                            /* isIncomplete */ true, 
                            /* isPending */ true, entryEvaluationCount);
                            try {
                                const flowTypeResult = getTypeFromFlowNode(antecedent);
                                if (flowTypeResult.isIncomplete) {
                                    sawIncomplete = true;
                                    if (index === 0) {
                                        firstAntecedentTypeIsIncomplete = true;
                                    }
                                }
                                cacheEntry = setIncompleteSubtype(loopNode, index, (_b = flowTypeResult.type) !== null && _b !== void 0 ? _b : (flowTypeResult.isIncomplete
                                    ? types_1.UnknownType.create(/* isIncomplete */ true)
                                    : types_1.NeverType.createNever()), flowTypeResult.isIncomplete, 
                                /* isPending */ firstAntecedentTypeIsPending, entryEvaluationCount + 1);
                            }
                            catch (e) {
                                cacheEntry = setIncompleteSubtype(loopNode, index, types_1.UnknownType.create(/* isIncomplete */ true), 
                                /* isIncomplete */ true, 
                                /* isPending */ firstAntecedentTypeIsPending, entryEvaluationCount + 1);
                                throw e;
                            }
                        }
                        if (reference === undefined && (cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.type) !== undefined) {
                            isProvenReachable = true;
                        }
                    });
                    if (isProvenReachable) {
                        // If we saw a pending entry, do not save over the top of the cache
                        // entry because we'll overwrite a pending evaluation. The type that
                        // we return here doesn't matter as long as it's not undefined.
                        return sawPending
                            ? { type: types_1.UnknownType.create(), isIncomplete: false }
                            : setCacheEntry(loopNode, types_1.UnknownType.create(), /* isIncomplete */ false);
                    }
                    let effectiveType = cacheEntry.type;
                    if (sawIncomplete) {
                        // If there is an incomplete "Unknown" type within a union type, remove
                        // it. Otherwise we might end up resolving the cycle with a type
                        // that includes an undesirable unknown.
                        if (effectiveType) {
                            const cleanedType = (0, typeUtils_1.cleanIncompleteUnknown)(effectiveType);
                            if (cleanedType !== effectiveType) {
                                effectiveType = cleanedType;
                            }
                        }
                    }
                    if (!sawIncomplete || attemptCount >= maxAttemptCount) {
                        // If we were able to evaluate a type along at least one antecedent
                        // path, mark it as complete. If we couldn't evaluate a type along
                        // any antecedent path, assume that some recursive call further
                        // up the stack will be able to produce a valid type.
                        let reportIncomplete = sawIncomplete;
                        if (sawIncomplete &&
                            !sawPending &&
                            effectiveType &&
                            !(0, typeUtils_1.isIncompleteUnknown)(effectiveType) &&
                            !firstAntecedentTypeIsIncomplete) {
                            reportIncomplete = false;
                        }
                        // If we saw a pending or incomplete entry, do not save over the top
                        // of the cache entry because we'll overwrite the partial result.
                        if (sawPending || sawIncomplete) {
                            if (!reportIncomplete) {
                                // Bump the generation count because we need to recalculate
                                // other incomplete types based on this now-complete type.
                                flowIncompleteGeneration++;
                            }
                            return { type: effectiveType, isIncomplete: reportIncomplete };
                        }
                        // If the first antecedent was pending, we skipped all of the other
                        // antecedents, so the type is incomplete.
                        if (firstAntecedentTypeIsPending) {
                            return { type: effectiveType, isIncomplete: true };
                        }
                        return setCacheEntry(loopNode, effectiveType, /* isIncomplete */ false);
                    }
                    attemptCount++;
                }
            }
            function getTypeFromPreFinallyGateFlowNode(preFinallyFlowNode) {
                // Is the finally gate closed?
                if (flowNodeTypeCache.closedFinallyGateNodes.has(preFinallyFlowNode.id)) {
                    return { type: undefined, isIncomplete: false };
                }
                const flowTypeResult = getTypeFromFlowNode(preFinallyFlowNode.antecedent);
                // We want to cache the type only if we're evaluating the "gate closed" path.
                deleteCacheEntry(preFinallyFlowNode);
                return {
                    type: flowTypeResult.type,
                    isIncomplete: flowTypeResult.isIncomplete,
                };
            }
            function getTypeFromPostFinallyFlowNode(postFinallyFlowNode) {
                const wasGateClosed = flowNodeTypeCache.closedFinallyGateNodes.has(postFinallyFlowNode.preFinallyGate.id);
                try {
                    flowNodeTypeCache.closedFinallyGateNodes.add(postFinallyFlowNode.preFinallyGate.id);
                    let flowTypeResult;
                    // Use speculative mode for the remainder of the finally suite
                    // because the final types within this parse node block should be
                    // evaluated when the gate is open.
                    evaluator.useSpeculativeMode(postFinallyFlowNode.finallyNode, () => {
                        flowTypeResult = getTypeFromFlowNode(postFinallyFlowNode.antecedent);
                    });
                    // If the type is incomplete, don't write back to the cache.
                    return flowTypeResult.isIncomplete
                        ? flowTypeResult
                        : setCacheEntry(postFinallyFlowNode, flowTypeResult.type, /* isIncomplete */ false);
                }
                finally {
                    if (!wasGateClosed) {
                        flowNodeTypeCache.closedFinallyGateNodes.delete(postFinallyFlowNode.preFinallyGate.id);
                    }
                }
            }
            if (!flowNode) {
                // This should happen only in cases where we're evaluating
                // parse nodes that are created after the initial parse
                // (namely, string literals that are used for forward
                // referenced types).
                return {
                    type: (_a = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _a === void 0 ? void 0 : _a.type,
                    isIncomplete: !!((_b = options === null || options === void 0 ? void 0 : options.typeAtStart) === null || _b === void 0 ? void 0 : _b.isIncomplete),
                };
            }
            return getTypeFromFlowNode(flowNode);
        }
        return {
            getTypeFromCodeFlow,
        };
    }
    // Determines whether the specified flowNode can be reached by any
    // control flow path within the execution context. If sourceFlowNode
    // is specified, it returns true only if at least one control flow
    // path passes through sourceFlowNode.
    function isFlowNodeReachable(flowNode, sourceFlowNode, ignoreNoReturn = false) {
        const visitedFlowNodeSet = new Set();
        const closedFinallyGateSet = new Set();
        if (enablePrintControlFlowGraph) {
            printControlFlowGraph(flowNode, /* reference */ undefined, 'isFlowNodeReachable');
        }
        function isFlowNodeReachableRecursive(flowNode, sourceFlowNode, recursionCount = 0) {
            var _a;
            // Cut off the recursion at some point to prevent a stack overflow.
            const maxFlowNodeReachableRecursionCount = 64;
            if (recursionCount > maxFlowNodeReachableRecursionCount) {
                return true;
            }
            recursionCount++;
            let curFlowNode = flowNode;
            while (true) {
                // If we've already visited this node, we can assume
                // it wasn't reachable.
                if (visitedFlowNodeSet.has(curFlowNode.id)) {
                    return false;
                }
                // Note that we've been here before.
                visitedFlowNodeSet.add(curFlowNode.id);
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Unreachable) {
                    return false;
                }
                if (curFlowNode === sourceFlowNode) {
                    return true;
                }
                if (curFlowNode.flags &
                    (codeFlowTypes_1.FlowFlags.VariableAnnotation |
                        codeFlowTypes_1.FlowFlags.Assignment |
                        codeFlowTypes_1.FlowFlags.TrueCondition |
                        codeFlowTypes_1.FlowFlags.FalseCondition |
                        codeFlowTypes_1.FlowFlags.WildcardImport |
                        codeFlowTypes_1.FlowFlags.NarrowForPattern |
                        codeFlowTypes_1.FlowFlags.ExhaustedMatch)) {
                    const typedFlowNode = curFlowNode;
                    curFlowNode = typedFlowNode.antecedent;
                    continue;
                }
                if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.TrueNeverCondition | codeFlowTypes_1.FlowFlags.FalseNeverCondition)) {
                    const conditionalFlowNode = curFlowNode;
                    if (conditionalFlowNode.reference) {
                        // Make sure the reference type has a declared type. If not,
                        // don't bother trying to infer its type because that would be
                        // too expensive.
                        const symbolWithScope = evaluator.lookUpSymbolRecursive(conditionalFlowNode.reference, conditionalFlowNode.reference.value, 
                        /* honorCodeFlow */ false);
                        if (symbolWithScope && symbolWithScope.symbol.hasTypedDeclarations()) {
                            let isUnreachable = false;
                            const typeNarrowingCallback = (0, typeGuards_1.getTypeNarrowingCallback)(evaluator, conditionalFlowNode.reference, conditionalFlowNode.expression, !!(conditionalFlowNode.flags & (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.TrueNeverCondition)));
                            if (typeNarrowingCallback) {
                                const refTypeInfo = evaluator.getTypeOfExpression(conditionalFlowNode.reference);
                                const narrowedTypeResult = typeNarrowingCallback(refTypeInfo.type);
                                const narrowedType = (_a = narrowedTypeResult === null || narrowedTypeResult === void 0 ? void 0 : narrowedTypeResult.type) !== null && _a !== void 0 ? _a : refTypeInfo.type;
                                if ((0, types_1.isNever)(narrowedType) && !refTypeInfo.isIncomplete) {
                                    isUnreachable = true;
                                }
                            }
                            if (isUnreachable) {
                                return false;
                            }
                        }
                    }
                    curFlowNode = conditionalFlowNode.antecedent;
                    continue;
                }
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Call) {
                    const callFlowNode = curFlowNode;
                    // If this function returns a "NoReturn" type, that means
                    // it always raises an exception or otherwise doesn't return,
                    // so we can assume that the code before this is unreachable.
                    if (!ignoreNoReturn && isCallNoReturn(evaluator, callFlowNode)) {
                        return false;
                    }
                    curFlowNode = callFlowNode.antecedent;
                    continue;
                }
                if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.BranchLabel | codeFlowTypes_1.FlowFlags.LoopLabel)) {
                    if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PostContextManager) {
                        // Determine whether any of the context managers support exception
                        // suppression. If not, none of its antecedents are reachable.
                        const contextMgrNode = curFlowNode;
                        if (!contextMgrNode.expressions.some((expr) => isExceptionContextManager(evaluator, expr, contextMgrNode.isAsync))) {
                            return false;
                        }
                    }
                    const labelNode = curFlowNode;
                    for (const antecedent of labelNode.antecedents) {
                        if (isFlowNodeReachableRecursive(antecedent, sourceFlowNode, recursionCount)) {
                            return true;
                        }
                    }
                    return false;
                }
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.Start) {
                    // If we hit the start but were looking for a particular source flow
                    // node, return false. Otherwise, the start is what we're looking for.
                    return sourceFlowNode ? false : true;
                }
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PreFinallyGate) {
                    const preFinallyFlowNode = curFlowNode;
                    if (closedFinallyGateSet.has(preFinallyFlowNode.id)) {
                        return false;
                    }
                    curFlowNode = preFinallyFlowNode.antecedent;
                    continue;
                }
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.PostFinally) {
                    const postFinallyFlowNode = curFlowNode;
                    const wasGateClosed = closedFinallyGateSet.has(postFinallyFlowNode.preFinallyGate.id);
                    try {
                        closedFinallyGateSet.add(postFinallyFlowNode.preFinallyGate.id);
                        return isFlowNodeReachableRecursive(postFinallyFlowNode.antecedent, sourceFlowNode, recursionCount);
                    }
                    finally {
                        if (!wasGateClosed) {
                            closedFinallyGateSet.delete(postFinallyFlowNode.preFinallyGate.id);
                        }
                    }
                }
                // We shouldn't get here.
                (0, debug_1.fail)('Unexpected flow node flags');
                return false;
            }
        }
        // Protect against infinite recursion.
        if (isReachableRecursionSet.has(flowNode.id)) {
            return true;
        }
        isReachableRecursionSet.add(flowNode.id);
        try {
            return isFlowNodeReachableRecursive(flowNode, sourceFlowNode);
        }
        finally {
            isReachableRecursionSet.delete(flowNode.id);
        }
    }
    // Determines whether the specified typeVar, which is assumed to be constrained,
    // can be narrowed to one of its constrained types based on isinstance type
    // guard checks.
    function narrowConstrainedTypeVar(flowNode, typeVar) {
        (0, debug_1.assert)(!typeVar.details.isParamSpec);
        (0, debug_1.assert)(!typeVar.details.isVariadic);
        (0, debug_1.assert)(!typeVar.details.boundType);
        (0, debug_1.assert)(typeVar.details.constraints.length > 0);
        const visitedFlowNodeMap = new Set();
        const startingConstraints = [];
        for (const constraint of typeVar.details.constraints) {
            if ((0, types_1.isClassInstance)(constraint)) {
                startingConstraints.push(constraint);
            }
            else {
                // If one or more constraints are Unknown, Any, union types, etc.,
                // we can't narrow them.
                return undefined;
            }
        }
        function narrowConstrainedTypeVarRecursive(flowNode, typeVar) {
            let curFlowNode = flowNode;
            while (true) {
                if (visitedFlowNodeMap.has(curFlowNode.id)) {
                    return startingConstraints;
                }
                if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.Unreachable | codeFlowTypes_1.FlowFlags.Start)) {
                    return startingConstraints;
                }
                if (curFlowNode.flags &
                    (codeFlowTypes_1.FlowFlags.VariableAnnotation |
                        codeFlowTypes_1.FlowFlags.Assignment |
                        codeFlowTypes_1.FlowFlags.WildcardImport |
                        codeFlowTypes_1.FlowFlags.TrueNeverCondition |
                        codeFlowTypes_1.FlowFlags.FalseNeverCondition |
                        codeFlowTypes_1.FlowFlags.ExhaustedMatch |
                        codeFlowTypes_1.FlowFlags.PostFinally |
                        codeFlowTypes_1.FlowFlags.PreFinallyGate |
                        codeFlowTypes_1.FlowFlags.Call)) {
                    const typedFlowNode = curFlowNode;
                    curFlowNode = typedFlowNode.antecedent;
                    continue;
                }
                // Handle a case statement with a class pattern.
                if (curFlowNode.flags & codeFlowTypes_1.FlowFlags.NarrowForPattern) {
                    const narrowForPatternFlowNode = curFlowNode;
                    if (narrowForPatternFlowNode.statement.nodeType === 64 /* ParseNodeType.Case */) {
                        const subjectType = evaluator.getTypeOfExpression(narrowForPatternFlowNode.subjectExpression).type;
                        if (isCompatibleWithConstrainedTypeVar(subjectType, typeVar)) {
                            const patternNode = narrowForPatternFlowNode.statement.pattern;
                            if (patternNode.nodeType === 66 /* ParseNodeType.PatternAs */ &&
                                patternNode.orPatterns.length === 1 &&
                                patternNode.orPatterns[0].nodeType === 68 /* ParseNodeType.PatternClass */) {
                                const classPatternNode = patternNode.orPatterns[0];
                                const classType = evaluator.getTypeOfExpression(classPatternNode.className, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                                if ((0, types_1.isInstantiableClass)(classType)) {
                                    const priorRemainingConstraints = narrowConstrainedTypeVarRecursive(narrowForPatternFlowNode.antecedent, typeVar);
                                    return priorRemainingConstraints.filter((subtype) => types_1.ClassType.isSameGenericClass(subtype, classType));
                                }
                            }
                        }
                    }
                    curFlowNode = narrowForPatternFlowNode.antecedent;
                    continue;
                }
                // Handle an isinstance type guard.
                if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.FalseCondition)) {
                    const conditionFlowNode = curFlowNode;
                    const testExpression = conditionFlowNode.expression;
                    const isPositiveTest = (curFlowNode.flags & codeFlowTypes_1.FlowFlags.TrueCondition) !== 0;
                    if (testExpression.nodeType === 9 /* ParseNodeType.Call */ &&
                        testExpression.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                        testExpression.leftExpression.value === 'isinstance' &&
                        testExpression.arguments.length === 2) {
                        const arg0Expr = testExpression.arguments[0].valueExpression;
                        const arg0Type = evaluator.getTypeOfExpression(arg0Expr).type;
                        if (isCompatibleWithConstrainedTypeVar(arg0Type, typeVar)) {
                            // Prevent infinite recursion by noting that we've been here before.
                            visitedFlowNodeMap.add(curFlowNode.id);
                            const priorRemainingConstraints = narrowConstrainedTypeVarRecursive(conditionFlowNode.antecedent, typeVar);
                            visitedFlowNodeMap.delete(curFlowNode.id);
                            const arg1Expr = testExpression.arguments[1].valueExpression;
                            const arg1Type = evaluator.getTypeOfExpression(arg1Expr, 8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
                                32 /* EvaluatorFlags.DisallowParamSpec */ |
                                64 /* EvaluatorFlags.DisallowTypeVarTuple */).type;
                            if ((0, types_1.isInstantiableClass)(arg1Type)) {
                                return priorRemainingConstraints.filter((subtype) => {
                                    if (types_1.ClassType.isSameGenericClass(subtype, arg1Type)) {
                                        return isPositiveTest;
                                    }
                                    else {
                                        return !isPositiveTest;
                                    }
                                });
                            }
                        }
                    }
                    curFlowNode = conditionFlowNode.antecedent;
                    continue;
                }
                if (curFlowNode.flags & (codeFlowTypes_1.FlowFlags.BranchLabel | codeFlowTypes_1.FlowFlags.LoopLabel)) {
                    const labelNode = curFlowNode;
                    const newConstraints = [];
                    // Prevent infinite recursion by noting that we've been here before.
                    visitedFlowNodeMap.add(curFlowNode.id);
                    for (const antecedent of labelNode.antecedents) {
                        const constraintsToAdd = narrowConstrainedTypeVarRecursive(antecedent, typeVar);
                        for (const constraint of constraintsToAdd) {
                            if (!newConstraints.some((t) => (0, types_1.isTypeSame)(t, constraint))) {
                                newConstraints.push(constraint);
                            }
                        }
                    }
                    visitedFlowNodeMap.delete(curFlowNode.id);
                    return newConstraints;
                }
                // We shouldn't get here.
                (0, debug_1.fail)('Unexpected flow node flags');
                return startingConstraints;
            }
        }
        const narrowedConstrainedType = narrowConstrainedTypeVarRecursive(flowNode, typeVar);
        // Have we narrowed the typeVar to a single constraint?
        return narrowedConstrainedType.length === 1 ? narrowedConstrainedType[0] : undefined;
    }
    // Determines whether a specified type is the same as a constrained
    // TypeVar or is conditioned on that same TypeVar or is some union of
    // the above.
    function isCompatibleWithConstrainedTypeVar(type, typeVar) {
        let isCompatible = true;
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if ((0, types_1.isTypeVar)(subtype)) {
                if (!(0, types_1.isTypeSame)(subtype, typeVar)) {
                    isCompatible = false;
                }
            }
            else if (subtype.condition) {
                if (!subtype.condition.some((condition) => condition.typeVar.details.constraints.length > 0 &&
                    condition.typeVar.nameWithScope === typeVar.nameWithScope)) {
                    isCompatible = false;
                }
            }
            else {
                isCompatible = false;
            }
        });
        return isCompatible;
    }
    // Determines whether a call associated with this flow node returns a NoReturn
    // type, thus preventing further traversal of the code flow graph.
    function isCallNoReturn(evaluator, flowNode) {
        const node = flowNode.node;
        if (enablePrintCallNoReturn) {
            console.log(`isCallNoReturn@${flowNode.id} Pre depth ${noReturnAnalysisDepth}`);
        }
        // See if this information is cached already.
        if (callIsNoReturnCache.has(node.id)) {
            const result = callIsNoReturnCache.get(node.id);
            if (enablePrintCallNoReturn) {
                console.log(`isCallNoReturn@${flowNode.id} Post: ${result ? 'true' : 'false'} (cached)`);
            }
            return result;
        }
        // See if we've exceeded the max recursion depth.
        if (noReturnAnalysisDepth > types_1.maxTypeRecursionCount) {
            return false;
        }
        // Don't attempt to evaluate a lambda call. We need to evaluate these in the
        // context of its arguments.
        if (node.leftExpression.nodeType === 30 /* ParseNodeType.Lambda */) {
            return false;
        }
        // Initially set to false to avoid recursion.
        callIsNoReturnCache.set(node.id, false);
        noReturnAnalysisDepth++;
        try {
            let noReturnTypeCount = 0;
            let subtypeCount = 0;
            // Evaluate the call base type.
            const callTypeResult = evaluator.getTypeOfExpression(node.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
            const callType = callTypeResult.type;
            (0, typeUtils_1.doForEachSubtype)(callType, (callSubtype) => {
                var _a;
                // Track the number of subtypes we've examined.
                subtypeCount++;
                if ((0, types_1.isInstantiableClass)(callSubtype)) {
                    // Does the class have a custom metaclass that implements a `__call__` method?
                    // If so, it will be called instead of `__init__` or `__new__`. We'll assume
                    // in this case that the __call__ method is not a NoReturn type.
                    const metaclassCallResult = (0, constructors_1.getBoundCallMethod)(evaluator, node, callSubtype);
                    if (metaclassCallResult) {
                        return;
                    }
                    const newMethodResult = (0, constructors_1.getBoundNewMethod)(evaluator, node, callSubtype);
                    if (newMethodResult) {
                        if ((0, types_1.isFunction)(newMethodResult.type) || (0, types_1.isOverloadedFunction)(newMethodResult.type)) {
                            callSubtype = newMethodResult.type;
                        }
                    }
                }
                else if ((0, types_1.isClassInstance)(callSubtype)) {
                    const callMethodType = evaluator.getBoundMagicMethod(callSubtype, '__call__');
                    if (callMethodType) {
                        callSubtype = callMethodType;
                    }
                }
                const isCallAwaited = ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 6 /* ParseNodeType.Await */;
                if ((0, types_1.isFunction)(callSubtype)) {
                    if (isFunctionNoReturn(callSubtype, isCallAwaited)) {
                        noReturnTypeCount++;
                    }
                }
                else if ((0, types_1.isOverloadedFunction)(callSubtype)) {
                    let overloadCount = 0;
                    let noReturnOverloadCount = 0;
                    types_1.OverloadedFunctionType.getOverloads(callSubtype).forEach((overload) => {
                        overloadCount++;
                        if (isFunctionNoReturn(overload, isCallAwaited)) {
                            noReturnOverloadCount++;
                        }
                    });
                    // Was at least one of the overloaded return types NoReturn?
                    if (noReturnOverloadCount > 0) {
                        // Do all of the overloads return NoReturn?
                        if (noReturnOverloadCount === overloadCount) {
                            noReturnTypeCount++;
                        }
                        else {
                            // Perform a more complete evaluation to determine whether
                            // the applicable overload returns a NoReturn.
                            const callResult = evaluator.validateOverloadedFunctionArguments(node, node.arguments, { type: callSubtype, isIncomplete: callTypeResult.isIncomplete }, undefined /* typeVarContext */, false /* skipUnknownArgCheck */, undefined /* expectedType */);
                            if (callResult.returnType && (0, types_1.isNever)(callResult.returnType)) {
                                noReturnTypeCount++;
                            }
                        }
                    }
                }
            });
            // The call is considered NoReturn if all subtypes evaluate to NoReturn.
            const callIsNoReturn = subtypeCount > 0 && noReturnTypeCount === subtypeCount;
            // Cache the value for next time.
            callIsNoReturnCache.set(node.id, callIsNoReturn);
            if (enablePrintCallNoReturn) {
                console.log(`isCallNoReturn@${flowNode.id} Post: ${callIsNoReturn ? 'true' : 'false'}`);
            }
            return callIsNoReturn;
        }
        finally {
            noReturnAnalysisDepth--;
        }
    }
    function isFunctionNoReturn(functionType, isCallAwaited) {
        const returnType = functionType.details.declaredReturnType;
        if (returnType) {
            if ((0, types_1.isClassInstance)(returnType) &&
                types_1.ClassType.isBuiltIn(returnType, 'Coroutine') &&
                returnType.typeArguments &&
                returnType.typeArguments.length >= 3) {
                if ((0, types_1.isNever)(returnType.typeArguments[2]) && isCallAwaited) {
                    return true;
                }
            }
            return (0, types_1.isNever)(returnType);
        }
        else if (!inferNoReturnForUnannotatedFunctions) {
            return false;
        }
        else if (functionType.details.declaration) {
            // If the function is a generator (i.e. it has yield statements)
            // then it is not a "no return" call. Also, don't infer a "no
            // return" type for abstract methods.
            if (!functionType.details.declaration.isGenerator &&
                !types_1.FunctionType.isAbstractMethod(functionType) &&
                !types_1.FunctionType.isStubDefinition(functionType) &&
                !types_1.FunctionType.isPyTypedDefinition(functionType)) {
                // Check specifically for a common idiom where the only statement
                // (other than a possible docstring) is a "raise NotImplementedError".
                const functionStatements = functionType.details.declaration.node.suite.statements;
                let foundRaiseNotImplemented = false;
                for (const statement of functionStatements) {
                    if (statement.nodeType !== 47 /* ParseNodeType.StatementList */ || statement.statements.length !== 1) {
                        break;
                    }
                    const simpleStatement = statement.statements[0];
                    if (simpleStatement.nodeType === 48 /* ParseNodeType.StringList */) {
                        continue;
                    }
                    if (simpleStatement.nodeType === 43 /* ParseNodeType.Raise */ && simpleStatement.typeExpression) {
                        // Check for a raising about 'NotImplementedError' or a subtype thereof.
                        const exceptionType = evaluator.getType(simpleStatement.typeExpression);
                        if (exceptionType &&
                            (0, types_1.isClass)(exceptionType) &&
                            (0, typeUtils_1.derivesFromStdlibClass)(exceptionType, 'NotImplementedError')) {
                            foundRaiseNotImplemented = true;
                        }
                    }
                    break;
                }
                if (!foundRaiseNotImplemented && !isAfterNodeReachable(evaluator, functionType)) {
                    return true;
                }
            }
        }
        return false;
    }
    function isAfterNodeReachable(evaluator, functionType) {
        if (!functionType.details.declaration) {
            return true;
        }
        return evaluator.isAfterNodeReachable(functionType.details.declaration.node);
    }
    // Performs a cursory analysis to determine whether the expression
    // corresponds to a context manager object that supports the swallowing
    // of exceptions. By convention, these objects have an "__exit__" method
    // that returns a bool response (as opposed to a None). This function is
    // called during code flow, so it can't rely on full type evaluation. It
    // makes some simplifying assumptions that work in most cases.
    function isExceptionContextManager(evaluator, node, isAsync) {
        // See if this information is cached already.
        if (isExceptionContextManagerCache.has(node.id)) {
            return isExceptionContextManagerCache.get(node.id);
        }
        // Initially set to false to avoid infinite recursion.
        isExceptionContextManagerCache.set(node.id, false);
        // See if we've exceeded the max recursion depth.
        if (contextManagerAnalysisDepth > types_1.maxTypeRecursionCount) {
            return false;
        }
        contextManagerAnalysisDepth++;
        let cmSwallowsExceptions = false;
        try {
            const cmType = evaluator.getTypeOfExpression(node).type;
            if (cmType && (0, types_1.isClassInstance)(cmType)) {
                const exitMethodName = isAsync ? '__aexit__' : '__exit__';
                const exitType = evaluator.getBoundMagicMethod(cmType, exitMethodName);
                if (exitType && (0, types_1.isFunction)(exitType) && exitType.details.declaredReturnType) {
                    let returnType = exitType.details.declaredReturnType;
                    // If it's an __aexit__ method, its return type will typically be wrapped
                    // in a Coroutine, so we need to extract the return type from the third
                    // type argument.
                    if (isAsync) {
                        if ((0, types_1.isClassInstance)(returnType) &&
                            types_1.ClassType.isBuiltIn(returnType, 'Coroutine') &&
                            returnType.typeArguments &&
                            returnType.typeArguments.length >= 3) {
                            returnType = returnType.typeArguments[2];
                        }
                    }
                    cmSwallowsExceptions = false;
                    if ((0, types_1.isClassInstance)(returnType) && types_1.ClassType.isBuiltIn(returnType, 'bool')) {
                        if (returnType.literalValue === undefined || returnType.literalValue === true) {
                            cmSwallowsExceptions = true;
                        }
                    }
                }
            }
        }
        finally {
            contextManagerAnalysisDepth--;
        }
        // Cache the value for next time.
        isExceptionContextManagerCache.set(node.id, cmSwallowsExceptions);
        return cmSwallowsExceptions;
    }
    function getTypeFromWildcardImport(flowNode, name) {
        const importInfo = (0, analyzerNodeInfo_1.getImportInfo)(flowNode.node.module);
        (0, debug_1.assert)(importInfo !== undefined && importInfo.isImportFound);
        (0, debug_1.assert)(flowNode.node.isWildcardImport);
        const symbolWithScope = evaluator.lookUpSymbolRecursive(flowNode.node, name, /* honorCodeFlow */ false);
        (0, debug_1.assert)(symbolWithScope !== undefined);
        const decls = symbolWithScope.symbol.getDeclarations();
        const wildcardDecl = decls.find((decl) => decl.node === flowNode.node);
        if (!wildcardDecl) {
            return types_1.UnknownType.create();
        }
        return evaluator.getInferredTypeOfDeclaration(symbolWithScope.symbol, wildcardDecl) || types_1.UnknownType.create();
    }
    function printControlFlowGraph(flowNode, reference, callName, logger = console) {
        let referenceText = '';
        if (reference) {
            const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(reference);
            const pos = (0, positionUtils_1.convertOffsetToPosition)(reference.start, fileInfo.lines);
            referenceText = `${(0, parseTreeUtils_1.printExpression)(reference)}[${pos.line + 1}:${pos.character + 1}]`;
        }
        logger.log(`${callName}@${flowNode.id}: ${referenceText || '(none)'}`);
        logger.log((0, codeFlowUtils_1.formatControlFlowGraph)(flowNode));
    }
    return {
        createCodeFlowAnalyzer,
        isFlowNodeReachable,
        narrowConstrainedTypeVar,
        printControlFlowGraph,
    };
}
exports.getCodeFlowEngine = getCodeFlowEngine;


/***/ }),

/***/ "../pyright-internal/src/analyzer/codeFlowTypes.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/analyzer/codeFlowTypes.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * codeFlowTypes.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Data structures that track the code flow (or more accurately,
 * the inverse of code flow) starting with return statements and
 * working back to the entry. This allows us to work out the
 * types at each point of the code flow.
 *
 * This is largely based on the code flow engine in the
 * TypeScript compiler.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.wildcardImportReferenceKey = exports.createKeysForReferenceSubexpressions = exports.createKeyForReference = exports.isCodeFlowSupportedForReference = exports.getUniqueFlowNodeId = exports.FlowFlags = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
var FlowFlags;
(function (FlowFlags) {
    FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
    FlowFlags[FlowFlags["Start"] = 2] = "Start";
    FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
    FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
    FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
    FlowFlags[FlowFlags["Unbind"] = 32] = "Unbind";
    FlowFlags[FlowFlags["WildcardImport"] = 64] = "WildcardImport";
    FlowFlags[FlowFlags["TrueCondition"] = 128] = "TrueCondition";
    FlowFlags[FlowFlags["FalseCondition"] = 512] = "FalseCondition";
    FlowFlags[FlowFlags["Call"] = 1024] = "Call";
    FlowFlags[FlowFlags["PreFinallyGate"] = 2048] = "PreFinallyGate";
    FlowFlags[FlowFlags["PostFinally"] = 4096] = "PostFinally";
    FlowFlags[FlowFlags["VariableAnnotation"] = 16384] = "VariableAnnotation";
    FlowFlags[FlowFlags["PostContextManager"] = 32768] = "PostContextManager";
    FlowFlags[FlowFlags["TrueNeverCondition"] = 65536] = "TrueNeverCondition";
    FlowFlags[FlowFlags["FalseNeverCondition"] = 131072] = "FalseNeverCondition";
    FlowFlags[FlowFlags["NarrowForPattern"] = 262144] = "NarrowForPattern";
    FlowFlags[FlowFlags["ExhaustedMatch"] = 524288] = "ExhaustedMatch";
    FlowFlags[FlowFlags["NotTypeChecking"] = 1048576] = "NotTypeChecking";
})(FlowFlags || (exports.FlowFlags = FlowFlags = {}));
let _nextFlowNodeId = 1;
function getUniqueFlowNodeId() {
    return _nextFlowNodeId++;
}
exports.getUniqueFlowNodeId = getUniqueFlowNodeId;
function isCodeFlowSupportedForReference(reference) {
    if (reference.nodeType === 38 /* ParseNodeType.Name */) {
        return true;
    }
    if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        return isCodeFlowSupportedForReference(reference.leftExpression);
    }
    if (reference.nodeType === 24 /* ParseNodeType.Index */) {
        // Allow index expressions that have a single subscript that is a
        // literal integer or string value.
        if (reference.items.length !== 1 ||
            reference.trailingComma ||
            reference.items[0].name !== undefined ||
            reference.items[0].argumentCategory !== 0 /* ArgumentCategory.Simple */) {
            return false;
        }
        const subscriptNode = reference.items[0].valueExpression;
        const isIntegerIndex = subscriptNode.nodeType === 40 /* ParseNodeType.Number */ && !subscriptNode.isImaginary && subscriptNode.isInteger;
        const isNegativeIntegerIndex = subscriptNode.nodeType === 55 /* ParseNodeType.UnaryOperation */ &&
            subscriptNode.operator === 33 /* OperatorType.Subtract */ &&
            subscriptNode.expression.nodeType === 40 /* ParseNodeType.Number */ &&
            !subscriptNode.expression.isImaginary &&
            subscriptNode.expression.isInteger;
        const isStringIndex = subscriptNode.nodeType === 48 /* ParseNodeType.StringList */ &&
            subscriptNode.strings.length === 1 &&
            subscriptNode.strings[0].nodeType === 49 /* ParseNodeType.String */;
        if (!isIntegerIndex && !isNegativeIntegerIndex && !isStringIndex) {
            return false;
        }
        return isCodeFlowSupportedForReference(reference.baseExpression);
    }
    return false;
}
exports.isCodeFlowSupportedForReference = isCodeFlowSupportedForReference;
function createKeyForReference(reference) {
    let key;
    if (reference.nodeType === 38 /* ParseNodeType.Name */) {
        key = reference.value;
    }
    else if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        const leftKey = createKeyForReference(reference.leftExpression);
        key = `${leftKey}.${reference.memberName.value}`;
    }
    else if (reference.nodeType === 24 /* ParseNodeType.Index */) {
        const leftKey = createKeyForReference(reference.baseExpression);
        (0, debug_1.assert)(reference.items.length === 1);
        const expr = reference.items[0].valueExpression;
        if (expr.nodeType === 40 /* ParseNodeType.Number */) {
            key = `${leftKey}[${expr.value.toString()}]`;
        }
        else if (expr.nodeType === 48 /* ParseNodeType.StringList */) {
            const valExpr = expr;
            (0, debug_1.assert)(valExpr.strings.length === 1 && valExpr.strings[0].nodeType === 49 /* ParseNodeType.String */);
            key = `${leftKey}["${valExpr.strings[0].value}"]`;
        }
        else if (expr.nodeType === 55 /* ParseNodeType.UnaryOperation */ &&
            expr.operator === 33 /* OperatorType.Subtract */ &&
            expr.expression.nodeType === 40 /* ParseNodeType.Number */) {
            key = `${leftKey}[-${expr.expression.value.toString()}]`;
        }
        else {
            (0, debug_1.fail)('createKeyForReference received unexpected index type');
        }
    }
    else {
        (0, debug_1.fail)('createKeyForReference received unexpected expression type');
    }
    return key;
}
exports.createKeyForReference = createKeyForReference;
function createKeysForReferenceSubexpressions(reference) {
    if (reference.nodeType === 38 /* ParseNodeType.Name */) {
        return [createKeyForReference(reference)];
    }
    if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        return [
            ...createKeysForReferenceSubexpressions(reference.leftExpression),
            createKeyForReference(reference),
        ];
    }
    if (reference.nodeType === 24 /* ParseNodeType.Index */) {
        return [
            ...createKeysForReferenceSubexpressions(reference.baseExpression),
            createKeyForReference(reference),
        ];
    }
    (0, debug_1.fail)('createKeyForReference received unexpected expression type');
}
exports.createKeysForReferenceSubexpressions = createKeysForReferenceSubexpressions;
// A reference key that corresponds to a wildcard import.
exports.wildcardImportReferenceKey = '*';


/***/ }),

/***/ "../pyright-internal/src/analyzer/codeFlowUtils.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/analyzer/codeFlowUtils.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * codeFlowUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility functions that operate on code flow nodes and graphs.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatControlFlowGraph = void 0;
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const codeFlowTypes_1 = __webpack_require__(/*! ./codeFlowTypes */ "../pyright-internal/src/analyzer/codeFlowTypes.ts");
function formatControlFlowGraph(flowNode) {
    const links = Object.create(/* o */ null);
    const nodes = [];
    const edges = [];
    const root = buildGraphNode(flowNode, new Set());
    for (const node of nodes) {
        node.text = renderFlowNode(node.flowNode, node.circular);
        computeLevel(node);
    }
    const height = computeHeight(root);
    const columnWidths = computeColumnWidths(height);
    computeLanes(root, 0);
    return renderGraph();
    function getAntecedents(f) {
        if (f.flags & (codeFlowTypes_1.FlowFlags.LoopLabel | codeFlowTypes_1.FlowFlags.BranchLabel)) {
            return f.antecedents;
        }
        if (f.flags &
            (codeFlowTypes_1.FlowFlags.Assignment |
                codeFlowTypes_1.FlowFlags.VariableAnnotation |
                codeFlowTypes_1.FlowFlags.WildcardImport |
                codeFlowTypes_1.FlowFlags.TrueCondition |
                codeFlowTypes_1.FlowFlags.FalseCondition |
                codeFlowTypes_1.FlowFlags.TrueNeverCondition |
                codeFlowTypes_1.FlowFlags.FalseNeverCondition |
                codeFlowTypes_1.FlowFlags.NarrowForPattern |
                codeFlowTypes_1.FlowFlags.ExhaustedMatch |
                codeFlowTypes_1.FlowFlags.Call |
                codeFlowTypes_1.FlowFlags.PreFinallyGate |
                codeFlowTypes_1.FlowFlags.PostFinally)) {
            const typedFlowNode = f;
            return [typedFlowNode.antecedent];
        }
        return [];
    }
    function getChildren(node) {
        const children = [];
        for (const edge of node.edges) {
            if (edge.source === node) {
                children.push(edge.target);
            }
        }
        return children;
    }
    function getParents(node) {
        const parents = [];
        for (const edge of node.edges) {
            if (edge.target === node) {
                parents.push(edge.source);
            }
        }
        return parents;
    }
    function buildGraphNode(flowNode, seen) {
        const id = flowNode.id;
        let graphNode = links[id];
        if (graphNode && seen.has(flowNode)) {
            graphNode = {
                id: -1,
                flowNode,
                edges: [],
                text: '',
                lane: -1,
                endLane: -1,
                level: -1,
                circular: true,
            };
            nodes.push(graphNode);
            return graphNode;
        }
        seen.add(flowNode);
        if (!graphNode) {
            links[id] = graphNode = {
                id,
                flowNode,
                edges: [],
                text: '',
                lane: -1,
                endLane: -1,
                level: -1,
                circular: false,
            };
            nodes.push(graphNode);
            const antecedents = getAntecedents(flowNode);
            for (const antecedent of antecedents) {
                buildGraphEdge(graphNode, antecedent, seen);
            }
        }
        seen.delete(flowNode);
        return graphNode;
    }
    function buildGraphEdge(source, antecedent, seen) {
        const target = buildGraphNode(antecedent, seen);
        const edge = { source, target };
        edges.push(edge);
        source.edges.push(edge);
        target.edges.push(edge);
    }
    function computeLevel(node) {
        if (node.level !== -1) {
            return node.level;
        }
        let level = 0;
        for (const parent of getParents(node)) {
            level = Math.max(level, computeLevel(parent) + 1);
        }
        return (node.level = level);
    }
    function computeHeight(node) {
        let height = 0;
        for (const child of getChildren(node)) {
            height = Math.max(height, computeHeight(child));
        }
        return height + 1;
    }
    function computeColumnWidths(height) {
        const columns = fill(Array(height), 0);
        for (const node of nodes) {
            columns[node.level] = Math.max(columns[node.level], node.text.length);
        }
        return columns;
    }
    function computeLanes(node, lane) {
        if (node.lane === -1) {
            node.lane = lane;
            node.endLane = lane;
            const children = getChildren(node);
            for (let i = 0; i < children.length; i++) {
                if (i > 0)
                    lane++;
                const child = children[i];
                computeLanes(child, lane);
                if (child.endLane > node.endLane) {
                    lane = child.endLane;
                }
            }
            node.endLane = lane;
        }
    }
    function getHeader(flags) {
        if (flags & codeFlowTypes_1.FlowFlags.Start)
            return 'Start';
        if (flags & codeFlowTypes_1.FlowFlags.BranchLabel)
            return 'Branch';
        if (flags & codeFlowTypes_1.FlowFlags.LoopLabel)
            return 'Loop';
        if (flags & codeFlowTypes_1.FlowFlags.Unbind)
            return 'Unbind';
        if (flags & codeFlowTypes_1.FlowFlags.Assignment)
            return 'Assign';
        if (flags & codeFlowTypes_1.FlowFlags.TrueCondition)
            return 'True';
        if (flags & codeFlowTypes_1.FlowFlags.FalseCondition)
            return 'False';
        if (flags & codeFlowTypes_1.FlowFlags.Call)
            return 'Call';
        if (flags & codeFlowTypes_1.FlowFlags.Unreachable)
            return 'Unreachable';
        if (flags & codeFlowTypes_1.FlowFlags.WildcardImport)
            return 'Wildcard';
        if (flags & codeFlowTypes_1.FlowFlags.PreFinallyGate)
            return 'PreFinal';
        if (flags & codeFlowTypes_1.FlowFlags.PostFinally)
            return 'PostFinal';
        if (flags & codeFlowTypes_1.FlowFlags.VariableAnnotation)
            return 'Annotate';
        if (flags & codeFlowTypes_1.FlowFlags.TrueNeverCondition)
            return 'TrueNever';
        if (flags & codeFlowTypes_1.FlowFlags.FalseNeverCondition)
            return 'FalseNever';
        if (flags & codeFlowTypes_1.FlowFlags.NarrowForPattern)
            return 'Pattern';
        if (flags & codeFlowTypes_1.FlowFlags.ExhaustedMatch)
            return 'Exhaust';
        if (flags & codeFlowTypes_1.FlowFlags.NotTypeChecking)
            return 'NotTypeChecking';
        throw new Error();
    }
    function getParseNode(f) {
        if (f.flags & codeFlowTypes_1.FlowFlags.Assignment) {
            return f.node;
        }
        if (f.flags & codeFlowTypes_1.FlowFlags.WildcardImport) {
            return f.node;
        }
        if (f.flags & (codeFlowTypes_1.FlowFlags.TrueCondition | codeFlowTypes_1.FlowFlags.FalseCondition)) {
            return f.expression;
        }
        if (f.flags & codeFlowTypes_1.FlowFlags.NarrowForPattern) {
            return f.statement;
        }
        if (f.flags & codeFlowTypes_1.FlowFlags.Call) {
            return f.node;
        }
        return undefined;
    }
    function getNodeText(f) {
        const parseNode = getParseNode(f);
        if (!parseNode) {
            return undefined;
        }
        const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(parseNode);
        const startPos = (0, positionUtils_1.convertOffsetToPosition)(parseNode.start, fileInfo.lines);
        return `[${startPos.line + 1}:${startPos.character + 1}]`;
    }
    function renderFlowNode(flowNode, circular) {
        const text = `${getHeader(flowNode.flags)}@${flowNode.id}${getNodeText(flowNode) || ''}`;
        return circular ? `Circular(${text})` : text;
    }
    function renderGraph() {
        const columnCount = columnWidths.length;
        const laneCount = nodes.reduce((x, n) => Math.max(x, n.lane), 0) + 1;
        const lanes = fill(Array(laneCount), '');
        const grid = columnWidths.map(() => Array(laneCount));
        const connectors = columnWidths.map(() => fill(Array(laneCount), 0));
        // Build connectors.
        for (const node of nodes) {
            grid[node.level][node.lane] = node;
            const children = getChildren(node);
            for (let i = 0; i < children.length; i++) {
                const child = children[i];
                let connector = 8 /* Connection.Right */;
                if (child.lane === node.lane)
                    connector |= 4 /* Connection.Left */;
                if (i > 0)
                    connector |= 1 /* Connection.Up */;
                if (i < children.length - 1)
                    connector |= 2 /* Connection.Down */;
                connectors[node.level][child.lane] |= connector;
            }
            if (children.length === 0) {
                connectors[node.level][node.lane] |= 16 /* Connection.NoChildren */;
            }
            const parents = getParents(node);
            for (let i = 0; i < parents.length; i++) {
                const parent = parents[i];
                let connector = 4 /* Connection.Left */;
                if (i > 0)
                    connector |= 1 /* Connection.Up */;
                if (i < parents.length - 1)
                    connector |= 2 /* Connection.Down */;
                connectors[node.level - 1][parent.lane] |= connector;
            }
        }
        // Fill in missing connectors.
        for (let column = 0; column < columnCount; column++) {
            for (let lane = 0; lane < laneCount; lane++) {
                const left = column > 0 ? connectors[column - 1][lane] : 0;
                const above = lane > 0 ? connectors[column][lane - 1] : 0;
                let connector = connectors[column][lane];
                if (!connector) {
                    connector = 0 /* Connection.None */;
                    if (left & 8 /* Connection.Right */) {
                        connector |= 12 /* Connection.LeftRight */;
                    }
                    if (above & 2 /* Connection.Down */) {
                        connector |= 3 /* Connection.UpDown */;
                    }
                    connectors[column][lane] = connector;
                }
            }
        }
        for (let column = 0; column < columnCount; column++) {
            for (let lane = 0; lane < lanes.length; lane++) {
                const connector = connectors[column][lane];
                const fill = connector & 4 /* Connection.Left */ ? "\u2500" /* BoxCharacter.lr */ : ' ';
                const node = grid[column][lane];
                if (!node) {
                    if (column < columnCount - 1) {
                        writeLane(lane, repeat(fill, columnWidths[column] + 1));
                    }
                }
                else {
                    writeLane(lane, node.text);
                    if (column < columnCount - 1) {
                        writeLane(lane, ' ');
                        writeLane(lane, repeat(fill, columnWidths[column] - node.text.length));
                    }
                }
                writeLane(lane, getBoxCharacter(connector));
                writeLane(lane, connector & 8 /* Connection.Right */ && column < columnCount - 1 && !grid[column + 1][lane]
                    ? "\u2500" /* BoxCharacter.lr */
                    : ' ');
            }
        }
        return `${lanes.join('\n')}\n`;
        function writeLane(lane, text) {
            lanes[lane] += text;
        }
    }
    function getBoxCharacter(connector) {
        switch (connector) {
            case 3 /* Connection.UpDown */:
                return "\u2502" /* BoxCharacter.ud */;
            case 12 /* Connection.LeftRight */:
                return "\u2500" /* BoxCharacter.lr */;
            case 5 /* Connection.UpLeft */:
                return "\u256F" /* BoxCharacter.ul */;
            case 9 /* Connection.UpRight */:
                return "\u2570" /* BoxCharacter.ur */;
            case 6 /* Connection.DownLeft */:
                return "\u256E" /* BoxCharacter.dl */;
            case 10 /* Connection.DownRight */:
                return "\u256D" /* BoxCharacter.dr */;
            case 7 /* Connection.UpDownLeft */:
                return "\u2524" /* BoxCharacter.udl */;
            case 11 /* Connection.UpDownRight */:
                return "\u251C" /* BoxCharacter.udr */;
            case 13 /* Connection.UpLeftRight */:
                return "\u2534" /* BoxCharacter.ulr */;
            case 14 /* Connection.DownLeftRight */:
                return "\u252C" /* BoxCharacter.dlr */;
            case 15 /* Connection.UpDownLeftRight */:
                return "\u256B" /* BoxCharacter.udlr */;
        }
        return ' ';
    }
    function fill(array, value) {
        if (array.fill) {
            array.fill(value);
        }
        else {
            for (let i = 0; i < array.length; i++) {
                array[i] = value;
            }
        }
        return array;
    }
    function repeat(ch, length) {
        if (ch.repeat) {
            return length > 0 ? ch.repeat(length) : '';
        }
        let s = '';
        while (s.length < length) {
            s += ch;
        }
        return s;
    }
}
exports.formatControlFlowGraph = formatControlFlowGraph;


/***/ }),

/***/ "../pyright-internal/src/analyzer/commentUtils.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/commentUtils.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * commentUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility functions that parse comments and extract commands
 * or other directives from them.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getFileLevelDirectives = void 0;
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const strictSetting = 'strict';
const standardSetting = 'standard';
const basicSetting = 'basic';
function getFileLevelDirectives(tokens, lines, defaultRuleSet, useStrict, diagnostics) {
    let ruleSet = (0, configOptions_1.cloneDiagnosticRuleSet)(defaultRuleSet);
    if (useStrict) {
        _applyStrictRules(ruleSet);
    }
    for (let i = 0; i < tokens.count; i++) {
        const token = tokens.getItemAt(i);
        if (token.comments) {
            for (const comment of token.comments) {
                const [value, textRange] = _trimTextWithRange(comment.value, {
                    start: comment.start,
                    length: comment.length,
                });
                const isCommentOnOwnLine = () => {
                    const curTokenLineOffset = (0, positionUtils_1.convertOffsetToPosition)(comment.start, lines).character;
                    return curTokenLineOffset <= 1;
                };
                ruleSet = _parsePyrightComment(value, textRange, isCommentOnOwnLine, ruleSet, diagnostics);
            }
        }
    }
    return ruleSet;
}
exports.getFileLevelDirectives = getFileLevelDirectives;
function _applyStrictRules(ruleSet) {
    _overrideRules(ruleSet, (0, configOptions_1.getStrictDiagnosticRuleSet)(), (0, configOptions_1.getStrictModeNotOverriddenRules)());
}
function _applyStandardRules(ruleSet) {
    _overwriteRules(ruleSet, (0, configOptions_1.getStandardDiagnosticRuleSet)());
}
function _applyBasicRules(ruleSet) {
    _overwriteRules(ruleSet, (0, configOptions_1.getBasicDiagnosticRuleSet)());
}
function _overrideRules(ruleSet, overrideRuleSet, skipRuleNames) {
    const boolRuleNames = (0, configOptions_1.getBooleanDiagnosticRules)();
    const diagRuleNames = (0, configOptions_1.getDiagLevelDiagnosticRules)();
    // Enable the strict rules as appropriate.
    for (const ruleName of boolRuleNames) {
        if (skipRuleNames.find((r) => r === ruleName)) {
            continue;
        }
        if (overrideRuleSet[ruleName]) {
            ruleSet[ruleName] = true;
        }
    }
    for (const ruleName of diagRuleNames) {
        if (skipRuleNames.find((r) => r === ruleName)) {
            continue;
        }
        const overrideValue = overrideRuleSet[ruleName];
        const prevValue = ruleSet[ruleName];
        // Override only if the new value is more strict than the existing value.
        if (overrideValue === 'error' ||
            (overrideValue === 'warning' && prevValue !== 'error') ||
            (overrideValue === 'information' && prevValue !== 'error' && prevValue !== 'warning')) {
            ruleSet[ruleName] = overrideValue;
        }
    }
}
function _overwriteRules(ruleSet, overrideRuleSet) {
    const boolRuleNames = (0, configOptions_1.getBooleanDiagnosticRules)();
    const diagRuleNames = (0, configOptions_1.getDiagLevelDiagnosticRules)();
    for (const ruleName of boolRuleNames) {
        ruleSet[ruleName] = overrideRuleSet[ruleName];
    }
    for (const ruleName of diagRuleNames) {
        ruleSet[ruleName] = overrideRuleSet[ruleName];
    }
}
function _parsePyrightComment(commentValue, commentRange, isCommentOnOwnLine, ruleSet, diagnostics) {
    // Is this a pyright comment?
    const commentPrefix = 'pyright:';
    if (commentValue.startsWith(commentPrefix)) {
        const operands = commentValue.substring(commentPrefix.length);
        // Handle (actual ignore) "ignore" directives.
        if (operands.trim().startsWith('ignore')) {
            return ruleSet;
        }
        if (!isCommentOnOwnLine()) {
            const diagAddendum = new diagnostic_1.DiagnosticAddendum();
            diagAddendum.addMessage(localize_1.LocAddendum.pyrightCommentIgnoreTip());
            const diag = {
                message: localize_1.LocMessage.pyrightCommentNotOnOwnLine() + diagAddendum.getString(),
                range: commentRange,
            };
            diagnostics.push(diag);
        }
        const operandList = operands.split(',');
        // If it contains a "strict" operand, replace the existing
        // diagnostic rules with their strict counterparts.
        if (operandList.some((s) => s.trim() === strictSetting)) {
            _applyStrictRules(ruleSet);
        }
        else if (operandList.some((s) => s.trim() === standardSetting)) {
            _applyStandardRules(ruleSet);
        }
        else if (operandList.some((s) => s.trim() === basicSetting)) {
            _applyBasicRules(ruleSet);
        }
        let rangeOffset = 0;
        for (const operand of operandList) {
            const [trimmedOperand, operandRange] = _trimTextWithRange(operand, {
                start: commentRange.start + commentPrefix.length + rangeOffset,
                length: operand.length,
            });
            ruleSet = _parsePyrightOperand(trimmedOperand, operandRange, ruleSet, diagnostics);
            rangeOffset += operand.length + 1;
        }
    }
    return ruleSet;
}
function _parsePyrightOperand(operand, operandRange, ruleSet, diagnostics) {
    const operandSplit = operand.split('=');
    const [trimmedRule, ruleRange] = _trimTextWithRange(operandSplit[0], {
        start: operandRange.start,
        length: operandSplit[0].length,
    });
    // Handle basic directives "basic" and "strict".
    if (operandSplit.length === 1) {
        if (trimmedRule && [strictSetting, basicSetting].some((setting) => trimmedRule === setting)) {
            return ruleSet;
        }
    }
    const diagLevelRules = (0, configOptions_1.getDiagLevelDiagnosticRules)();
    const boolRules = (0, configOptions_1.getBooleanDiagnosticRules)();
    const ruleValue = operandSplit.length > 0 ? operandSplit.slice(1).join('=') : '';
    const [trimmedRuleValue, ruleValueRange] = _trimTextWithRange(ruleValue, {
        start: operandRange.start + operandSplit[0].length + 1,
        length: ruleValue.length,
    });
    if (diagLevelRules.find((r) => r === trimmedRule)) {
        const diagLevelValue = _parseDiagLevel(trimmedRuleValue);
        if (diagLevelValue !== undefined) {
            ruleSet[trimmedRule] = diagLevelValue;
        }
        else {
            const diag = {
                message: localize_1.LocMessage.pyrightCommentInvalidDiagnosticSeverityValue(),
                range: trimmedRuleValue ? ruleValueRange : ruleRange,
            };
            diagnostics.push(diag);
        }
    }
    else if (boolRules.find((r) => r === trimmedRule)) {
        const boolValue = _parseBoolSetting(trimmedRuleValue);
        if (boolValue !== undefined) {
            ruleSet[trimmedRule] = boolValue;
        }
        else {
            const diag = {
                message: localize_1.LocMessage.pyrightCommentInvalidDiagnosticBoolValue(),
                range: trimmedRuleValue ? ruleValueRange : ruleRange,
            };
            diagnostics.push(diag);
        }
    }
    else if (trimmedRule) {
        const diag = {
            message: trimmedRuleValue
                ? localize_1.LocMessage.pyrightCommentUnknownDiagnosticRule().format({ rule: trimmedRule })
                : localize_1.LocMessage.pyrightCommentUnknownDirective().format({ directive: trimmedRule }),
            range: ruleRange,
        };
        diagnostics.push(diag);
    }
    else {
        const diag = {
            message: localize_1.LocMessage.pyrightCommentMissingDirective(),
            range: ruleRange,
        };
        diagnostics.push(diag);
    }
    return ruleSet;
}
function _parseDiagLevel(value) {
    switch (value) {
        case 'false':
        case 'none':
            return 'none';
        case 'true':
        case 'error':
            return 'error';
        case 'warning':
            return 'warning';
        case 'information':
            return 'information';
        default:
            return undefined;
    }
}
function _parseBoolSetting(value) {
    if (value === 'false') {
        return false;
    }
    else if (value === 'true') {
        return true;
    }
    return undefined;
}
// Calls "trim" on the text and adjusts the corresponding range
// if characters are trimmed from the beginning or end.
function _trimTextWithRange(text, range) {
    (0, debug_1.assert)(text.length === range.length);
    const value1 = text.trimStart();
    let updatedRange = range;
    if (value1 !== text) {
        const delta = text.length - value1.length;
        updatedRange = { start: updatedRange.start + delta, length: updatedRange.length - delta };
    }
    const value2 = value1.trimEnd();
    if (value2 !== value1) {
        updatedRange = { start: updatedRange.start, length: updatedRange.length - value1.length + value2.length };
    }
    (0, debug_1.assert)(value2.length === updatedRange.length);
    return [value2, updatedRange];
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/constraintSolver.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/analyzer/constraintSolver.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * constraintSolver.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Code that solves a TypeVar, TypeVarTuple or ParamSpec based on
 * all of the provided constraints.
 *
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.populateTypeVarContextBasedOnExpectedType = exports.updateTypeVarType = exports.assignTypeToTypeVar = void 0;
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const typeEvaluatorTypes_1 = __webpack_require__(/*! ./typeEvaluatorTypes */ "../pyright-internal/src/analyzer/typeEvaluatorTypes.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
// As we widen the narrow bound of a type variable, we may end up with
// many subtypes. For performance reasons, we need to cap this at some
// point. This constant determines the cap.
const maxSubtypeCountForTypeVarNarrowBound = 64;
// This debugging switch enables logging of the TypeVarContext before and
// after it is updated by the constraint solver.
const logTypeVarContextUpdates = false;
// Assigns the source type to the dest type var in the type var context. If an existing
// type is already associated with that type var name, it attempts to either widen or
// narrow the type (depending on the value of the isContravariant parameter). The goal is
// to produce the narrowest type that meets all of the requirements. If the type var context
// has been "locked", it simply validates that the srcType is compatible (with no attempt
// to widen or narrow).
function assignTypeToTypeVar(evaluator, destType, srcType, diag, typeVarContext, flags = 0 /* AssignTypeFlags.Default */, recursionCount = 0) {
    if (logTypeVarContextUpdates) {
        const indent = ' '.repeat(recursionCount * 2);
        console.log(`${indent}`);
        console.log(`${indent}assignTypeToTypeVar called with`);
        console.log(`${indent}destType: ${evaluator.printType(destType)}`);
        console.log(`${indent}srcType: ${evaluator.printType(srcType)}`);
        console.log(`${indent}flags: ${flags}`);
        console.log(`${indent}scopes: ${(typeVarContext.getSolveForScopes() || []).join(', ')}`);
        console.log(`${indent}pre-call context #${typeVarContext.getId()}: `);
        logTypeVarContext(evaluator, typeVarContext, indent);
    }
    let isTypeVarInScope = true;
    const isInvariant = (flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0;
    const isContravariant = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) !== 0;
    // If the TypeVar doesn't have a scope ID, then it's being used
    // outside of a valid TypeVar scope. This will be reported as a
    // separate error. Just ignore this case to avoid redundant errors.
    if (!destType.scopeId) {
        return true;
    }
    // Handle type[T] as a dest and a special form as a source.
    if (types_1.TypeBase.isInstantiable(destType) &&
        (0, types_1.isInstantiableClass)(srcType) &&
        evaluator.isSpecialFormClass(srcType, flags)) {
        return false;
    }
    // Verify that we are solving for the scope associated with this
    // type variable.
    if (!typeVarContext.hasSolveForScope(destType.scopeId)) {
        // Handle Any as a source.
        if ((0, types_1.isAnyOrUnknown)(srcType) || ((0, types_1.isClass)(srcType) && types_1.ClassType.derivesFromAnyOrUnknown(srcType))) {
            return true;
        }
        // Handle a type[Any] as a source.
        if ((0, types_1.isClassInstance)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'type')) {
            if (!srcType.typeArguments ||
                srcType.typeArguments.length < 1 ||
                (0, types_1.isAnyOrUnknown)(srcType.typeArguments[0])) {
                if (types_1.TypeBase.isInstantiable(destType)) {
                    return true;
                }
            }
        }
        // Is this the equivalent of an "Unknown" for a ParamSpec?
        if (destType.details.isParamSpec &&
            (0, types_1.isFunction)(srcType) &&
            types_1.FunctionType.isParamSpecValue(srcType) &&
            types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(srcType)) {
            return true;
        }
        // Never or NoReturn is always assignable to all type variables unless
        // we're enforcing invariance.
        if ((0, types_1.isNever)(srcType) && !isInvariant) {
            return true;
        }
        // If we're in "ignore type var scope" mode, don't generate
        // an error in this path.
        if ((flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */) !== 0) {
            return true;
        }
        isTypeVarInScope = false;
        // Emit an error unless this is a synthesized type variable used
        // for pseudo-generic classes.
        if (!destType.details.isSynthesized || destType.details.isSynthesizedSelf) {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(srcType, destType)));
            return false;
        }
    }
    // An in-scope placeholder TypeVar can always be assigned to itself,
    // but we won't record this in the typeVarContext.
    if ((0, types_1.isTypeSame)(destType, srcType) && destType.isInScopePlaceholder) {
        return true;
    }
    if ((flags & 8 /* AssignTypeFlags.SkipSolveTypeVars */) !== 0) {
        return evaluator.assignType(evaluator.makeTopLevelTypeVarsConcrete(destType), evaluator.makeTopLevelTypeVarsConcrete(srcType), diag, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, flags, recursionCount);
    }
    if (destType.details.isParamSpec) {
        return assignTypeToParamSpec(evaluator, destType, srcType, diag, typeVarContext, recursionCount);
    }
    if (destType.details.isVariadic && !destType.isVariadicInUnion) {
        if (!(0, types_1.isUnpacked)(srcType)) {
            const tupleClassType = evaluator.getTupleClassType();
            if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                // Package up the type into a tuple.
                srcType = (0, typeUtils_1.convertToInstance)((0, typeUtils_1.specializeTupleClass)(tupleClassType, [{ type: srcType, isUnbounded: false }], 
                /* isTypeArgumentExplicit */ true, 
                /* isUnpackedTuple */ true));
            }
            else {
                srcType = types_1.UnknownType.create();
            }
        }
    }
    // If we're assigning an unpacked TypeVarTuple to a regular TypeVar,
    // we need to treat it as a union of the unpacked TypeVarTuple.
    if ((0, types_1.isTypeVar)(srcType) &&
        srcType.details.isVariadic &&
        srcType.isVariadicUnpacked &&
        !srcType.isVariadicInUnion &&
        !destType.details.isVariadic) {
        srcType = types_1.TypeVarType.cloneForUnpacked(srcType, /* isInUnion */ true);
    }
    // Handle the constrained case. This case needs to be handled specially
    // because type narrowing isn't used in this case. For example, if the
    // source type is "Literal[1]" and the constraint list includes the type
    // "float", the resulting type is float.
    if (destType.details.constraints.length > 0) {
        return assignTypeToConstrainedTypeVar(evaluator, destType, srcType, diag, typeVarContext, flags, isTypeVarInScope, recursionCount);
    }
    // Handle the unconstrained (but possibly bound) case.
    const curEntry = typeVarContext.getPrimarySignature().getTypeVar(destType);
    let curWideTypeBound = curEntry === null || curEntry === void 0 ? void 0 : curEntry.wideBound;
    if (!curWideTypeBound && !destType.details.isSynthesizedSelf) {
        curWideTypeBound = destType.details.boundType;
    }
    let curNarrowTypeBound = curEntry === null || curEntry === void 0 ? void 0 : curEntry.narrowBound;
    let newNarrowTypeBound = curNarrowTypeBound;
    let newWideTypeBound = curWideTypeBound;
    const diagAddendum = diag ? new diagnostic_1.DiagnosticAddendum() : undefined;
    let adjSrcType = srcType;
    // If the source is a class that is missing type arguments, fill
    // in missing type arguments with Unknown.
    if ((flags & 8192 /* AssignTypeFlags.AllowUnspecifiedTypeArguments */) === 0) {
        if ((0, types_1.isClass)(adjSrcType) && adjSrcType.includeSubclasses) {
            adjSrcType = (0, typeUtils_1.specializeWithDefaultTypeArgs)(adjSrcType);
        }
    }
    if (types_1.TypeBase.isInstantiable(destType)) {
        if ((0, typeUtils_1.isEffectivelyInstantiable)(adjSrcType)) {
            adjSrcType = (0, typeUtils_1.convertToInstance)(adjSrcType, /* includeSubclasses */ false);
        }
        else {
            // Handle the case of a TypeVar that has a bound of `type`.
            const concreteAdjSrcType = evaluator.makeTopLevelTypeVarsConcrete(adjSrcType);
            if ((0, typeUtils_1.isEffectivelyInstantiable)(concreteAdjSrcType)) {
                adjSrcType = (0, typeUtils_1.convertToInstance)(concreteAdjSrcType);
            }
            else {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(srcType, destType)));
                return false;
            }
        }
    }
    else if ((0, types_1.isTypeVar)(srcType) &&
        types_1.TypeBase.isInstantiable(srcType) &&
        (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(srcType), destType)) {
        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(adjSrcType, destType)));
        return false;
    }
    if ((flags & 2048 /* AssignTypeFlags.PopulatingExpectedType */) !== 0) {
        if ((flags & 4096 /* AssignTypeFlags.SkipPopulateUnknownExpectedType */) !== 0 && (0, types_1.isUnknown)(adjSrcType)) {
            return true;
        }
        // If we're populating the expected type, constrain either the
        // narrow type bound, wide type bound or both. Don't overwrite
        // an existing entry.
        if (!curEntry) {
            if (isInvariant) {
                newNarrowTypeBound = adjSrcType;
                newWideTypeBound = adjSrcType;
            }
            else if (isContravariant) {
                newNarrowTypeBound = adjSrcType;
            }
            else {
                newWideTypeBound = adjSrcType;
            }
        }
    }
    else if (isContravariant) {
        // Update the wide type bound.
        if (!curWideTypeBound || (0, types_1.isTypeSame)(destType, curWideTypeBound)) {
            newWideTypeBound = adjSrcType;
        }
        else if (!(0, types_1.isTypeSame)(curWideTypeBound, adjSrcType, {}, recursionCount)) {
            if (evaluator.assignType(curWideTypeBound, evaluator.makeTopLevelTypeVarsConcrete(adjSrcType), diagAddendum, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                // The srcType is narrower than the current wideTypeBound, so replace it.
                // If it's Any, don't replace it because Any is the narrowest type already.
                if (!(0, types_1.isAnyOrUnknown)(curWideTypeBound)) {
                    newWideTypeBound = adjSrcType;
                }
            }
            else if (!evaluator.assignType(adjSrcType, curWideTypeBound, diagAddendum, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                if (diag && diagAddendum) {
                    diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(curWideTypeBound, adjSrcType)));
                    diag.addAddendum(diagAddendum);
                }
                return false;
            }
        }
        // Make sure we haven't narrowed it beyond the current narrow bound.
        if (curNarrowTypeBound) {
            if (!evaluator.assignType(newWideTypeBound, curNarrowTypeBound, 
            /* diag */ undefined, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                if (diag && diagAddendum) {
                    diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(curNarrowTypeBound, newWideTypeBound)));
                    diag.addAddendum(diagAddendum);
                }
                return false;
            }
        }
    }
    else {
        if (!curNarrowTypeBound || (0, types_1.isTypeSame)(destType, curNarrowTypeBound)) {
            // There was previously no narrow bound. We've now established one.
            newNarrowTypeBound = adjSrcType;
        }
        else if ((0, types_1.isTypeSame)(curNarrowTypeBound, adjSrcType, {}, recursionCount)) {
            // If this is an invariant context and there is currently no wide type bound
            // established, use the "no literals" version of the narrow type bounds rather
            // than a version that has literals.
            if (!newWideTypeBound && isInvariant && (curEntry === null || curEntry === void 0 ? void 0 : curEntry.narrowBoundNoLiterals)) {
                newNarrowTypeBound = curEntry.narrowBoundNoLiterals;
            }
        }
        else {
            if ((0, types_1.isAnyOrUnknown)(adjSrcType) && (curEntry === null || curEntry === void 0 ? void 0 : curEntry.tupleTypes)) {
                // Handle the tuple case specially. If Any or Unknown is assigned
                // during the construction of a tuple, the resulting tuple type must
                // be tuple[Any, ...], which is compatible with any tuple.
                newNarrowTypeBound = adjSrcType;
            }
            else if (evaluator.assignType(curNarrowTypeBound, adjSrcType, diagAddendum, typeVarContext, 
            /* srcTypeVarContext */ undefined, flags, recursionCount)) {
                // No need to widen. Stick with the existing type unless it's unknown
                // or partly unknown, in which case we'll replace it with a known type
                // as long as it doesn't violate the current narrow bound.
                if ((0, typeUtils_1.isPartlyUnknown)(curNarrowTypeBound) &&
                    !(0, types_1.isUnknown)(adjSrcType) &&
                    evaluator.assignType(adjSrcType, curNarrowTypeBound, 
                    /* diag */ undefined, typeVarContext, 
                    /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                    newNarrowTypeBound = adjSrcType;
                }
                else {
                    newNarrowTypeBound = (0, typeUtils_1.applySolvedTypeVars)(curNarrowTypeBound, typeVarContext);
                }
            }
            else if ((0, types_1.isTypeVar)(curNarrowTypeBound) &&
                !(0, types_1.isTypeVar)(adjSrcType) &&
                evaluator.assignType(evaluator.makeTopLevelTypeVarsConcrete(curNarrowTypeBound), adjSrcType, diagAddendum, typeVarContext, 
                /* srcTypeVarContext */ undefined, flags, recursionCount)) {
                // If the existing narrow type bound was a TypeVar that is not
                // part of the current context we can replace it with the new
                // source type.
                newNarrowTypeBound = adjSrcType;
            }
            else {
                // We need to widen the type.
                if (typeVarContext.isLocked()) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(adjSrcType, curNarrowTypeBound)));
                    return false;
                }
                if (evaluator.assignType(adjSrcType, curNarrowTypeBound, 
                /* diag */ undefined, typeVarContext, 
                /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                    newNarrowTypeBound = adjSrcType;
                }
                else if ((0, types_1.isVariadicTypeVar)(destType)) {
                    const widenedType = widenTypeForVariadicTypeVar(evaluator, curNarrowTypeBound, adjSrcType);
                    if (!widenedType) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(curNarrowTypeBound, adjSrcType)));
                        return false;
                    }
                    newNarrowTypeBound = widenedType;
                }
                else {
                    const objectType = evaluator.getObjectType();
                    // If this is an invariant context and there is currently no wide type bound
                    // established, use the "no literals" version of the narrow type bounds rather
                    // than a version that has literals.
                    if (!newWideTypeBound && isInvariant && (curEntry === null || curEntry === void 0 ? void 0 : curEntry.narrowBoundNoLiterals)) {
                        curNarrowTypeBound = curEntry.narrowBoundNoLiterals;
                    }
                    const curSolvedNarrowTypeBound = (0, typeUtils_1.applySolvedTypeVars)(curNarrowTypeBound, typeVarContext);
                    // In some extreme edge cases, the narrow type bound can become
                    // a union with so many subtypes that performance grinds to a
                    // halt. We'll detect this case and widen the resulting type
                    // to an 'object' instead of making the union even bigger. This
                    // is still a valid solution to the TypeVar.
                    if ((0, types_1.isUnion)(curSolvedNarrowTypeBound) &&
                        curSolvedNarrowTypeBound.subtypes.length > typeEvaluatorTypes_1.maxSubtypesForInferredType &&
                        destType.details.boundType !== undefined &&
                        (0, types_1.isClassInstance)(objectType)) {
                        newNarrowTypeBound = (0, types_1.combineTypes)([curSolvedNarrowTypeBound, objectType], maxSubtypeCountForTypeVarNarrowBound);
                    }
                    else {
                        newNarrowTypeBound = (0, types_1.combineTypes)([curSolvedNarrowTypeBound, adjSrcType], maxSubtypeCountForTypeVarNarrowBound);
                    }
                }
            }
        }
        // Make sure we don't exceed the wide type bound.
        if (curWideTypeBound && newNarrowTypeBound) {
            if (!(0, types_1.isTypeSame)(curWideTypeBound, newNarrowTypeBound, {}, recursionCount)) {
                let makeConcrete = true;
                // Handle the case where the wide type is type T and the narrow type
                // is type T | <some other type>. In this case, it violates the
                // wide type bound.
                if ((0, types_1.isTypeVar)(curWideTypeBound)) {
                    if ((0, types_1.isTypeSame)(newNarrowTypeBound, curWideTypeBound)) {
                        makeConcrete = false;
                    }
                    else if ((0, types_1.isUnion)(newNarrowTypeBound) &&
                        newNarrowTypeBound.subtypes.some((subtype) => (0, types_1.isTypeSame)(subtype, curWideTypeBound))) {
                        makeConcrete = false;
                    }
                }
                const adjWideTypeBound = makeConcrete
                    ? evaluator.makeTopLevelTypeVarsConcrete(curWideTypeBound, /* makeParamSpecsConcrete */ true)
                    : curWideTypeBound;
                if (!evaluator.assignType(adjWideTypeBound, newNarrowTypeBound, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), typeVarContext, 
                /* srcTypeVarContext */ undefined, 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
                    if (diag && diagAddendum) {
                        diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(newNarrowTypeBound, adjWideTypeBound)));
                    }
                    return false;
                }
            }
        }
    }
    if (!newWideTypeBound && isInvariant) {
        newWideTypeBound = newNarrowTypeBound;
    }
    // If there's a bound type, make sure the source is assignable to it.
    if (destType.details.boundType) {
        const updatedType = (newNarrowTypeBound || newWideTypeBound);
        // If the dest is a Type[T] but the source is not a valid Type,
        // skip the assignType check and the diagnostic addendum, which will
        // be confusing and inaccurate.
        if (types_1.TypeBase.isInstantiable(destType) && !types_1.TypeBase.isInstantiable(srcType)) {
            return false;
        }
        // In general, bound types cannot be generic, but the "Self" type is an
        // exception. In this case, we need to use the original TypeVarContext
        // to solve for the generic type variable(s) in the bound type.
        const effectiveTypeVarContext = destType.details.isSynthesizedSelf
            ? typeVarContext
            : new typeVarContext_1.TypeVarContext(destType.scopeId);
        if (!evaluator.assignType(destType.details.boundType, evaluator.makeTopLevelTypeVarsConcrete(updatedType), diag === null || diag === void 0 ? void 0 : diag.createAddendum(), effectiveTypeVarContext, 
        /* srcTypeVarContext */ undefined, flags & 1024 /* AssignTypeFlags.IgnoreTypeVarScope */, recursionCount)) {
            // Avoid adding a message that will confuse users if the TypeVar was
            // synthesized for internal purposes.
            if (!destType.details.isSynthesized) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeBound().format({
                    sourceType: evaluator.printType(updatedType),
                    destType: evaluator.printType(destType.details.boundType),
                    name: types_1.TypeVarType.getReadableName(destType),
                }));
            }
            return false;
        }
    }
    // Update the tuple types based on the new type bounds. We need to
    // switch to an unbounded tuple type since the length of the resulting
    // tuple is indeterminate.
    let newTupleTypes = curEntry === null || curEntry === void 0 ? void 0 : curEntry.tupleTypes;
    if (newTupleTypes) {
        const updatedType = newNarrowTypeBound !== null && newNarrowTypeBound !== void 0 ? newNarrowTypeBound : newWideTypeBound;
        if (updatedType) {
            newTupleTypes = [{ type: updatedType, isUnbounded: true }];
        }
    }
    if (!typeVarContext.isLocked() && isTypeVarInScope) {
        updateTypeVarType(evaluator, typeVarContext, destType, newNarrowTypeBound, newWideTypeBound, newTupleTypes, (flags & (2048 /* AssignTypeFlags.PopulatingExpectedType */ | 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */)) !== 0);
    }
    if (logTypeVarContextUpdates) {
        const indent = ' '.repeat(recursionCount * 2);
        console.log(`${indent}`);
        console.log(`${indent}post-call context #${typeVarContext.getId()}: `);
        logTypeVarContext(evaluator, typeVarContext, indent);
    }
    return true;
}
exports.assignTypeToTypeVar = assignTypeToTypeVar;
// Updates the narrow and wide type bounds for a type variable. It also calculates the
// narrowTypeBoundNoLiterals, which is a variant of the narrow type bound that has
// literals stripped. By default, the constraint solver always uses the "no literals"
// type in its solutions unless the version with literals is required to satisfy
// the wide type bound.
function updateTypeVarType(evaluator, typeVarContext, destType, narrowTypeBound, wideTypeBound, tupleTypes = undefined, forceRetainLiterals = false) {
    let narrowTypeBoundNoLiterals;
    if (narrowTypeBound && !forceRetainLiterals) {
        const strippedLiteral = (0, types_1.isVariadicTypeVar)(destType)
            ? stripLiteralValueForUnpackedTuple(evaluator, narrowTypeBound)
            : evaluator.stripLiteralValue(narrowTypeBound);
        // Strip the literals from the narrow type bound and see if it is still
        // narrower than the wide bound.
        if (strippedLiteral !== narrowTypeBound) {
            if (!wideTypeBound || evaluator.assignType(wideTypeBound, strippedLiteral)) {
                narrowTypeBoundNoLiterals = strippedLiteral;
            }
        }
    }
    typeVarContext.setTypeVarType(destType, narrowTypeBound, narrowTypeBoundNoLiterals, wideTypeBound, tupleTypes);
}
exports.updateTypeVarType = updateTypeVarType;
function assignTypeToConstrainedTypeVar(evaluator, destType, srcType, diag, typeVarContext, flags, isTypeVarInScope, recursionCount) {
    let constrainedType;
    const concreteSrcType = evaluator.makeTopLevelTypeVarsConcrete(srcType);
    const curEntry = typeVarContext.getPrimarySignature().getTypeVar(destType);
    const curWideTypeBound = curEntry === null || curEntry === void 0 ? void 0 : curEntry.wideBound;
    const curNarrowTypeBound = curEntry === null || curEntry === void 0 ? void 0 : curEntry.narrowBound;
    let forceRetainLiterals = false;
    if ((0, types_1.isTypeVar)(srcType)) {
        if (evaluator.assignType(destType, concreteSrcType, 
        /* diag */ undefined, new typeVarContext_1.TypeVarContext(destType.scopeId), 
        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
            constrainedType = srcType;
            // If the source and dest are both instantiables (type[T]), then
            // we need to convert to an instance (T).
            if (types_1.TypeBase.isInstantiable(srcType)) {
                constrainedType = (0, typeUtils_1.convertToInstance)(srcType, /* includeSubclasses */ false);
            }
        }
    }
    else {
        let isCompatible = true;
        // Subtypes that are not conditionally dependent on the dest type var
        // must all map to the same constraint. For example, Union[str, bytes]
        // cannot be assigned to AnyStr.
        let unconditionalConstraintIndex;
        // Find the narrowest constrained type that is compatible.
        constrainedType = (0, typeUtils_1.mapSubtypes)(concreteSrcType, (srcSubtype) => {
            let constrainedSubtype;
            if ((0, types_1.isAnyOrUnknown)(srcSubtype)) {
                return srcSubtype;
            }
            let constraintIndexUsed;
            destType.details.constraints.forEach((constraint, i) => {
                const adjustedConstraint = types_1.TypeBase.isInstantiable(destType)
                    ? (0, typeUtils_1.convertToInstantiable)(constraint)
                    : constraint;
                if (evaluator.assignType(adjustedConstraint, srcSubtype, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
                    if (!constrainedSubtype ||
                        evaluator.assignType(types_1.TypeBase.isInstantiable(destType)
                            ? (0, typeUtils_1.convertToInstantiable)(constrainedSubtype)
                            : constrainedSubtype, adjustedConstraint, 
                        /* diag */ undefined, 
                        /* destTypeVarContext */ undefined, 
                        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
                        constrainedSubtype = (0, typeUtils_1.addConditionToType)(constraint, (0, typeUtils_1.getTypeCondition)(srcSubtype));
                        constraintIndexUsed = i;
                    }
                }
            });
            if (!constrainedSubtype) {
                // We found a source subtype that is not compatible with the dest.
                // This is OK if we're handling the contravariant case because only
                // one subtype needs to be assignable in that case.
                if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0) {
                    isCompatible = false;
                }
            }
            // If this subtype isn't conditional, make sure it maps to the same
            // constraint index as previous unconditional subtypes.
            if (constraintIndexUsed !== undefined && !(0, typeUtils_1.getTypeCondition)(srcSubtype)) {
                if (unconditionalConstraintIndex !== undefined &&
                    unconditionalConstraintIndex !== constraintIndexUsed) {
                    isCompatible = false;
                }
                unconditionalConstraintIndex = constraintIndexUsed;
            }
            return constrainedSubtype;
        });
        if ((0, types_1.isNever)(constrainedType) || !isCompatible) {
            constrainedType = undefined;
        }
        // If the type is a union, see if the entire union is assignable to one
        // of the constraints.
        if (!constrainedType && (0, types_1.isUnion)(concreteSrcType)) {
            constrainedType = destType.details.constraints.find((constraint) => {
                const adjustedConstraint = types_1.TypeBase.isInstantiable(destType)
                    ? (0, typeUtils_1.convertToInstantiable)(constraint)
                    : constraint;
                return evaluator.assignType(adjustedConstraint, concreteSrcType, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount);
            });
        }
    }
    // If there was no constrained type that was assignable
    // or there were multiple types that were assignable and they
    // are not conditional, it's an error.
    if (!constrainedType) {
        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeConstrainedTypeVar().format({
            type: evaluator.printType(srcType),
            name: destType.details.name,
        }));
        return false;
    }
    else if ((0, typeUtils_1.isLiteralTypeOrUnion)(constrainedType)) {
        forceRetainLiterals = true;
    }
    if (curNarrowTypeBound && !(0, types_1.isAnyOrUnknown)(curNarrowTypeBound)) {
        if (!evaluator.assignType(curNarrowTypeBound, constrainedType, 
        /* diag */ undefined, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
            // Handle the case where one of the constrained types is a wider
            // version of another constrained type that was previously assigned
            // to the type variable.
            if (evaluator.assignType(constrainedType, curNarrowTypeBound, 
            /* diag */ undefined, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
                if (!typeVarContext.isLocked() && isTypeVarInScope) {
                    updateTypeVarType(evaluator, typeVarContext, destType, constrainedType, curWideTypeBound);
                }
            }
            else {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeConstrainedTypeVar().format({
                    type: evaluator.printType(constrainedType),
                    name: evaluator.printType(curNarrowTypeBound),
                }));
                return false;
            }
        }
    }
    else {
        // Assign the type to the type var.
        if (!typeVarContext.isLocked() && isTypeVarInScope) {
            updateTypeVarType(evaluator, typeVarContext, destType, constrainedType, curWideTypeBound, 
            /* tupleTypes */ undefined, forceRetainLiterals);
        }
    }
    return true;
}
function assignTypeToParamSpec(evaluator, destType, srcType, diag, typeVarContext, recursionCount = 0) {
    let isAssignable = true;
    typeVarContext.doForEachSignature((signatureContext) => {
        if ((0, types_1.isTypeVar)(srcType) && srcType.details.isParamSpec) {
            const existingType = signatureContext.getParamSpecType(destType);
            if (existingType) {
                if (existingType.details.parameters.length === 0 && existingType.details.paramSpec) {
                    // If there's an existing entry that matches, that's fine.
                    if ((0, types_1.isTypeSame)(existingType.details.paramSpec, srcType, {}, recursionCount)) {
                        return;
                    }
                }
            }
            else {
                if (!typeVarContext.isLocked() && typeVarContext.hasSolveForScope(destType.scopeId)) {
                    signatureContext.setTypeVarType(destType, (0, typeUtils_1.convertTypeToParamSpecValue)(srcType));
                }
                return;
            }
        }
        else if ((0, types_1.isFunction)(srcType)) {
            const functionSrcType = srcType;
            const parameters = srcType.details.parameters.map((p, index) => {
                const param = {
                    category: p.category,
                    name: p.name,
                    isNameSynthesized: p.isNameSynthesized,
                    hasDefault: !!p.hasDefault,
                    defaultValueExpression: p.defaultValueExpression,
                    hasDeclaredType: p.hasDeclaredType,
                    type: types_1.FunctionType.getEffectiveParameterType(functionSrcType, index),
                };
                return param;
            });
            const newFunction = types_1.FunctionType.createInstance('', '', '', srcType.details.flags | 65536 /* FunctionTypeFlags.ParamSpecValue */);
            parameters.forEach((param) => {
                types_1.FunctionType.addParameter(newFunction, param);
            });
            newFunction.details.typeVarScopeId = srcType.details.typeVarScopeId;
            newFunction.details.constructorTypeVarScopeId = srcType.details.constructorTypeVarScopeId;
            types_1.FunctionType.addHigherOrderTypeVarScopeIds(newFunction, srcType.details.higherOrderTypeVarScopeIds);
            newFunction.details.docString = srcType.details.docString;
            newFunction.details.deprecatedMessage = srcType.details.deprecatedMessage;
            newFunction.details.paramSpec = srcType.details.paramSpec;
            newFunction.details.methodClass = srcType.details.methodClass;
            let updateContextWithNewFunction = false;
            const existingType = signatureContext.getParamSpecType(destType);
            if (existingType) {
                // Convert the remaining portion of the signature to a function
                // for comparison purposes.
                const existingFunction = (0, typeUtils_1.convertParamSpecValueToType)(existingType);
                const isNewNarrower = evaluator.assignType(existingFunction, newFunction, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */, recursionCount);
                const isNewWider = evaluator.assignType(newFunction, existingFunction, 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */, recursionCount);
                // Should we widen the type?
                if (isNewNarrower && isNewWider) {
                    // The new type is both a supertype and a subtype of the existing type.
                    // That means the two types are the same or one (or both) have the type
                    // "..." (which is the ParamSpec equivalent of "Any"). If only one has
                    // the type "...", we'll prefer the other one. This is analogous to
                    // what we do with regular TypeVars, where we prefer non-Any values.
                    if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(newFunction)) {
                        updateContextWithNewFunction = true;
                    }
                    else {
                        return;
                    }
                }
                else if (isNewWider) {
                    updateContextWithNewFunction = true;
                }
                else if (isNewNarrower) {
                    // The existing function is already narrower than the new function, so
                    // no need to narrow it further.
                    return;
                }
            }
            else {
                updateContextWithNewFunction = true;
            }
            if (updateContextWithNewFunction) {
                if (!typeVarContext.isLocked() && typeVarContext.hasSolveForScope(destType.scopeId)) {
                    signatureContext.setTypeVarType(destType, newFunction);
                }
                return;
            }
        }
        else if ((0, types_1.isAnyOrUnknown)(srcType)) {
            return;
        }
        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeParamSpec().format({
            type: evaluator.printType(srcType),
            name: destType.details.name,
        }));
        isAssignable = false;
    });
    if (logTypeVarContextUpdates) {
        const indent = ' '.repeat(recursionCount * 2);
        console.log(`${indent}`);
        console.log(`${indent}post-call typeVarContext: `);
        logTypeVarContext(evaluator, typeVarContext, indent);
    }
    return isAssignable;
}
// In cases where the expected type is a specialized base class of the
// source type, we need to determine which type arguments in the derived
// class will make it compatible with the specialized base class. This method
// performs this reverse mapping of type arguments and populates the type var
// map for the target type. If the type is not assignable to the expected type,
// it returns false.
function populateTypeVarContextBasedOnExpectedType(evaluator, type, expectedType, typeVarContext, liveTypeVarScopes, usageOffset = undefined) {
    if ((0, types_1.isAny)(expectedType)) {
        type.details.typeParameters.forEach((typeParam) => {
            updateTypeVarType(evaluator, typeVarContext, typeParam, expectedType, expectedType);
        });
        return true;
    }
    if ((0, types_1.isTypeVar)(expectedType) && expectedType.details.isSynthesizedSelf && expectedType.details.boundType) {
        expectedType = expectedType.details.boundType;
    }
    if (!(0, types_1.isClass)(expectedType)) {
        return false;
    }
    // If the expected type is generic (but not specialized), we can't proceed.
    const expectedTypeArgs = expectedType.typeArguments;
    if (!expectedTypeArgs) {
        return evaluator.assignType(type, expectedType, 
        /* diag */ undefined, typeVarContext, 
        /* srcTypeVarContext */ undefined, 2048 /* AssignTypeFlags.PopulatingExpectedType */);
    }
    evaluator.inferTypeParameterVarianceForClass(type);
    // If the expected type is the same as the target type (commonly the case),
    // we can use a faster method.
    if (types_1.ClassType.isSameGenericClass(expectedType, type)) {
        const sameClassTypeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(expectedType);
        sameClassTypeVarContext
            .getPrimarySignature()
            .getTypeVars()
            .forEach((entry) => {
            let typeArgValue = sameClassTypeVarContext.getPrimarySignature().getTypeVarType(entry.typeVar);
            if (typeArgValue && liveTypeVarScopes) {
                typeArgValue = (0, typeUtils_1.transformExpectedType)(typeArgValue, liveTypeVarScopes, usageOffset);
            }
            if (typeArgValue) {
                const variance = types_1.TypeVarType.getVariance(entry.typeVar);
                updateTypeVarType(evaluator, typeVarContext, entry.typeVar, variance === 3 /* Variance.Covariant */ ? undefined : typeArgValue, variance === 4 /* Variance.Contravariant */ ? undefined : typeArgValue);
                if (entry.tupleTypes) {
                    typeVarContext.setTupleTypeVar(entry.typeVar, entry.tupleTypes.map((tupleEntry) => {
                        let tupleType = tupleEntry.type;
                        if (liveTypeVarScopes) {
                            tupleType = (0, typeUtils_1.transformExpectedType)(tupleEntry.type, liveTypeVarScopes, usageOffset);
                        }
                        return {
                            type: tupleType,
                            isUnbounded: tupleEntry.isUnbounded,
                            isOptional: tupleEntry.isOptional,
                        };
                    }));
                }
            }
        });
        return true;
    }
    // Create a generic version of the expected type.
    const expectedTypeScopeId = (0, typeUtils_1.getTypeVarScopeId)(expectedType);
    const synthExpectedTypeArgs = types_1.ClassType.getTypeParameters(expectedType).map((typeParam, index) => {
        const typeVar = types_1.TypeVarType.createInstance(`__dest${index}`);
        typeVar.details.isSynthesized = true;
        if (typeParam.details.isParamSpec) {
            typeVar.details.isParamSpec = true;
        }
        // Use invariance here so we set the narrow and wide values on the TypeVar.
        typeVar.details.declaredVariance = 2 /* Variance.Invariant */;
        typeVar.scopeId = expectedTypeScopeId;
        return typeVar;
    });
    const genericExpectedType = types_1.ClassType.cloneForSpecialization(expectedType, synthExpectedTypeArgs, 
    /* isTypeArgumentExplicit */ true);
    // For each type param in the target type, create a placeholder type variable.
    const typeArgs = types_1.ClassType.getTypeParameters(type).map((typeParam, index) => {
        const typeVar = types_1.TypeVarType.createInstance(`__source${index}`);
        typeVar.details.isSynthesized = true;
        typeVar.details.synthesizedIndex = index;
        typeVar.details.isExemptFromBoundCheck = true;
        if (typeParam.details.isParamSpec) {
            typeVar.details.isParamSpec = true;
        }
        return types_1.TypeVarType.cloneAsInScopePlaceholder(typeVar);
    });
    const specializedType = types_1.ClassType.cloneForSpecialization(type, typeArgs, /* isTypeArgumentExplicit */ true);
    const syntheticTypeVarContext = new typeVarContext_1.TypeVarContext(expectedTypeScopeId);
    if (evaluator.assignType(genericExpectedType, specializedType, 
    /* diag */ undefined, syntheticTypeVarContext, 
    /* srcTypeVarContext */ undefined, 2048 /* AssignTypeFlags.PopulatingExpectedType */)) {
        let isResultValid = true;
        synthExpectedTypeArgs.forEach((typeVar, index) => {
            let synthTypeVar = syntheticTypeVarContext.getPrimarySignature().getTypeVarType(typeVar);
            const otherSubtypes = [];
            // If the resulting type is a union, try to find a matching type var and move
            // the remaining subtypes to the "otherSubtypes" array.
            if (synthTypeVar) {
                if (typeVar.details.isParamSpec && (0, types_1.isFunction)(synthTypeVar)) {
                    synthTypeVar = (0, typeUtils_1.convertParamSpecValueToType)(synthTypeVar);
                }
                if ((0, types_1.isUnion)(synthTypeVar)) {
                    let foundSynthTypeVar;
                    (0, typeUtils_1.sortTypes)(synthTypeVar.subtypes).forEach((subtype) => {
                        if ((0, types_1.isTypeVar)(subtype) &&
                            subtype.details.isSynthesized &&
                            subtype.details.synthesizedIndex !== undefined &&
                            !foundSynthTypeVar) {
                            foundSynthTypeVar = subtype;
                        }
                        else {
                            otherSubtypes.push(subtype);
                        }
                    });
                    if (foundSynthTypeVar) {
                        synthTypeVar = foundSynthTypeVar;
                    }
                }
            }
            // Is this one of the synthesized type vars we allocated above? If so,
            // the type arg that corresponds to this type var maps back to the target type.
            if (synthTypeVar &&
                (0, types_1.isTypeVar)(synthTypeVar) &&
                synthTypeVar.details.isSynthesized &&
                synthTypeVar.details.synthesizedIndex !== undefined) {
                const targetTypeVar = types_1.ClassType.getTypeParameters(specializedType)[synthTypeVar.details.synthesizedIndex];
                if (index < expectedTypeArgs.length) {
                    let typeArgValue = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(expectedTypeArgs[index]);
                    if (otherSubtypes.length > 0) {
                        typeArgValue = (0, types_1.combineTypes)([typeArgValue, ...otherSubtypes]);
                    }
                    if (liveTypeVarScopes) {
                        typeArgValue = (0, typeUtils_1.transformExpectedType)(typeArgValue, liveTypeVarScopes, usageOffset);
                    }
                    if (typeArgValue) {
                        const variance = types_1.TypeVarType.getVariance(typeVar);
                        // If this type variable already has a type, don't overwrite it. This can
                        // happen if a single type variable in the derived class is used multiple times
                        // in the specialized base class type (e.g. Mapping[T, T]).
                        if (typeVarContext.getPrimarySignature().getTypeVarType(targetTypeVar)) {
                            isResultValid = false;
                            typeArgValue = types_1.UnknownType.create();
                        }
                        updateTypeVarType(evaluator, typeVarContext, targetTypeVar, variance === 3 /* Variance.Covariant */ ? undefined : typeArgValue, variance === 4 /* Variance.Contravariant */ ? undefined : typeArgValue);
                    }
                    else {
                        isResultValid = false;
                    }
                }
            }
        });
        return isResultValid;
    }
    return false;
}
exports.populateTypeVarContextBasedOnExpectedType = populateTypeVarContextBasedOnExpectedType;
// For normal TypeVars, the constraint solver can widen a type by combining
// two otherwise incompatible types into a union. For TypeVarTuples, we need
// to do the equivalent operation for unpacked tuples.
function widenTypeForVariadicTypeVar(evaluator, type1, type2) {
    // The typing spec indicates that the type should always be "exactly
    // the same type" if a TypeVarTuple is used in multiple locations.
    // This is problematic for a number of reasons, but in the interest
    // of sticking to the spec, we'll enforce that here.
    // If the two types are not unpacked tuples, we can't combine them.
    if (!(0, types_1.isUnpackedClass)(type1) || !(0, types_1.isUnpackedClass)(type2)) {
        return undefined;
    }
    // If the two unpacked tuples are not the same length, we can't combine them.
    if (!type1.tupleTypeArguments ||
        !type2.tupleTypeArguments ||
        type1.tupleTypeArguments.length !== type2.tupleTypeArguments.length) {
        return undefined;
    }
    const strippedType1 = stripLiteralValueForUnpackedTuple(evaluator, type1);
    const strippedType2 = stripLiteralValueForUnpackedTuple(evaluator, type2);
    if ((0, types_1.isTypeSame)(strippedType1, strippedType2)) {
        return strippedType1;
    }
    return undefined;
}
// If the provided type is an unpacked tuple, this function strips the
// literals from types of the corresponding elements.
function stripLiteralValueForUnpackedTuple(evaluator, type) {
    if (!(0, types_1.isUnpackedClass)(type) || !type.tupleTypeArguments) {
        return type;
    }
    let strippedLiteral = false;
    const tupleTypeArgs = type.tupleTypeArguments.map((arg) => {
        const strippedType = evaluator.stripLiteralValue(arg.type);
        if (strippedType !== arg.type) {
            strippedLiteral = true;
        }
        return {
            isUnbounded: arg.isUnbounded,
            isOptional: arg.isOptional,
            type: strippedType,
        };
    });
    if (!strippedLiteral) {
        return type;
    }
    return (0, typeUtils_1.specializeTupleClass)(type, tupleTypeArgs, /* isTypeArgumentExplicit */ true, /* isUnpackedTuple */ true);
}
// This function is used for debugging only. It dumps the current contents of
// the TypeVarContext to the console.
function logTypeVarContext(evaluator, typeVarContext, indent) {
    const signatureContextCount = typeVarContext.getSignatureContexts().length;
    if (signatureContextCount === 0) {
        console.log(`${indent}  no signatures`);
    }
    else if (signatureContextCount === 1) {
        logTypeVarSignatureContext(evaluator, typeVarContext.getSignatureContexts()[0], `${indent}  `);
    }
    else {
        typeVarContext.doForEachSignatureContext((context, signatureIndex) => {
            console.log(`${indent}  signature ${signatureIndex}`);
            logTypeVarSignatureContext(evaluator, context, `${indent}    `);
        });
    }
}
function logTypeVarSignatureContext(evaluator, context, indent) {
    let loggedConstraint = false;
    context.getTypeVars().forEach((entry) => {
        var _a;
        const typeVarName = `${indent}${entry.typeVar.details.name}`;
        const narrowBound = (_a = entry.narrowBoundNoLiterals) !== null && _a !== void 0 ? _a : entry.narrowBound;
        const wideBound = entry.wideBound;
        // Log the narrow and wide bounds.
        if (narrowBound && wideBound && (0, types_1.isTypeSame)(narrowBound, wideBound)) {
            console.log(`${typeVarName} = ${evaluator.printType(narrowBound)}`);
            loggedConstraint = true;
        }
        else {
            if (narrowBound) {
                console.log(`${typeVarName} ≤ ${evaluator.printType(narrowBound)}`);
                loggedConstraint = true;
            }
            if (wideBound) {
                console.log(`${typeVarName} ≥ ${evaluator.printType(wideBound)}`);
                loggedConstraint = true;
            }
        }
    });
    if (!loggedConstraint) {
        console.log(`${indent}no constraints`);
    }
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/constructorTransform.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/analyzer/constructorTransform.ts ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * constructorTransform.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Code that transforms a newly-created object after a call to the
 * constructor is evaluated. It allows for special-case behavior that
 * cannot otherwise be described in the Python type system.
 *
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.applyConstructorTransform = exports.hasConstructorTransform = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const constructors_1 = __webpack_require__(/*! ./constructors */ "../pyright-internal/src/analyzer/constructors.ts");
const parameterUtils_1 = __webpack_require__(/*! ./parameterUtils */ "../pyright-internal/src/analyzer/parameterUtils.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
function hasConstructorTransform(classType) {
    if (classType.details.fullName === 'functools.partial') {
        return true;
    }
    return false;
}
exports.hasConstructorTransform = hasConstructorTransform;
function applyConstructorTransform(evaluator, errorNode, argList, classType, result) {
    if (classType.details.fullName === 'functools.partial') {
        return applyPartialTransform(evaluator, errorNode, argList, result);
    }
    // By default, return the result unmodified.
    return result;
}
exports.applyConstructorTransform = applyConstructorTransform;
// Applies a transform for the functools.partial class constructor.
function applyPartialTransform(evaluator, errorNode, argList, result) {
    // We assume that the normal return result is a functools.partial class instance.
    if (!(0, types_1.isClassInstance)(result.returnType) || result.returnType.details.fullName !== 'functools.partial') {
        return result;
    }
    const callMemberResult = (0, typeUtils_1.lookUpObjectMember)(result.returnType, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
    if (!callMemberResult || !(0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(callMemberResult.classType), result.returnType)) {
        return result;
    }
    const callMemberType = evaluator.getTypeOfMember(callMemberResult);
    if (!(0, types_1.isFunction)(callMemberType) || callMemberType.details.parameters.length < 1) {
        return result;
    }
    if (argList.length < 1) {
        return result;
    }
    const origFunctionTypeResult = evaluator.getTypeOfArgument(argList[0]);
    let origFunctionType = origFunctionTypeResult.type;
    const origFunctionTypeConcrete = evaluator.makeTopLevelTypeVarsConcrete(origFunctionType);
    if ((0, types_1.isInstantiableClass)(origFunctionTypeConcrete)) {
        const constructor = (0, constructors_1.createFunctionFromConstructor)(evaluator, origFunctionTypeConcrete, (0, types_1.isTypeVar)(origFunctionType) ? (0, typeUtils_1.convertToInstance)(origFunctionType) : undefined);
        if (constructor) {
            origFunctionType = constructor;
        }
    }
    // Evaluate the inferred return type if necessary.
    evaluator.inferReturnTypeIfNecessary(origFunctionType);
    // We don't currently handle unpacked arguments.
    if (argList.some((arg) => arg.argumentCategory !== 0 /* ArgumentCategory.Simple */)) {
        return result;
    }
    // Make sure the first argument is a simple function.
    if ((0, types_1.isFunction)(origFunctionType)) {
        const transformResult = applyPartialTransformToFunction(evaluator, errorNode, argList, callMemberType, origFunctionType);
        if (!transformResult) {
            return result;
        }
        // Create a new copy of the functools.partial class that overrides the __call__ method.
        const newPartialClass = types_1.ClassType.cloneForSymbolTableUpdate(result.returnType);
        types_1.ClassType.getSymbolTable(newPartialClass).set('__call__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, transformResult.returnType));
        return {
            returnType: newPartialClass,
            isTypeIncomplete: result.isTypeIncomplete,
            argumentErrors: transformResult.argumentErrors,
        };
    }
    if ((0, types_1.isOverloadedFunction)(origFunctionType)) {
        const applicableOverloads = [];
        let sawArgErrors = false;
        // Apply the partial transform to each of the functions in the overload.
        types_1.OverloadedFunctionType.getOverloads(origFunctionType).forEach((overload) => {
            // Apply the transform to this overload, but don't report errors.
            const transformResult = applyPartialTransformToFunction(evaluator, 
            /* errorNode */ undefined, argList, callMemberType, overload);
            if (transformResult) {
                if (transformResult.argumentErrors) {
                    sawArgErrors = true;
                }
                else if ((0, types_1.isFunction)(transformResult.returnType)) {
                    applicableOverloads.push(transformResult.returnType);
                }
            }
        });
        if (applicableOverloads.length === 0) {
            if (sawArgErrors) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.noOverload().format({
                    name: origFunctionType.overloads[0].details.name,
                }), errorNode);
            }
            return result;
        }
        // Create a new copy of the functools.partial class that overrides the __call__ method.
        const newPartialClass = types_1.ClassType.cloneForSymbolTableUpdate(result.returnType);
        let synthesizedCallType;
        if (applicableOverloads.length === 1) {
            synthesizedCallType = applicableOverloads[0];
        }
        else {
            synthesizedCallType = types_1.OverloadedFunctionType.create(
            // Set the "overloaded" flag for each of the __call__ overloads.
            applicableOverloads.map((overload) => types_1.FunctionType.cloneWithNewFlags(overload, overload.details.flags | 256 /* FunctionTypeFlags.Overloaded */)));
        }
        types_1.ClassType.getSymbolTable(newPartialClass).set('__call__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, synthesizedCallType));
        return {
            returnType: newPartialClass,
            isTypeIncomplete: result.isTypeIncomplete,
            argumentErrors: false,
        };
    }
    return result;
}
function applyPartialTransformToFunction(evaluator, errorNode, argList, partialCallMemberType, origFunctionType) {
    // Create a map to track which parameters have supplied arguments.
    const paramMap = new Map();
    const paramListDetails = (0, parameterUtils_1.getParameterListDetails)(origFunctionType);
    // Verify the types of the provided arguments.
    let argumentErrors = false;
    let reportedPositionalError = false;
    const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(origFunctionType));
    const remainingArgsList = argList.slice(1);
    remainingArgsList.forEach((arg, argIndex) => {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        if (!arg.valueExpression) {
            return;
        }
        // Is it a positional argument or a keyword argument?
        if (!arg.name) {
            // Does this positional argument map to a positional parameter?
            if (argIndex >= paramListDetails.params.length ||
                paramListDetails.params[argIndex].source === parameterUtils_1.ParameterSource.KeywordOnly) {
                if (paramListDetails.argsIndex !== undefined) {
                    const paramType = types_1.FunctionType.getEffectiveParameterType(origFunctionType, paramListDetails.params[paramListDetails.argsIndex].index);
                    const diag = new diagnostic_1.DiagnosticAddendum();
                    const argTypeResult = evaluator.getTypeOfExpression(arg.valueExpression, 
                    /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(paramType));
                    if (!evaluator.assignType(paramType, argTypeResult.type, diag, typeVarContext)) {
                        if (errorNode) {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.argAssignmentParamFunction().format({
                                argType: evaluator.printType(argTypeResult.type),
                                paramType: evaluator.printType(paramType),
                                functionName: origFunctionType.details.name,
                                paramName: (_a = paramListDetails.params[paramListDetails.argsIndex].param.name) !== null && _a !== void 0 ? _a : '',
                            }), (_b = arg.valueExpression) !== null && _b !== void 0 ? _b : errorNode);
                        }
                        argumentErrors = true;
                    }
                }
                else {
                    // Don't report multiple positional errors.
                    if (!reportedPositionalError) {
                        if (errorNode) {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, paramListDetails.positionParamCount === 1
                                ? localize_1.LocMessage.argPositionalExpectedOne()
                                : localize_1.LocMessage.argPositionalExpectedCount().format({
                                    expected: paramListDetails.positionParamCount,
                                }), (_c = arg.valueExpression) !== null && _c !== void 0 ? _c : errorNode);
                        }
                    }
                    reportedPositionalError = true;
                    argumentErrors = true;
                }
            }
            else {
                const paramType = types_1.FunctionType.getEffectiveParameterType(origFunctionType, argIndex);
                const diag = new diagnostic_1.DiagnosticAddendum();
                const paramName = (_d = paramListDetails.params[argIndex].param.name) !== null && _d !== void 0 ? _d : '';
                const argTypeResult = evaluator.getTypeOfExpression(arg.valueExpression, 
                /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(paramType));
                if (!evaluator.assignType(paramType, argTypeResult.type, diag, typeVarContext)) {
                    if (errorNode) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.argAssignmentParamFunction().format({
                            argType: evaluator.printType(argTypeResult.type),
                            paramType: evaluator.printType(paramType),
                            functionName: origFunctionType.details.name,
                            paramName,
                        }), (_e = arg.valueExpression) !== null && _e !== void 0 ? _e : errorNode);
                    }
                    argumentErrors = true;
                }
                // Mark the parameter as assigned.
                paramMap.set(paramName, false);
            }
        }
        else {
            const matchingParam = paramListDetails.params.find((paramInfo) => { var _a; return paramInfo.param.name === ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) && paramInfo.source !== parameterUtils_1.ParameterSource.PositionOnly; });
            if (!matchingParam) {
                // Is there a kwargs parameter?
                if (paramListDetails.kwargsIndex === undefined) {
                    if (errorNode) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramNameMissing().format({ name: arg.name.value }), arg.name);
                    }
                    argumentErrors = true;
                }
                else {
                    const paramType = types_1.FunctionType.getEffectiveParameterType(origFunctionType, paramListDetails.params[paramListDetails.kwargsIndex].index);
                    const diag = new diagnostic_1.DiagnosticAddendum();
                    const argTypeResult = evaluator.getTypeOfExpression(arg.valueExpression, 
                    /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(paramType));
                    if (!evaluator.assignType(paramType, argTypeResult.type, diag, typeVarContext)) {
                        if (errorNode) {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.argAssignmentParamFunction().format({
                                argType: evaluator.printType(argTypeResult.type),
                                paramType: evaluator.printType(paramType),
                                functionName: origFunctionType.details.name,
                                paramName: (_f = paramListDetails.params[paramListDetails.kwargsIndex].param.name) !== null && _f !== void 0 ? _f : '',
                            }), (_g = arg.valueExpression) !== null && _g !== void 0 ? _g : errorNode);
                        }
                        argumentErrors = true;
                    }
                }
            }
            else {
                const paramName = matchingParam.param.name;
                const paramType = types_1.FunctionType.getEffectiveParameterType(origFunctionType, matchingParam.index);
                if (paramMap.has(paramName)) {
                    if (errorNode) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramAlreadyAssigned().format({ name: arg.name.value }), arg.name);
                    }
                    argumentErrors = true;
                }
                else {
                    const diag = new diagnostic_1.DiagnosticAddendum();
                    const argTypeResult = evaluator.getTypeOfExpression(arg.valueExpression, 
                    /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(paramType));
                    if (!evaluator.assignType(paramType, argTypeResult.type, diag, typeVarContext)) {
                        if (errorNode) {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.argAssignmentParamFunction().format({
                                argType: evaluator.printType(argTypeResult.type),
                                paramType: evaluator.printType(paramType),
                                functionName: origFunctionType.details.name,
                                paramName,
                            }), (_h = arg.valueExpression) !== null && _h !== void 0 ? _h : errorNode);
                        }
                        argumentErrors = true;
                    }
                    paramMap.set(paramName, true);
                }
            }
        }
    });
    const specializedFunctionType = (0, typeUtils_1.applySolvedTypeVars)(origFunctionType, typeVarContext);
    if (!(0, types_1.isFunction)(specializedFunctionType)) {
        return undefined;
    }
    // Create a new parameter list that omits parameters that have been
    // populated already.
    const updatedParamList = specializedFunctionType.details.parameters.map((param, index) => {
        const specializedParam = { ...param };
        specializedParam.type = types_1.FunctionType.getEffectiveParameterType(specializedFunctionType, index);
        // If it's a keyword parameter that has been assigned a value through
        // the "partial" mechanism, mark it has having a default value.
        if (param.name && paramMap.get(param.name)) {
            specializedParam.hasDefault = true;
        }
        return specializedParam;
    });
    const unassignedParamList = updatedParamList.filter((param) => {
        if (param.category === 2 /* ParameterCategory.KwargsDict */) {
            return false;
        }
        if (param.category === 1 /* ParameterCategory.ArgsList */) {
            return true;
        }
        return !param.name || !paramMap.has(param.name);
    });
    const assignedKeywordParamList = updatedParamList.filter((param) => {
        return param.name && paramMap.get(param.name);
    });
    const kwargsParam = updatedParamList.filter((param) => {
        return param.category === 2 /* ParameterCategory.KwargsDict */;
    });
    const newParamList = [];
    (0, collectionUtils_1.appendArray)(newParamList, unassignedParamList);
    (0, collectionUtils_1.appendArray)(newParamList, assignedKeywordParamList);
    (0, collectionUtils_1.appendArray)(newParamList, kwargsParam);
    // Create a new __call__ method that uses the remaining parameters.
    const newCallMemberType = types_1.FunctionType.createInstance(partialCallMemberType.details.name, partialCallMemberType.details.fullName, partialCallMemberType.details.moduleName, partialCallMemberType.details.flags, specializedFunctionType.details.docString);
    if (partialCallMemberType.details.parameters.length > 0) {
        types_1.FunctionType.addParameter(newCallMemberType, partialCallMemberType.details.parameters[0]);
    }
    newParamList.forEach((param) => {
        types_1.FunctionType.addParameter(newCallMemberType, param);
    });
    newCallMemberType.details.declaredReturnType = specializedFunctionType.details.declaredReturnType
        ? types_1.FunctionType.getSpecializedReturnType(specializedFunctionType)
        : specializedFunctionType.inferredReturnType;
    newCallMemberType.details.declaration = partialCallMemberType.details.declaration;
    newCallMemberType.details.typeVarScopeId = specializedFunctionType.details.typeVarScopeId;
    return { returnType: newCallMemberType, isTypeIncomplete: false, argumentErrors };
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/constructors.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/constructors.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * constructors.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides type evaluation logic for constructors. A constructor
 * in Python is implemented by a `__call__` method on the metaclass,
 * which is typically the `type` class. The default implementation
 * calls the `__new__` method on the class to allocate the object.
 * If the resulting object is an instance of the class, it then calls
 * the `__init__` method on the resulting object with the same arguments.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFunctionFromConstructor = exports.validateConstructorArguments = exports.getBoundCallMethod = exports.getBoundInitMethod = exports.getBoundNewMethod = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const constraintSolver_1 = __webpack_require__(/*! ./constraintSolver */ "../pyright-internal/src/analyzer/constraintSolver.ts");
const constructorTransform_1 = __webpack_require__(/*! ./constructorTransform */ "../pyright-internal/src/analyzer/constructorTransform.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// Fetches and binds the __new__ method from a class.
function getBoundNewMethod(evaluator, errorNode, type, diag = undefined, additionalFlags = 4 /* MemberAccessFlags.SkipObjectBaseClass */) {
    const flags = 32 /* MemberAccessFlags.SkipClassMembers */ |
        512 /* MemberAccessFlags.SkipAttributeAccessOverride */ |
        256 /* MemberAccessFlags.TreatConstructorAsClassMethod */ |
        additionalFlags;
    return evaluator.getTypeOfBoundMember(errorNode, type, '__new__', { method: 'get' }, diag, flags);
}
exports.getBoundNewMethod = getBoundNewMethod;
// Fetches and binds the __init__ method from a class instance.
function getBoundInitMethod(evaluator, errorNode, type, diag = undefined, additionalFlags = 4 /* MemberAccessFlags.SkipObjectBaseClass */) {
    const flags = 16 /* MemberAccessFlags.SkipInstanceMembers */ | 512 /* MemberAccessFlags.SkipAttributeAccessOverride */ | additionalFlags;
    return evaluator.getTypeOfBoundMember(errorNode, type, '__init__', { method: 'get' }, diag, flags);
}
exports.getBoundInitMethod = getBoundInitMethod;
// Fetches and binds the __call__ method from a class or its metaclass.
function getBoundCallMethod(evaluator, errorNode, type) {
    return evaluator.getTypeOfBoundMember(errorNode, type, '__call__', { method: 'get' }, 
    /* diag */ undefined, 16 /* MemberAccessFlags.SkipInstanceMembers */ |
        8 /* MemberAccessFlags.SkipTypeBaseClass */ |
        512 /* MemberAccessFlags.SkipAttributeAccessOverride */);
}
exports.getBoundCallMethod = getBoundCallMethod;
// Matches the arguments of a call to the constructor for a class.
// If successful, it returns the resulting (specialized) object type that
// is allocated by the constructor. If unsuccessful, it reports diagnostics.
function validateConstructorArguments(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext) {
    var _a;
    const metaclassResult = validateMetaclassCall(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext);
    if (metaclassResult) {
        const metaclassReturnType = (_a = metaclassResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        // If there a custom `__call__` method on the metaclass that returns
        // something other than an instance of the class, assume that it
        // overrides the normal `type.__call__` logic and don't perform the usual
        // __new__ and __init__ validation.
        if (metaclassResult.argumentErrors || shouldSkipNewAndInitEvaluation(evaluator, type, metaclassReturnType)) {
            return metaclassResult;
        }
    }
    // Determine whether the class overrides the object.__new__ method.
    const newMethodDiag = new diagnostic_1.DiagnosticAddendum();
    const newMethodTypeResult = getBoundNewMethod(evaluator, errorNode, type, newMethodDiag);
    if (newMethodTypeResult === null || newMethodTypeResult === void 0 ? void 0 : newMethodTypeResult.typeErrors) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, newMethodDiag.getString(), errorNode);
    }
    const useConstructorTransform = (0, constructorTransform_1.hasConstructorTransform)(type);
    // If there is a constructor transform, evaluate all arguments speculatively
    // so we can later re-evaluate them in the context of the transform.
    const returnResult = evaluator.useSpeculativeMode(useConstructorTransform ? errorNode : undefined, () => {
        return validateNewAndInitMethods(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult);
    });
    let validatedArgExpressions = !useConstructorTransform || returnResult.argumentErrors;
    // Apply a constructor transform if applicable.
    if (useConstructorTransform) {
        if (returnResult.argumentErrors) {
            // If there were errors when validating the __new__ and __init__ methods,
            // we need to re-evaluate the arguments to generate error messages because
            // we previously evaluated them speculatively.
            validateNewAndInitMethods(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult);
            validatedArgExpressions = true;
        }
        else if (returnResult.returnType) {
            const transformed = (0, constructorTransform_1.applyConstructorTransform)(evaluator, errorNode, argList, type, {
                argumentErrors: !!returnResult.argumentErrors,
                returnType: returnResult.returnType,
                isTypeIncomplete: !!returnResult.isTypeIncomplete,
            });
            returnResult.returnType = transformed.returnType;
            if (transformed.isTypeIncomplete) {
                returnResult.isTypeIncomplete = true;
            }
            if (transformed.argumentErrors) {
                returnResult.argumentErrors = true;
            }
            validatedArgExpressions = true;
        }
    }
    // If we weren't able to validate the args, analyze the expressions here
    // to mark symbols referenced and report expression evaluation errors.
    if (!validatedArgExpressions) {
        argList.forEach((arg) => {
            if (arg.valueExpression && !evaluator.isSpeculativeModeInUse(arg.valueExpression)) {
                evaluator.getTypeOfExpression(arg.valueExpression);
            }
        });
    }
    return returnResult;
}
exports.validateConstructorArguments = validateConstructorArguments;
function validateNewAndInitMethods(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult) {
    var _a, _b;
    let returnType;
    let validatedArgExpressions = false;
    let argumentErrors = false;
    let isTypeIncomplete = false;
    const overloadsUsedForCall = [];
    let newMethodReturnType;
    // Validate __new__ if it is present.
    if (newMethodTypeResult) {
        // Use speculative mode for arg expressions because we don't know whether
        // we'll need to re-evaluate these expressions later for __init__.
        const newCallResult = validateNewMethod(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult, 
        /* useSpeculativeModeForArgs */ true);
        if (newCallResult.argumentErrors) {
            argumentErrors = true;
        }
        else {
            (0, collectionUtils_1.appendArray)(overloadsUsedForCall, (_a = newCallResult.overloadsUsedForCall) !== null && _a !== void 0 ? _a : []);
        }
        if (newCallResult.isTypeIncomplete) {
            isTypeIncomplete = true;
        }
        newMethodReturnType = newCallResult.returnType;
    }
    if (!newMethodReturnType || isDefaultNewMethod(newMethodTypeResult === null || newMethodTypeResult === void 0 ? void 0 : newMethodTypeResult.type)) {
        // If there is no __new__ method or it uses a default signature,
        // (cls, *args, **kwargs) -> Self, allow the __init__ method to
        // determine the specialized type of the class.
        newMethodReturnType = types_1.ClassType.cloneAsInstance(type);
    }
    else if ((0, types_1.isAnyOrUnknown)(newMethodReturnType)) {
        // If the __new__ method returns Any or Unknown, we'll ignore its return
        // type and assume that it returns Self.
        newMethodReturnType = (0, typeUtils_1.applySolvedTypeVars)(types_1.ClassType.cloneAsInstance(type), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type)), { unknownIfNotFound: true });
    }
    let initMethodTypeResult;
    // Validate __init__ if it's present. Skip if the __new__ method produced errors.
    if (!argumentErrors &&
        !(0, types_1.isNever)(newMethodReturnType) &&
        !shouldSkipInitEvaluation(evaluator, type, newMethodReturnType) &&
        (0, types_1.isClassInstance)(newMethodReturnType)) {
        // If the __new__ method returned the same type as the class it's constructing
        // but didn't supply solved type arguments, we'll ignore its specialized return
        // type and rely on the __init__ method to supply the type arguments instead.
        let initMethodBindToType = newMethodReturnType;
        if (initMethodBindToType.typeArguments &&
            initMethodBindToType.typeArguments.some((typeArg) => (0, types_1.isUnknown)(typeArg))) {
            initMethodBindToType = types_1.ClassType.cloneAsInstance(type);
        }
        // Determine whether the class overrides the object.__init__ method.
        const initMethodDiag = new diagnostic_1.DiagnosticAddendum();
        initMethodTypeResult = getBoundInitMethod(evaluator, errorNode, initMethodBindToType, initMethodDiag);
        if (initMethodTypeResult === null || initMethodTypeResult === void 0 ? void 0 : initMethodTypeResult.typeErrors) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, initMethodDiag.getString(), errorNode);
        }
        // Validate __init__ if it's present.
        if (initMethodTypeResult) {
            const initCallResult = validateInitMethod(evaluator, errorNode, argList, initMethodBindToType, skipUnknownArgCheck, inferenceContext, initMethodTypeResult.type);
            if (initCallResult.argumentErrors) {
                argumentErrors = true;
            }
            else if (initCallResult.overloadsUsedForCall) {
                overloadsUsedForCall.push(...initCallResult.overloadsUsedForCall);
            }
            if (initCallResult.isTypeIncomplete) {
                isTypeIncomplete = true;
            }
            returnType = initCallResult.returnType;
            validatedArgExpressions = true;
            skipUnknownArgCheck = true;
        }
    }
    if (!validatedArgExpressions && newMethodTypeResult) {
        // If we skipped the __init__ method and the __new__ method was evaluated only
        // speculatively, evaluate it non-speculatively now so we can report errors.
        if (!evaluator.isSpeculativeModeInUse(errorNode)) {
            validateNewMethod(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult, 
            /* useSpeculativeModeForArgs */ false);
        }
        validatedArgExpressions = true;
        returnType = newMethodReturnType;
    }
    // If the class doesn't override object.__new__ or object.__init__, use the
    // fallback constructor type evaluation for the `object` class.
    if (!newMethodTypeResult && !initMethodTypeResult) {
        const callResult = validateFallbackConstructorCall(evaluator, errorNode, argList, type, inferenceContext);
        if (callResult.argumentErrors) {
            argumentErrors = true;
        }
        else if (callResult.overloadsUsedForCall) {
            (0, collectionUtils_1.appendArray)(overloadsUsedForCall, callResult.overloadsUsedForCall);
        }
        if (callResult.isTypeIncomplete) {
            isTypeIncomplete = true;
        }
        returnType = (_b = callResult.returnType) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
    }
    return { argumentErrors, returnType, isTypeIncomplete, overloadsUsedForCall };
}
// Evaluates the __new__ method for type correctness. If useSpeculativeModeForArgs
// is true, use speculative mode to evaluate the arguments (unless an argument
// error is produced, in which case it's OK to use speculative mode).
function validateNewMethod(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, newMethodTypeResult, useSpeculativeModeForArgs) {
    let newReturnType;
    let isTypeIncomplete = false;
    let argumentErrors = false;
    const overloadsUsedForCall = [];
    if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker) {
        newMethodTypeResult.type = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(newMethodTypeResult.type, inferenceContext.signatureTracker, errorNode.start);
    }
    const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type));
    typeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(newMethodTypeResult.type));
    if (type.typeAliasInfo) {
        typeVarContext.addSolveForScope(type.typeAliasInfo.typeVarScopeId);
    }
    const callResult = evaluator.useSpeculativeMode(useSpeculativeModeForArgs ? errorNode : undefined, () => {
        return evaluator.validateCallArguments(errorNode, argList, newMethodTypeResult, typeVarContext, skipUnknownArgCheck, inferenceContext);
    });
    if (callResult.isTypeIncomplete) {
        isTypeIncomplete = true;
    }
    if (callResult.argumentErrors) {
        argumentErrors = true;
        // Evaluate the arguments in a non-speculative manner to generate any diagnostics.
        typeVarContext.unlock();
        evaluator.validateCallArguments(errorNode, argList, newMethodTypeResult, typeVarContext, skipUnknownArgCheck);
    }
    else {
        newReturnType = callResult.returnType;
        if (overloadsUsedForCall.length === 0 && callResult.overloadsUsedForCall) {
            overloadsUsedForCall.push(...callResult.overloadsUsedForCall);
        }
    }
    if (newReturnType) {
        // Special-case the 'tuple' type specialization to use the homogenous
        // arbitrary-length form.
        if ((0, types_1.isClassInstance)(newReturnType) && (0, typeUtils_1.isTupleClass)(newReturnType) && !newReturnType.tupleTypeArguments) {
            if (newReturnType.typeArguments && newReturnType.typeArguments.length === 1) {
                newReturnType = (0, typeUtils_1.specializeTupleClass)(newReturnType, [
                    { type: newReturnType.typeArguments[0], isUnbounded: true },
                ]);
            }
            newReturnType = applyExpectedTypeForTupleConstructor(newReturnType, inferenceContext);
        }
    }
    else {
        newReturnType = applyExpectedTypeForConstructor(evaluator, type, inferenceContext, typeVarContext);
    }
    return { argumentErrors, returnType: newReturnType, isTypeIncomplete, overloadsUsedForCall };
}
function validateInitMethod(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext, initMethodType) {
    let returnType;
    let isTypeIncomplete = false;
    let argumentErrors = false;
    const overloadsUsedForCall = [];
    if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker) {
        initMethodType = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(initMethodType, inferenceContext.signatureTracker, errorNode.start);
    }
    // If there is an expected type, analyze the __init__ call for each of the
    // subtypes that comprise the expected type. If one or more analyzes with no
    // errors, use those results. This requires special-case processing because
    // the __init__ method doesn't return the expected type. It always
    // returns None.
    if (inferenceContext) {
        let foundWorkingExpectedType = false;
        returnType = (0, typeUtils_1.mapSubtypes)(inferenceContext.expectedType, (expectedSubType) => {
            // If we've already successfully evaluated the __init__ method with
            // one expected type, ignore the remaining ones.
            if (foundWorkingExpectedType) {
                return undefined;
            }
            expectedSubType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(expectedSubType);
            // If the expected type is the same type as the class and the class
            // is already explicitly specialized, don't override the explicit
            // specialization.
            if ((0, types_1.isClassInstance)(expectedSubType) &&
                types_1.ClassType.isSameGenericClass(type, expectedSubType) &&
                type.typeArguments) {
                return undefined;
            }
            const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type));
            typeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(initMethodType));
            if ((0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluator, types_1.ClassType.cloneAsInstance(type), expectedSubType, typeVarContext, (0, parseTreeUtils_1.getTypeVarScopesForNode)(errorNode), errorNode.start)) {
                const specializedConstructor = (0, typeUtils_1.applySolvedTypeVars)(initMethodType, typeVarContext);
                let callResult;
                callResult = evaluator.useSpeculativeMode(errorNode, () => {
                    return evaluator.validateCallArguments(errorNode, argList, { type: specializedConstructor }, typeVarContext.clone(), skipUnknownArgCheck);
                });
                if (!callResult.argumentErrors) {
                    // Call validateCallArguments again, this time without speculative
                    // mode, so any errors are reported.
                    callResult = evaluator.validateCallArguments(errorNode, argList, { type: specializedConstructor }, typeVarContext, skipUnknownArgCheck);
                    if (callResult.isTypeIncomplete) {
                        isTypeIncomplete = true;
                    }
                    if (callResult.argumentErrors) {
                        argumentErrors = true;
                    }
                    if (callResult.overloadsUsedForCall) {
                        (0, collectionUtils_1.appendArray)(overloadsUsedForCall, callResult.overloadsUsedForCall);
                    }
                    // Note that we've found an expected type that works.
                    foundWorkingExpectedType = true;
                    return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubType, typeVarContext);
                }
            }
            return undefined;
        }, 
        /* sortSubtypes */ true);
        if ((0, types_1.isNever)(returnType) || argumentErrors) {
            returnType = undefined;
        }
    }
    if (!returnType) {
        const typeVarContext = type.typeArguments
            ? (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(type)
            : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type));
        typeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(initMethodType));
        const callResult = evaluator.validateCallArguments(errorNode, argList, { type: initMethodType }, typeVarContext, skipUnknownArgCheck);
        let adjustedClassType = type;
        if (callResult.specializedInitSelfType &&
            (0, types_1.isClassInstance)(callResult.specializedInitSelfType) &&
            types_1.ClassType.isSameGenericClass(callResult.specializedInitSelfType, adjustedClassType)) {
            adjustedClassType = types_1.ClassType.cloneAsInstantiable(callResult.specializedInitSelfType);
        }
        returnType = applyExpectedTypeForConstructor(evaluator, adjustedClassType, 
        /* inferenceContext */ undefined, typeVarContext);
        if (callResult.isTypeIncomplete) {
            isTypeIncomplete = true;
        }
        if (callResult.argumentErrors) {
            argumentErrors = true;
        }
        else if (callResult.overloadsUsedForCall) {
            overloadsUsedForCall.push(...callResult.overloadsUsedForCall);
        }
    }
    return { argumentErrors, returnType, isTypeIncomplete, overloadsUsedForCall };
}
function validateFallbackConstructorCall(evaluator, errorNode, argList, type, inferenceContext) {
    let reportedErrors = false;
    // It's OK if the argument list consists only of `*args` and `**kwargs`.
    if (argList.length > 0 && argList.some((arg) => arg.argumentCategory === 0 /* ArgumentCategory.Simple */)) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.constructorNoArgs().format({ type: type.aliasName || type.details.name }), errorNode);
        reportedErrors = true;
    }
    if (!inferenceContext && type.typeArguments) {
        // If there was no expected type but the type was already specialized,
        // assume that we're constructing an instance of the specialized type.
        return {
            argumentErrors: reportedErrors,
            overloadsUsedForCall: [],
            returnType: (0, typeUtils_1.convertToInstance)(type),
        };
    }
    // Do our best to specialize the instantiated class based on the expected
    // type if provided.
    const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type));
    if (inferenceContext) {
        (0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluator, types_1.ClassType.cloneAsInstance(type), inferenceContext.expectedType, typeVarContext, (0, parseTreeUtils_1.getTypeVarScopesForNode)(errorNode), errorNode.start);
    }
    return {
        argumentErrors: reportedErrors,
        overloadsUsedForCall: [],
        returnType: applyExpectedTypeForConstructor(evaluator, type, inferenceContext, typeVarContext),
    };
}
function validateMetaclassCall(evaluator, errorNode, argList, type, skipUnknownArgCheck, inferenceContext) {
    const metaclassCallMethodInfo = getBoundCallMethod(evaluator, errorNode, type);
    if (metaclassCallMethodInfo) {
        const callResult = evaluator.validateCallArguments(errorNode, argList, metaclassCallMethodInfo, 
        /* typeVarContext */ undefined, skipUnknownArgCheck, inferenceContext);
        if (!callResult.returnType || (0, types_1.isUnknown)(callResult.returnType)) {
            // The return result isn't known. We'll assume in this case that
            // the metaclass __call__ method allocated a new instance of the
            // requested class.
            const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type));
            callResult.returnType = applyExpectedTypeForConstructor(evaluator, type, inferenceContext, typeVarContext);
        }
        return callResult;
    }
    return undefined;
}
function applyExpectedSubtypeForConstructor(evaluator, type, expectedSubtype, typeVarContext) {
    const specializedType = (0, typeUtils_1.applySolvedTypeVars)(types_1.ClassType.cloneAsInstance(type), typeVarContext, {
        applyInScopePlaceholders: true,
    });
    if (!evaluator.assignType(expectedSubtype, specializedType)) {
        return undefined;
    }
    // If the expected type is "Any", transform it to an Any.
    if ((0, types_1.isAny)(expectedSubtype)) {
        return expectedSubtype;
    }
    return specializedType;
}
// Handles the case where a constructor is a generic type and the type
// arguments are not specified but can be provided by the expected type.
function applyExpectedTypeForConstructor(evaluator, type, inferenceContext, typeVarContext) {
    let unsolvedTypeVarsAreUnknown = true;
    // If this isn't a generic type or it's a type that has already been
    // explicitly specialized, the expected type isn't applicable.
    if (type.details.typeParameters.length === 0 || type.typeArguments) {
        return (0, typeUtils_1.applySolvedTypeVars)(types_1.ClassType.cloneAsInstance(type), typeVarContext, { applyInScopePlaceholders: true });
    }
    if (inferenceContext) {
        const specializedExpectedType = (0, typeUtils_1.mapSubtypes)(inferenceContext.expectedType, (expectedSubtype) => {
            return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubtype, typeVarContext);
        });
        if (!(0, types_1.isNever)(specializedExpectedType)) {
            return specializedExpectedType;
        }
        // If the expected type didn't provide TypeVar values, remaining
        // unsolved TypeVars should be considered Unknown unless they were
        // provided explicitly in the constructor call.
        if (type.typeArguments) {
            unsolvedTypeVarsAreUnknown = false;
        }
    }
    const specializedType = (0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, {
        unknownIfNotFound: unsolvedTypeVarsAreUnknown,
    });
    return types_1.ClassType.cloneAsInstance(specializedType);
}
// Similar to applyExpectedTypeForConstructor, this function handles the
// special case of the tuple class.
function applyExpectedTypeForTupleConstructor(type, inferenceContext) {
    let specializedType = type;
    if (inferenceContext &&
        (0, types_1.isClassInstance)(inferenceContext.expectedType) &&
        (0, typeUtils_1.isTupleClass)(inferenceContext.expectedType) &&
        inferenceContext.expectedType.tupleTypeArguments) {
        specializedType = (0, typeUtils_1.specializeTupleClass)(type, inferenceContext.expectedType.tupleTypeArguments);
    }
    return specializedType;
}
// Synthesize a function that represents the constructor for this class
// taking into consideration the __init__ and __new__ methods.
function createFunctionFromConstructor(evaluator, classType, selfType = undefined, recursionCount = 0) {
    const fromMetaclassCall = createFunctionFromMetaclassCall(evaluator, classType, recursionCount);
    if (fromMetaclassCall) {
        return fromMetaclassCall;
    }
    const fromNew = createFunctionFromNewMethod(evaluator, classType, selfType, recursionCount);
    if (fromNew) {
        let skipInitMethod = false;
        (0, typeUtils_1.doForEachSignature)(fromNew, (signature) => {
            const newMethodReturnType = types_1.FunctionType.getSpecializedReturnType(signature);
            if (newMethodReturnType && shouldSkipInitEvaluation(evaluator, classType, newMethodReturnType)) {
                skipInitMethod = true;
            }
        });
        if (skipInitMethod) {
            return fromNew;
        }
    }
    const fromInit = createFunctionFromInitMethod(evaluator, classType, selfType, recursionCount);
    // If there is both a __new__ and __init__ method, return a union
    // comprised of both resulting function types.
    if (fromNew && fromInit) {
        return (0, types_1.combineTypes)([fromInit, fromNew]);
    }
    if (fromNew || fromInit) {
        return fromNew !== null && fromNew !== void 0 ? fromNew : fromInit;
    }
    return fromNew !== null && fromNew !== void 0 ? fromNew : createFunctionFromObjectNewMethod(classType);
}
exports.createFunctionFromConstructor = createFunctionFromConstructor;
function createFunctionFromMetaclassCall(evaluator, classType, recursionCount) {
    const metaclass = classType.details.effectiveMetaclass;
    if (!metaclass || !(0, types_1.isClass)(metaclass)) {
        return undefined;
    }
    const callInfo = (0, typeUtils_1.lookUpClassMember)(metaclass, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */ |
        8 /* MemberAccessFlags.SkipTypeBaseClass */ |
        512 /* MemberAccessFlags.SkipAttributeAccessOverride */);
    if (!callInfo) {
        return undefined;
    }
    const callType = evaluator.getTypeOfMember(callInfo);
    if (!(0, types_1.isFunction)(callType) && !(0, types_1.isOverloadedFunction)(callType)) {
        return undefined;
    }
    const boundCallType = evaluator.bindFunctionToClassOrObject(classType, callType, callInfo && (0, types_1.isInstantiableClass)(callInfo.classType) ? callInfo.classType : undefined, 
    /* treatConstructorAsClassMethod */ false, types_1.ClassType.cloneAsInstantiable(classType), 
    /* diag */ undefined, recursionCount);
    if (!boundCallType) {
        return undefined;
    }
    let useMetaclassCall = false;
    // Look at the signatures of all the __call__ methods to determine whether
    // any of them returns something other than the instance of the class being
    // constructed.
    (0, typeUtils_1.doForEachSignature)(boundCallType, (signature) => {
        if (signature.details.declaredReturnType) {
            const returnType = types_1.FunctionType.getSpecializedReturnType(signature);
            if (returnType && shouldSkipNewAndInitEvaluation(evaluator, classType, returnType)) {
                useMetaclassCall = true;
            }
        }
    });
    return useMetaclassCall ? boundCallType : undefined;
}
function createFunctionFromNewMethod(evaluator, classType, selfType, recursionCount) {
    const newInfo = (0, typeUtils_1.lookUpClassMember)(classType, '__new__', 16 /* MemberAccessFlags.SkipInstanceMembers */ |
        512 /* MemberAccessFlags.SkipAttributeAccessOverride */ |
        4 /* MemberAccessFlags.SkipObjectBaseClass */);
    if (!newInfo) {
        return undefined;
    }
    const newType = evaluator.getTypeOfMember(newInfo);
    const convertNewToConstructor = (newSubtype) => {
        // If there are no parameters that include class-scoped type parameters,
        // self-specialize the class because the type arguments for the class
        // can't be solved if there are no parameters to supply them.
        const hasParametersWithTypeVars = newSubtype.details.parameters.some((param, index) => {
            if (index === 0 || !param.name) {
                return false;
            }
            const paramType = types_1.FunctionType.getEffectiveParameterType(newSubtype, index);
            const typeVars = (0, typeUtils_1.getTypeVarArgumentsRecursive)(paramType);
            return typeVars.some((typeVar) => typeVar.scopeId === (0, typeUtils_1.getTypeVarScopeId)(classType));
        });
        const boundNew = evaluator.bindFunctionToClassOrObject(hasParametersWithTypeVars ? (0, typeUtils_1.selfSpecializeClass)(classType) : classType, newSubtype, newInfo && (0, types_1.isInstantiableClass)(newInfo.classType) ? newInfo.classType : undefined, 
        /* treatConstructorAsClassMethod */ true, selfType, 
        /* diag */ undefined, recursionCount);
        if (!boundNew) {
            return undefined;
        }
        const convertedNew = types_1.FunctionType.clone(boundNew);
        convertedNew.details.typeVarScopeId = newSubtype.details.typeVarScopeId;
        if (!convertedNew.details.docString && classType.details.docString) {
            convertedNew.details.docString = classType.details.docString;
        }
        convertedNew.details.flags &= ~(4 /* FunctionTypeFlags.StaticMethod */ | 1 /* FunctionTypeFlags.ConstructorMethod */);
        convertedNew.details.constructorTypeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(classType);
        return convertedNew;
    };
    if ((0, types_1.isFunction)(newType)) {
        return convertNewToConstructor(newType);
    }
    if (!(0, types_1.isOverloadedFunction)(newType)) {
        return undefined;
    }
    const newOverloads = [];
    newType.overloads.forEach((overload) => {
        const converted = convertNewToConstructor(overload);
        if (converted) {
            newOverloads.push(converted);
        }
    });
    if (newOverloads.length === 0) {
        return undefined;
    }
    if (newOverloads.length === 1) {
        return newOverloads[0];
    }
    return types_1.OverloadedFunctionType.create(newOverloads);
}
function createFunctionFromObjectNewMethod(classType) {
    // Return a fallback constructor based on the object.__new__ method.
    const constructorFunction = types_1.FunctionType.createSynthesizedInstance('__new__', 0 /* FunctionTypeFlags.None */);
    constructorFunction.details.declaredReturnType = types_1.ClassType.cloneAsInstance(classType);
    // If this is type[T] or a protocol, we don't know what parameters are accepted
    // by the constructor, so add the default parameters.
    if (classType.includeSubclasses || types_1.ClassType.isProtocolClass(classType)) {
        types_1.FunctionType.addDefaultParameters(constructorFunction);
    }
    if (!constructorFunction.details.docString && classType.details.docString) {
        constructorFunction.details.docString = classType.details.docString;
    }
    return constructorFunction;
}
function createFunctionFromInitMethod(evaluator, classType, selfType, recursionCount) {
    // Use the __init__ method if available. It's usually more detailed.
    const initInfo = (0, typeUtils_1.lookUpClassMember)(classType, '__init__', 16 /* MemberAccessFlags.SkipInstanceMembers */ |
        512 /* MemberAccessFlags.SkipAttributeAccessOverride */ |
        4 /* MemberAccessFlags.SkipObjectBaseClass */);
    if (!initInfo) {
        return undefined;
    }
    const initType = evaluator.getTypeOfMember(initInfo);
    const objectType = types_1.ClassType.cloneAsInstance(classType);
    function convertInitToConstructor(initSubtype) {
        var _a, _b;
        const boundInit = evaluator.bindFunctionToClassOrObject(objectType, initSubtype, initInfo && (0, types_1.isInstantiableClass)(initInfo.classType) ? initInfo.classType : undefined, 
        /* treatConstructorAsClassMethod */ undefined, selfType, 
        /* diag */ undefined, recursionCount);
        if (!boundInit) {
            return undefined;
        }
        const convertedInit = types_1.FunctionType.clone(boundInit);
        convertedInit.details.declaredReturnType = (_b = (_a = boundInit.strippedFirstParamType) !== null && _a !== void 0 ? _a : selfType) !== null && _b !== void 0 ? _b : objectType;
        convertedInit.details.name = '';
        convertedInit.details.fullName = '';
        if (convertedInit.specializedTypes) {
            convertedInit.specializedTypes.returnType = selfType !== null && selfType !== void 0 ? selfType : objectType;
        }
        if (!convertedInit.details.docString && classType.details.docString) {
            convertedInit.details.docString = classType.details.docString;
        }
        convertedInit.details.flags &= ~4 /* FunctionTypeFlags.StaticMethod */;
        convertedInit.details.constructorTypeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(classType);
        return convertedInit;
    }
    if ((0, types_1.isFunction)(initType)) {
        return convertInitToConstructor(initType);
    }
    if (!(0, types_1.isOverloadedFunction)(initType)) {
        return undefined;
    }
    const initOverloads = [];
    initType.overloads.forEach((overload) => {
        const converted = convertInitToConstructor(overload);
        if (converted) {
            initOverloads.push(converted);
        }
    });
    if (initOverloads.length === 0) {
        return undefined;
    }
    if (initOverloads.length === 1) {
        return initOverloads[0];
    }
    return types_1.OverloadedFunctionType.create(initOverloads);
}
// If the __call__ method returns a type that is not an instance of the class,
// skip the __new__ and __init__ method evaluation.
function shouldSkipNewAndInitEvaluation(evaluator, classType, callMethodReturnType) {
    if (!evaluator.assignType((0, typeUtils_1.convertToInstance)(classType), callMethodReturnType) ||
        (0, types_1.isNever)(callMethodReturnType) ||
        (0, types_1.findSubtype)(callMethodReturnType, (subtype) => (0, types_1.isAny)(subtype))) {
        return true;
    }
    // Handle the special case of an enum class, where the __new__ and __init__
    // methods are replaced at runtime by the metaclass.
    if (types_1.ClassType.isEnumClass(classType)) {
        return true;
    }
    return false;
}
// If __new__ returns a type that is not an instance of the class, skip the
// __init__ method evaluation. This is consistent with the behavior of the
// type.__call__ runtime behavior.
function shouldSkipInitEvaluation(evaluator, classType, newMethodReturnType) {
    const returnType = evaluator.makeTopLevelTypeVarsConcrete(newMethodReturnType);
    let skipInitCheck = false;
    (0, typeUtils_1.doForEachSubtype)(returnType, (subtype) => {
        if ((0, types_1.isUnknown)(subtype)) {
            return;
        }
        if ((0, types_1.isClassInstance)(subtype)) {
            const inheritanceChain = [];
            const isDerivedFrom = types_1.ClassType.isDerivedFrom(subtype, classType, inheritanceChain);
            if (!isDerivedFrom) {
                skipInitCheck = true;
            }
            return;
        }
        skipInitCheck = true;
    });
    return skipInitCheck;
}
// Determine whether the __new__ method is the placeholder signature
// of "def __new__(cls, *args, **kwargs) -> Self".
function isDefaultNewMethod(newMethod) {
    var _a;
    if (!newMethod || !(0, types_1.isFunction)(newMethod)) {
        return false;
    }
    if (newMethod.details.paramSpec) {
        return false;
    }
    const params = newMethod.details.parameters;
    if (params.length !== 2) {
        return false;
    }
    if (params[0].category !== 1 /* ParameterCategory.ArgsList */ || params[1].category !== 2 /* ParameterCategory.KwargsDict */) {
        return false;
    }
    const returnType = (_a = newMethod.details.declaredReturnType) !== null && _a !== void 0 ? _a : newMethod.inferredReturnType;
    if (!returnType || !(0, types_1.isTypeVar)(returnType) || !returnType.details.isSynthesizedSelf) {
        return false;
    }
    return true;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/dataClasses.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/analyzer/dataClasses.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * dataClasses.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides special-case logic for the construction of dataclass
 * classes and dataclass transform.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.applyDataClassDecorator = exports.applyDataClassDefaultBehaviors = exports.applyDataClassClassBehaviorOverrides = exports.getDataclassDecoratorBehaviors = exports.validateDataClassTransformDecorator = exports.synthesizeDataClassMethods = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const constructors_1 = __webpack_require__(/*! ./constructors */ "../pyright-internal/src/analyzer/constructors.ts");
const namedTuples_1 = __webpack_require__(/*! ./namedTuples */ "../pyright-internal/src/analyzer/namedTuples.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const staticExpressions_1 = __webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
// Validates fields for compatibility with a dataclass and synthesizes
// an appropriate __new__ and __init__ methods plus __dataclass_fields__
// and __match_args__ class variables.
function synthesizeDataClassMethods(evaluator, node, classType, skipSynthesizeInit, hasExistingInitMethod, skipSynthesizeHash) {
    var _a;
    (0, debug_1.assert)(types_1.ClassType.isDataClass(classType));
    const classTypeVar = (0, typeUtils_1.synthesizeTypeVarForSelfCls)(classType, /* isClsParam */ true);
    const newType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* FunctionTypeFlags.ConstructorMethod */);
    newType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    const initType = types_1.FunctionType.createSynthesizedInstance('__init__');
    initType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    // Override `__new__` because some dataclasses (such as those that are
    // created by subclassing from NamedTuple) may have their own custom
    // __new__ that requires overriding.
    types_1.FunctionType.addParameter(newType, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'cls',
        type: classTypeVar,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addDefaultParameters(newType);
    newType.details.declaredReturnType = (0, typeUtils_1.convertToInstance)(classTypeVar);
    const selfParam = {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: (0, typeUtils_1.synthesizeTypeVarForSelfCls)(classType, /* isClsParam */ false),
        hasDeclaredType: true,
    };
    types_1.FunctionType.addParameter(initType, selfParam);
    initType.details.declaredReturnType = evaluator.getNoneType();
    // Maintain a list of all dataclass entries (including
    // those from inherited classes) plus a list of only those
    // entries added by this class.
    const localDataClassEntries = [];
    const fullDataClassEntries = [];
    const allAncestorsKnown = addInheritedDataClassEntries(classType, fullDataClassEntries);
    if (!allAncestorsKnown) {
        // If one or more ancestor classes have an unknown type, we cannot
        // safely determine the parameter list, so we'll accept any parameters
        // to avoid a false positive.
        types_1.FunctionType.addDefaultParameters(initType);
    }
    const localEntryTypeEvaluator = [];
    let sawKeywordOnlySeparator = false;
    types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
        var _a, _b, _c, _d, _e, _f, _g;
        if (symbol.isIgnoredForProtocolMatch()) {
            return;
        }
        // Apparently, `__hash__` is special-cased in a dataclass. I can't find
        // this in the spec, but the runtime seems to treat is specially.
        if (name === '__hash__') {
            return;
        }
        // Only variables (not functions, classes, etc.) are considered.
        const classVarDecl = symbol.getTypedDeclarations().find((decl) => {
            if (decl.type !== 1 /* DeclarationType.Variable */) {
                return false;
            }
            const container = (0, parseTreeUtils_1.getEnclosingClassOrFunction)(decl.node);
            if (!container || container.nodeType !== 10 /* ParseNodeType.Class */) {
                return false;
            }
            return true;
        });
        if (classVarDecl) {
            let statement = classVarDecl.node;
            while (statement) {
                if (statement.nodeType === 3 /* ParseNodeType.Assignment */) {
                    break;
                }
                if (statement.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
                    if (((_a = statement.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */) {
                        statement = statement.parent;
                    }
                    break;
                }
                statement = statement.parent;
            }
            if (!statement) {
                return;
            }
            let variableNameNode;
            let aliasName;
            let variableTypeEvaluator;
            let hasDefaultValue = false;
            let isKeywordOnly = types_1.ClassType.isDataClassKeywordOnlyParams(classType) || sawKeywordOnlySeparator;
            let defaultValueExpression;
            let includeInInit = true;
            let converter;
            if (statement.nodeType === 3 /* ParseNodeType.Assignment */) {
                if (statement.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */ &&
                    statement.leftExpression.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    variableNameNode = statement.leftExpression.valueExpression;
                    const assignmentStatement = statement;
                    variableTypeEvaluator = () => evaluator.getTypeOfAnnotation(assignmentStatement.leftExpression.typeAnnotation, {
                        isVariableAnnotation: true,
                        allowFinal: true,
                        allowClassVar: true,
                    });
                }
                hasDefaultValue = true;
                defaultValueExpression = statement.rightExpression;
                // If the RHS of the assignment is assigning a field instance where the
                // "init" parameter is set to false, do not include it in the init method.
                if (statement.rightExpression.nodeType === 9 /* ParseNodeType.Call */) {
                    const callTypeResult = evaluator.getTypeOfExpression(statement.rightExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                    const callType = callTypeResult.type;
                    if (isDataclassFieldConstructor(callType, ((_b = classType.details.dataClassBehaviors) === null || _b === void 0 ? void 0 : _b.fieldDescriptorNames) || [])) {
                        const initArg = statement.rightExpression.arguments.find((arg) => { var _a; return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'init'; });
                        if (initArg && initArg.valueExpression) {
                            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
                            includeInInit =
                                (_c = (0, staticExpressions_1.evaluateStaticBoolExpression)(initArg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants)) !== null && _c !== void 0 ? _c : includeInInit;
                        }
                        else {
                            includeInInit =
                                (_d = getDefaultArgValueForFieldSpecifier(evaluator, statement.rightExpression, callTypeResult, 'init')) !== null && _d !== void 0 ? _d : includeInInit;
                        }
                        const kwOnlyArg = statement.rightExpression.arguments.find((arg) => { var _a; return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'kw_only'; });
                        if (kwOnlyArg && kwOnlyArg.valueExpression) {
                            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
                            isKeywordOnly =
                                (_e = (0, staticExpressions_1.evaluateStaticBoolExpression)(kwOnlyArg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants)) !== null && _e !== void 0 ? _e : isKeywordOnly;
                        }
                        else {
                            isKeywordOnly =
                                (_f = getDefaultArgValueForFieldSpecifier(evaluator, statement.rightExpression, callTypeResult, 'kw_only')) !== null && _f !== void 0 ? _f : isKeywordOnly;
                        }
                        const defaultArg = statement.rightExpression.arguments.find((arg) => {
                            var _a, _b, _c;
                            return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'default' ||
                                ((_b = arg.name) === null || _b === void 0 ? void 0 : _b.value) === 'default_factory' ||
                                ((_c = arg.name) === null || _c === void 0 ? void 0 : _c.value) === 'factory';
                        });
                        hasDefaultValue = !!defaultArg;
                        if (defaultArg === null || defaultArg === void 0 ? void 0 : defaultArg.valueExpression) {
                            defaultValueExpression = defaultArg.valueExpression;
                        }
                        const aliasArg = statement.rightExpression.arguments.find((arg) => { var _a; return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'alias'; });
                        if (aliasArg) {
                            const valueType = evaluator.getTypeOfExpression(aliasArg.valueExpression).type;
                            if ((0, types_1.isClassInstance)(valueType) &&
                                types_1.ClassType.isBuiltIn(valueType, 'str') &&
                                (0, typeUtils_1.isLiteralType)(valueType)) {
                                aliasName = valueType.literalValue;
                            }
                        }
                        const converterArg = statement.rightExpression.arguments.find((arg) => { var _a; return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'converter'; });
                        if (converterArg && converterArg.valueExpression) {
                            converter = converterArg;
                        }
                    }
                }
            }
            else if (statement.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
                if (statement.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    variableNameNode = statement.valueExpression;
                    const annotationStatement = statement;
                    variableTypeEvaluator = () => evaluator.getTypeOfAnnotation(annotationStatement.typeAnnotation, {
                        isVariableAnnotation: true,
                        allowFinal: true,
                        allowClassVar: true,
                    });
                    // Is this a KW_ONLY separator introduced in Python 3.10?
                    if (statement.valueExpression.value === '_') {
                        const annotatedType = variableTypeEvaluator();
                        if ((0, types_1.isClassInstance)(annotatedType) && types_1.ClassType.isBuiltIn(annotatedType, 'KW_ONLY')) {
                            sawKeywordOnlySeparator = true;
                            variableNameNode = undefined;
                            variableTypeEvaluator = undefined;
                        }
                    }
                }
            }
            if (variableNameNode && variableTypeEvaluator) {
                const variableName = variableNameNode.value;
                // Don't include class vars. PEP 557 indicates that they shouldn't
                // be considered data class entries.
                const variableSymbol = types_1.ClassType.getSymbolTable(classType).get(variableName);
                if ((variableSymbol === null || variableSymbol === void 0 ? void 0 : variableSymbol.isClassVar()) && !(variableSymbol === null || variableSymbol === void 0 ? void 0 : variableSymbol.isFinalVarInClassBody())) {
                    // If an ancestor class declared an instance variable but this dataclass
                    // declares a ClassVar, delete the older one from the full data class entries.
                    // We exclude final variables here because a Final type annotation is implicitly
                    // considered a ClassVar by the binder, but dataclass rules are different.
                    const index = fullDataClassEntries.findIndex((p) => p.name === variableName);
                    if (index >= 0) {
                        fullDataClassEntries.splice(index, 1);
                    }
                    const dataClassEntry = {
                        name: variableName,
                        classType,
                        alias: aliasName,
                        isKeywordOnly: false,
                        hasDefault: hasDefaultValue,
                        defaultValueExpression,
                        includeInInit,
                        nameNode: variableNameNode,
                        type: types_1.UnknownType.create(),
                        isClassVar: true,
                        converter,
                    };
                    localDataClassEntries.push(dataClassEntry);
                }
                else {
                    // Create a new data class entry, but defer evaluation of the type until
                    // we've compiled the full list of data class entries for this class. This
                    // allows us to handle circular references in types.
                    const dataClassEntry = {
                        name: variableName,
                        classType,
                        alias: aliasName,
                        isKeywordOnly,
                        hasDefault: hasDefaultValue,
                        defaultValueExpression,
                        includeInInit,
                        nameNode: variableNameNode,
                        type: types_1.UnknownType.create(),
                        isClassVar: false,
                        converter,
                    };
                    localEntryTypeEvaluator.push({ entry: dataClassEntry, evaluator: variableTypeEvaluator });
                    // Add the new entry to the local entry list.
                    let insertIndex = localDataClassEntries.findIndex((e) => e.name === variableName);
                    if (insertIndex >= 0) {
                        localDataClassEntries[insertIndex] = dataClassEntry;
                    }
                    else {
                        localDataClassEntries.push(dataClassEntry);
                    }
                    // Add the new entry to the full entry list.
                    insertIndex = fullDataClassEntries.findIndex((p) => p.name === variableName);
                    if (insertIndex >= 0) {
                        const oldEntry = fullDataClassEntries[insertIndex];
                        // While this isn't documented behavior, it appears that the dataclass implementation
                        // causes overridden variables to "inherit" default values from parent classes.
                        if (!dataClassEntry.hasDefault && oldEntry.hasDefault && oldEntry.includeInInit) {
                            dataClassEntry.hasDefault = true;
                            dataClassEntry.defaultValueExpression = oldEntry.defaultValueExpression;
                            hasDefaultValue = true;
                            // Warn the user of this case because it can result in type errors if the
                            // default value is incompatible with the new type.
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassFieldInheritedDefault().format({ fieldName: variableName }), variableNameNode);
                        }
                        fullDataClassEntries[insertIndex] = dataClassEntry;
                    }
                    else {
                        fullDataClassEntries.push(dataClassEntry);
                        insertIndex = fullDataClassEntries.length - 1;
                    }
                    // If we've already seen a entry with a default value defined,
                    // all subsequent entries must also have default values.
                    if (!isKeywordOnly && includeInInit && !skipSynthesizeInit && !hasDefaultValue) {
                        const firstDefaultValueIndex = fullDataClassEntries.findIndex((p) => p.hasDefault && p.includeInInit && !p.isKeywordOnly);
                        if (firstDefaultValueIndex >= 0 && firstDefaultValueIndex < insertIndex) {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassFieldWithDefault(), variableNameNode);
                        }
                    }
                }
            }
        }
        else {
            // The symbol had no declared type, so it is (mostly) ignored by dataclasses.
            // However, if it is assigned a field descriptor, it will result in a
            // runtime exception.
            const declarations = symbol.getDeclarations();
            if (declarations.length === 0) {
                return;
            }
            const lastDecl = declarations[declarations.length - 1];
            if (lastDecl.type !== 1 /* DeclarationType.Variable */) {
                return;
            }
            const statement = lastDecl.node.parent;
            if (!statement || statement.nodeType !== 3 /* ParseNodeType.Assignment */) {
                return;
            }
            // If the RHS of the assignment is assigning a field instance where the
            // "init" parameter is set to false, do not include it in the init method.
            if (statement.rightExpression.nodeType === 9 /* ParseNodeType.Call */) {
                const callType = evaluator.getTypeOfExpression(statement.rightExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                if (isDataclassFieldConstructor(callType, ((_g = classType.details.dataClassBehaviors) === null || _g === void 0 ? void 0 : _g.fieldDescriptorNames) || [])) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassFieldWithoutAnnotation(), statement.rightExpression);
                }
            }
        }
    });
    classType.details.dataClassEntries = localDataClassEntries;
    // Now that the dataClassEntries field has been set with a complete list
    // of local data class entries for this class, perform deferred type
    // evaluations. This could involve circular type dependencies, so it's
    // required that the list be complete (even if types are not yet accurate)
    // before we perform the type evaluations.
    localEntryTypeEvaluator.forEach((entryEvaluator) => {
        entryEvaluator.entry.type = entryEvaluator.evaluator();
    });
    const symbolTable = types_1.ClassType.getSymbolTable(classType);
    const keywordOnlyParams = [];
    if (!skipSynthesizeInit && !hasExistingInitMethod) {
        if (allAncestorsKnown) {
            fullDataClassEntries.forEach((entry) => {
                if (entry.includeInInit) {
                    // If the type refers to Self of the parent class, we need to
                    // transform it to refer to the Self of this subclass.
                    let effectiveType = entry.type;
                    if (entry.classType !== classType && (0, typeUtils_1.requiresSpecialization)(effectiveType)) {
                        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(entry.classType));
                        (0, typeUtils_1.populateTypeVarContextForSelfType)(typeVarContext, entry.classType, classType);
                        effectiveType = (0, typeUtils_1.applySolvedTypeVars)(effectiveType, typeVarContext);
                    }
                    // Is the field type a descriptor object? If so, we need to extract the corresponding
                    // type of the __init__ method parameter from the __set__ method.
                    effectiveType = transformDescriptorType(evaluator, effectiveType);
                    if (entry.converter) {
                        const fieldType = effectiveType;
                        effectiveType = getConverterInputType(evaluator, entry.converter, effectiveType, entry.name);
                        symbolTable.set(entry.name, getDescriptorForConverterField(evaluator, node, entry.converter, entry.name, fieldType, effectiveType));
                    }
                    const effectiveName = entry.alias || entry.name;
                    if (!entry.alias && entry.nameNode && (0, symbolNameUtils_1.isPrivateName)(entry.nameNode.value)) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassFieldWithPrivateName(), entry.nameNode);
                    }
                    const functionParam = {
                        category: 0 /* ParameterCategory.Simple */,
                        name: effectiveName,
                        hasDefault: entry.hasDefault,
                        defaultValueExpression: entry.defaultValueExpression,
                        type: effectiveType,
                        hasDeclaredType: true,
                    };
                    if (entry.isKeywordOnly) {
                        keywordOnlyParams.push(functionParam);
                    }
                    else {
                        types_1.FunctionType.addParameter(initType, functionParam);
                    }
                }
            });
            if (keywordOnlyParams.length > 0) {
                types_1.FunctionType.addKeywordOnlyParameterSeparator(initType);
                keywordOnlyParams.forEach((param) => {
                    types_1.FunctionType.addParameter(initType, param);
                });
            }
        }
        symbolTable.set('__init__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, initType));
        symbolTable.set('__new__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, newType));
    }
    // Synthesize the __match_args__ class variable if it doesn't exist.
    const strType = evaluator.getBuiltInType(node, 'str');
    const tupleClassType = evaluator.getBuiltInType(node, 'tuple');
    if (tupleClassType &&
        (0, types_1.isInstantiableClass)(tupleClassType) &&
        strType &&
        (0, types_1.isInstantiableClass)(strType) &&
        !symbolTable.has('__match_args__')) {
        const matchArgsNames = [];
        fullDataClassEntries.forEach((entry) => {
            if (entry.includeInInit && !entry.isKeywordOnly) {
                // Use the field name, not its alias (if it has one).
                matchArgsNames.push(entry.name);
            }
        });
        const literalTypes = matchArgsNames.map((name) => {
            return { type: types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneWithLiteral(strType, name)), isUnbounded: false };
        });
        const matchArgsType = types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeTupleClass)(tupleClassType, literalTypes));
        symbolTable.set('__match_args__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, matchArgsType));
    }
    const synthesizeComparisonMethod = (operator, paramType) => {
        const operatorMethod = types_1.FunctionType.createSynthesizedInstance(operator);
        types_1.FunctionType.addParameter(operatorMethod, selfParam);
        types_1.FunctionType.addParameter(operatorMethod, {
            category: 0 /* ParameterCategory.Simple */,
            name: 'other',
            type: paramType,
            hasDeclaredType: true,
        });
        operatorMethod.details.declaredReturnType = evaluator.getBuiltInObject(node, 'bool');
        // If a method of this name already exists, don't override it.
        if (!symbolTable.get(operator)) {
            symbolTable.set(operator, symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, operatorMethod));
        }
    };
    // Synthesize comparison operators.
    if (!types_1.ClassType.isSkipSynthesizedDataClassEq(classType)) {
        synthesizeComparisonMethod('__eq__', evaluator.getBuiltInObject(node, 'object'));
    }
    if (types_1.ClassType.isSynthesizedDataclassOrder(classType)) {
        const objType = types_1.ClassType.cloneAsInstance(classType);
        ['__lt__', '__le__', '__gt__', '__ge__'].forEach((operator) => {
            synthesizeComparisonMethod(operator, objType);
        });
    }
    let synthesizeHashFunction = types_1.ClassType.isFrozenDataClass(classType);
    const synthesizeHashNone = !types_1.ClassType.isSkipSynthesizedDataClassEq(classType) && !types_1.ClassType.isFrozenDataClass(classType);
    if (skipSynthesizeHash) {
        synthesizeHashFunction = false;
    }
    // If the user has indicated that a hash function should be generated even if it's unsafe
    // to do so or there is already a hash function present, override the default logic.
    if (types_1.ClassType.isSynthesizeDataClassUnsafeHash(classType)) {
        synthesizeHashFunction = true;
    }
    if (synthesizeHashFunction) {
        const hashMethod = types_1.FunctionType.createSynthesizedInstance('__hash__');
        types_1.FunctionType.addParameter(hashMethod, selfParam);
        hashMethod.details.declaredReturnType = evaluator.getBuiltInObject(node, 'int');
        symbolTable.set('__hash__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 4096 /* SymbolFlags.IgnoredForOverrideChecks */, hashMethod));
    }
    else if (synthesizeHashNone && !skipSynthesizeHash) {
        symbolTable.set('__hash__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 4096 /* SymbolFlags.IgnoredForOverrideChecks */, evaluator.getNoneType()));
    }
    let dictType = evaluator.getBuiltInType(node, 'dict');
    if ((0, types_1.isInstantiableClass)(dictType)) {
        dictType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictType, [evaluator.getBuiltInObject(node, 'str'), types_1.AnyType.create()], 
        /* isTypeArgumentExplicit */ true));
    }
    symbolTable.set('__dataclass_fields__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 128 /* SymbolFlags.ClassVar */, dictType));
    if (types_1.ClassType.isGeneratedDataClassSlots(classType) && classType.details.localSlotsNames === undefined) {
        classType.details.localSlotsNames = localDataClassEntries.map((entry) => entry.name);
    }
    // Should we synthesize a __slots__ symbol?
    if (types_1.ClassType.isGeneratedDataClassSlots(classType)) {
        let iterableType = (_a = evaluator.getTypingType(node, 'Iterable')) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        if ((0, types_1.isInstantiableClass)(iterableType)) {
            iterableType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(iterableType, [evaluator.getBuiltInObject(node, 'str')], 
            /* isTypeArgumentExplicit */ true));
        }
        symbolTable.set('__slots__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 128 /* SymbolFlags.ClassVar */, iterableType));
    }
    // If this dataclass derived from a NamedTuple, update the NamedTuple with
    // the specialized entry types.
    if ((0, namedTuples_1.updateNamedTupleBaseClass)(classType, fullDataClassEntries.map((entry) => entry.type), 
    /* isTypeArgumentExplicit */ true)) {
        // Recompute the MRO based on the updated NamedTuple base class.
        (0, typeUtils_1.computeMroLinearization)(classType);
    }
}
exports.synthesizeDataClassMethods = synthesizeDataClassMethods;
// If a field specifier is used to define a field, it may define a default
// argument value (either True or False) for a supported keyword parameter.
// This function extracts that default value if present and returns it. If
// it's not present, it returns undefined.
function getDefaultArgValueForFieldSpecifier(evaluator, callNode, callTypeResult, paramName) {
    const callType = callTypeResult.type;
    let callTarget;
    if ((0, types_1.isFunction)(callType)) {
        callTarget = callType;
    }
    else if ((0, types_1.isOverloadedFunction)(callType)) {
        callTarget = evaluator.getBestOverloadForArguments(callNode, { type: callType, isIncomplete: callTypeResult.isIncomplete }, callNode.arguments);
    }
    else if ((0, types_1.isInstantiableClass)(callType)) {
        const initMethodResult = (0, constructors_1.getBoundInitMethod)(evaluator, callNode, callType);
        if (initMethodResult) {
            if ((0, types_1.isFunction)(initMethodResult.type)) {
                callTarget = initMethodResult.type;
            }
            else if ((0, types_1.isOverloadedFunction)(initMethodResult.type)) {
                callTarget = evaluator.getBestOverloadForArguments(callNode, { type: initMethodResult.type }, callNode.arguments);
            }
        }
    }
    if (callTarget) {
        const initParam = callTarget.details.parameters.find((p) => p.name === paramName);
        if (initParam) {
            // Is the parameter type a literal bool?
            if (initParam.hasDeclaredType &&
                (0, types_1.isClass)(initParam.type) &&
                typeof initParam.type.literalValue === 'boolean') {
                return initParam.type.literalValue;
            }
            // Is the default argument value a literal bool?
            if (initParam.defaultValueExpression &&
                initParam.defaultType &&
                (0, types_1.isClass)(initParam.defaultType) &&
                typeof initParam.defaultType.literalValue === 'boolean') {
                return initParam.defaultType.literalValue;
            }
        }
    }
    return undefined;
}
// Validates converter and, if valid, returns its input type. If invalid,
// fieldType is returned.
function getConverterInputType(evaluator, converterNode, fieldType, fieldName) {
    var _a;
    const converterType = getConverterAsFunction(evaluator, evaluator.getTypeOfExpression(converterNode.valueExpression).type);
    if (!converterType) {
        return fieldType;
    }
    // Create synthesized function of the form Callable[[T], fieldType] which
    // will be used to check compatibility of the provided converter.
    const typeVar = types_1.TypeVarType.createInstance('__converterInput');
    typeVar.scopeId = (0, parseTreeUtils_1.getScopeIdForNode)(converterNode);
    const targetFunction = types_1.FunctionType.createSynthesizedInstance('');
    targetFunction.details.typeVarScopeId = typeVar.scopeId;
    targetFunction.details.declaredReturnType = fieldType;
    types_1.FunctionType.addParameter(targetFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: '__input',
        type: typeVar,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addPositionOnlyParameterSeparator(targetFunction);
    if ((0, types_1.isFunction)(converterType)) {
        const typeVarContext = new typeVarContext_1.TypeVarContext(typeVar.scopeId);
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        if (evaluator.assignType(targetFunction, converterType, diagAddendum, typeVarContext)) {
            const solution = (0, typeUtils_1.applySolvedTypeVars)(typeVar, typeVarContext, { unknownIfNotFound: true });
            return solution;
        }
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassConverterFunction().format({
            argType: evaluator.printType(converterType),
            fieldType: evaluator.printType(fieldType),
            fieldName: fieldName,
        }) + diagAddendum.getString(), converterNode, (_a = diagAddendum.getEffectiveTextRange()) !== null && _a !== void 0 ? _a : converterNode);
    }
    else {
        const acceptedTypes = [];
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        types_1.OverloadedFunctionType.getOverloads(converterType).forEach((overload) => {
            const typeVarContext = new typeVarContext_1.TypeVarContext(typeVar.scopeId);
            if (evaluator.assignType(targetFunction, overload, diagAddendum, typeVarContext)) {
                const overloadSolution = (0, typeUtils_1.applySolvedTypeVars)(typeVar, typeVarContext, { unknownIfNotFound: true });
                acceptedTypes.push(overloadSolution);
            }
        });
        if (acceptedTypes.length > 0) {
            return (0, types_1.combineTypes)(acceptedTypes);
        }
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassConverterOverloads().format({
            funcName: converterType.overloads[0].details.name || '<anonymous function>',
            fieldType: evaluator.printType(fieldType),
            fieldName: fieldName,
        }) + diagAddendum.getString(), converterNode);
    }
    return fieldType;
}
function getConverterAsFunction(evaluator, converterType) {
    if ((0, types_1.isFunction)(converterType) || (0, types_1.isOverloadedFunction)(converterType)) {
        return converterType;
    }
    if ((0, types_1.isClassInstance)(converterType)) {
        return evaluator.getBoundMagicMethod(converterType, '__call__');
    }
    if ((0, types_1.isInstantiableClass)(converterType)) {
        let fromConstructor = (0, constructors_1.createFunctionFromConstructor)(evaluator, converterType);
        if (fromConstructor) {
            // If conversion to a constructor resulted in a union type, we'll
            // choose the first of the two subtypes, which typically corresponds
            // to the __init__ method (rather than the __new__ method).
            if ((0, types_1.isUnion)(fromConstructor)) {
                fromConstructor = fromConstructor.subtypes[0];
            }
            if ((0, types_1.isFunction)(fromConstructor) || (0, types_1.isOverloadedFunction)(fromConstructor)) {
                return fromConstructor;
            }
        }
    }
    return undefined;
}
// Synthesizes an asymmetric descriptor class to be used in place of the
// annotated type of a field with a converter. The descriptor's __get__ method
// returns the declared type of the field and its __set__ method accepts the
// converter's input type. Returns the symbol for an instance of this descriptor
// type.
function getDescriptorForConverterField(evaluator, dataclassNode, converterNode, fieldName, getType, setType) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(dataclassNode);
    const typeMetaclass = evaluator.getBuiltInType(dataclassNode, 'type');
    const descriptorName = `__converterDescriptor_${fieldName}`;
    const descriptorClass = types_1.ClassType.createInstantiable(descriptorName, (0, parseTreeUtils_1.getClassFullName)(converterNode, fileInfo.moduleName, descriptorName), fileInfo.moduleName, fileInfo.fileUri, 0 /* ClassTypeFlags.None */, (0, parseTreeUtils_1.getTypeSourceId)(converterNode), 
    /* declaredMetaclass */ undefined, (0, types_1.isInstantiableClass)(typeMetaclass) ? typeMetaclass : types_1.UnknownType.create());
    descriptorClass.details.baseClasses.push(evaluator.getBuiltInType(dataclassNode, 'object'));
    (0, typeUtils_1.computeMroLinearization)(descriptorClass);
    const fields = types_1.ClassType.getSymbolTable(descriptorClass);
    const selfType = (0, typeUtils_1.synthesizeTypeVarForSelfCls)(descriptorClass, /* isClsParam */ false);
    const setFunction = types_1.FunctionType.createSynthesizedInstance('__set__');
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: selfType,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'value',
        type: setType,
        hasDeclaredType: true,
    });
    setFunction.details.declaredReturnType = evaluator.getNoneType();
    const setSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, setFunction);
    fields.set('__set__', setSymbol);
    const getFunction = types_1.FunctionType.createSynthesizedInstance('__get__');
    types_1.FunctionType.addParameter(getFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: selfType,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(getFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(getFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'objtype',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    getFunction.details.declaredReturnType = getType;
    const getSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, getFunction);
    fields.set('__get__', getSymbol);
    return symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.ClassType.cloneAsInstance(descriptorClass));
}
// If the specified type is a descriptor — in particular, if it implements a
// __set__ method, this method transforms the type into the input parameter
// for the set method.
function transformDescriptorType(evaluator, type) {
    if (!(0, types_1.isClassInstance)(type) || (0, typeUtils_1.isMetaclassInstance)(type)) {
        return type;
    }
    const setMethodType = evaluator.getBoundMagicMethod(type, '__set__');
    if (!setMethodType) {
        return type;
    }
    if (!(0, types_1.isFunction)(setMethodType)) {
        return type;
    }
    // The value parameter for a bound __set__ method is parameter index 1.
    return types_1.FunctionType.getEffectiveParameterType(setMethodType, 1);
}
// Builds a sorted list of dataclass entries that are inherited by
// the specified class. These entries must be unique and in reverse-MRO
// order. Returns true if all of the class types in the hierarchy are
// known, false if one or more are unknown.
function addInheritedDataClassEntries(classType, entries) {
    let allAncestorsAreKnown = true;
    types_1.ClassType.getReverseMro(classType).forEach((mroClass) => {
        if ((0, types_1.isInstantiableClass)(mroClass)) {
            const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(mroClass);
            const dataClassEntries = types_1.ClassType.getDataClassEntries(mroClass);
            // Add the entries to the end of the list, replacing same-named
            // entries if found.
            dataClassEntries.forEach((entry) => {
                const existingIndex = entries.findIndex((e) => e.name === entry.name);
                // If the type from the parent class is generic, we need to convert
                // to the type parameter namespace of child class.
                const updatedEntry = { ...entry };
                updatedEntry.type = (0, typeUtils_1.applySolvedTypeVars)(updatedEntry.type, typeVarContext);
                if (entry.isClassVar) {
                    // If this entry is a class variable, it overrides an existing
                    // instance variable, so delete it.
                    if (existingIndex >= 0) {
                        entries.splice(existingIndex, 1);
                    }
                }
                else if (existingIndex >= 0) {
                    entries[existingIndex] = updatedEntry;
                }
                else {
                    entries.push(updatedEntry);
                }
            });
        }
        else {
            allAncestorsAreKnown = false;
        }
    });
    return allAncestorsAreKnown;
}
function isDataclassFieldConstructor(type, fieldDescriptorNames) {
    let callName;
    if ((0, types_1.isFunction)(type)) {
        callName = type.details.fullName;
    }
    else if ((0, types_1.isOverloadedFunction)(type)) {
        callName = type.overloads[0].details.fullName;
    }
    else if ((0, types_1.isInstantiableClass)(type)) {
        callName = type.details.fullName;
    }
    if (!callName) {
        return false;
    }
    return fieldDescriptorNames.some((name) => name === callName);
}
function validateDataClassTransformDecorator(evaluator, node) {
    const behaviors = {
        keywordOnlyParams: false,
        generateEq: true,
        generateOrder: false,
        frozen: false,
        fieldDescriptorNames: [],
    };
    const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
    // Parse the arguments to the call.
    node.arguments.forEach((arg) => {
        if (!arg.name || arg.argumentCategory !== 0 /* ArgumentCategory.Simple */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.dataClassTransformPositionalParam(), arg);
            return;
        }
        switch (arg.name.value) {
            case 'kw_only_default': {
                const value = (0, staticExpressions_1.evaluateStaticBoolExpression)(arg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                if (value === undefined) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformExpectedBoolLiteral(), arg.valueExpression);
                    return;
                }
                behaviors.keywordOnlyParams = value;
                break;
            }
            case 'eq_default': {
                const value = (0, staticExpressions_1.evaluateStaticBoolExpression)(arg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                if (value === undefined) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformExpectedBoolLiteral(), arg.valueExpression);
                    return;
                }
                behaviors.generateEq = value;
                break;
            }
            case 'order_default': {
                const value = (0, staticExpressions_1.evaluateStaticBoolExpression)(arg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                if (value === undefined) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformExpectedBoolLiteral(), arg.valueExpression);
                    return;
                }
                behaviors.generateOrder = value;
                break;
            }
            case 'frozen_default': {
                const value = (0, staticExpressions_1.evaluateStaticBoolExpression)(arg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                if (value === undefined) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformExpectedBoolLiteral(), arg.valueExpression);
                    return;
                }
                behaviors.frozen = value;
                break;
            }
            // Earlier versions of the dataclass_transform spec used the name "field_descriptors"
            // rather than "field_specifiers". The older name is now deprecated but still supported
            // for the time being because some libraries shipped with the older __dataclass_transform__
            // form that supported this older parameter name.
            case 'field_descriptors':
            case 'field_specifiers': {
                const valueType = evaluator.getTypeOfExpression(arg.valueExpression).type;
                if (!(0, types_1.isClassInstance)(valueType) ||
                    !types_1.ClassType.isBuiltIn(valueType, 'tuple') ||
                    !valueType.tupleTypeArguments ||
                    valueType.tupleTypeArguments.some((entry) => !(0, types_1.isInstantiableClass)(entry.type) &&
                        !(0, types_1.isFunction)(entry.type) &&
                        !(0, types_1.isOverloadedFunction)(entry.type))) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformFieldSpecifier().format({
                        type: evaluator.printType(valueType),
                    }), arg.valueExpression);
                    return;
                }
                if (!behaviors.fieldDescriptorNames) {
                    behaviors.fieldDescriptorNames = [];
                }
                valueType.tupleTypeArguments.forEach((arg) => {
                    if ((0, types_1.isInstantiableClass)(arg.type) || (0, types_1.isFunction)(arg.type)) {
                        behaviors.fieldDescriptorNames.push(arg.type.details.fullName);
                    }
                    else if ((0, types_1.isOverloadedFunction)(arg.type)) {
                        behaviors.fieldDescriptorNames.push(arg.type.overloads[0].details.fullName);
                    }
                });
                break;
            }
            default:
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassTransformUnknownArgument().format({ name: arg.name.value }), arg.valueExpression);
                break;
        }
    });
    return behaviors;
}
exports.validateDataClassTransformDecorator = validateDataClassTransformDecorator;
function getDataclassDecoratorBehaviors(type) {
    var _a;
    let functionType;
    if ((0, types_1.isFunction)(type)) {
        functionType = type;
    }
    else if ((0, types_1.isOverloadedFunction)(type)) {
        // Find the first overload or implementation that contains a
        // dataclass_transform decorator. If more than one have such a decorator,
        // only the first one will be honored, as per PEP 681.
        functionType =
            (_a = type.overloads.find((overload) => !!overload.details.decoratorDataClassBehaviors)) !== null && _a !== void 0 ? _a : type.overloads[0];
    }
    if (!functionType) {
        return undefined;
    }
    if (functionType.details.decoratorDataClassBehaviors) {
        return functionType.details.decoratorDataClassBehaviors;
    }
    // Is this the built-in dataclass? If so, return the default behaviors.
    if (functionType.details.fullName === 'dataclasses.dataclass') {
        return {
            keywordOnlyParams: false,
            generateEq: true,
            generateOrder: false,
            frozen: false,
            fieldDescriptorNames: ['dataclasses.field', 'dataclasses.Field'],
        };
    }
    return undefined;
}
exports.getDataclassDecoratorBehaviors = getDataclassDecoratorBehaviors;
function applyDataClassBehaviorOverride(evaluator, errorNode, classType, argName, argValueExpr) {
    const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
    const value = (0, staticExpressions_1.evaluateStaticBoolExpression)(argValueExpr, fileInfo.executionEnvironment, fileInfo.definedConstants);
    applyDataClassBehaviorOverrideValue(evaluator, errorNode, classType, argName, value);
}
function applyDataClassBehaviorOverrideValue(evaluator, errorNode, classType, argName, argValue) {
    switch (argName) {
        case 'order':
            if (argValue === true) {
                classType.details.flags |= 64 /* ClassTypeFlags.SynthesizedDataClassOrder */;
            }
            else if (argValue === false) {
                classType.details.flags &= ~64 /* ClassTypeFlags.SynthesizedDataClassOrder */;
            }
            break;
        case 'kw_only':
            if (argValue === false) {
                classType.details.flags &= ~4194304 /* ClassTypeFlags.DataClassKeywordOnlyParams */;
            }
            else if (argValue === true) {
                classType.details.flags |= 4194304 /* ClassTypeFlags.DataClassKeywordOnlyParams */;
            }
            break;
        case 'frozen': {
            let hasUnfrozenBaseClass = false;
            let hasFrozenBaseClass = false;
            if (argValue === false) {
                classType.details.flags &= ~8 /* ClassTypeFlags.FrozenDataClass */;
            }
            else if (argValue === true) {
                classType.details.flags |= 8 /* ClassTypeFlags.FrozenDataClass */;
            }
            classType.details.baseClasses.forEach((baseClass) => {
                if ((0, types_1.isInstantiableClass)(baseClass) && types_1.ClassType.isDataClass(baseClass)) {
                    if (types_1.ClassType.isFrozenDataClass(baseClass)) {
                        hasFrozenBaseClass = true;
                    }
                    else if (!baseClass.details.classDataClassTransform &&
                        !(baseClass.details.declaredMetaclass &&
                            (0, types_1.isInstantiableClass)(baseClass.details.declaredMetaclass) &&
                            !!baseClass.details.declaredMetaclass.details.classDataClassTransform)) {
                        // If this base class is unfrozen and isn't the class that directly
                        // references the metaclass that provides dataclass-like behaviors,
                        // we'll assume we're deriving from an unfrozen dataclass.
                        hasUnfrozenBaseClass = true;
                    }
                }
            });
            if (argValue) {
                // A frozen dataclass cannot derive from a non-frozen dataclass.
                if (hasUnfrozenBaseClass) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassBaseClassNotFrozen(), errorNode);
                }
            }
            else {
                // A non-frozen dataclass cannot derive from a frozen dataclass.
                if (hasFrozenBaseClass) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassBaseClassFrozen(), errorNode);
                }
            }
            break;
        }
        case 'init':
            if (argValue === false) {
                classType.details.flags |= 16 /* ClassTypeFlags.SkipSynthesizedDataClassInit */;
            }
            else if (argValue === true) {
                classType.details.flags &= ~16 /* ClassTypeFlags.SkipSynthesizedDataClassInit */;
            }
            break;
        case 'eq':
            if (argValue === false) {
                classType.details.flags |= 32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */;
            }
            else if (argValue === true) {
                classType.details.flags &= ~32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */;
            }
            break;
        case 'slots':
            if (argValue === true) {
                classType.details.flags |= 67108864 /* ClassTypeFlags.GenerateDataClassSlots */;
                if (classType.details.localSlotsNames) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dataClassSlotsOverwrite(), errorNode);
                }
            }
            else if (argValue === false) {
                classType.details.flags &= ~67108864 /* ClassTypeFlags.GenerateDataClassSlots */;
            }
            break;
        case 'hash':
        case 'unsafe_hash':
            if (argValue === true) {
                classType.details.flags |= 134217728 /* ClassTypeFlags.SynthesizeDataClassUnsafeHash */;
            }
            break;
    }
}
function applyDataClassClassBehaviorOverrides(evaluator, errorNode, classType, args, defaultBehaviors) {
    let sawFrozenArg = false;
    args.forEach((arg) => {
        if (arg.valueExpression && arg.name) {
            applyDataClassBehaviorOverride(evaluator, arg.name, classType, arg.name.value, arg.valueExpression);
            if (arg.name.value === 'frozen') {
                sawFrozenArg = true;
            }
        }
    });
    // If there was no frozen argument, it is implicitly false. This will
    // validate that we're not overriding a frozen class with a non-frozen class.
    if (!sawFrozenArg) {
        applyDataClassBehaviorOverrideValue(evaluator, errorNode, classType, 'frozen', defaultBehaviors.frozen);
    }
}
exports.applyDataClassClassBehaviorOverrides = applyDataClassClassBehaviorOverrides;
function applyDataClassDefaultBehaviors(classType, defaultBehaviors) {
    classType.details.dataClassBehaviors = defaultBehaviors;
    classType.details.flags |= 4 /* ClassTypeFlags.DataClass */;
    if (defaultBehaviors.keywordOnlyParams) {
        classType.details.flags |= 4194304 /* ClassTypeFlags.DataClassKeywordOnlyParams */;
    }
    if (!defaultBehaviors.generateEq) {
        classType.details.flags |= 32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */;
    }
    if (defaultBehaviors.generateOrder) {
        classType.details.flags |= 64 /* ClassTypeFlags.SynthesizedDataClassOrder */;
    }
    if (defaultBehaviors.frozen) {
        classType.details.flags |= 8 /* ClassTypeFlags.FrozenDataClass */;
    }
}
exports.applyDataClassDefaultBehaviors = applyDataClassDefaultBehaviors;
function applyDataClassDecorator(evaluator, errorNode, classType, defaultBehaviors, callNode) {
    var _a;
    applyDataClassDefaultBehaviors(classType, defaultBehaviors);
    applyDataClassClassBehaviorOverrides(evaluator, errorNode, classType, (_a = callNode === null || callNode === void 0 ? void 0 : callNode.arguments) !== null && _a !== void 0 ? _a : [], defaultBehaviors);
}
exports.applyDataClassDecorator = applyDataClassDecorator;


/***/ }),

/***/ "../pyright-internal/src/analyzer/declaration.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/analyzer/declaration.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * declaration.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Tracks the location within the code where a named entity
 * is declared and its associated declared type (if the type
 * is explicitly declared).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isUnresolvedAliasDeclaration = exports.isIntrinsicDeclaration = exports.isSpecialBuiltInClassDeclaration = exports.isAliasDeclaration = exports.isVariableDeclaration = exports.isTypeAliasDeclaration = exports.isTypeParameterDeclaration = exports.isParameterDeclaration = exports.isClassDeclaration = exports.isFunctionDeclaration = exports.UnresolvedModuleMarker = void 0;
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
exports.UnresolvedModuleMarker = uri_1.Uri.constant('*** unresolved module ***');
function isFunctionDeclaration(decl) {
    return decl.type === 5 /* DeclarationType.Function */;
}
exports.isFunctionDeclaration = isFunctionDeclaration;
function isClassDeclaration(decl) {
    return decl.type === 6 /* DeclarationType.Class */;
}
exports.isClassDeclaration = isClassDeclaration;
function isParameterDeclaration(decl) {
    return decl.type === 2 /* DeclarationType.Parameter */;
}
exports.isParameterDeclaration = isParameterDeclaration;
function isTypeParameterDeclaration(decl) {
    return decl.type === 3 /* DeclarationType.TypeParameter */;
}
exports.isTypeParameterDeclaration = isTypeParameterDeclaration;
function isTypeAliasDeclaration(decl) {
    return decl.type === 4 /* DeclarationType.TypeAlias */;
}
exports.isTypeAliasDeclaration = isTypeAliasDeclaration;
function isVariableDeclaration(decl) {
    return decl.type === 1 /* DeclarationType.Variable */;
}
exports.isVariableDeclaration = isVariableDeclaration;
function isAliasDeclaration(decl) {
    return decl.type === 8 /* DeclarationType.Alias */;
}
exports.isAliasDeclaration = isAliasDeclaration;
function isSpecialBuiltInClassDeclaration(decl) {
    return decl.type === 7 /* DeclarationType.SpecialBuiltInClass */;
}
exports.isSpecialBuiltInClassDeclaration = isSpecialBuiltInClassDeclaration;
function isIntrinsicDeclaration(decl) {
    return decl.type === 0 /* DeclarationType.Intrinsic */;
}
exports.isIntrinsicDeclaration = isIntrinsicDeclaration;
function isUnresolvedAliasDeclaration(decl) {
    return isAliasDeclaration(decl) && decl.uri.equals(exports.UnresolvedModuleMarker);
}
exports.isUnresolvedAliasDeclaration = isUnresolvedAliasDeclaration;


/***/ }),

/***/ "../pyright-internal/src/analyzer/declarationUtils.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/analyzer/declarationUtils.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * declarationUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Collection of static methods that operate on declarations.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.resolveAliasDeclaration = exports.createSynthesizedAliasDeclaration = exports.getDeclarationsWithUsesLocalNameRemoved = exports.isDefinedInFile = exports.getNameNodeForDeclaration = exports.getNameFromDeclaration = exports.areDeclarationsSame = exports.hasTypeForDeclaration = void 0;
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const declaration_1 = __webpack_require__(/*! ./declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
function hasTypeForDeclaration(declaration) {
    switch (declaration.type) {
        case 0 /* DeclarationType.Intrinsic */:
        case 6 /* DeclarationType.Class */:
        case 7 /* DeclarationType.SpecialBuiltInClass */:
        case 5 /* DeclarationType.Function */:
        case 3 /* DeclarationType.TypeParameter */:
        case 4 /* DeclarationType.TypeAlias */:
            return true;
        case 2 /* DeclarationType.Parameter */: {
            if (declaration.node.typeAnnotation || declaration.node.typeAnnotationComment) {
                return true;
            }
            // Handle function type comments.
            const parameterParent = declaration.node.parent;
            if ((parameterParent === null || parameterParent === void 0 ? void 0 : parameterParent.nodeType) === 28 /* ParseNodeType.Function */) {
                if (parameterParent.functionAnnotationComment &&
                    !parameterParent.functionAnnotationComment.isParamListEllipsis) {
                    const paramAnnotations = parameterParent.functionAnnotationComment.paramTypeAnnotations;
                    // Handle the case where the annotation comment is missing an
                    // annotation for the first parameter (self or cls).
                    if (parameterParent.parameters.length > paramAnnotations.length &&
                        declaration.node === parameterParent.parameters[0]) {
                        return false;
                    }
                    return true;
                }
            }
            return false;
        }
        case 1 /* DeclarationType.Variable */:
            return !!declaration.typeAnnotationNode;
        case 8 /* DeclarationType.Alias */:
            return false;
    }
}
exports.hasTypeForDeclaration = hasTypeForDeclaration;
function areDeclarationsSame(decl1, decl2, treatModuleInImportAndFromImportSame = false, skipRangeForAliases = false) {
    if (decl1.type !== decl2.type) {
        return false;
    }
    if (!decl1.uri.equals(decl2.uri)) {
        return false;
    }
    if (!skipRangeForAliases || decl1.type !== 8 /* DeclarationType.Alias */) {
        if (decl1.range.start.line !== decl2.range.start.line ||
            decl1.range.start.character !== decl2.range.start.character) {
            return false;
        }
    }
    // Alias declarations refer to the entire import statement.
    // We need to further differentiate.
    if (decl1.type === 8 /* DeclarationType.Alias */ && decl2.type === 8 /* DeclarationType.Alias */) {
        if (decl1.symbolName !== decl2.symbolName || decl1.usesLocalName !== decl2.usesLocalName) {
            return false;
        }
        if (treatModuleInImportAndFromImportSame) {
            // Treat "module" in "import [|module|]", "from [|module|] import ..."
            // or "from ... import [|module|]" same in IDE services.
            //
            // Some case such as "from [|module|] import ...", symbol for [|module|] doesn't even
            // exist and it can't be referenced inside of a module, but nonetheless, IDE still
            // needs these sometimes for things like hover tooltip, highlight references,
            // find all references and etc.
            return true;
        }
        if (decl1.node !== decl2.node) {
            return false;
        }
    }
    return true;
}
exports.areDeclarationsSame = areDeclarationsSame;
function getNameFromDeclaration(declaration) {
    var _a;
    switch (declaration.type) {
        case 8 /* DeclarationType.Alias */:
            return declaration.symbolName;
        case 6 /* DeclarationType.Class */:
        case 5 /* DeclarationType.Function */:
        case 3 /* DeclarationType.TypeParameter */:
        case 4 /* DeclarationType.TypeAlias */:
            return declaration.node.name.value;
        case 2 /* DeclarationType.Parameter */:
            return (_a = declaration.node.name) === null || _a === void 0 ? void 0 : _a.value;
        case 1 /* DeclarationType.Variable */:
            return declaration.node.nodeType === 38 /* ParseNodeType.Name */ ? declaration.node.value : undefined;
        case 0 /* DeclarationType.Intrinsic */:
        case 7 /* DeclarationType.SpecialBuiltInClass */:
            return declaration.node.nodeType === 54 /* ParseNodeType.TypeAnnotation */ &&
                declaration.node.valueExpression.nodeType === 38 /* ParseNodeType.Name */
                ? declaration.node.valueExpression.value
                : undefined;
    }
    throw new Error(`Shouldn't reach here`);
}
exports.getNameFromDeclaration = getNameFromDeclaration;
function getNameNodeForDeclaration(declaration) {
    var _a, _b;
    switch (declaration.type) {
        case 8 /* DeclarationType.Alias */:
            if (declaration.node.nodeType === 21 /* ParseNodeType.ImportAs */) {
                return (_a = declaration.node.alias) !== null && _a !== void 0 ? _a : declaration.node.module.nameParts[0];
            }
            else if (declaration.node.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
                return (_b = declaration.node.alias) !== null && _b !== void 0 ? _b : declaration.node.name;
            }
            else {
                return declaration.node.module.nameParts[0];
            }
        case 6 /* DeclarationType.Class */:
        case 5 /* DeclarationType.Function */:
        case 3 /* DeclarationType.TypeParameter */:
        case 2 /* DeclarationType.Parameter */:
        case 4 /* DeclarationType.TypeAlias */:
            return declaration.node.name;
        case 1 /* DeclarationType.Variable */:
            return declaration.node.nodeType === 38 /* ParseNodeType.Name */ ? declaration.node : undefined;
        case 0 /* DeclarationType.Intrinsic */:
        case 7 /* DeclarationType.SpecialBuiltInClass */:
            return undefined;
    }
    throw new Error(`Shouldn't reach here`);
}
exports.getNameNodeForDeclaration = getNameNodeForDeclaration;
function isDefinedInFile(decl, fileUri) {
    var _a;
    if ((0, declaration_1.isAliasDeclaration)(decl)) {
        // Alias decl's path points to the original symbol
        // the alias is pointing to. So, we need to get the
        // filepath in that the alias is defined from the node.
        return (_a = (0, parseTreeUtils_1.getFileInfoFromNode)(decl.node)) === null || _a === void 0 ? void 0 : _a.fileUri.equals(fileUri);
    }
    // Other decls, the path points to the file the symbol is defined in.
    return decl.uri.equals(fileUri);
}
exports.isDefinedInFile = isDefinedInFile;
function getDeclarationsWithUsesLocalNameRemoved(decls) {
    // Make a shallow copy and clear the "usesLocalName" field.
    return decls.map((localDecl) => {
        if (localDecl.type !== 8 /* DeclarationType.Alias */) {
            return localDecl;
        }
        const nonLocalDecl = { ...localDecl };
        nonLocalDecl.usesLocalName = false;
        return nonLocalDecl;
    });
}
exports.getDeclarationsWithUsesLocalNameRemoved = getDeclarationsWithUsesLocalNameRemoved;
function createSynthesizedAliasDeclaration(uri) {
    // The only time this decl is used is for IDE services such as
    // the find all references, hover provider and etc.
    return {
        type: 8 /* DeclarationType.Alias */,
        node: undefined,
        uri,
        loadSymbolsFromPath: false,
        range: (0, textRange_1.getEmptyRange)(),
        implicitImports: new Map(),
        usesLocalName: false,
        moduleName: '',
        isInExceptSuite: false,
    };
}
exports.createSynthesizedAliasDeclaration = createSynthesizedAliasDeclaration;
// If the specified declaration is an alias declaration that points to a symbol,
// it resolves the alias and looks up the symbol, then returns a declaration
// (typically the last) associated with that symbol. It does this recursively if
// necessary. If a symbol lookup fails, undefined is returned. If resolveLocalNames
// is true, the method resolves aliases through local renames ("as" clauses found
// in import statements).
function resolveAliasDeclaration(importLookup, declaration, options) {
    let curDeclaration = declaration;
    const alreadyVisited = [];
    let isPrivate = false;
    // These variables are used to find a transition from a non-py.typed to
    // a py.typed resolution chain. In this case, if the imported symbol
    // is a private symbol (i.e. not intended to be re-exported), we store
    // the name of the importer and imported modules so the caller can
    // report an error.
    let sawPyTypedTransition = false;
    let privateImported;
    let privatePyTypedImporter;
    let privateNonPyTypedImporter;
    while (true) {
        if (curDeclaration.type !== 8 /* DeclarationType.Alias */ || !curDeclaration.symbolName) {
            return {
                declaration: curDeclaration,
                isPrivate,
                privateImported,
                privatePyTypedImporter,
                privateNonPyTypedImporter,
            };
        }
        // If we are not supposed to follow local alias names and this
        // is a local name, don't continue to follow the alias.
        if (!options.resolveLocalNames && curDeclaration.usesLocalName) {
            return {
                declaration: curDeclaration,
                isPrivate,
                privateImported,
                privatePyTypedImporter,
                privateNonPyTypedImporter,
            };
        }
        let lookupResult;
        if (!curDeclaration.uri.isEmpty() && curDeclaration.loadSymbolsFromPath) {
            lookupResult = importLookup(curDeclaration.uri, {
                skipFileNeededCheck: options.skipFileNeededCheck,
            });
        }
        const symbol = lookupResult
            ? lookupResult.symbolTable.get(curDeclaration.symbolName)
            : undefined;
        if (!symbol) {
            if (curDeclaration.submoduleFallback) {
                if (curDeclaration.symbolName) {
                    // See if we are resolving a specific imported symbol name and the submodule
                    // fallback cannot be resolved. For example, `from a import b`. If b is both
                    // a symbol in `a/__init__.py` and a submodule `a/b.py` and we are not using
                    // type information from this library (e.g. a non-py.typed library source file
                    // when useLibraryCodeForTypes is disabled), b should be evaluated as Unknown,
                    // not as a module.
                    if (!curDeclaration.uri.isEmpty() &&
                        curDeclaration.submoduleFallback.type === 8 /* DeclarationType.Alias */ &&
                        !curDeclaration.submoduleFallback.uri.isEmpty()) {
                        const lookupResult = importLookup(curDeclaration.submoduleFallback.uri, {
                            skipFileNeededCheck: options.skipFileNeededCheck,
                            skipParsing: true,
                        });
                        if (!lookupResult) {
                            return undefined;
                        }
                    }
                }
                let submoduleFallback = curDeclaration.submoduleFallback;
                if (curDeclaration.symbolName) {
                    submoduleFallback = { ...curDeclaration.submoduleFallback };
                    let baseModuleName = submoduleFallback.moduleName;
                    if (baseModuleName) {
                        baseModuleName = `${baseModuleName}.`;
                    }
                    submoduleFallback.moduleName = `${baseModuleName}${curDeclaration.symbolName}`;
                }
                return resolveAliasDeclaration(importLookup, submoduleFallback, options);
            }
            // If the symbol comes from a native library, we won't
            // be able to resolve its type directly.
            if (curDeclaration.isNativeLib) {
                return {
                    declaration: undefined,
                    isPrivate,
                };
            }
            return undefined;
        }
        if (symbol.isPrivateMember() && !sawPyTypedTransition) {
            isPrivate = true;
        }
        if (symbol.isExternallyHidden() && !options.allowExternallyHiddenAccess) {
            return undefined;
        }
        // Prefer declarations with specified types. If we don't have any of those,
        // fall back on declarations with inferred types.
        let declarations = symbol.getTypedDeclarations();
        // Try not to use declarations within an except suite even if it's a typed
        // declaration. These are typically used for fallback exception handling.
        declarations = declarations.filter((decl) => !decl.isInExceptSuite);
        if (declarations.length === 0) {
            declarations = symbol.getDeclarations();
            declarations = declarations.filter((decl) => !decl.isInExceptSuite);
        }
        if (declarations.length === 0) {
            // Use declarations within except clauses if there are no alternatives.
            declarations = symbol.getDeclarations();
        }
        if (declarations.length === 0) {
            return undefined;
        }
        const prevDeclaration = curDeclaration;
        // Prefer the last unvisited declaration in the list. This ensures that
        // we use all of the overloads if it's an overloaded function.
        const unvisitedDecls = declarations.filter((decl) => !alreadyVisited.includes(decl));
        if (unvisitedDecls.length > 0) {
            curDeclaration = unvisitedDecls[unvisitedDecls.length - 1];
        }
        else {
            curDeclaration = declarations[declarations.length - 1];
        }
        if (lookupResult === null || lookupResult === void 0 ? void 0 : lookupResult.isInPyTypedPackage) {
            if (!sawPyTypedTransition) {
                if (symbol.isPrivatePyTypedImport()) {
                    privatePyTypedImporter = prevDeclaration === null || prevDeclaration === void 0 ? void 0 : prevDeclaration.moduleName;
                }
                // Note that we've seen a transition from a non-py.typed to a py.typed
                // import. No further check is needed.
                sawPyTypedTransition = true;
            }
            else {
                // If we've already seen a transition, look for the first non-private
                // symbol that is resolved so we can tell the user to import from this
                // location instead.
                if (!symbol.isPrivatePyTypedImport()) {
                    privateImported = privateImported !== null && privateImported !== void 0 ? privateImported : curDeclaration === null || curDeclaration === void 0 ? void 0 : curDeclaration.moduleName;
                }
            }
        }
        else if (!sawPyTypedTransition) {
            if (symbol.isPrivateLocalImport()) {
                privateNonPyTypedImporter = prevDeclaration === null || prevDeclaration === void 0 ? void 0 : prevDeclaration.moduleName;
            }
            // TODO: i dont really get what this code is doing, i just copied it from the py.typed check above.
            // for local imports, the py.typed is not relevant because it's implicitly treated as typed
            sawPyTypedTransition = true;
        }
        else {
            if (!symbol.isPrivateLocalImport()) {
                privateImported = privateImported !== null && privateImported !== void 0 ? privateImported : curDeclaration === null || curDeclaration === void 0 ? void 0 : curDeclaration.moduleName;
            }
        }
        // Make sure we don't follow a circular list indefinitely.
        if (alreadyVisited.find((decl) => decl === curDeclaration)) {
            // If the path path of the alias points back to the original path, use the submodule
            // fallback instead. This happens in the case where a module's __init__.py file
            // imports a submodule using itself as the import target. For example, if
            // the module is foo, and the foo.__init__.py file contains the statement
            // "from foo import bar", we want to import the foo/bar.py submodule.
            if (curDeclaration.uri.equals(declaration.uri) &&
                curDeclaration.type === 8 /* DeclarationType.Alias */ &&
                curDeclaration.submoduleFallback) {
                return resolveAliasDeclaration(importLookup, curDeclaration.submoduleFallback, options);
            }
            return {
                declaration,
                isPrivate,
                privateImported,
                privatePyTypedImporter,
                privateNonPyTypedImporter,
            };
        }
        alreadyVisited.push(curDeclaration);
    }
}
exports.resolveAliasDeclaration = resolveAliasDeclaration;


/***/ }),

/***/ "../pyright-internal/src/analyzer/decorators.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/decorators.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * decorators.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides type evaluation logic that is specific to the application of
 * function or class decorators.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.addOverloadsToFunctionType = exports.applyClassDecorator = exports.applyFunctionDecorator = exports.getFunctionInfoFromDecorators = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const dataClasses_1 = __webpack_require__(/*! ./dataClasses */ "../pyright-internal/src/analyzer/dataClasses.ts");
const docStringConversion_1 = __webpack_require__(/*! ./docStringConversion */ "../pyright-internal/src/analyzer/docStringConversion.ts");
const properties_1 = __webpack_require__(/*! ./properties */ "../pyright-internal/src/analyzer/properties.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// Scans through the decorators to find a few built-in decorators
// that affect the function flags.
function getFunctionInfoFromDecorators(evaluator, node, isInClass) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(node);
    let flags = 0 /* FunctionTypeFlags.None */;
    let deprecationMessage;
    if (isInClass) {
        // The "__new__" magic method is not an instance method.
        // It acts as a static method instead.
        if (node.name.value === '__new__') {
            flags |= 1 /* FunctionTypeFlags.ConstructorMethod */;
        }
        // Several magic methods are treated as class methods implicitly
        // by the runtime. Check for these here.
        const implicitClassMethods = ['__init_subclass__', '__class_getitem__'];
        if (implicitClassMethods.some((name) => node.name.value === name)) {
            flags |= 2 /* FunctionTypeFlags.ClassMethod */;
        }
    }
    for (const decoratorNode of node.decorators) {
        // Some stub files (e.g. builtins.pyi) rely on forward declarations of decorators.
        let evaluatorFlags = fileInfo.isStubFile ? 4 /* EvaluatorFlags.AllowForwardReferences */ : 0 /* EvaluatorFlags.None */;
        if (decoratorNode.expression.nodeType !== 9 /* ParseNodeType.Call */) {
            evaluatorFlags |= 2 /* EvaluatorFlags.CallBaseDefaults */;
        }
        else {
            if (decoratorNode.expression.nodeType === 9 /* ParseNodeType.Call */) {
                const decoratorCallType = evaluator.getTypeOfExpression(decoratorNode.expression.leftExpression, evaluatorFlags | 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                if ((0, typeUtils_1.isBuiltInDeprecatedType)(decoratorCallType)) {
                    deprecationMessage = getCustomDeprecationMessage(decoratorNode);
                }
            }
        }
        const decoratorTypeResult = evaluator.getTypeOfExpression(decoratorNode.expression, evaluatorFlags);
        const decoratorType = decoratorTypeResult.type;
        if ((0, types_1.isFunction)(decoratorType)) {
            if (decoratorType.details.builtInName === 'abstractmethod') {
                if (isInClass) {
                    flags |= 8 /* FunctionTypeFlags.AbstractMethod */;
                }
            }
            else if (decoratorType.details.builtInName === 'final') {
                flags |= 8192 /* FunctionTypeFlags.Final */;
            }
            else if (decoratorType.details.builtInName === 'override') {
                flags |= 262144 /* FunctionTypeFlags.Overridden */;
            }
            else if (decoratorType.details.builtInName === 'type_check_only') {
                flags |= 128 /* FunctionTypeFlags.TypeCheckOnly */;
            }
            else if (decoratorType.details.builtInName === 'no_type_check') {
                flags |= 524288 /* FunctionTypeFlags.NoTypeCheck */;
            }
            else if (decoratorType.details.builtInName === 'overload') {
                flags |= 256 /* FunctionTypeFlags.Overloaded */;
            }
        }
        else if ((0, types_1.isInstantiableClass)(decoratorType)) {
            if (types_1.ClassType.isBuiltIn(decoratorType, 'staticmethod')) {
                if (isInClass) {
                    flags |= 4 /* FunctionTypeFlags.StaticMethod */;
                }
            }
            else if (types_1.ClassType.isBuiltIn(decoratorType, 'classmethod')) {
                if (isInClass) {
                    flags |= 2 /* FunctionTypeFlags.ClassMethod */;
                }
            }
        }
        if ((0, typeUtils_1.isBuiltInDeprecatedType)(decoratorType)) {
            deprecationMessage = getCustomDeprecationMessage(decoratorNode);
        }
    }
    return { flags, deprecationMessage };
}
exports.getFunctionInfoFromDecorators = getFunctionInfoFromDecorators;
// Transforms the input function type into an output type based on the
// decorator function described by the decoratorNode.
function applyFunctionDecorator(evaluator, inputFunctionType, undecoratedType, decoratorNode, functionNode) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(decoratorNode);
    // Some stub files (e.g. builtins.pyi) rely on forward declarations of decorators.
    let evaluatorFlags = fileInfo.isStubFile ? 4 /* EvaluatorFlags.AllowForwardReferences */ : 0 /* EvaluatorFlags.None */;
    if (decoratorNode.expression.nodeType !== 9 /* ParseNodeType.Call */) {
        evaluatorFlags |= 2 /* EvaluatorFlags.CallBaseDefaults */;
    }
    const decoratorTypeResult = evaluator.getTypeOfExpression(decoratorNode.expression, evaluatorFlags);
    const decoratorType = decoratorTypeResult.type;
    // Special-case the "overload" because it has no definition. Older versions of typeshed
    // defined "overload" as an object, but newer versions define it as a function.
    if (((0, types_1.isInstantiableClass)(decoratorType) && types_1.ClassType.isSpecialBuiltIn(decoratorType, 'overload')) ||
        ((0, types_1.isFunction)(decoratorType) && decoratorType.details.builtInName === 'overload')) {
        if ((0, types_1.isFunction)(inputFunctionType)) {
            inputFunctionType.details.flags |= 256 /* FunctionTypeFlags.Overloaded */;
            undecoratedType.details.flags |= 256 /* FunctionTypeFlags.Overloaded */;
            return inputFunctionType;
        }
    }
    if (decoratorNode.expression.nodeType === 9 /* ParseNodeType.Call */) {
        const decoratorCallType = evaluator.getTypeOfExpression(decoratorNode.expression.leftExpression, evaluatorFlags | 2 /* EvaluatorFlags.CallBaseDefaults */).type;
        if ((0, types_1.isFunction)(decoratorCallType)) {
            if (decoratorCallType.details.name === '__dataclass_transform__' ||
                decoratorCallType.details.builtInName === 'dataclass_transform') {
                undecoratedType.details.decoratorDataClassBehaviors = (0, dataClasses_1.validateDataClassTransformDecorator)(evaluator, decoratorNode.expression);
                return inputFunctionType;
            }
        }
        if ((0, typeUtils_1.isBuiltInDeprecatedType)(decoratorCallType)) {
            return inputFunctionType;
        }
    }
    let returnType = getTypeOfDecorator(evaluator, decoratorNode, inputFunctionType);
    // Check for some built-in decorator types with known semantics.
    if ((0, types_1.isFunction)(decoratorType)) {
        if (decoratorType.details.builtInName === 'abstractmethod') {
            return inputFunctionType;
        }
        if (decoratorType.details.builtInName === 'type_check_only') {
            undecoratedType.details.flags |= 128 /* FunctionTypeFlags.TypeCheckOnly */;
            return inputFunctionType;
        }
        // Handle property setters and deleters.
        if (decoratorNode.expression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            const baseType = evaluator.getTypeOfExpression(decoratorNode.expression.leftExpression, evaluatorFlags | 2 /* EvaluatorFlags.MemberAccessBaseDefaults */).type;
            if ((0, typeUtils_1.isProperty)(baseType)) {
                const memberName = decoratorNode.expression.memberName.value;
                if (memberName === 'setter') {
                    if ((0, types_1.isFunction)(inputFunctionType)) {
                        (0, properties_1.validatePropertyMethod)(evaluator, inputFunctionType, decoratorNode);
                        return (0, properties_1.clonePropertyWithSetter)(evaluator, baseType, inputFunctionType, functionNode);
                    }
                    else {
                        return inputFunctionType;
                    }
                }
                else if (memberName === 'deleter') {
                    if ((0, types_1.isFunction)(inputFunctionType)) {
                        (0, properties_1.validatePropertyMethod)(evaluator, inputFunctionType, decoratorNode);
                        return (0, properties_1.clonePropertyWithDeleter)(evaluator, baseType, inputFunctionType, functionNode);
                    }
                    else {
                        return inputFunctionType;
                    }
                }
            }
        }
    }
    else if ((0, types_1.isInstantiableClass)(decoratorType)) {
        if (types_1.ClassType.isBuiltIn(decoratorType)) {
            switch (decoratorType.details.name) {
                case 'classmethod':
                case 'staticmethod': {
                    const requiredFlag = decoratorType.details.name === 'classmethod'
                        ? 2 /* FunctionTypeFlags.ClassMethod */
                        : 4 /* FunctionTypeFlags.StaticMethod */;
                    // If the function isn't currently a class method or static method
                    // (which can happen if the function was wrapped in a decorator),
                    // add the appropriate flag.
                    if ((0, types_1.isFunction)(inputFunctionType) && (inputFunctionType.details.flags & requiredFlag) === 0) {
                        const newFunction = types_1.FunctionType.clone(inputFunctionType);
                        newFunction.details.flags &= ~(1 /* FunctionTypeFlags.ConstructorMethod */ |
                            4 /* FunctionTypeFlags.StaticMethod */ |
                            2 /* FunctionTypeFlags.ClassMethod */);
                        newFunction.details.flags |= requiredFlag;
                        return newFunction;
                    }
                    return inputFunctionType;
                }
            }
        }
        if ((0, typeUtils_1.isBuiltInDeprecatedType)(decoratorType)) {
            return inputFunctionType;
        }
        // Handle properties and subclasses of properties specially.
        if (types_1.ClassType.isPropertyClass(decoratorType)) {
            if ((0, types_1.isFunction)(inputFunctionType)) {
                (0, properties_1.validatePropertyMethod)(evaluator, inputFunctionType, decoratorNode);
                return (0, properties_1.createProperty)(evaluator, decoratorNode, decoratorType, inputFunctionType);
            }
            else if ((0, types_1.isClassInstance)(inputFunctionType)) {
                const boundMethod = evaluator.getBoundMagicMethod(inputFunctionType, '__call__');
                if (boundMethod && (0, types_1.isFunction)(boundMethod)) {
                    return (0, properties_1.createProperty)(evaluator, decoratorNode, decoratorType, boundMethod);
                }
                return types_1.UnknownType.create();
            }
        }
    }
    if ((0, types_1.isFunction)(inputFunctionType) && (0, types_1.isFunction)(returnType)) {
        returnType = types_1.FunctionType.clone(returnType);
        // Copy the overload flag from the input function type.
        if (types_1.FunctionType.isOverloaded(inputFunctionType)) {
            returnType.details.flags |= 256 /* FunctionTypeFlags.Overloaded */;
        }
        // Copy the docstrings from the input function type if the
        // decorator didn't have its own docstring.
        if (!returnType.details.docString) {
            returnType.details.docString = inputFunctionType.details.docString;
        }
    }
    return returnType;
}
exports.applyFunctionDecorator = applyFunctionDecorator;
function applyClassDecorator(evaluator, inputClassType, originalClassType, decoratorNode) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(decoratorNode);
    let flags = fileInfo.isStubFile ? 4 /* EvaluatorFlags.AllowForwardReferences */ : 0 /* EvaluatorFlags.None */;
    if (decoratorNode.expression.nodeType !== 9 /* ParseNodeType.Call */) {
        flags |= 2 /* EvaluatorFlags.CallBaseDefaults */;
    }
    const decoratorType = evaluator.getTypeOfExpression(decoratorNode.expression, flags).type;
    if (decoratorNode.expression.nodeType === 9 /* ParseNodeType.Call */) {
        const decoratorCallType = evaluator.getTypeOfExpression(decoratorNode.expression.leftExpression, flags | 2 /* EvaluatorFlags.CallBaseDefaults */).type;
        if ((0, types_1.isFunction)(decoratorCallType)) {
            if (decoratorCallType.details.name === '__dataclass_transform__' ||
                decoratorCallType.details.builtInName === 'dataclass_transform') {
                originalClassType.details.classDataClassTransform = (0, dataClasses_1.validateDataClassTransformDecorator)(evaluator, decoratorNode.expression);
            }
        }
        if ((0, typeUtils_1.isBuiltInDeprecatedType)(decoratorCallType)) {
            originalClassType.details.deprecatedMessage = getCustomDeprecationMessage(decoratorNode);
            return inputClassType;
        }
    }
    if ((0, types_1.isOverloadedFunction)(decoratorType)) {
        const dataclassBehaviors = (0, dataClasses_1.getDataclassDecoratorBehaviors)(decoratorType);
        if (dataclassBehaviors) {
            (0, dataClasses_1.applyDataClassDecorator)(evaluator, decoratorNode, originalClassType, dataclassBehaviors, 
            /* callNode */ undefined);
            return inputClassType;
        }
    }
    else if ((0, types_1.isFunction)(decoratorType)) {
        if (decoratorType.details.builtInName === 'final') {
            originalClassType.details.flags |= 8192 /* ClassTypeFlags.Final */;
            // Don't call getTypeOfDecorator for final. We'll hard-code its
            // behavior because its function definition results in a cyclical
            // dependency between builtins, typing and _typeshed stubs.
            return inputClassType;
        }
        if (decoratorType.details.builtInName === 'type_check_only') {
            originalClassType.details.flags |= 268435456 /* ClassTypeFlags.TypeCheckOnly */;
            return inputClassType;
        }
        if (decoratorType.details.builtInName === 'runtime_checkable') {
            originalClassType.details.flags |= 65536 /* ClassTypeFlags.RuntimeCheckable */;
            // Don't call getTypeOfDecorator for runtime_checkable. It appears
            // frequently in stubs, and it's a waste of time to validate its
            // parameters.
            return inputClassType;
        }
        // Is this a dataclass decorator?
        let dataclassBehaviors;
        let callNode;
        if (decoratorNode.expression.nodeType === 9 /* ParseNodeType.Call */) {
            callNode = decoratorNode.expression;
            const decoratorCallType = evaluator.getTypeOfExpression(callNode.leftExpression, flags | 2 /* EvaluatorFlags.CallBaseDefaults */).type;
            dataclassBehaviors = (0, dataClasses_1.getDataclassDecoratorBehaviors)(decoratorCallType);
        }
        else {
            const decoratorType = evaluator.getTypeOfExpression(decoratorNode.expression, flags).type;
            dataclassBehaviors = (0, dataClasses_1.getDataclassDecoratorBehaviors)(decoratorType);
        }
        if (dataclassBehaviors) {
            (0, dataClasses_1.applyDataClassDecorator)(evaluator, decoratorNode, originalClassType, dataclassBehaviors, callNode);
            return inputClassType;
        }
    }
    return getTypeOfDecorator(evaluator, decoratorNode, inputClassType);
}
exports.applyClassDecorator = applyClassDecorator;
function getTypeOfDecorator(evaluator, node, functionOrClassType) {
    var _a, _b;
    // Evaluate the type of the decorator expression.
    let flags = (0, analyzerNodeInfo_1.getFileInfo)(node).isStubFile ? 4 /* EvaluatorFlags.AllowForwardReferences */ : 0 /* EvaluatorFlags.None */;
    if (node.expression.nodeType !== 9 /* ParseNodeType.Call */) {
        flags |= 2 /* EvaluatorFlags.CallBaseDefaults */;
    }
    const decoratorTypeResult = evaluator.getTypeOfExpression(node.expression, flags);
    // Special-case the combination of a classmethod decorator applied
    // to a property. This is allowed in Python 3.9, but it's not reflected
    // in the builtins.pyi stub for classmethod.
    if ((0, types_1.isInstantiableClass)(decoratorTypeResult.type) &&
        types_1.ClassType.isBuiltIn(decoratorTypeResult.type, 'classmethod') &&
        (0, typeUtils_1.isProperty)(functionOrClassType)) {
        return functionOrClassType;
    }
    const argList = [
        {
            argumentCategory: 0 /* ArgumentCategory.Simple */,
            typeResult: { type: functionOrClassType },
        },
    ];
    const callTypeResult = evaluator.validateCallArguments(node.expression, argList, decoratorTypeResult, 
    /* typeVarContext */ undefined, 
    /* skipUnknownArgCheck */ true);
    evaluator.setTypeResultForNode(node, {
        type: (_a = callTypeResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(),
        overloadsUsedForCall: callTypeResult.overloadsUsedForCall,
        isIncomplete: callTypeResult.isTypeIncomplete,
    });
    const returnType = (_b = callTypeResult.returnType) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
    // If the return type is a function that has no annotations
    // and just *args and **kwargs parameters, assume that it
    // preserves the type of the input function.
    if ((0, types_1.isFunction)(returnType) && !returnType.details.declaredReturnType) {
        if (!returnType.details.parameters.some((param, index) => {
            // Don't allow * or / separators or params with declared types.
            if (!param.name || param.hasDeclaredType) {
                return true;
            }
            // Allow *args or **kwargs parameters.
            if (param.category !== 0 /* ParameterCategory.Simple */) {
                return false;
            }
            // Allow inferred "self" or "cls" parameters.
            return index !== 0 || !param.isTypeInferred;
        })) {
            return functionOrClassType;
        }
    }
    // If the decorator is completely unannotated and the return type
    // includes unknowns, assume that it preserves the type of the input
    // function.
    if ((0, typeUtils_1.isPartlyUnknown)(returnType)) {
        if ((0, types_1.isFunction)(decoratorTypeResult.type)) {
            if (!decoratorTypeResult.type.details.parameters.find((param) => param.typeAnnotation !== undefined) &&
                decoratorTypeResult.type.details.declaredReturnType === undefined) {
                return functionOrClassType;
            }
        }
    }
    return returnType;
}
// Given a function node and the function type associated with it, this
// method searches for prior function nodes that are marked as @overload
// and creates an OverloadedFunctionType that includes this function and
// all previous ones.
function addOverloadsToFunctionType(evaluator, node, type) {
    let functionDecl;
    const decl = (0, analyzerNodeInfo_1.getDeclaration)(node);
    if (decl) {
        functionDecl = decl;
    }
    const symbolWithScope = evaluator.lookUpSymbolRecursive(node, node.name.value, /* honorCodeFlow */ false);
    if (symbolWithScope) {
        const decls = symbolWithScope.symbol.getDeclarations();
        // Find this function's declaration.
        const declIndex = decls.findIndex((decl) => decl === functionDecl);
        if (declIndex > 0) {
            // Evaluate all of the previous function declarations. They will
            // be cached. We do it in this order to avoid a stack overflow due
            // to recursion if there is a large number (1000's) of overloads.
            for (let i = 0; i < declIndex; i++) {
                const decl = decls[i];
                if (decl.type === 5 /* DeclarationType.Function */) {
                    evaluator.getTypeOfFunction(decl.node);
                }
            }
            let overloadedTypes = [];
            // Look at the previous declaration's type.
            const prevDecl = decls[declIndex - 1];
            if (prevDecl.type === 5 /* DeclarationType.Function */) {
                const prevDeclDeclTypeInfo = evaluator.getTypeOfFunction(prevDecl.node);
                if (prevDeclDeclTypeInfo) {
                    if ((0, types_1.isFunction)(prevDeclDeclTypeInfo.decoratedType)) {
                        if (types_1.FunctionType.isOverloaded(prevDeclDeclTypeInfo.decoratedType)) {
                            overloadedTypes.push(prevDeclDeclTypeInfo.decoratedType);
                        }
                    }
                    else if ((0, types_1.isOverloadedFunction)(prevDeclDeclTypeInfo.decoratedType)) {
                        // If the previous declaration was itself an overloaded function,
                        // copy the entries from it.
                        (0, collectionUtils_1.appendArray)(overloadedTypes, prevDeclDeclTypeInfo.decoratedType.overloads);
                    }
                }
            }
            overloadedTypes.push(type);
            if (overloadedTypes.length === 1) {
                return overloadedTypes[0];
            }
            // Apply the implementation's docstring to any overloads that don't
            // have their own docstrings.
            const implementation = overloadedTypes.find((signature) => !types_1.FunctionType.isOverloaded(signature));
            if (implementation === null || implementation === void 0 ? void 0 : implementation.details.docString) {
                overloadedTypes = overloadedTypes.map((overload) => {
                    if (types_1.FunctionType.isOverloaded(overload) && !overload.details.docString) {
                        return types_1.FunctionType.cloneWithDocString(overload, implementation.details.docString);
                    }
                    return overload;
                });
            }
            // PEP 702 indicates that if the implementation of an overloaded
            // function is marked deprecated, all of the overloads should be
            // treated as deprecated as well.
            if (implementation && implementation.details.deprecatedMessage !== undefined) {
                overloadedTypes = overloadedTypes.map((overload) => {
                    if (types_1.FunctionType.isOverloaded(overload) && overload.details.deprecatedMessage === undefined) {
                        return types_1.FunctionType.cloneWithDeprecatedMessage(overload, implementation.details.deprecatedMessage);
                    }
                    return overload;
                });
            }
            // Create a new overloaded type that copies the contents of the previous
            // one and adds a new function.
            const newOverload = types_1.OverloadedFunctionType.create(overloadedTypes);
            const prevOverload = overloadedTypes[overloadedTypes.length - 2];
            const isPrevOverloadAbstract = types_1.FunctionType.isAbstractMethod(prevOverload);
            const isCurrentOverloadAbstract = types_1.FunctionType.isAbstractMethod(type);
            if (isPrevOverloadAbstract !== isCurrentOverloadAbstract) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInconsistentOverload, localize_1.LocMessage.overloadAbstractMismatch().format({ name: node.name.value }), node.name);
            }
            return newOverload;
        }
    }
    return type;
}
exports.addOverloadsToFunctionType = addOverloadsToFunctionType;
// Given a @typing.deprecated decorator node, returns either '' or a custom
// deprecation message if one is provided.
function getCustomDeprecationMessage(decorator) {
    if (decorator.expression.nodeType === 9 /* ParseNodeType.Call */ &&
        decorator.expression.arguments.length > 0 &&
        decorator.expression.arguments[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
        decorator.expression.arguments[0].valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
        const stringListNode = decorator.expression.arguments[0].valueExpression;
        const message = stringListNode.strings.map((s) => s.value).join('');
        return (0, docStringConversion_1.convertDocStringToPlainText)(message);
    }
    return '';
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/deprecatedSymbols.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/analyzer/deprecatedSymbols.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * deprecatedSymbols.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A list of implicitly-deprecated symbols as defined in PEP 585, etc.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.deprecatedSpecialForms = exports.deprecatedAliases = void 0;
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
exports.deprecatedAliases = new Map([
    ['Tuple', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.tuple', replacementText: 'tuple' }],
    ['List', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.list', replacementText: 'list' }],
    ['Dict', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.dict', replacementText: 'dict' }],
    ['Set', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.set', replacementText: 'set' }],
    ['FrozenSet', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.frozenset', replacementText: 'frozenset' }],
    ['Type', { version: pythonVersion_1.pythonVersion3_9, fullName: 'builtins.type', replacementText: 'type' }],
    ['Deque', { version: pythonVersion_1.pythonVersion3_9, fullName: 'collections.deque', replacementText: 'collections.deque' }],
    [
        'DefaultDict',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'collections.defaultdict',
            replacementText: 'collections.defaultdict',
        },
    ],
    [
        'OrderedDict',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'collections.OrderedDict',
            replacementText: 'collections.OrderedDict',
            typingImportOnly: true,
        },
    ],
    [
        'Counter',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'collections.Counter',
            replacementText: 'collections.Counter',
            typingImportOnly: true,
        },
    ],
    [
        'ChainMap',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'collections.ChainMap',
            replacementText: 'collections.ChainMap',
            typingImportOnly: true,
        },
    ],
    [
        'Awaitable',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Awaitable',
            replacementText: 'collections.abc.Awaitable',
            typingImportOnly: true,
        },
    ],
    [
        'Coroutine',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Coroutine',
            replacementText: 'collections.abc.Coroutine',
            typingImportOnly: true,
        },
    ],
    [
        'AsyncIterable',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.AsyncIterable',
            replacementText: 'collections.abc.AsyncIterable',
            typingImportOnly: true,
        },
    ],
    [
        'AsyncIterator',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.AsyncIterator',
            replacementText: 'collections.abc.AsyncIterator',
            typingImportOnly: true,
        },
    ],
    [
        'AsyncGenerator',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.AsyncGenerator',
            replacementText: 'collections.abc.AsyncGenerator',
            typingImportOnly: true,
        },
    ],
    [
        'Iterable',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Iterable',
            replacementText: 'collections.abc.Iterable',
            typingImportOnly: true,
        },
    ],
    [
        'Iterator',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Iterator',
            replacementText: 'collections.abc.Iterator',
            typingImportOnly: true,
        },
    ],
    [
        'Generator',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Generator',
            replacementText: 'collections.abc.Generator',
            typingImportOnly: true,
        },
    ],
    [
        'Reversible',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Reversible',
            replacementText: 'collections.abc.Reversible',
            typingImportOnly: true,
        },
    ],
    [
        'Container',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Container',
            replacementText: 'collections.abc.Container',
            typingImportOnly: true,
        },
    ],
    [
        'Collection',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Collection',
            replacementText: 'collections.abc.Collection',
            typingImportOnly: true,
        },
    ],
    [
        'AbstractSet',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.AbstractSet',
            replacementText: 'collections.abc.Set',
        },
    ],
    [
        'MutableSet',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.MutableSet',
            replacementText: 'collections.abc.MutableSet',
            typingImportOnly: true,
        },
    ],
    [
        'Mapping',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Mapping',
            replacementText: 'collections.abc.Mapping',
            typingImportOnly: true,
        },
    ],
    [
        'MutableMapping',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.MutableMapping',
            replacementText: 'collections.abc.MutableMapping',
            typingImportOnly: true,
        },
    ],
    [
        'Sequence',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.Sequence',
            replacementText: 'collections.abc.Sequence',
            typingImportOnly: true,
        },
    ],
    [
        'MutableSequence',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.MutableSequence',
            replacementText: 'collections.abc.MutableSequence',
            typingImportOnly: true,
        },
    ],
    [
        'ByteString',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.ByteString',
            replacementText: 'collections.abc.ByteString',
            typingImportOnly: true,
        },
    ],
    [
        'MappingView',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.MappingView',
            replacementText: 'collections.abc.MappingView',
            typingImportOnly: true,
        },
    ],
    [
        'KeysView',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.KeysView',
            replacementText: 'collections.abc.KeysView',
            typingImportOnly: true,
        },
    ],
    [
        'ItemsView',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.ItemsView',
            replacementText: 'collections.abc.ItemsView',
            typingImportOnly: true,
        },
    ],
    [
        'ValuesView',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'typing.ValuesView',
            replacementText: 'collections.abc.ValuesView',
            typingImportOnly: true,
        },
    ],
    [
        'ContextManager',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'contextlib.AbstractContextManager',
            replacementText: 'contextlib.AbstractContextManager',
            typingImportOnly: true,
        },
    ],
    [
        'AsyncContextManager',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 'contextlib.AbstractAsyncContextManager',
            replacementText: 'contextlib.AbstractAsyncContextManager',
            typingImportOnly: true,
        },
    ],
    [
        'Pattern',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 're.Pattern',
            replacementText: 're.Pattern',
            typingImportOnly: true,
        },
    ],
    [
        'Match',
        {
            version: pythonVersion_1.pythonVersion3_9,
            fullName: 're.Match',
            replacementText: 're.Match',
            typingImportOnly: true,
        },
    ],
]);
exports.deprecatedSpecialForms = new Map([
    ['Optional', { version: pythonVersion_1.pythonVersion3_10, fullName: 'typing.Optional', replacementText: '| None' }],
    ['Union', { version: pythonVersion_1.pythonVersion3_10, fullName: 'typing.Union', replacementText: '|' }],
]);


/***/ }),

/***/ "../pyright-internal/src/analyzer/docStringConversion.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/analyzer/docStringConversion.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * docStringConversion.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Python doc string to markdown/plain text format conversion.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertDocStringToPlainText = exports.convertDocStringToMarkdown = void 0;
const docStringUtils_1 = __webpack_require__(/*! ./docStringUtils */ "../pyright-internal/src/analyzer/docStringUtils.ts");
// Converts a docstring to markdown format.
//
// This does various things, including removing common indention, escaping
// characters, handling code blocks, and more.
//
// This is a straight port of
// https://github.com/microsoft/python-language-server/blob/master/src/LanguageServer/Impl/Documentation/DocstringConverter.cs
//
// The restructured npm library was evaluated, and while it worked well for
// parsing valid input, it was going to be more difficult to handle invalid
// RST input.
function convertDocStringToMarkdown(docString) {
    return new DocStringConverter(docString).convert();
}
exports.convertDocStringToMarkdown = convertDocStringToMarkdown;
//  Converts a docstring to a plaintext, human readable form. This will
//  first strip any common leading indention (like inspect.cleandoc),
//  then remove duplicate empty/whitespace lines.
function convertDocStringToPlainText(docString) {
    const lines = (0, docStringUtils_1.cleanAndSplitDocString)(docString);
    const output = [];
    for (const line of lines) {
        const last = output.length > 0 ? output[output.length - 1] : undefined;
        if (_isUndefinedOrWhitespace(line) && _isUndefinedOrWhitespace(last)) {
            continue;
        }
        output.push(line);
    }
    return output.join('\n').trimEnd();
}
exports.convertDocStringToPlainText = convertDocStringToPlainText;
// Regular expressions for one match
const LeadingSpaceCountRegExp = /\S|$/;
const NonWhitespaceRegExp = /\S/;
const TildaHeaderRegExp = /^\s*~~~+$/;
const PlusHeaderRegExp = /^\s*\+\+\++$/;
const EqualHeaderRegExp = /^\s*===+\s+===+$/;
const DashHeaderRegExp = /^\s*---+\s+---+$/;
const LeadingDashListRegExp = /^(\s*)-\s/;
const LeadingAsteriskListRegExp = /^(\s*)\*\s/;
const LeadingNumberListRegExp = /^(\s*)\d+\.\s/;
const LeadingAsteriskRegExp = /^(\s+\* )(.*)$/;
const SpaceDotDotRegExp = /^\s*\.\. /;
const DirectiveLikeRegExp = /^\s*\.\.\s+(.*)::\s*(.*)$/;
const DoctestRegExp = / *>>> /;
const DirectivesExtraNewlineRegExp = /^\s*:(param|arg|type|return|rtype|raise|except|var|ivar|cvar|copyright|license)/;
const epyDocFieldTokensRegExp = /^\.[\s\t]+(@\w)/gm; // cv2 has leading '.' http://epydoc.sourceforge.net/manual-epytext.html
const epyDocCv2FixRegExp = /^(\.\s{3})|^(\.)/;
const PotentialHeaders = [
    { exp: /^\s*=+(\s+=+)+$/, replacement: '=' },
    { exp: /^\s*-+(\s+-+)+$/, replacement: '-' },
    { exp: /^\s*~+(\s+-+)+$/, replacement: '~' },
    { exp: /^\s*\++(\s+\++)+$/, replacement: '+' },
];
// Regular expressions for replace all
const WhitespaceRegExp = /\s/g;
const DoubleTickRegExp = /``/g;
const TildeRegExp = /~/g;
const PlusRegExp = /\+/g;
const UnescapedMarkdownCharsRegExp = /(?<!\\)([_*~[\]])/g;
const linkRegExp = /(\[.*\]\(.*\))/g;
const CodeBlockStartRegExp = /^\s*(?<block>`{3}(?!`)|~{3}(?!~))(\w*)/;
const CodeBlockEndRegExp = /^\s*(?<block>`{3}(?!`)|~{3}(?!~))/;
const HtmlEscapes = [
    { exp: /</g, replacement: '&lt;' },
    { exp: />/g, replacement: '&gt;' },
];
const MarkdownLineBreak = '  \n';
// http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#literal-blocks
const LiteralBlockEmptyRegExp = /^\s*::$/;
const LiteralBlockReplacements = [
    { exp: /\s+::$/g, replacement: '' },
    { exp: /(\S)\s*::$/g, replacement: '$1:' },
    // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#interpreted-text
    { exp: /:[\w_\-+:.]+:`/g, replacement: '`' },
    { exp: /`:[\w_\-+:.]+:/g, replacement: '`' },
];
class DocStringConverter {
    constructor(input) {
        this._builder = '';
        this._skipAppendEmptyLine = true;
        this._insideInlineCode = false;
        this._appendDirectiveBlock = false;
        this._stateStack = [];
        this._lineNum = 0;
        this._blockIndent = 0;
        this._state = this._parseText;
        this._input = input;
        this._lines = (0, docStringUtils_1.cleanAndSplitDocString)(input);
    }
    convert() {
        const isEpyDoc = epyDocFieldTokensRegExp.test(this._input);
        if (isEpyDoc) {
            // fixup cv2 leading '.'
            this._lines = this._lines.map((v) => v.replace(epyDocCv2FixRegExp, ''));
        }
        while (this._currentLineOrUndefined() !== undefined) {
            const before = this._state;
            const beforeLine = this._lineNum;
            this._state();
            // Parser must make progress; either the state or line number must change.
            if (this._state === before && this._lineNum === beforeLine) {
                break;
            }
        }
        // Close out any outstanding code blocks.
        if (this._state === this._parseBacktickBlock ||
            this._state === this._parseDocTest ||
            this._state === this._parseLiteralBlock) {
            // See what the current backtick block is. We want to match it.
            this._trimOutputAndAppendLine(this._lastBacktickString || '```');
        }
        else if (this._insideInlineCode) {
            this._trimOutputAndAppendLine('`', /* noNewLine */ true);
        }
        return this._builder.trim();
    }
    _eatLine() {
        this._lineNum++;
    }
    _currentLineOrUndefined() {
        return this._lineNum < this._lines.length ? this._lines[this._lineNum] : undefined;
    }
    _currentLine() {
        return this._currentLineOrUndefined() || '';
    }
    _currentIndent() {
        return _countLeadingSpaces(this._currentLine());
    }
    _prevIndent() {
        var _a;
        return _countLeadingSpaces((_a = this._lineAt(this._lineNum - 1)) !== null && _a !== void 0 ? _a : '');
    }
    _lineAt(i) {
        return i < this._lines.length ? this._lines[i] : undefined;
    }
    _nextBlockIndent() {
        return _countLeadingSpaces(this._lines.slice(this._lineNum + 1).find((v) => !_isUndefinedOrWhitespace(v)) || '');
    }
    _currentLineIsOutsideBlock() {
        return this._currentIndent() < this._blockIndent;
    }
    _currentLineWithinBlock() {
        return this._currentLine().substr(this._blockIndent);
    }
    _pushAndSetState(next) {
        if (this._state === this._parseText) {
            this._insideInlineCode = false;
        }
        this._stateStack.push(this._state);
        this._state = next;
    }
    _popState() {
        this._state = this._stateStack.splice(0, 1)[0];
        if (this._state === this._parseText) {
            // Terminate inline code when leaving a block.
            this._insideInlineCode = false;
        }
    }
    _parseText() {
        if (_isUndefinedOrWhitespace(this._currentLineOrUndefined())) {
            this._state = this._parseEmpty;
            return;
        }
        if (this._beginBacktickBlock()) {
            return;
        }
        if (this._beginLiteralBlock()) {
            return;
        }
        if (this._beginDocTest()) {
            return;
        }
        if (this._beginDirective()) {
            return;
        }
        if (this._beginList()) {
            return;
        }
        if (this._beginFieldList()) {
            return;
        }
        if (this._beginTableBlock()) {
            return;
        }
        const line = this._formatPlainTextIndent(this._currentLine());
        this._appendTextLine(line);
        this._eatLine();
    }
    _formatPlainTextIndent(line) {
        const prev = this._lineAt(this._lineNum - 1);
        const prevIndent = this._prevIndent();
        const currIndent = this._currentIndent();
        if (currIndent > prevIndent &&
            !_isUndefinedOrWhitespace(prev) &&
            !this._builder.endsWith(MarkdownLineBreak) &&
            !this._builder.endsWith('\n\n') &&
            !_isHeader(prev)) {
            this._builder = this._builder.slice(0, -1) + MarkdownLineBreak;
        }
        if (prevIndent > currIndent &&
            !_isUndefinedOrWhitespace(prev) &&
            !this._builder.endsWith(MarkdownLineBreak) &&
            !this._builder.endsWith('\n\n')) {
            this._builder = this._builder.slice(0, -1) + MarkdownLineBreak;
        }
        if (prevIndent === 0 || this._builder.endsWith(MarkdownLineBreak) || this._builder.endsWith('\n\n')) {
            line = this._convertIndent(line);
        }
        else {
            line = line.trimStart();
        }
        return line;
    }
    _convertIndent(line) {
        line = line.replace(/^([ \t]+)(.+)$/g, (_match, g1, g2) => '&nbsp;'.repeat(g1.length) + g2);
        return line;
    }
    _escapeHtml(line) {
        HtmlEscapes.forEach((escape) => {
            line = line.replace(escape.exp, escape.replacement);
        });
        return line;
    }
    _appendTextLine(line) {
        line = this._preprocessTextLine(line);
        const parts = line.split('`');
        for (let i = 0; i < parts.length; i++) {
            let part = parts[i];
            if (i > 0) {
                this._insideInlineCode = !this._insideInlineCode;
                this._append('`');
            }
            if (this._insideInlineCode) {
                this._append(part);
                continue;
            }
            part = this._escapeHtml(part);
            if (i === 0) {
                // Only one part, and not inside code, so check header cases.
                if (parts.length === 1) {
                    // Handle weird separator lines which contain random spaces.
                    for (const expReplacement of PotentialHeaders) {
                        if (expReplacement.exp.test(part)) {
                            part = part.replace(WhitespaceRegExp, expReplacement.replacement);
                            break;
                        }
                    }
                    // Replace ReST style ~~~ header to prevent it being interpreted as a code block
                    // (an alternative in Markdown to triple backtick blocks).
                    if (TildaHeaderRegExp.test(part)) {
                        this._append(part.replace(TildeRegExp, '-'));
                        continue;
                    }
                    // Replace +++ heading too.
                    // TODO: Handle the rest of these, and the precedence order (which depends on the
                    // order heading lines are seen, not what the line contains).
                    // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#sections
                    if (PlusHeaderRegExp.test(part)) {
                        this._append(part.replace(PlusRegExp, '-'));
                        continue;
                    }
                }
                // Don't strip away asterisk-based bullet point lists.
                //
                // TODO: Replace this with real list parsing. This may have
                // false positives and cause random italics when the ReST list
                // doesn't match Markdown's specification.
                const match = LeadingAsteriskRegExp.exec(part);
                if (match !== null && match.length === 3) {
                    this._append(match[1]);
                    part = match[2];
                }
            }
            // TODO: Find a better way to handle this; the below breaks escaped
            // characters which appear at the beginning or end of a line.
            // Applying this only when i == 0 or i == parts.Length-1 may work.
            // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#hyperlink-references
            // part = RegExp.Replace(part, @"^_+", "");
            // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-internal-targets
            // part = RegExp.Replace(part, @"_+$", "");
            // TODO: Strip footnote/citation references.
            // Escape _, *, and ~, but ignore things like ":param \*\*kwargs:".
            const subparts = part.split(linkRegExp);
            subparts.forEach((item) => {
                // Don't escape links
                if (linkRegExp.test(item)) {
                    this._append(item);
                }
                else {
                    this._append(item.replace(UnescapedMarkdownCharsRegExp, '\\$1'));
                }
            });
        }
        // Go straight to the builder so that _appendLine doesn't think
        // we're actually trying to insert an extra blank line and skip
        // future whitespace. Empty line deduplication is already handled
        // because Append is used above.
        this._builder += '\n';
    }
    _preprocessTextLine(line) {
        // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#literal-blocks
        if (LiteralBlockEmptyRegExp.test(line)) {
            return '';
        }
        LiteralBlockReplacements.forEach((item) => (line = line.replace(item.exp, item.replacement)));
        line = line.replace(DoubleTickRegExp, '`');
        return line;
    }
    _parseEmpty() {
        if (_isUndefinedOrWhitespace(this._currentLineOrUndefined())) {
            this._appendLine();
            this._eatLine();
            return;
        }
        this._state = this._parseText;
    }
    _beginMinIndentCodeBlock(state) {
        this._appendLine('```');
        this._pushAndSetState(state);
        this._blockIndent = this._currentIndent();
    }
    _beginBacktickBlock() {
        const match = this._currentLine().match(CodeBlockStartRegExp);
        if (match !== null) {
            this._blockIndent = this._currentIndent();
            this._lastBacktickString = match[1];
            // Remove indentation and preserve language tag.
            this._appendLine(match[1] + match[2]);
            this._pushAndSetState(this._parseBacktickBlock);
            this._eatLine();
            return true;
        }
        return false;
    }
    _parseBacktickBlock() {
        // Only match closing ``` at same indent level of opening.
        if (CodeBlockEndRegExp.test(this._currentLine()) && this._currentIndent() === this._blockIndent) {
            const match = this._currentLine().match(CodeBlockEndRegExp);
            this._lastBacktickString = match ? match[1] : '```';
            this._appendLine(this._lastBacktickString);
            this._appendLine();
            this._popState();
        }
        else {
            this._appendLine(this._currentLine());
        }
        this._eatLine();
    }
    _beginDocTest() {
        if (!DoctestRegExp.test(this._currentLine())) {
            return false;
        }
        this._beginMinIndentCodeBlock(this._parseDocTest);
        this._appendLine(this._currentLineWithinBlock());
        this._eatLine();
        return true;
    }
    _parseDocTest() {
        if (this._currentLineIsOutsideBlock() || _isUndefinedOrWhitespace(this._currentLine())) {
            this._trimOutputAndAppendLine('```');
            this._appendLine();
            this._popState();
            return;
        }
        this._appendLine(this._currentLineWithinBlock());
        this._eatLine();
    }
    _beginLiteralBlock() {
        // The previous line must be empty.
        const prev = this._lineAt(this._lineNum - 1);
        if (prev === undefined) {
            return false;
        }
        else if (!_isUndefinedOrWhitespace(prev)) {
            return false;
        }
        // Find the previous paragraph and check that it ends with ::
        let i = this._lineNum - 2;
        for (; i >= 0; i--) {
            const line = this._lineAt(i);
            if (_isUndefinedOrWhitespace(line)) {
                continue;
            }
            // Safe to ignore whitespace after the :: because all lines have been trimRight'd.
            if (line.endsWith('::')) {
                break;
            }
            return false;
        }
        if (i < 0) {
            return false;
        }
        // Special case: allow one-liners at the same indent level.
        if (this._currentIndent() === 0) {
            this._appendLine('```');
            this._pushAndSetState(this._parseLiteralBlockSingleLine);
            return true;
        }
        this._beginMinIndentCodeBlock(this._parseLiteralBlock);
        return true;
    }
    _parseLiteralBlock() {
        // Slightly different than doctest, wait until the first non-empty unindented line to exit.
        if (_isUndefinedOrWhitespace(this._currentLineOrUndefined())) {
            this._appendLine();
            this._eatLine();
            return;
        }
        const prev = this._lineAt(this._lineNum - 1);
        if (this._currentLineIsOutsideBlock() && _isUndefinedOrWhitespace(prev)) {
            this._trimOutputAndAppendLine('```');
            this._appendLine();
            this._popState();
            return;
        }
        this._appendLine(this._currentLine());
        this._eatLine();
    }
    _parseLiteralBlockSingleLine() {
        this._appendLine(this._currentLine());
        this._appendLine('```');
        this._appendLine();
        this._popState();
        this._eatLine();
    }
    _beginDirective() {
        if (!SpaceDotDotRegExp.test(this._currentLine())) {
            return false;
        }
        this._pushAndSetState(this._parseDirective);
        this._blockIndent = this._nextBlockIndent();
        this._appendDirectiveBlock = false;
        return true;
    }
    // https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html#field-lists
    // Python doesn't have a single standard for param documentation. There are four
    // popular styles.
    //
    // 1. Epytext:
    //      @param param1: description
    // 2. reST:
    //      :param param1: description
    // 3. Google (variant 1):
    //      Args:
    //          param1: description
    // 4. Google (variant 2):
    //      Args:
    //          param1 (type): description
    _beginFieldList() {
        if (this._insideInlineCode) {
            return false;
        }
        let line = this._currentLine();
        // Handle epyDocs
        if (line.startsWith('@')) {
            this._appendLine();
            this._appendTextLine(line);
            this._eatLine();
            return true;
        }
        // catch-all for styles except reST
        const hasArguments = !(line === null || line === void 0 ? void 0 : line.endsWith(':')) && !(line === null || line === void 0 ? void 0 : line.endsWith('::')) && !!line.match(/.*?\s*:\s*(.+)/gu);
        // reSt params. Attempt to put directives lines into their own paragraphs.
        const restDirective = DirectivesExtraNewlineRegExp.test(line); //line.match(/^\s*:param/);
        if (hasArguments || restDirective) {
            const prev = this._lineAt(this._lineNum - 1);
            // Force a line break, if previous line doesn't already have a break or is blank
            if (!this._builder.endsWith(MarkdownLineBreak) && !this._builder.endsWith(`\n\n`) && !_isHeader(prev)) {
                this._builder = this._builder.slice(0, -1) + MarkdownLineBreak;
            }
            // force indent for fields
            line = this._convertIndent(line);
            this._appendTextLine(line);
            this._eatLine();
            return true;
        }
        return false;
    }
    _beginTableBlock() {
        if (this._insideInlineCode) {
            return false;
        }
        const line = this._currentLine();
        if (EqualHeaderRegExp.test(line)) {
            this._tableState = { header: line.trimStart(), inHeader: true };
            this._eatLine();
            this._pushAndSetState(this._parseTableBlock);
            return true;
        }
        return false;
    }
    // Converts ReST style tables to ones that vscode will render.
    //
    //    ReST:
    //    ========= ============
    //    Syntax    Description
    //    --------- ------------
    //    Header    Title
    //    Paragraph Text
    //    ========= ============
    //
    //    Markdown:
    //    | Syntax      | Description |
    //    | ----------- | ----------- |
    //    | Header      | Title       |
    //    | Paragraph   | Text        |
    _parseTableBlock() {
        if (_isUndefinedOrWhitespace(this._currentLineOrUndefined()) || !this._tableState) {
            this._tableState = undefined;
            this._popState();
            return;
        }
        let line = this._currentLine();
        if (EqualHeaderRegExp.test(line)) {
            this._eatLine();
            this._appendLine('\n<br/>\n');
            this._popState();
            this._tableState = undefined;
            return;
        }
        else {
            let formattedLine = '|';
            const columnParts = this._tableState.header.split(' ');
            const headerStrings = [];
            if (this._tableState.inHeader) {
                do {
                    // Special header parsing to handle multiline headers
                    // for now we just append the multi header rows into a single line
                    // using the html <br> to signify newlines, but vscode doesn't seem to support it yet
                    // So headers will appear as a single line for now
                    let colStart = 0;
                    for (let i = 0; i < columnParts.length; i++) {
                        const equalStr = columnParts[i];
                        const len = equalStr.length + 1;
                        const columnStr = line.slice(colStart, colStart + len);
                        if (headerStrings[i] === undefined) {
                            headerStrings[i] = `${columnStr} `;
                        }
                        else {
                            headerStrings[i] = headerStrings[i].concat(`<br>${columnStr} `);
                        }
                        colStart += len;
                    }
                    this._eatLine();
                    line = this._currentLine();
                } while (!_isUndefinedOrWhitespace(this._currentLineOrUndefined()) &&
                    !DashHeaderRegExp.test(line) &&
                    !EqualHeaderRegExp.test(line));
                this._tableState.inHeader = false;
                // Append header
                headerStrings.forEach((h) => {
                    formattedLine += `${h}|`;
                });
                this._appendLine(formattedLine);
                // Convert header end
                const endHeaderStr = line.trimStart().replace(/=/g, '-').replace(' ', '|');
                this._appendLine(`|${endHeaderStr}|`);
                this._eatLine();
            }
            else {
                // Normal row parsing
                let colStart = 0;
                columnParts.forEach((column) => {
                    const len = column.length + 1;
                    const columnStr = line.slice(colStart, colStart + len);
                    formattedLine += `${columnStr}|`;
                    colStart += len;
                });
                this._appendLine(formattedLine);
                this._eatLine();
            }
        }
    }
    _beginList() {
        if (this._insideInlineCode) {
            return false;
        }
        let line = this._currentLine();
        const dashMatch = LeadingDashListRegExp.exec(line);
        if ((dashMatch === null || dashMatch === void 0 ? void 0 : dashMatch.length) === 2) {
            // Prevent list item from being see as code, by halving leading spaces
            if (dashMatch[1].length >= 4) {
                line = ' '.repeat(dashMatch[1].length / 2) + line.trimLeft();
            }
            this._appendTextLine(line);
            this._eatLine();
            if (this._state !== this._parseList) {
                this._pushAndSetState(this._parseList);
            }
            return true;
        }
        const asteriskMatch = LeadingAsteriskListRegExp.exec(line);
        if ((asteriskMatch === null || asteriskMatch === void 0 ? void 0 : asteriskMatch.length) === 2) {
            if (asteriskMatch[1].length === 0) {
                line = line = ' ' + line;
            }
            else if (asteriskMatch[1].length >= 4) {
                // Prevent list item from being see as code, by halving leading spaces
                line = ' '.repeat(asteriskMatch[1].length / 2) + line.trimLeft();
            }
            this._appendTextLine(line);
            this._eatLine();
            if (this._state !== this._parseList) {
                this._pushAndSetState(this._parseList);
            }
            return true;
        }
        const leadingNumberList = LeadingNumberListRegExp.exec(line);
        if ((leadingNumberList === null || leadingNumberList === void 0 ? void 0 : leadingNumberList.length) === 2) {
            this._appendTextLine(line);
            this._eatLine();
            return true;
        }
        return false;
    }
    _parseList() {
        if (_isUndefinedOrWhitespace(this._currentLineOrUndefined()) || this._currentLineIsOutsideBlock()) {
            this._popState();
            return;
        }
        // Check for the start of a new list item
        const isMultiLineItem = !this._beginList();
        // Remove leading spaces so that multiline items get appear in a single block
        if (isMultiLineItem) {
            const line = this._currentLine().trimStart();
            this._appendTextLine(line);
            this._eatLine();
        }
    }
    _parseDirective() {
        // http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#directives
        const match = DirectiveLikeRegExp.exec(this._currentLine());
        if (match !== null && match.length === 3) {
            const directiveType = match[1];
            const directive = match[2];
            if (directiveType === 'class') {
                this._appendDirectiveBlock = true;
                this._appendLine();
                this._appendLine('```');
                this._appendLine(directive);
                this._appendLine('```');
                this._appendLine();
            }
            else if (directiveType === 'code-block') {
                this._appendDirectiveBlock = true;
                this._beginMinIndentCodeBlock(this._parseLiteralBlock);
                this._eatLine();
                return;
            }
        }
        if (this._blockIndent === 0) {
            // This is a one-liner directive, so pop back.
            this._popState();
        }
        else {
            this._state = this._parseDirectiveBlock;
        }
        this._eatLine();
    }
    _parseDirectiveBlock() {
        if (!_isUndefinedOrWhitespace(this._currentLineOrUndefined()) && this._currentLineIsOutsideBlock()) {
            this._popState();
            return;
        }
        if (this._appendDirectiveBlock) {
            // This is a bit of a hack. This just trims the text and appends it
            // like top-level text, rather than doing actual indent-based recursion.
            this._appendTextLine(this._currentLine().trimLeft());
        }
        this._eatLine();
    }
    _appendLine(line) {
        if (!_isUndefinedOrWhitespace(line)) {
            this._builder += line + '\n';
            this._skipAppendEmptyLine = false;
        }
        else if (!this._skipAppendEmptyLine) {
            this._builder += '\n';
            this._skipAppendEmptyLine = true;
        }
    }
    _append(text) {
        this._builder += text;
        this._skipAppendEmptyLine = false;
    }
    _trimOutputAndAppendLine(line, noNewLine = false) {
        this._builder = this._builder.trimRight();
        this._skipAppendEmptyLine = false;
        if (!noNewLine) {
            this._appendLine();
        }
        this._appendLine(line);
    }
}
function _countLeadingSpaces(s) {
    return s.search(LeadingSpaceCountRegExp);
}
function _isUndefinedOrWhitespace(s) {
    return s === undefined || !NonWhitespaceRegExp.test(s);
}
function _isHeader(line) {
    var _a, _b;
    return line !== undefined && ((_b = (_a = line.match(/^\s*[#`~=-]{3,}/)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/docStringUtils.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/docStringUtils.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * docStringUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Static methods that format and parse doc strings based on
 * the rules specified in PEP 257
 * (https://www.python.org/dev/peps/pep-0257/).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extractParameterDocumentation = exports.cleanAndSplitDocString = exports.cleanDocString = void 0;
// Cleans the a docstring as inspect.cleandoc does.
function cleanDocString(rawString) {
    return cleanAndSplitDocString(rawString).join('\n');
}
exports.cleanDocString = cleanDocString;
function cleanAndSplitDocString(rawString) {
    // Remove carriage returns and replace tabs.
    const unescaped = rawString.replace(/\r/g, '').replace(/\t/g, '        ');
    // Split into lines.
    const lines = unescaped.split('\n');
    // Determine the max indent amount.
    let leftSpacesToRemove = Number.MAX_VALUE;
    lines.forEach((line, index) => {
        // First line is special.
        if (lines.length <= 1 || index > 0) {
            const trimmed = line.trimLeft();
            if (trimmed) {
                leftSpacesToRemove = Math.min(leftSpacesToRemove, line.length - trimmed.length);
            }
        }
    });
    // Handle the case where there were only empty lines.
    if (leftSpacesToRemove >= Number.MAX_VALUE) {
        leftSpacesToRemove = 0;
    }
    // Trim the lines.
    const trimmedLines = [];
    lines.forEach((line, index) => {
        if (index === 0) {
            trimmedLines.push(line.trim());
        }
        else {
            trimmedLines.push(line.substr(leftSpacesToRemove).trimRight());
        }
    });
    // Strip off leading and trailing blank lines.
    while (trimmedLines.length > 0 && trimmedLines[0].length === 0) {
        trimmedLines.shift();
    }
    while (trimmedLines.length > 0 && trimmedLines[trimmedLines.length - 1].length === 0) {
        trimmedLines.pop();
    }
    return trimmedLines;
}
exports.cleanAndSplitDocString = cleanAndSplitDocString;
function extractParameterDocumentation(functionDocString, paramName) {
    if (!functionDocString || !paramName) {
        return undefined;
    }
    // Python doesn't have a single standard for param documentation. There are three
    // popular styles.
    //
    // 1. Epytext:
    //      @param param1: description
    // 2. reST:
    //      :param param1: description
    // 3. Google (variant 1):
    //      Args:
    //          param1: description
    // 4. Google (variant 2):
    //      Args:
    //          param1 (type): description
    const docStringLines = cleanAndSplitDocString(functionDocString);
    for (const line of docStringLines) {
        const trimmedLine = line.trim();
        // Check for Epytext
        let paramOffset = trimmedLine.indexOf('@param ' + paramName);
        if (paramOffset >= 0) {
            return trimmedLine.substr(paramOffset + 7);
        }
        // Check for reST format
        paramOffset = trimmedLine.indexOf(':param ' + paramName);
        if (paramOffset >= 0) {
            return trimmedLine.substr(paramOffset + 7);
        }
        // Check for Google (variant 1) format
        paramOffset = trimmedLine.indexOf(paramName + ': ');
        if (paramOffset >= 0) {
            return trimmedLine.substr(paramOffset);
        }
        // Check for Google (variant 2) format
        paramOffset = trimmedLine.indexOf(paramName + ' (');
        if (paramOffset >= 0) {
            return trimmedLine.substr(paramOffset);
        }
    }
    return undefined;
}
exports.extractParameterDocumentation = extractParameterDocumentation;


/***/ }),

/***/ "../pyright-internal/src/analyzer/enums.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/analyzer/enums.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * enums.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides special-case logic for the Enum class.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getEnumAutoValueType = exports.getTypeOfEnumMember = exports.getEnumDeclaredValueType = exports.isDeclInEnumClass = exports.transformTypeForPossibleEnumClass = exports.createEnumType = exports.isEnumClassWithMembers = exports.isEnumMetaclass = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const typeGuards_1 = __webpack_require__(/*! ./typeGuards */ "../pyright-internal/src/analyzer/typeGuards.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// Determines whether the class is an Enum metaclass or a subclass thereof.
function isEnumMetaclass(classType) {
    return classType.details.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, ['EnumMeta', 'EnumType']));
}
exports.isEnumMetaclass = isEnumMetaclass;
// Determines whether this is an enum class that has at least one enum
// member defined.
function isEnumClassWithMembers(evaluator, classType) {
    if (!(0, types_1.isClass)(classType) || !types_1.ClassType.isEnumClass(classType)) {
        return false;
    }
    // Determine whether the enum class defines a member.
    let definesValue = false;
    types_1.ClassType.getSymbolTable(classType).forEach((symbol) => {
        const symbolType = evaluator.getEffectiveTypeOfSymbol(symbol);
        if ((0, types_1.isClassInstance)(symbolType) && types_1.ClassType.isSameGenericClass(symbolType, classType)) {
            definesValue = true;
        }
    });
    return definesValue;
}
exports.isEnumClassWithMembers = isEnumClassWithMembers;
// Creates a new custom enum class with named values.
function createEnumType(evaluator, errorNode, enumClass, argList) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(errorNode);
    if (argList.length === 0) {
        return undefined;
    }
    const nameArg = argList[0];
    if (nameArg.argumentCategory !== 0 /* ArgumentCategory.Simple */ ||
        !nameArg.valueExpression ||
        nameArg.valueExpression.nodeType !== 48 /* ParseNodeType.StringList */ ||
        nameArg.valueExpression.strings.length !== 1 ||
        nameArg.valueExpression.strings[0].nodeType !== 49 /* ParseNodeType.String */) {
        return undefined;
    }
    const className = nameArg.valueExpression.strings.map((s) => s.value).join('');
    const classType = types_1.ClassType.createInstantiable(className, (0, parseTreeUtils_1.getClassFullName)(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 2097152 /* ClassTypeFlags.EnumClass */ | 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */, (0, parseTreeUtils_1.getTypeSourceId)(errorNode), 
    /* declaredMetaclass */ undefined, enumClass.details.effectiveMetaclass);
    classType.details.baseClasses.push(enumClass);
    (0, typeUtils_1.computeMroLinearization)(classType);
    const classFields = types_1.ClassType.getSymbolTable(classType);
    classFields.set('__class__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 64 /* SymbolFlags.IgnoredForProtocolMatch */, classType));
    if (argList.length < 2) {
        return undefined;
    }
    const initArg = argList[1];
    if (initArg.argumentCategory !== 0 /* ArgumentCategory.Simple */ || !initArg.valueExpression) {
        return undefined;
    }
    const intClassType = evaluator.getBuiltInType(errorNode, 'int');
    if (!intClassType || !(0, types_1.isInstantiableClass)(intClassType)) {
        return undefined;
    }
    const classInstanceType = types_1.ClassType.cloneAsInstance(classType);
    // The Enum functional form supports various forms of arguments:
    //   Enum('name', 'a b c')
    //   Enum('name', 'a,b,c')
    //   Enum('name', ['a', 'b', 'c'])
    //   Enum('name', ('a', 'b', 'c'))
    //   Enum('name', (('a', 1), ('b', 2), ('c', 3)))
    //   Enum('name', [('a', 1), ('b', 2), ('c', 3))]
    //   Enum('name', {'a': 1, 'b': 2, 'c': 3})
    if (initArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
        // Don't allow format strings in the init arg.
        if (!initArg.valueExpression.strings.every((str) => str.nodeType === 49 /* ParseNodeType.String */)) {
            return undefined;
        }
        const initStr = initArg.valueExpression.strings
            .map((s) => s.value)
            .join('')
            .trim();
        // Split by comma or whitespace.
        const entryNames = initStr.split(/[\s,]+/);
        for (const [index, entryName] of entryNames.entries()) {
            if (!entryName) {
                return undefined;
            }
            const valueType = types_1.ClassType.cloneWithLiteral(types_1.ClassType.cloneAsInstance(intClassType), index + 1);
            const enumLiteral = new types_1.EnumLiteral(classType.details.fullName, classType.details.name, entryName, valueType);
            const newSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.ClassType.cloneWithLiteral(classInstanceType, enumLiteral));
            classFields.set(entryName, newSymbol);
        }
        return classType;
    }
    if (initArg.valueExpression.nodeType === 31 /* ParseNodeType.List */ ||
        initArg.valueExpression.nodeType === 52 /* ParseNodeType.Tuple */) {
        const entries = initArg.valueExpression.nodeType === 31 /* ParseNodeType.List */
            ? initArg.valueExpression.entries
            : initArg.valueExpression.expressions;
        if (entries.length === 0) {
            return undefined;
        }
        // Entries can be either string literals or tuples of a string
        // literal and a value. All entries must follow the same pattern.
        let isSimpleString = false;
        for (const [index, entry] of entries.entries()) {
            if (index === 0) {
                isSimpleString = entry.nodeType === 48 /* ParseNodeType.StringList */;
            }
            let nameNode;
            let valueType;
            if (entry.nodeType === 48 /* ParseNodeType.StringList */) {
                if (!isSimpleString) {
                    return undefined;
                }
                nameNode = entry;
                valueType = types_1.ClassType.cloneWithLiteral(types_1.ClassType.cloneAsInstance(intClassType), index + 1);
            }
            else if (entry.nodeType === 52 /* ParseNodeType.Tuple */) {
                if (isSimpleString) {
                    return undefined;
                }
                if (entry.expressions.length !== 2) {
                    return undefined;
                }
                nameNode = entry.expressions[0];
                valueType = evaluator.getTypeOfExpression(entry.expressions[1]).type;
            }
            else {
                return undefined;
            }
            if (nameNode.nodeType !== 48 /* ParseNodeType.StringList */ ||
                nameNode.strings.length !== 1 ||
                nameNode.strings[0].nodeType !== 49 /* ParseNodeType.String */) {
                return undefined;
            }
            const entryName = nameNode.strings[0].value;
            const enumLiteral = new types_1.EnumLiteral(classType.details.fullName, classType.details.name, entryName, valueType);
            const newSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.ClassType.cloneWithLiteral(classInstanceType, enumLiteral));
            classFields.set(entryName, newSymbol);
        }
    }
    if (initArg.valueExpression.nodeType === 15 /* ParseNodeType.Dictionary */) {
        const entries = initArg.valueExpression.entries;
        if (entries.length === 0) {
            return undefined;
        }
        for (const entry of entries) {
            // Don't support dictionary expansion expressions.
            if (entry.nodeType !== 17 /* ParseNodeType.DictionaryKeyEntry */) {
                return undefined;
            }
            const nameNode = entry.keyExpression;
            const valueType = evaluator.getTypeOfExpression(entry.valueExpression).type;
            if (nameNode.nodeType !== 48 /* ParseNodeType.StringList */ ||
                nameNode.strings.length !== 1 ||
                nameNode.strings[0].nodeType !== 49 /* ParseNodeType.String */) {
                return undefined;
            }
            const entryName = nameNode.strings[0].value;
            const enumLiteral = new types_1.EnumLiteral(classType.details.fullName, classType.details.name, entryName, valueType);
            const newSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.ClassType.cloneWithLiteral(classInstanceType, enumLiteral));
            classFields.set(entryName, newSymbol);
        }
    }
    return classType;
}
exports.createEnumType = createEnumType;
function transformTypeForPossibleEnumClass(evaluator, statementNode, nameNode, getValueType) {
    var _a, _b, _c, _d;
    // If the node is within a class that derives from the metaclass
    // "EnumMeta", we need to treat assignments differently.
    const enclosingClassNode = (0, parseTreeUtils_1.getEnclosingClass)(statementNode, /* stopAtFunction */ true);
    if (!enclosingClassNode) {
        return undefined;
    }
    const enumClassInfo = evaluator.getTypeOfClass(enclosingClassNode);
    if (!enumClassInfo || !types_1.ClassType.isEnumClass(enumClassInfo.classType)) {
        return undefined;
    }
    // In ".py" files, the transform applies only to members that are
    // assigned within the class. In stub files, it applies to most variables
    // even if they are not assigned. This unfortunate convention means
    // there is no way in a stub to specify both enum members and instance
    // variables used within each enum instance. Unless/until there is
    // a change to this convention and all type checkers and stubs adopt
    // it, we're stuck with this limitation.
    let isMemberOfEnumeration = false;
    let isUnpackedTuple = false;
    if (statementNode.nodeType === 3 /* ParseNodeType.Assignment */ &&
        (0, parseTreeUtils_1.isNodeContainedWithin)(nameNode, statementNode.leftExpression)) {
        isMemberOfEnumeration = true;
        if ((0, parseTreeUtils_1.getParentNodeOfType)(nameNode, 52 /* ParseNodeType.Tuple */)) {
            isUnpackedTuple = true;
        }
    }
    else if ((0, analyzerNodeInfo_1.getFileInfo)(nameNode).isStubFile &&
        ((_a = nameNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 54 /* ParseNodeType.TypeAnnotation */ &&
        nameNode.parent.valueExpression === nameNode) {
        isMemberOfEnumeration = true;
    }
    // The spec specifically excludes names that start and end with a single underscore.
    // This also includes dunder names.
    if ((0, symbolNameUtils_1.isSingleDunderName)(nameNode.value)) {
        return undefined;
    }
    // Specifically exclude "value" and "name". These are reserved by the enum metaclass.
    if (nameNode.value === 'name' || nameNode.value === 'value') {
        return undefined;
    }
    const valueTypeInfo = getValueType();
    const declaredType = valueTypeInfo.declaredType;
    let assignedType = valueTypeInfo.assignedType;
    let valueType = (_b = declaredType !== null && declaredType !== void 0 ? declaredType : assignedType) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
    // If the LHS is an unpacked tuple, we need to handle this as
    // a special case.
    if (isUnpackedTuple) {
        valueType =
            (_d = (_c = evaluator.getTypeOfIterator({ type: valueType }, 
            /* isAsync */ false, nameNode, 
            /* emitNotIterableError */ false)) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : types_1.UnknownType.create();
    }
    // The spec excludes descriptors.
    if ((0, types_1.isClassInstance)(valueType) && types_1.ClassType.getSymbolTable(valueType).get('__get__')) {
        return undefined;
    }
    // The spec excludes private (mangled) names.
    if ((0, symbolNameUtils_1.isPrivateName)(nameNode.value)) {
        return undefined;
    }
    // The enum spec doesn't explicitly specify this, but it
    // appears that callables are excluded.
    if (!(0, types_1.findSubtype)(valueType, (subtype) => !(0, types_1.isFunction)(subtype) && !(0, types_1.isOverloadedFunction)(subtype))) {
        return undefined;
    }
    if (!assignedType && statementNode.nodeType === 3 /* ParseNodeType.Assignment */) {
        assignedType = evaluator.getTypeOfExpression(statementNode.rightExpression, 
        /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(declaredType)).type;
    }
    // Handle the Python 3.11 "enum.member()" and "enum.nonmember()" features.
    if (assignedType && (0, types_1.isClassInstance)(assignedType) && types_1.ClassType.isBuiltIn(assignedType)) {
        if (assignedType.details.fullName === 'enum.nonmember') {
            const nonMemberType = assignedType.typeArguments && assignedType.typeArguments.length > 0
                ? assignedType.typeArguments[0]
                : types_1.UnknownType.create();
            // If the type of the nonmember is declared and the assigned value has
            // a compatible type, use the declared type.
            if (declaredType && evaluator.assignType(declaredType, nonMemberType)) {
                return declaredType;
            }
            return nonMemberType;
        }
        if (assignedType.details.fullName === 'enum.member') {
            valueType =
                assignedType.typeArguments && assignedType.typeArguments.length > 0
                    ? assignedType.typeArguments[0]
                    : types_1.UnknownType.create();
            isMemberOfEnumeration = true;
        }
    }
    // Handle aliases to other enum members within the same enum.
    if ((0, types_1.isClassInstance)(valueType) &&
        types_1.ClassType.isSameGenericClass(valueType, types_1.ClassType.cloneAsInstance(enumClassInfo.classType)) &&
        valueType.literalValue !== undefined) {
        return undefined;
    }
    if (!isMemberOfEnumeration) {
        return undefined;
    }
    const enumLiteral = new types_1.EnumLiteral(enumClassInfo.classType.details.fullName, enumClassInfo.classType.details.name, nameNode.value, valueType);
    return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneWithLiteral(enumClassInfo.classType, enumLiteral));
}
exports.transformTypeForPossibleEnumClass = transformTypeForPossibleEnumClass;
function isDeclInEnumClass(evaluator, decl) {
    const classNode = (0, parseTreeUtils_1.getEnclosingClass)(decl.node, /* stopAtFunction */ true);
    if (!classNode) {
        return false;
    }
    const classInfo = evaluator.getTypeOfClass(classNode);
    if (!classInfo) {
        return false;
    }
    return types_1.ClassType.isEnumClass(classInfo.classType);
}
exports.isDeclInEnumClass = isDeclInEnumClass;
function getEnumDeclaredValueType(evaluator, classType, declaredTypesOnly = false) {
    // See if there is a declared type for "_value_".
    let valueType;
    const declaredValueMember = (0, typeUtils_1.lookUpClassMember)(classType, '_value_', declaredTypesOnly ? 64 /* MemberAccessFlags.DeclaredTypesOnly */ : 0 /* MemberAccessFlags.Default */);
    // If the declared type comes from the 'Enum' base class, ignore it
    // because it will be "Any", which isn't useful to us here.
    if (declaredValueMember &&
        declaredValueMember.classType &&
        (0, types_1.isClass)(declaredValueMember.classType) &&
        !types_1.ClassType.isBuiltIn(declaredValueMember.classType, 'Enum')) {
        valueType = evaluator.getTypeOfMember(declaredValueMember);
    }
    return valueType;
}
exports.getEnumDeclaredValueType = getEnumDeclaredValueType;
function getTypeOfEnumMember(evaluator, errorNode, classType, memberName, isIncomplete) {
    // Handle the special case of 'name' and 'value' members within an enum.
    if (!(0, types_1.isClassInstance)(classType) || !types_1.ClassType.isEnumClass(classType)) {
        return undefined;
    }
    const literalValue = classType.literalValue;
    if (memberName === 'name' || memberName === '_name_') {
        const strClass = evaluator.getBuiltInType(errorNode, 'str');
        if (!(0, types_1.isInstantiableClass)(strClass)) {
            return undefined;
        }
        const makeNameType = (value) => {
            return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneWithLiteral(strClass, value.itemName));
        };
        if (literalValue) {
            (0, debug_1.assert)(literalValue instanceof types_1.EnumLiteral);
            return { type: makeNameType(literalValue), isIncomplete };
        }
        // The type wasn't associated with a particular enum literal, so return
        // a union of all possible enum literals.
        const literalValues = (0, typeGuards_1.enumerateLiteralsForType)(evaluator, classType);
        if (literalValues && literalValues.length > 0) {
            return {
                type: (0, types_1.combineTypes)(literalValues.map((literalClass) => {
                    const literalValue = literalClass.literalValue;
                    (0, debug_1.assert)(literalValue instanceof types_1.EnumLiteral);
                    return makeNameType(literalValue);
                })),
                isIncomplete,
            };
        }
    }
    // See if there is a declared type for "_value_".
    const valueType = getEnumDeclaredValueType(evaluator, classType);
    if (memberName === 'value' || memberName === '_value_') {
        // If the enum class has a custom metaclass, it may implement some
        // "magic" that computes different values for the "_value_" attribute.
        // This occurs, for example, in the django TextChoices class. If we
        // detect a custom metaclass, we'll use the declared type of _value_
        // if it is declared.
        const metaclass = classType.details.effectiveMetaclass;
        if (metaclass && (0, types_1.isClass)(metaclass) && !types_1.ClassType.isBuiltIn(metaclass)) {
            return { type: valueType !== null && valueType !== void 0 ? valueType : types_1.AnyType.create(), isIncomplete };
        }
        // If the enum class has a custom __new__ or __init__ method,
        // it may implement some magic that computes different values for
        // the "_value_" attribute. If we see a customer __new__ or __init__,
        // we'll assume the value type is what we computed above, or Any.
        const newMember = (0, typeUtils_1.lookUpClassMember)(classType, '__new__', 4 /* MemberAccessFlags.SkipObjectBaseClass */);
        const initMember = (0, typeUtils_1.lookUpClassMember)(classType, '__init__', 4 /* MemberAccessFlags.SkipObjectBaseClass */);
        if (newMember && (0, types_1.isClass)(newMember.classType) && !types_1.ClassType.isBuiltIn(newMember.classType)) {
            return { type: valueType !== null && valueType !== void 0 ? valueType : types_1.AnyType.create(), isIncomplete };
        }
        if (initMember && (0, types_1.isClass)(initMember.classType) && !types_1.ClassType.isBuiltIn(initMember.classType)) {
            return { type: valueType !== null && valueType !== void 0 ? valueType : types_1.AnyType.create(), isIncomplete };
        }
        // There were no explicit assignments to the "_value_" attribute, so we can
        // assume that the values are assigned directly to the "_value_" by
        // the EnumMeta metaclass.
        if (literalValue) {
            (0, debug_1.assert)(literalValue instanceof types_1.EnumLiteral);
            // If there is no known value type for this literal value,
            // return undefined. This will cause the caller to fall back
            // on the definition of "_value_" within the class definition
            // (if present).
            if ((0, types_1.isAny)(literalValue.itemType)) {
                return valueType ? { type: valueType, isIncomplete } : undefined;
            }
            return { type: literalValue.itemType, isIncomplete };
        }
        // The type wasn't associated with a particular enum literal, so return
        // a union of all possible enum literals.
        const literalValues = (0, typeGuards_1.enumerateLiteralsForType)(evaluator, classType);
        if (literalValues && literalValues.length > 0) {
            return {
                type: (0, types_1.combineTypes)(literalValues.map((literalClass) => {
                    const literalValue = literalClass.literalValue;
                    (0, debug_1.assert)(literalValue instanceof types_1.EnumLiteral);
                    return literalValue.itemType;
                })),
                isIncomplete,
            };
        }
    }
    return undefined;
}
exports.getTypeOfEnumMember = getTypeOfEnumMember;
function getEnumAutoValueType(evaluator, node) {
    const containingClassNode = (0, parseTreeUtils_1.getEnclosingClass)(node);
    if (containingClassNode) {
        const classTypeInfo = evaluator.getTypeOfClass(containingClassNode);
        if (classTypeInfo) {
            const memberInfo = evaluator.getTypeOfBoundMember(node, types_1.ClassType.cloneAsInstance(classTypeInfo.classType), '_generate_next_value_');
            // Did we find a custom _generate_next_value_ sunder override?
            // Ignore if this comes from Enum because it is declared as
            // returning an "Any" type in the typeshed stubs.
            if (memberInfo &&
                !memberInfo.typeErrors &&
                (0, types_1.isFunction)(memberInfo.type) &&
                memberInfo.classType &&
                (0, types_1.isClass)(memberInfo.classType) &&
                !types_1.ClassType.isBuiltIn(memberInfo.classType, 'Enum')) {
                if (memberInfo.type.details.declaredReturnType) {
                    return memberInfo.type.details.declaredReturnType;
                }
            }
        }
    }
    return evaluator.getBuiltInObject(node, 'int');
}
exports.getEnumAutoValueType = getEnumAutoValueType;


/***/ }),

/***/ "../pyright-internal/src/analyzer/functionTransform.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/analyzer/functionTransform.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * functionTransform.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Code that transforms the return result of a function.
 *
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.applyFunctionTransform = void 0;
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
function applyFunctionTransform(evaluator, errorNode, argList, functionType, result) {
    if ((0, types_1.isFunction)(functionType)) {
        if (functionType.details.fullName === 'functools.total_ordering') {
            return applyTotalOrderingTransform(evaluator, errorNode, argList, result);
        }
    }
    // By default, return the result unmodified.
    return result;
}
exports.applyFunctionTransform = applyFunctionTransform;
function applyTotalOrderingTransform(evaluator, errorNode, argList, result) {
    var _a;
    if (argList.length !== 1) {
        return result;
    }
    // This function is meant to apply to a concrete instantiable class.
    const classType = (_a = argList[0].typeResult) === null || _a === void 0 ? void 0 : _a.type;
    if (!classType || !(0, types_1.isInstantiableClass)(classType) || classType.includeSubclasses) {
        return result;
    }
    const orderingMethods = ['__lt__', '__le__', '__gt__', '__ge__'];
    const instanceType = types_1.ClassType.cloneAsInstance(classType);
    // Verify that the class has at least one of the required functions.
    let firstMemberFound;
    const missingMethods = orderingMethods.filter((methodName) => {
        const memberInfo = (0, typeUtils_1.lookUpObjectMember)(instanceType, methodName, 16 /* MemberAccessFlags.SkipInstanceMembers */);
        if (memberInfo && !firstMemberFound) {
            firstMemberFound = memberInfo;
        }
        return !memberInfo;
    });
    if (!firstMemberFound) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.totalOrderingMissingMethod(), errorNode);
        return result;
    }
    // Determine what type to use for the parameter corresponding to
    // the second operand. This will be taken from the existing method.
    let operandType;
    const firstMemberType = evaluator.getTypeOfMember(firstMemberFound);
    if ((0, types_1.isFunction)(firstMemberType) &&
        firstMemberType.details.parameters.length >= 2 &&
        firstMemberType.details.parameters[1].hasDeclaredType) {
        operandType = firstMemberType.details.parameters[1].type;
    }
    // If there was no provided operand type, fall back to object.
    if (!operandType) {
        const objectType = evaluator.getBuiltInObject(errorNode, 'object');
        if (!objectType || !(0, types_1.isClassInstance)(objectType)) {
            return result;
        }
        operandType = objectType;
    }
    const boolType = evaluator.getBuiltInObject(errorNode, 'bool');
    if (!boolType || !(0, types_1.isClassInstance)(boolType)) {
        return result;
    }
    const selfParam = {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: (0, typeUtils_1.synthesizeTypeVarForSelfCls)(classType, /* isClsParam */ false),
        hasDeclaredType: true,
    };
    const objParam = {
        category: 0 /* ParameterCategory.Simple */,
        name: '__value',
        type: operandType,
        hasDeclaredType: true,
    };
    // Add the missing members to the class's symbol table.
    missingMethods.forEach((methodName) => {
        const methodToAdd = types_1.FunctionType.createSynthesizedInstance(methodName);
        types_1.FunctionType.addParameter(methodToAdd, selfParam);
        types_1.FunctionType.addParameter(methodToAdd, objParam);
        methodToAdd.details.declaredReturnType = boolType;
        types_1.ClassType.getSymbolTable(classType).set(methodName, symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, methodToAdd));
    });
    return result;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/importResolver.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/importResolver.ts ***!
  \**********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * importResolver.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides the logic for resolving imports according to the
 * runtime rules of Python.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ImportResolver = exports.supportedFileExtensions = exports.createImportedModuleDescriptor = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const pathConsts_1 = __webpack_require__(/*! ../common/pathConsts */ "../pyright-internal/src/common/pathConsts.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const StringUtils = __importStar(__webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts"));
const stringUtils_1 = __webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const characters_1 = __webpack_require__(/*! ../parser/characters */ "../pyright-internal/src/parser/characters.ts");
const importStatementUtils_1 = __webpack_require__(/*! ./importStatementUtils */ "../pyright-internal/src/analyzer/importStatementUtils.ts");
const parentDirectoryCache_1 = __webpack_require__(/*! ./parentDirectoryCache */ "../pyright-internal/src/analyzer/parentDirectoryCache.ts");
const pyTypedUtils_1 = __webpack_require__(/*! ./pyTypedUtils */ "../pyright-internal/src/analyzer/pyTypedUtils.ts");
const PythonPathUtils = __importStar(__webpack_require__(/*! ./pythonPathUtils */ "../pyright-internal/src/analyzer/pythonPathUtils.ts"));
const SymbolNameUtils = __importStar(__webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
function createImportedModuleDescriptor(moduleName) {
    if (moduleName.length === 0) {
        return { leadingDots: 0, nameParts: [], importedSymbols: new Set() };
    }
    let startIndex = 0;
    let leadingDots = 0;
    for (; startIndex < moduleName.length; startIndex++) {
        if (moduleName[startIndex] !== '.') {
            break;
        }
        leadingDots++;
    }
    return {
        leadingDots,
        nameParts: moduleName.slice(startIndex).split('.'),
        importedSymbols: new Set(),
    };
}
exports.createImportedModuleDescriptor = createImportedModuleDescriptor;
const supportedNativeLibExtensions = ['.pyd', '.so', '.dylib'];
const supportedSourceFileExtensions = ['.py', '.pyi'];
exports.supportedFileExtensions = [...supportedSourceFileExtensions, ...supportedNativeLibExtensions];
// Should we allow partial resolution for third-party packages? Some use tricks
// to populate their package namespaces, so we might be able to partially resolve
// a multi - part import(e.g. "a.b.c") but not fully resolve it. If this is set to
// false, we will have some false positives. If it is set to true, we won't report
// errors when these partial-resolutions fail.
const allowPartialResolutionForThirdPartyPackages = false;
class ImportResolver {
    constructor(serviceProvider, _configOptions, host) {
        this.serviceProvider = serviceProvider;
        this._configOptions = _configOptions;
        this.host = host;
        this._cachedImportResults = new Map();
        this._cachedModuleNameResults = new Map();
        this._cachedEntriesForPath = new Map();
        this._cachedFilesForPath = new Map();
        this._cachedDirExistenceForRoot = new Map();
        this.cachedParentImportResults = new parentDirectoryCache_1.ParentDirectoryCache(() => this.getPythonSearchPaths([]));
    }
    get fileSystem() {
        return this.serviceProvider.fs();
    }
    get tmp() {
        return this.serviceProvider.tmp();
    }
    get partialStubs() {
        return this.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.partialStubs);
    }
    static isSupportedImportSourceFile(uri) {
        const fileExtension = uri.lastExtension.toLowerCase();
        return supportedSourceFileExtensions.some((ext) => fileExtension === ext);
    }
    static isSupportedImportFile(uri) {
        const fileExtension = uri.lastExtension.toLowerCase();
        return exports.supportedFileExtensions.some((ext) => fileExtension === ext);
    }
    invalidateCache() {
        var _a;
        this._cachedImportResults = new Map();
        this._cachedModuleNameResults = new Map();
        this.cachedParentImportResults.reset();
        this._stdlibModules = undefined;
        this._invalidateFileSystemCache();
        (_a = this.partialStubs) === null || _a === void 0 ? void 0 : _a.clearPartialStubs();
    }
    // Resolves the import and returns the path if it exists, otherwise
    // returns undefined.
    resolveImport(sourceFileUri, execEnv, moduleDescriptor) {
        // Wrap internal call to resolveImportInternal() to prevent calling any
        // child class version of resolveImport().
        return this.resolveImportInternal(sourceFileUri, execEnv, moduleDescriptor);
    }
    getCompletionSuggestions(sourceFileUri, execEnv, moduleDescriptor) {
        const suggestions = this._getCompletionSuggestionsStrict(sourceFileUri, execEnv, moduleDescriptor);
        // We only do parent import resolution for absolute path.
        if (moduleDescriptor.leadingDots > 0) {
            return suggestions;
        }
        const root = this.getParentImportResolutionRoot(sourceFileUri, execEnv.root);
        const origin = sourceFileUri.getDirectory();
        let current = origin;
        while (this._shouldWalkUp(current, root, execEnv) && current) {
            this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, current, moduleDescriptor, suggestions, 
            /* strictOnly */ false);
            current = this._tryWalkUp(current);
        }
        return suggestions;
    }
    getConfigOptions() {
        return this._configOptions;
    }
    setConfigOptions(configOptions) {
        this._configOptions = configOptions;
        this.invalidateCache();
    }
    // Returns the implementation file(s) for the given stub file.
    getSourceFilesFromStub(stubFileUri, execEnv, _mapCompiled) {
        const sourceFileUris = [];
        // When ImportResolver resolves an import to a stub file, a second resolve is done
        // ignoring stub files, which gives us an approximation of where the implementation
        // for that stub is located.
        this._cachedImportResults.forEach((map) => {
            map.forEach((result) => {
                if (result.isStubFile && result.isImportFound && result.nonStubImportResult) {
                    if (result.resolvedUris[result.resolvedUris.length - 1].equals(stubFileUri)) {
                        if (result.nonStubImportResult.isImportFound) {
                            const nonEmptyUri = result.nonStubImportResult.resolvedUris[result.nonStubImportResult.resolvedUris.length - 1];
                            if (nonEmptyUri.hasExtension('.py') || nonEmptyUri.hasExtension('.pyi')) {
                                // We allow pyi in case there are multiple pyi for a compiled module such as
                                // numpy.random.mtrand
                                sourceFileUris.push(nonEmptyUri);
                            }
                        }
                    }
                }
            });
        });
        // We haven't seen an import of that stub, attempt to find the source
        // in some other ways.
        if (sourceFileUris.length === 0) {
            // Simple case where the stub and source files are next to each other.
            const sourceFileUri = stubFileUri.replaceExtension('.py');
            if (this.dirExistsCached(sourceFileUri)) {
                sourceFileUris.push(sourceFileUri);
            }
        }
        if (sourceFileUris.length === 0) {
            // The stub and the source file may have the same name, but be located
            // in different folder hierarchies.
            // Example:
            // <stubPath>\package\module.pyi
            // <site-packages>\package\module.py
            // We get the relative path(s) of the stub to its import root(s),
            // in theory there can be more than one, then look for source
            // files in all the import roots using the same relative path(s).
            const importRoots = this.getImportRoots(execEnv);
            const relativeStubPaths = [];
            for (const importRootUri of importRoots) {
                if (stubFileUri.isChild(importRootUri)) {
                    const parts = Array.from(importRootUri.getRelativePathComponents(stubFileUri));
                    if (parts.length >= 1) {
                        // Handle the case where the symbol was resolved to a stubs package
                        // rather than the real package. We'll strip off the "-stubs" suffix
                        // in this case.
                        if (parts[0].endsWith(pathConsts_1.stubsSuffix)) {
                            parts[0] = parts[0].slice(0, parts[0].length - pathConsts_1.stubsSuffix.length);
                        }
                        relativeStubPaths.push(parts.join('/'));
                    }
                }
            }
            for (const relativeStubPath of relativeStubPaths) {
                for (const importRootUri of importRoots) {
                    const absoluteStubPath = importRootUri.resolvePaths(relativeStubPath);
                    let absoluteSourcePath = absoluteStubPath.replaceExtension('.py');
                    if (this.fileExistsCached(absoluteSourcePath)) {
                        sourceFileUris.push(absoluteSourcePath);
                    }
                    else {
                        const filePathWithoutExtension = absoluteSourcePath.stripExtension();
                        if (filePathWithoutExtension.pathEndsWith('__init__')) {
                            // Did not match: <root>/package/__init__.py
                            // Try equivalent: <root>/package.py
                            absoluteSourcePath = filePathWithoutExtension.getDirectory().packageUri;
                            if (this.fileExistsCached(absoluteSourcePath)) {
                                sourceFileUris.push(absoluteSourcePath);
                            }
                        }
                        else {
                            // Did not match: <root>/package.py
                            // Try equivalent: <root>/package/__init__.py
                            absoluteSourcePath = filePathWithoutExtension.initPyUri;
                            if (this.fileExistsCached(absoluteSourcePath)) {
                                sourceFileUris.push(absoluteSourcePath);
                            }
                        }
                    }
                }
            }
        }
        return sourceFileUris;
    }
    // Returns the module name (of the form X.Y.Z) that needs to be imported
    // from the current context to access the module with the specified file path.
    // In a sense, it's performing the inverse of resolveImport.
    getModuleNameForImport(fileUri, execEnv, allowInvalidModuleName = false, detectPyTyped = false) {
        var _a;
        // Cache results of the reverse of resolveImport as we cache resolveImport.
        const cache = (0, collectionUtils_1.getOrAdd)(this._cachedModuleNameResults, (_a = execEnv.root) === null || _a === void 0 ? void 0 : _a.key, () => new Map());
        const key = `${allowInvalidModuleName}.${detectPyTyped}.${fileUri.key}`;
        return (0, collectionUtils_1.getOrAdd)(cache, key, () => this._getModuleNameForImport(fileUri, execEnv, allowInvalidModuleName, detectPyTyped));
    }
    getTypeshedStdLibPath(execEnv) {
        const unused = [];
        return this._getStdlibTypeshedPath(this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, unused);
    }
    getTypeshedThirdPartyPath(execEnv) {
        const unused = [];
        return this._getThirdPartyTypeshedPath(this._configOptions.typeshedPath, unused);
    }
    isStdlibModule(module, execEnv) {
        if (!this._stdlibModules) {
            this._stdlibModules = this._buildStdlibCache(this.getTypeshedStdLibPath(execEnv));
        }
        return this._stdlibModules.has(module.nameParts.join('.'));
    }
    getImportRoots(execEnv, forLogging = false) {
        const importFailureInfo = [];
        const roots = [];
        const stdTypeshed = this._getStdlibTypeshedPath(this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, importFailureInfo);
        if (stdTypeshed) {
            roots.push(stdTypeshed);
        }
        // The "default" workspace has a root-less execution environment; ignore it.
        if (execEnv.root) {
            roots.push(execEnv.root);
        }
        (0, collectionUtils_1.appendArray)(roots, execEnv.extraPaths);
        if (this._configOptions.stubPath) {
            roots.push(this._configOptions.stubPath);
        }
        if (forLogging) {
            // There's one path for each third party package, which blows up logging.
            // Just get the root directly and show it with `...` to indicate that this
            // is where the third party folder is in the roots.
            const thirdPartyRoot = this._getThirdPartyTypeshedPath(this._configOptions.typeshedPath, importFailureInfo);
            if (thirdPartyRoot) {
                roots.push(thirdPartyRoot.resolvePaths('...'));
            }
        }
        else {
            const thirdPartyPaths = this._getThirdPartyTypeshedPackageRoots(importFailureInfo);
            (0, collectionUtils_1.appendArray)(roots, thirdPartyPaths);
        }
        const typeshedPathEx = this.getTypeshedPathEx(execEnv, importFailureInfo);
        if (typeshedPathEx) {
            roots.push(typeshedPathEx);
        }
        const pythonSearchPaths = this.getPythonSearchPaths(importFailureInfo);
        if (pythonSearchPaths.length > 0) {
            (0, collectionUtils_1.appendArray)(roots, pythonSearchPaths);
        }
        return roots;
    }
    ensurePartialStubPackages(execEnv) {
        var _a;
        if (!this.partialStubs) {
            return false;
        }
        if (this.partialStubs.isPartialStubPackagesScanned(execEnv)) {
            return false;
        }
        const ps = this.partialStubs;
        const ignored = [];
        const paths = [];
        const typeshedPathEx = this.getTypeshedPathEx(execEnv, ignored);
        // Add paths to search stub packages.
        addPaths(this._configOptions.stubPath);
        addPaths((_a = execEnv.root) !== null && _a !== void 0 ? _a : this._configOptions.projectRoot);
        execEnv.extraPaths.forEach((p) => addPaths(p));
        addPaths(typeshedPathEx);
        this.getPythonSearchPaths(ignored).forEach((p) => addPaths(p));
        this.partialStubs.processPartialStubPackages(paths, this.getImportRoots(execEnv), typeshedPathEx);
        this._invalidateFileSystemCache();
        return true;
        function addPaths(path) {
            if (!path || ps.isPathScanned(path)) {
                return;
            }
            paths.push(path);
        }
    }
    getPythonSearchPaths(importFailureInfo) {
        // Find the site packages for the configured virtual environment.
        if (!this._cachedPythonSearchPaths) {
            const info = [];
            const paths = (PythonPathUtils.findPythonSearchPaths(this.fileSystem, this._configOptions, this.host, info) || []).map((p) => this.fileSystem.realCasePath(p));
            // Remove duplicates (yes, it happens).
            this._cachedPythonSearchPaths = { paths: Array.from(new Set(paths)), failureInfo: info };
        }
        // Make sure we cache the logs as well so we can find out why search path failed.
        importFailureInfo.push(...this._cachedPythonSearchPaths.failureInfo);
        return this._cachedPythonSearchPaths.paths;
    }
    getTypeshedStdlibExcludeList(customTypeshedPath, pythonVersion, pythonPlatform) {
        const unused = [];
        const typeshedStdlibPath = this._getStdlibTypeshedPath(customTypeshedPath, pythonVersion, pythonPlatform, unused);
        const excludes = [];
        if (!typeshedStdlibPath) {
            return excludes;
        }
        if (!this._cachedTypeshedStdLibModuleVersionInfo) {
            this._cachedTypeshedStdLibModuleVersionInfo = this._readTypeshedStdLibVersions(customTypeshedPath, []);
        }
        this._cachedTypeshedStdLibModuleVersionInfo.forEach((versionInfo, moduleName) => {
            let shouldExcludeModule = false;
            if (versionInfo.max !== undefined && pythonVersion.isGreaterThan(versionInfo.max)) {
                shouldExcludeModule = true;
            }
            if (pythonPlatform !== undefined) {
                const pythonPlatformLower = pythonPlatform.toLowerCase();
                // If there are supported platforms listed, and we are not using one
                // of those supported platforms, exclude it.
                if (versionInfo.supportedPlatforms) {
                    if (versionInfo.supportedPlatforms.every((p) => p.toLowerCase() !== pythonPlatformLower)) {
                        shouldExcludeModule = true;
                    }
                }
                // If there are unsupported platforms listed, see if we're using one of them.
                if (versionInfo.unsupportedPlatforms) {
                    if (versionInfo.unsupportedPlatforms.some((p) => p.toLowerCase() === pythonPlatformLower)) {
                        shouldExcludeModule = true;
                    }
                }
            }
            if (shouldExcludeModule) {
                // Add excludes for both the ".pyi" file and the directory that contains it
                // (in case it's using a "__init__.pyi" file).
                const moduleDirPath = typeshedStdlibPath.combinePaths(...moduleName.split('.'));
                excludes.push(moduleDirPath);
                const moduleFilePath = moduleDirPath.replaceExtension('.pyi');
                excludes.push(moduleFilePath);
            }
        });
        return excludes;
    }
    readdirEntriesCached(uri) {
        const cachedValue = this._cachedEntriesForPath.get(uri.key);
        if (cachedValue) {
            return cachedValue;
        }
        let newCacheValue;
        try {
            newCacheValue = this.fileSystem.readdirEntriesSync(uri);
        }
        catch {
            newCacheValue = [];
        }
        // Populate cache for next time.
        this._cachedEntriesForPath.set(uri.key, newCacheValue);
        return newCacheValue;
    }
    // Resolves the import and returns the path if it exists, otherwise
    // returns undefined.
    resolveImportInternal(sourceFileUri, execEnv, moduleDescriptor) {
        const importName = this.formatImportName(moduleDescriptor);
        const importFailureInfo = [];
        const importResult = this._resolveImportStrict(importName, sourceFileUri, execEnv, moduleDescriptor, importFailureInfo);
        if (importResult.isImportFound || moduleDescriptor.leadingDots > 0) {
            return importResult;
        }
        // If the import is absolute and no other method works, try resolving the
        // absolute in the importing file's directory, then the parent directory,
        // and so on, until the import root is reached.
        const origin = sourceFileUri.getDirectory();
        const result = this.cachedParentImportResults.getImportResult(origin, importName, importResult);
        if (result) {
            // Already ran the parent directory resolution for this import name on this location.
            return this.filterImplicitImports(result, moduleDescriptor.importedSymbols);
        }
        // Check whether the given file is in the parent directory import resolution cache.
        const root = this.getParentImportResolutionRoot(sourceFileUri, execEnv.root);
        if (!this.cachedParentImportResults.checkValidPath(this.fileSystem, sourceFileUri, root)) {
            return importResult;
        }
        const importPath = { importPath: undefined };
        // Going up the given folder one by one until we can resolve the import.
        let current = origin;
        while (this._shouldWalkUp(current, root, execEnv) && current) {
            const result = this.resolveAbsoluteImport(sourceFileUri, current, execEnv, moduleDescriptor, importName, [], 
            /* allowPartial */ undefined, 
            /* allowNativeLib */ undefined, 
            /* useStubPackage */ false, 
            /* allowPyi */ true);
            this.cachedParentImportResults.checked(current, importName, importPath);
            if (result.isImportFound) {
                // This will make cache to point to actual path that contains the module we found
                importPath.importPath = current;
                if (!result.isNamespacePackage && !result.isStubFile) {
                    // TODO: figure out how namespace packages work. we identify this fake relative import functionality as such so it can be banned
                    // with a diagnostic rule, but it seems like stub imports and some mysterious namespace package functionality rely on this behavior.
                    // so for now i'm just not reporting it for namespace packages & stub files
                    result.isImplicitlyRelative = true;
                }
                this.cachedParentImportResults.add({
                    importResult: result,
                    path: current,
                    importName,
                });
                return this.filterImplicitImports(result, moduleDescriptor.importedSymbols);
            }
            current = this._tryWalkUp(current);
        }
        if (current) {
            this.cachedParentImportResults.checked(current, importName, importPath);
        }
        return importResult;
    }
    fileExistsCached(uri) {
        const directory = uri.getDirectory();
        if (directory.equals(uri)) {
            // Started at root, so this can't be a file.
            return false;
        }
        const fileName = uri.fileName;
        const entries = this.readdirEntriesCached(directory);
        const entry = entries.find((entry) => entry.name === fileName);
        if (entry === null || entry === void 0 ? void 0 : entry.isFile()) {
            return true;
        }
        if (entry === null || entry === void 0 ? void 0 : entry.isSymbolicLink()) {
            const realPath = (0, uriUtils_1.tryRealpath)(this.fileSystem, uri);
            if (realPath && this.fileSystem.existsSync(realPath) && (0, uriUtils_1.isFile)(this.fileSystem, realPath)) {
                return true;
            }
        }
        return false;
    }
    dirExistsCached(uri) {
        var _a, _b;
        const parent = uri.getDirectory();
        if (parent.equals(uri)) {
            // Started at root. No entries to read, so have to check ourselves.
            let cachedExistence = this._cachedDirExistenceForRoot.get(uri.key);
            // Check if the value was in the cache or not. Undefined means it wasn't.
            if (cachedExistence === undefined) {
                cachedExistence = (_b = (_a = (0, uriUtils_1.tryStat)(this.fileSystem, uri)) === null || _a === void 0 ? void 0 : _a.isDirectory()) !== null && _b !== void 0 ? _b : false;
                this._cachedDirExistenceForRoot.set(uri.key, cachedExistence);
            }
            return cachedExistence;
        }
        // Otherwise not a root, so read the entries we have cached to see if
        // the directory exists or not.
        const directoryName = uri.fileName;
        const entries = this.readdirEntriesCached(parent);
        const entry = entries.find((entry) => entry.name === directoryName);
        if (entry === null || entry === void 0 ? void 0 : entry.isDirectory()) {
            return true;
        }
        if (entry === null || entry === void 0 ? void 0 : entry.isSymbolicLink()) {
            const realPath = (0, uriUtils_1.tryRealpath)(this.fileSystem, uri);
            if (realPath && this.fileSystem.existsSync(realPath) && (0, uriUtils_1.isDirectory)(this.fileSystem, realPath)) {
                return true;
            }
        }
        return false;
    }
    addResultsToCache(sourceFileUri, execEnv, importName, importResult, moduleDescriptor, fromUserFile) {
        var _a;
        // If the import is relative, include the source file path in the key.
        const relativeSourceFileUri = moduleDescriptor && moduleDescriptor.leadingDots > 0 ? sourceFileUri : undefined;
        (0, collectionUtils_1.getOrAdd)(this._cachedImportResults, (_a = execEnv.root) === null || _a === void 0 ? void 0 : _a.key, () => new Map()).set(this._getImportCacheKey(relativeSourceFileUri, importName, fromUserFile), importResult);
        return this.filterImplicitImports(importResult, moduleDescriptor === null || moduleDescriptor === void 0 ? void 0 : moduleDescriptor.importedSymbols);
    }
    // Follows import resolution algorithm defined in PEP-420:
    // https://www.python.org/dev/peps/pep-0420/
    resolveAbsoluteImport(sourceFileUri, rootPath, execEnv, moduleDescriptor, importName, importFailureInfo, allowPartial = false, allowNativeLib = false, useStubPackage = false, allowPyi = true, lookForPyTyped = false) {
        if (allowPyi && useStubPackage) {
            // Look for packaged stubs first. PEP 561 indicates that package authors can ship
            // their stubs separately from their package implementation by appending the string
            // '-stubs' to its top - level directory name. We'll look there first.
            const importResult = this._resolveAbsoluteImport(rootPath, execEnv, moduleDescriptor, importName, importFailureInfo, allowPartial, 
            /* allowNativeLib */ false, 
            /* useStubPackage */ true, 
            /* allowPyi */ true, 
            /* lookForPyTyped */ true);
            // We found fully typed stub packages.
            if (importResult.packageDirectory) {
                // If this is a namespace package that wasn't resolved, assume that
                // it's a partial stub package and continue looking for a real package.
                if (!importResult.isNamespacePackage || importResult.isImportFound) {
                    return importResult;
                }
            }
        }
        return this._resolveAbsoluteImport(rootPath, execEnv, moduleDescriptor, importName, importFailureInfo, allowPartial, allowNativeLib, 
        /* useStubPackage */ false, allowPyi, lookForPyTyped);
    }
    // Intended to be overridden by subclasses to provide additional stub
    // path capabilities. Return undefined if no extra stub path were found.
    getTypeshedPathEx(execEnv, importFailureInfo) {
        return undefined;
    }
    // Intended to be overridden by subclasses to provide additional stub
    // resolving capabilities. Return undefined if no stubs were found for
    // this import.
    resolveImportEx(sourceFileUri, execEnv, moduleDescriptor, importName, importFailureInfo = [], allowPyi = true) {
        return undefined;
    }
    // Intended to be overridden by subclasses to provide additional stub
    // resolving capabilities for native (compiled) modules. Returns undefined
    // if no stubs were found for this import.
    resolveNativeImportEx(libraryFileUri, importName, importFailureInfo = []) {
        return undefined;
    }
    getNativeModuleName(uri) {
        const fileExtension = uri.lastExtension.toLowerCase();
        if (this._isNativeModuleFileExtension(fileExtension)) {
            return (0, pathUtils_1.stripFileExtension)(uri.fileName, /* multiDotExtension */ true);
        }
        return undefined;
    }
    getModuleNameFromPath(containerPath, fileUri, stripTopContainerDir = false) {
        const moduleNameInfo = this.getModuleNameInfoFromPath(containerPath, fileUri, stripTopContainerDir);
        if (!moduleNameInfo || moduleNameInfo.containsInvalidCharacters) {
            return undefined;
        }
        return moduleNameInfo.moduleName;
    }
    getModuleNameInfoFromPath(containerPath, fileUri, stripTopContainerDir = false) {
        let fileUriWithoutExtension = fileUri.stripExtension();
        // If module is native, strip platform part, such as 'cp36-win_amd64' in 'mtrand.cp36-win_amd64'.
        if (this._isNativeModuleFileExtension(fileUri.lastExtension)) {
            fileUriWithoutExtension = fileUriWithoutExtension.stripExtension();
        }
        if (!fileUriWithoutExtension.startsWith(containerPath)) {
            return undefined;
        }
        // Strip off the '/__init__' if it's present.
        if (fileUriWithoutExtension.pathEndsWith('__init__')) {
            fileUriWithoutExtension = fileUriWithoutExtension.getDirectory();
        }
        const parts = Array.from(containerPath.getRelativePathComponents(fileUriWithoutExtension));
        if (stripTopContainerDir) {
            if (parts.length === 0) {
                return undefined;
            }
            parts.shift();
        }
        if (parts.length === 0) {
            return undefined;
        }
        // Handle the case where the symbol was resolved to a stubs package
        // rather than the real package. We'll strip off the "-stubs" suffix
        // in this case.
        if (parts[0].endsWith(pathConsts_1.stubsSuffix)) {
            parts[0] = parts[0].substr(0, parts[0].length - pathConsts_1.stubsSuffix.length);
        }
        // Check whether parts contains invalid characters.
        const containsInvalidCharacters = parts.some((p) => !this._isIdentifier(p));
        return {
            moduleName: parts.join('.'),
            containsInvalidCharacters,
        };
    }
    // Potentially modifies the ImportResult by removing some or all of the
    // implicit import entries. Only the imported symbols should be included.
    filterImplicitImports(importResult, importedSymbols) {
        if (importedSymbols === undefined) {
            const newImportResult = Object.assign({}, importResult);
            newImportResult.filteredImplicitImports = new Map();
            return newImportResult;
        }
        if (importedSymbols.size === 0) {
            return importResult;
        }
        if (importResult.implicitImports.size === 0) {
            return importResult;
        }
        const filteredImplicitImports = new Map();
        importResult.implicitImports.forEach((implicitImport) => {
            if (importedSymbols.has(implicitImport.name)) {
                filteredImplicitImports.set(implicitImport.name, implicitImport);
            }
        });
        if (filteredImplicitImports.size === importResult.implicitImports.size) {
            return importResult;
        }
        const newImportResult = Object.assign({}, importResult);
        newImportResult.filteredImplicitImports = filteredImplicitImports;
        return newImportResult;
    }
    formatImportName(moduleDescriptor) {
        return '.'.repeat(moduleDescriptor.leadingDots) + moduleDescriptor.nameParts.join('.');
    }
    getParentImportResolutionRoot(sourceFileUri, executionRoot) {
        if (executionRoot && !executionRoot.isEmpty()) {
            return this.fileSystem.realCasePath(executionRoot);
        }
        return sourceFileUri.getDirectory();
    }
    _resolveImportStrict(importName, sourceFileUri, execEnv, moduleDescriptor, importFailureInfo) {
        const fromUserFile = (0, configOptions_1.matchFileSpecs)(this._configOptions, sourceFileUri);
        const notFoundResult = {
            importName,
            isRelative: false,
            isImplicitlyRelative: false,
            isImportFound: false,
            isPartlyResolved: false,
            isNamespacePackage: false,
            isInitFilePresent: false,
            isStubPackage: false,
            importFailureInfo,
            resolvedUris: [],
            importType: 2 /* ImportType.Local */,
            isStubFile: false,
            isNativeLib: false,
            implicitImports: new Map(),
            filteredImplicitImports: new Map(),
            nonStubImportResult: undefined,
        };
        this.ensurePartialStubPackages(execEnv);
        // Is it a relative import?
        if (moduleDescriptor.leadingDots > 0) {
            const cachedResults = this._lookUpResultsInCache(sourceFileUri, execEnv, importName, moduleDescriptor, fromUserFile);
            if (cachedResults) {
                return cachedResults;
            }
            const relativeImport = this._resolveRelativeImport(sourceFileUri, execEnv, moduleDescriptor, importName, importFailureInfo);
            if (relativeImport) {
                relativeImport.isRelative = true;
                return this.addResultsToCache(sourceFileUri, execEnv, importName, relativeImport, moduleDescriptor, fromUserFile);
            }
        }
        else {
            const cachedResults = this._lookUpResultsInCache(sourceFileUri, execEnv, importName, moduleDescriptor, fromUserFile);
            if (cachedResults) {
                // In most cases, we can simply return a cached entry. However, there are cases
                // where the cached entry refers to a previously-resolved namespace package
                // that does not resolve the symbols specified in the module descriptor.
                // In this case, we will ignore the cached value and run the full import
                // resolution again to try to find a package that resolves the import.
                const isUnresolvedNamespace = cachedResults.isImportFound &&
                    cachedResults.isNamespacePackage &&
                    !this._isNamespacePackageResolved(moduleDescriptor, cachedResults.implicitImports);
                if (!isUnresolvedNamespace) {
                    return cachedResults;
                }
            }
            const bestImport = this._resolveBestAbsoluteImport(sourceFileUri, execEnv, moduleDescriptor, 
            /* allowPyi */ true);
            if (bestImport) {
                if (bestImport.isStubFile) {
                    bestImport.nonStubImportResult =
                        this._resolveBestAbsoluteImport(sourceFileUri, execEnv, moduleDescriptor, 
                        /* allowPyi */ false) || notFoundResult;
                }
                return this.addResultsToCache(sourceFileUri, execEnv, importName, bestImport, moduleDescriptor, fromUserFile);
            }
        }
        return this.addResultsToCache(sourceFileUri, execEnv, importName, notFoundResult, 
        /* moduleDescriptor */ undefined, fromUserFile);
    }
    _getCompletionSuggestionsStrict(sourceFileUri, execEnv, moduleDescriptor) {
        const importFailureInfo = [];
        const suggestions = new Map();
        // Is it a relative import?
        if (moduleDescriptor.leadingDots > 0) {
            this._getCompletionSuggestionsRelative(sourceFileUri, execEnv, moduleDescriptor, suggestions);
        }
        else {
            // First check for a typeshed file.
            if (moduleDescriptor.nameParts.length > 0) {
                this._getCompletionSuggestionsTypeshedPath(sourceFileUri, execEnv, moduleDescriptor, true, suggestions);
            }
            // Look for it in the root directory of the execution environment.
            if (execEnv.root) {
                this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, execEnv.root, moduleDescriptor, suggestions);
            }
            for (const extraPath of execEnv.extraPaths) {
                this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, extraPath, moduleDescriptor, suggestions);
            }
            // Check for a typings file.
            if (this._configOptions.stubPath) {
                this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, this._configOptions.stubPath, moduleDescriptor, suggestions);
            }
            // Check for a typeshed file.
            this._getCompletionSuggestionsTypeshedPath(sourceFileUri, execEnv, moduleDescriptor, false, suggestions);
            // Look for the import in the list of third-party packages.
            const pythonSearchPaths = this.getPythonSearchPaths(importFailureInfo);
            for (const searchPath of pythonSearchPaths) {
                this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, searchPath, moduleDescriptor, suggestions);
            }
        }
        return suggestions;
    }
    _getModuleNameForImport(fileUri, execEnv, allowInvalidModuleName, detectPyTyped) {
        let moduleName;
        let importType = 0 /* ImportType.BuiltIn */;
        let isLocalTypingsFile = false;
        let isThirdPartyPyTypedPresent = false;
        let isTypeshedFile = false;
        const importFailureInfo = [];
        // If we cannot find a fully-qualified module name with legal characters,
        // look for one with invalid characters (e.g. "-"). This is important to
        // differentiate between different modules in a project in case they
        // declare types with the same (local) name.
        let moduleNameWithInvalidCharacters;
        // Is this a stdlib typeshed path?
        const stdLibTypeshedPath = this._getStdlibTypeshedPath(this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, importFailureInfo);
        if (stdLibTypeshedPath) {
            moduleName = this.getModuleNameFromPath(stdLibTypeshedPath, fileUri);
            if (moduleName) {
                const moduleDescriptor = {
                    leadingDots: 0,
                    nameParts: moduleName.split('.'),
                    importedSymbols: undefined,
                };
                if (this._isStdlibTypeshedStubValidForVersion(moduleDescriptor, this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, [])) {
                    return {
                        moduleName,
                        importType,
                        isTypeshedFile: true,
                        isLocalTypingsFile,
                        isThirdPartyPyTypedPresent,
                    };
                }
            }
        }
        // Look for it in the root directory of the execution environment.
        if (execEnv.root) {
            const candidateModuleNameInfo = this.getModuleNameInfoFromPath(execEnv.root, fileUri);
            if (candidateModuleNameInfo) {
                if (candidateModuleNameInfo.containsInvalidCharacters) {
                    moduleNameWithInvalidCharacters = candidateModuleNameInfo.moduleName;
                }
                else {
                    moduleName = candidateModuleNameInfo.moduleName;
                }
            }
            importType = 2 /* ImportType.Local */;
        }
        for (const extraPath of execEnv.extraPaths) {
            const candidateModuleNameInfo = this.getModuleNameInfoFromPath(extraPath, fileUri);
            if (candidateModuleNameInfo) {
                if (candidateModuleNameInfo.containsInvalidCharacters) {
                    moduleNameWithInvalidCharacters = candidateModuleNameInfo.moduleName;
                }
                else {
                    // Does this candidate look better than the previous best module name?
                    // We'll always try to use the shortest version.
                    const candidateModuleName = candidateModuleNameInfo.moduleName;
                    if (!moduleName || (candidateModuleName && candidateModuleName.length < moduleName.length)) {
                        moduleName = candidateModuleName;
                        importType = 2 /* ImportType.Local */;
                    }
                }
            }
        }
        // Check for a typings file.
        if (this._configOptions.stubPath) {
            const candidateModuleNameInfo = this.getModuleNameInfoFromPath(this._configOptions.stubPath, fileUri);
            if (candidateModuleNameInfo) {
                if (candidateModuleNameInfo.containsInvalidCharacters) {
                    moduleNameWithInvalidCharacters = candidateModuleNameInfo.moduleName;
                }
                else {
                    // Does this candidate look better than the previous best module name?
                    // We'll always try to use the shortest version.
                    const candidateModuleName = candidateModuleNameInfo.moduleName;
                    if (!moduleName || (candidateModuleName && candidateModuleName.length < moduleName.length)) {
                        moduleName = candidateModuleName;
                        // Treat the typings path as a local import so errors are reported for it.
                        importType = 2 /* ImportType.Local */;
                        isLocalTypingsFile = true;
                    }
                }
            }
        }
        // Check for a typeshed file.
        const thirdPartyTypeshedPath = this._getThirdPartyTypeshedPath(this._configOptions.typeshedPath, importFailureInfo);
        if (thirdPartyTypeshedPath) {
            const candidateModuleName = this.getModuleNameFromPath(thirdPartyTypeshedPath, fileUri, 
            /* stripTopContainerDir */ true);
            // Does this candidate look better than the previous best module name?
            // We'll always try to use the shortest version.
            if (!moduleName || (candidateModuleName && candidateModuleName.length < moduleName.length)) {
                moduleName = candidateModuleName;
                importType = 1 /* ImportType.ThirdParty */;
                isTypeshedFile = true;
            }
        }
        const thirdPartyTypeshedPathEx = this.getTypeshedPathEx(execEnv, importFailureInfo);
        if (thirdPartyTypeshedPathEx) {
            const candidateModuleName = this.getModuleNameFromPath(thirdPartyTypeshedPathEx, fileUri);
            // Does this candidate look better than the previous best module name?
            // We'll always try to use the shortest version.
            if (!moduleName || (candidateModuleName && candidateModuleName.length < moduleName.length)) {
                moduleName = candidateModuleName;
                importType = 1 /* ImportType.ThirdParty */;
                isTypeshedFile = true;
            }
        }
        // Look for the import in the list of third-party packages.
        const pythonSearchPaths = this.getPythonSearchPaths(importFailureInfo);
        for (const searchPath of pythonSearchPaths) {
            const candidateModuleNameInfo = this.getModuleNameInfoFromPath(searchPath, fileUri);
            if (candidateModuleNameInfo) {
                if (candidateModuleNameInfo.containsInvalidCharacters) {
                    moduleNameWithInvalidCharacters = candidateModuleNameInfo.moduleName;
                }
                else {
                    // Does this candidate look better than the previous best module name?
                    // We'll always try to use the shortest version.
                    const candidateModuleName = candidateModuleNameInfo.moduleName;
                    if (!moduleName || (candidateModuleName && candidateModuleName.length < moduleName.length)) {
                        moduleName = candidateModuleName;
                        importType = 1 /* ImportType.ThirdParty */;
                        isTypeshedFile = false;
                    }
                }
            }
        }
        if (detectPyTyped && importType === 1 /* ImportType.ThirdParty */) {
            const root = this.getParentImportResolutionRoot(fileUri, execEnv.root);
            // Go up directories one by one looking for a py.typed file.
            let current = fileUri.getDirectory();
            while (this._shouldWalkUp(current, root, execEnv)) {
                const pyTypedInfo = this._getPyTypedInfo(current);
                if (pyTypedInfo && !pyTypedInfo.isPartiallyTyped) {
                    isThirdPartyPyTypedPresent = true;
                }
                break;
                current = this._tryWalkUp(current);
            }
        }
        if (moduleName) {
            return { moduleName, importType, isTypeshedFile, isLocalTypingsFile, isThirdPartyPyTypedPresent };
        }
        if (allowInvalidModuleName && moduleNameWithInvalidCharacters) {
            return {
                moduleName: moduleNameWithInvalidCharacters,
                isTypeshedFile,
                importType,
                isLocalTypingsFile,
                isThirdPartyPyTypedPresent,
            };
        }
        // We didn't find any module name.
        return {
            moduleName: '',
            isTypeshedFile,
            importType: 2 /* ImportType.Local */,
            isLocalTypingsFile,
            isThirdPartyPyTypedPresent,
        };
    }
    _invalidateFileSystemCache() {
        this._cachedEntriesForPath.clear();
        this._cachedFilesForPath.clear();
        this._cachedDirExistenceForRoot.clear();
    }
    _resolveAbsoluteImport(rootPath, execEnv, moduleDescriptor, importName, importFailureInfo, allowPartial, allowNativeLib, useStubPackage, allowPyi, lookForPyTyped) {
        if (useStubPackage) {
            importFailureInfo.push(`Attempting to resolve stub package using root path '${rootPath}'`);
        }
        else {
            importFailureInfo.push(`Attempting to resolve using root path '${rootPath}'`);
        }
        // Starting at the specified path, walk the file system to find the
        // specified module.
        const resolvedPaths = [];
        let dirPath = rootPath;
        let isNamespacePackage = false;
        let isInitFilePresent = false;
        let isStubPackage = false;
        let isStubFile = false;
        let isNativeLib = false;
        let implicitImports = new Map();
        let packageDirectory;
        let pyTypedInfo;
        // Handle the "from . import XXX" case.
        if (moduleDescriptor.nameParts.length === 0) {
            const pyFilePath = dirPath.initPyUri;
            const pyiFilePath = dirPath.initPyiUri;
            if (allowPyi && this.fileExistsCached(pyiFilePath)) {
                importFailureInfo.push(`Resolved import with file '${pyiFilePath}'`);
                resolvedPaths.push(pyiFilePath);
                isStubFile = true;
            }
            else if (this.fileExistsCached(pyFilePath)) {
                importFailureInfo.push(`Resolved import with file '${pyFilePath}'`);
                resolvedPaths.push(pyFilePath);
            }
            else {
                importFailureInfo.push(`Partially resolved import with directory '${dirPath}'`);
                resolvedPaths.push(uri_1.Uri.empty());
                isNamespacePackage = true;
            }
            implicitImports = this._findImplicitImports(importName, dirPath, [pyFilePath, pyiFilePath]);
        }
        else {
            for (let i = 0; i < moduleDescriptor.nameParts.length; i++) {
                const isFirstPart = i === 0;
                const isLastPart = i === moduleDescriptor.nameParts.length - 1;
                dirPath = dirPath.combinePaths(moduleDescriptor.nameParts[i]);
                if (useStubPackage && isFirstPart) {
                    dirPath = dirPath.addPath(pathConsts_1.stubsSuffix);
                    isStubPackage = true;
                }
                const foundDirectory = this.dirExistsCached(dirPath);
                if (foundDirectory) {
                    if (isFirstPart) {
                        packageDirectory = dirPath;
                    }
                    // See if we can find an __init__.py[i] in this directory.
                    const pyFilePath = dirPath.initPyUri;
                    const pyiFilePath = dirPath.initPyiUri;
                    isInitFilePresent = false;
                    if (allowPyi && this.fileExistsCached(pyiFilePath)) {
                        importFailureInfo.push(`Resolved import with file '${pyiFilePath}'`);
                        resolvedPaths.push(pyiFilePath);
                        if (isLastPart) {
                            isStubFile = true;
                        }
                        isInitFilePresent = true;
                    }
                    else if (this.fileExistsCached(pyFilePath)) {
                        importFailureInfo.push(`Resolved import with file '${pyFilePath}'`);
                        resolvedPaths.push(pyFilePath);
                        isInitFilePresent = true;
                    }
                    if (!pyTypedInfo && lookForPyTyped) {
                        pyTypedInfo = this._getPyTypedInfo(dirPath);
                    }
                    if (!isLastPart) {
                        // We are not at the last part, and we found a directory,
                        // so continue to look for the next part.
                        if (!isInitFilePresent) {
                            resolvedPaths.push(uri_1.Uri.empty());
                            isNamespacePackage = true;
                            pyTypedInfo = undefined;
                        }
                        continue;
                    }
                    if (isInitFilePresent) {
                        implicitImports = this._findImplicitImports(moduleDescriptor.nameParts.join('.'), dirPath, [
                            pyFilePath,
                            pyiFilePath,
                        ]);
                        break;
                    }
                }
                // We weren't able to find a directory or we found a directory with
                // no __init__.py[i] file. See if we can find a ".py" or ".pyi" file
                // with this name.
                const pyFilePath = dirPath.packageUri;
                const pyiFilePath = dirPath.packageStubUri;
                const fileDirectory = dirPath.getDirectory();
                if (allowPyi && this.fileExistsCached(pyiFilePath)) {
                    importFailureInfo.push(`Resolved import with file '${pyiFilePath}'`);
                    resolvedPaths.push(pyiFilePath);
                    if (isLastPart) {
                        isStubFile = true;
                    }
                }
                else if (this.fileExistsCached(pyFilePath)) {
                    importFailureInfo.push(`Resolved import with file '${pyFilePath}'`);
                    resolvedPaths.push(pyFilePath);
                }
                else {
                    if (allowNativeLib && this.dirExistsCached(fileDirectory)) {
                        const filesInDir = this._getFilesInDirectory(fileDirectory);
                        const dirName = dirPath.fileName;
                        const nativeLibPath = filesInDir.find((f) => this._isNativeModuleFileName(dirName, f));
                        if (nativeLibPath) {
                            // Try resolving native library to a custom stub.
                            isNativeLib = this._resolveNativeModuleStub(nativeLibPath, execEnv, importName, moduleDescriptor, importFailureInfo, resolvedPaths);
                        }
                    }
                    if (!isNativeLib && foundDirectory) {
                        importFailureInfo.push(`Partially resolved import with directory '${dirPath}'`);
                        resolvedPaths.push(uri_1.Uri.empty());
                        if (isLastPart) {
                            implicitImports = this._findImplicitImports(importName, dirPath, [pyFilePath, pyiFilePath]);
                            isNamespacePackage = true;
                        }
                    }
                    else if (isNativeLib) {
                        importFailureInfo.push(`Did not find file '${pyiFilePath}' or '${pyFilePath}'`);
                    }
                }
                if (!pyTypedInfo && lookForPyTyped) {
                    pyTypedInfo = this._getPyTypedInfo(fileDirectory);
                }
                break;
            }
        }
        let importFound;
        const isPartlyResolved = resolvedPaths.length > 0 && resolvedPaths.length < moduleDescriptor.nameParts.length;
        if (allowPartial) {
            importFound = resolvedPaths.length > 0;
        }
        else {
            importFound = resolvedPaths.length >= moduleDescriptor.nameParts.length;
        }
        return {
            importName,
            isRelative: false,
            isImplicitlyRelative: false,
            isNamespacePackage,
            isInitFilePresent,
            isStubPackage,
            isImportFound: importFound,
            isPartlyResolved,
            importFailureInfo,
            importType: 2 /* ImportType.Local */,
            resolvedUris: resolvedPaths,
            searchPath: rootPath,
            isStubFile,
            isNativeLib,
            implicitImports,
            pyTypedInfo,
            filteredImplicitImports: implicitImports,
            packageDirectory,
        };
    }
    _getImportCacheKey(sourceFileUri, importName, fromUserFile) {
        var _a;
        return `${(_a = sourceFileUri === null || sourceFileUri === void 0 ? void 0 : sourceFileUri.key) !== null && _a !== void 0 ? _a : ''}-${importName}-${fromUserFile}`;
    }
    _lookUpResultsInCache(sourceFileUri, execEnv, importName, moduleDescriptor, fromUserFile) {
        var _a, _b;
        const cacheForExecEnv = this._cachedImportResults.get((_b = (_a = execEnv.root) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : '');
        if (!cacheForExecEnv) {
            return undefined;
        }
        // If the import is relative, include the source file path in the key.
        const relativeSourceFileUri = moduleDescriptor.leadingDots > 0 ? sourceFileUri : undefined;
        const cachedEntry = cacheForExecEnv.get(this._getImportCacheKey(relativeSourceFileUri, importName, fromUserFile));
        if (!cachedEntry) {
            return undefined;
        }
        return this.filterImplicitImports(cachedEntry, moduleDescriptor.importedSymbols);
    }
    // Determines whether a namespace package resolves all of the symbols
    // requested in the module descriptor. Namespace packages have no "__init__.py"
    // file, so the only way that symbols can be resolved is if submodules
    // are present. If specific symbols were requested, make sure they
    // are all satisfied by submodules (as listed in the implicit imports).
    _isNamespacePackageResolved(moduleDescriptor, implicitImports) {
        if (moduleDescriptor.importedSymbols) {
            if (!Array.from(moduleDescriptor.importedSymbols.keys()).some((symbol) => implicitImports.has(symbol))) {
                return false;
            }
        }
        else if (implicitImports.size === 0) {
            return false;
        }
        return true;
    }
    _resolveBestAbsoluteImport(sourceFileUri, execEnv, moduleDescriptor, allowPyi) {
        const importName = this.formatImportName(moduleDescriptor);
        const importFailureInfo = [];
        // Check for a local stub file using stubPath.
        if (allowPyi && this._configOptions.stubPath) {
            importFailureInfo.push(`Looking in stubPath '${this._configOptions.stubPath}'`);
            const typingsImport = this.resolveAbsoluteImport(sourceFileUri, this._configOptions.stubPath, execEnv, moduleDescriptor, importName, importFailureInfo, 
            /* allowPartial */ undefined, 
            /* allowNativeLib */ false, 
            /* useStubPackage */ true, allowPyi, 
            /* lookForPyTyped */ false);
            if (typingsImport.isImportFound) {
                // We will treat typings files as "local" rather than "third party".
                typingsImport.importType = 2 /* ImportType.Local */;
                typingsImport.isLocalTypingsFile = true;
                // If it's a namespace package that didn't resolve to a file, make sure that
                // the imported symbols are present in the implicit imports. If not, we'll
                // skip the typings import and continue searching.
                if (typingsImport.isNamespacePackage &&
                    typingsImport.resolvedUris[typingsImport.resolvedUris.length - 1].isEmpty()) {
                    if (this._isNamespacePackageResolved(moduleDescriptor, typingsImport.implicitImports)) {
                        return typingsImport;
                    }
                }
                else {
                    return typingsImport;
                }
            }
        }
        let bestResultSoFar;
        let localImport;
        // Look for it in the root directory of the execution environment.
        if (execEnv.root) {
            importFailureInfo.push(`Looking in root directory of execution environment ` + `'${execEnv.root}'`);
            localImport = this.resolveAbsoluteImport(sourceFileUri, execEnv.root, execEnv, moduleDescriptor, importName, importFailureInfo, 
            /* allowPartial */ undefined, 
            /* allowNativeLib */ true, 
            /* useStubPackage */ true, allowPyi, 
            /* lookForPyTyped */ false);
            bestResultSoFar = localImport;
        }
        for (const extraPath of execEnv.extraPaths) {
            importFailureInfo.push(`Looking in extraPath '${extraPath}'`);
            localImport = this.resolveAbsoluteImport(sourceFileUri, extraPath, execEnv, moduleDescriptor, importName, importFailureInfo, 
            /* allowPartial */ undefined, 
            /* allowNativeLib */ true, 
            /* useStubPackage */ true, allowPyi, 
            /* lookForPyTyped */ false);
            bestResultSoFar = this._pickBestImport(bestResultSoFar, localImport, moduleDescriptor);
        }
        // Look for the import in the list of third-party packages.
        const pythonSearchPaths = this.getPythonSearchPaths(importFailureInfo);
        if (pythonSearchPaths.length > 0) {
            for (const searchPath of pythonSearchPaths) {
                importFailureInfo.push(`Looking in python search path '${searchPath}'`);
                const thirdPartyImport = this.resolveAbsoluteImport(sourceFileUri, searchPath, execEnv, moduleDescriptor, importName, importFailureInfo, 
                /* allowPartial */ allowPartialResolutionForThirdPartyPackages, 
                /* allowNativeLib */ true, 
                /* useStubPackage */ true, allowPyi, 
                /* lookForPyTyped */ true);
                if (thirdPartyImport) {
                    thirdPartyImport.importType = 1 /* ImportType.ThirdParty */;
                    bestResultSoFar = this._pickBestImport(bestResultSoFar, thirdPartyImport, moduleDescriptor);
                }
            }
        }
        else {
            importFailureInfo.push('No python interpreter search path');
        }
        // If a library is fully py.typed, then we have found the best match,
        // unless the execution environment is typeshed itself, in which case
        // we don't want to favor py.typed libraries. Use the typeshed lookup below.
        if (execEnv.root !== this._getTypeshedRoot(this._configOptions.typeshedPath, importFailureInfo)) {
            if ((bestResultSoFar === null || bestResultSoFar === void 0 ? void 0 : bestResultSoFar.pyTypedInfo) && !bestResultSoFar.isPartlyResolved) {
                return bestResultSoFar;
            }
        }
        // Call the extensibility hook for subclasses.
        const extraResults = this.resolveImportEx(sourceFileUri, execEnv, moduleDescriptor, importName, importFailureInfo, allowPyi);
        if (extraResults) {
            return extraResults;
        }
        if (allowPyi && moduleDescriptor.nameParts.length > 0) {
            // Check for a stdlib typeshed file.
            importFailureInfo.push(`Looking for typeshed stdlib path`);
            const typeshedStdlibImport = this._findTypeshedPath(execEnv, moduleDescriptor, importName, 
            /* isStdLib */ true, importFailureInfo);
            if (typeshedStdlibImport) {
                typeshedStdlibImport.isStdlibTypeshedFile = true;
                return typeshedStdlibImport;
            }
            // Check for a third-party typeshed file.
            importFailureInfo.push(`Looking for typeshed third-party path`);
            const typeshedImport = this._findTypeshedPath(execEnv, moduleDescriptor, importName, 
            /* isStdLib */ false, importFailureInfo);
            if (typeshedImport) {
                typeshedImport.isThirdPartyTypeshedFile = true;
                bestResultSoFar = this._pickBestImport(bestResultSoFar, typeshedImport, moduleDescriptor);
            }
        }
        // We weren't able to find an exact match, so return the best
        // partial match.
        return bestResultSoFar;
    }
    _pickBestImport(bestImportSoFar, newImport, moduleDescriptor) {
        if (!bestImportSoFar) {
            return newImport;
        }
        if (!newImport) {
            return bestImportSoFar;
        }
        if (newImport.isImportFound) {
            // Prefer traditional packages over namespace packages.
            const soFarIndex = bestImportSoFar.resolvedUris.findIndex((path) => !path.isEmpty());
            const newIndex = newImport.resolvedUris.findIndex((path) => !path.isEmpty());
            if (soFarIndex !== newIndex) {
                if (soFarIndex < 0) {
                    return newImport;
                }
                else if (newIndex < 0) {
                    return bestImportSoFar;
                }
                return soFarIndex < newIndex ? bestImportSoFar : newImport;
            }
            // Prefer found over not found.
            if (!bestImportSoFar.isImportFound) {
                return newImport;
            }
            // If both are namespace imports, select the one that resolves the symbols.
            if (bestImportSoFar.isNamespacePackage && newImport.isNamespacePackage) {
                if (moduleDescriptor.importedSymbols) {
                    if (!this._isNamespacePackageResolved(moduleDescriptor, bestImportSoFar.implicitImports)) {
                        if (this._isNamespacePackageResolved(moduleDescriptor, newImport.implicitImports)) {
                            return newImport;
                        }
                        // Prefer the namespace package that has an __init__.py(i) file present
                        // in the final directory over one that does not.
                        if (bestImportSoFar.isInitFilePresent && !newImport.isInitFilePresent) {
                            return bestImportSoFar;
                        }
                        else if (!bestImportSoFar.isInitFilePresent && newImport.isInitFilePresent) {
                            return newImport;
                        }
                    }
                }
            }
            // Prefer local over third-party. We check local first, so we should never
            // see the reverse.
            if (bestImportSoFar.importType === 2 /* ImportType.Local */ && newImport.importType === 1 /* ImportType.ThirdParty */) {
                return bestImportSoFar;
            }
            // Prefer py.typed over non-py.typed.
            if (bestImportSoFar.pyTypedInfo && !newImport.pyTypedInfo) {
                return bestImportSoFar;
            }
            else if (!bestImportSoFar.pyTypedInfo && newImport.pyTypedInfo) {
                if (bestImportSoFar.importType === newImport.importType) {
                    return newImport;
                }
            }
            // Prefer pyi over py.
            if (bestImportSoFar.isStubFile && !newImport.isStubFile) {
                return bestImportSoFar;
            }
            else if (!bestImportSoFar.isStubFile && newImport.isStubFile) {
                return newImport;
            }
            // All else equal, prefer shorter resolution paths.
            if (bestImportSoFar.resolvedUris.length > newImport.resolvedUris.length) {
                return newImport;
            }
        }
        else if (newImport.isPartlyResolved) {
            // If the new import is a traditional package but only partly resolves
            // the import but the best import so far is a namespace package, we need
            // to consider whether the best import so far also resolves the first part
            // of the import with a traditional package. Using the example "import a.b.c.d"
            // and the symbol ~ to represent a namespace package, consider the following
            // cases:
            //  bestSoFar: a/~b/~c/~d   new: a      Result: bestSoFar wins
            //  bestSoFar: ~a/~b/~c/~d  new: a      Result: new wins
            //  bestSoFar: a/~b/~c/~d   new: a/b    Result: new wins
            const soFarIndex = bestImportSoFar.resolvedUris.findIndex((path) => !path.isEmpty());
            const newIndex = newImport.resolvedUris.findIndex((path) => !path.isEmpty());
            if (soFarIndex !== newIndex) {
                if (soFarIndex < 0) {
                    return newImport;
                }
                else if (newIndex < 0) {
                    return bestImportSoFar;
                }
                return soFarIndex < newIndex ? bestImportSoFar : newImport;
            }
        }
        return bestImportSoFar;
    }
    _isIdentifier(value) {
        for (let i = 0; i < value.length; i++) {
            if (i === 0 ? !(0, characters_1.isIdentifierStartChar)(value.charCodeAt(i)) : !(0, characters_1.isIdentifierChar)(value.charCodeAt(i))) {
                return false;
            }
        }
        return true;
    }
    _findTypeshedPath(execEnv, moduleDescriptor, importName, isStdLib, importFailureInfo) {
        importFailureInfo.push(`Looking for typeshed ${isStdLib ? PythonPathUtils.stdLibFolderName : PythonPathUtils.thirdPartyFolderName} path`);
        let typeshedPaths;
        if (isStdLib) {
            const path = this._getStdlibTypeshedPath(this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, importFailureInfo, moduleDescriptor);
            if (path) {
                typeshedPaths = [path];
            }
        }
        else {
            typeshedPaths = this._getThirdPartyTypeshedPackagePaths(moduleDescriptor, importFailureInfo);
        }
        if (typeshedPaths) {
            for (const typeshedPath of typeshedPaths) {
                if (this.dirExistsCached(typeshedPath)) {
                    const importInfo = this.resolveAbsoluteImport(undefined, typeshedPath, execEnv, moduleDescriptor, importName, importFailureInfo);
                    if (importInfo.isImportFound) {
                        let importType = isStdLib ? 0 /* ImportType.BuiltIn */ : 1 /* ImportType.ThirdParty */;
                        // Handle 'typing_extensions' as a special case because it's
                        // part of stdlib typeshed stubs, but it's not part of stdlib.
                        if (importName === 'typing_extensions') {
                            importType = 1 /* ImportType.ThirdParty */;
                        }
                        importInfo.importType = importType;
                        return importInfo;
                    }
                }
            }
        }
        importFailureInfo.push(`Typeshed path not found`);
        return undefined;
    }
    // Finds all of the stdlib modules and returns a Set containing all of their names.
    _buildStdlibCache(stdlibRoot) {
        const cache = new Set();
        if (stdlibRoot) {
            const readDir = (root, prefix) => {
                this.readdirEntriesCached(root).forEach((entry) => {
                    if (entry.isDirectory()) {
                        const dirRoot = root.combinePaths(entry.name);
                        readDir(dirRoot, prefix ? `${prefix}.${entry.name}` : entry.name);
                    }
                    else if (entry.name.includes('.py')) {
                        const stripped = (0, pathUtils_1.stripFileExtension)(entry.name);
                        // Skip anything starting with an underscore.
                        if (!stripped.startsWith('_')) {
                            cache.add(prefix ? `${prefix}.${stripped}` : stripped);
                        }
                    }
                });
            };
            readDir(stdlibRoot, undefined);
        }
        return cache;
    }
    // Populates a cache of third-party packages found within the typeshed
    // directory. They are organized such that top-level directories contain
    // the pypi-registered name of the package and an inner directory contains
    // the name of the package as it is referenced by import statements. These
    // don't always match.
    _buildTypeshedThirdPartyPackageMap(thirdPartyDir) {
        this._cachedTypeshedThirdPartyPackagePaths = new Map();
        if (thirdPartyDir) {
            this.readdirEntriesCached(thirdPartyDir).forEach((outerEntry) => {
                if (outerEntry.isDirectory()) {
                    const innerDirPath = thirdPartyDir.combinePaths(outerEntry.name);
                    this.readdirEntriesCached(innerDirPath).forEach((innerEntry) => {
                        if (innerEntry.name === '@python2') {
                            return;
                        }
                        if (innerEntry.isDirectory()) {
                            const pathList = this._cachedTypeshedThirdPartyPackagePaths.get(innerEntry.name);
                            if (pathList) {
                                pathList.push(innerDirPath);
                            }
                            else {
                                this._cachedTypeshedThirdPartyPackagePaths.set(innerEntry.name, [innerDirPath]);
                            }
                        }
                        else if (innerEntry.isFile()) {
                            if (innerEntry.name.endsWith('.pyi')) {
                                const strippedFileName = (0, pathUtils_1.stripFileExtension)(innerEntry.name);
                                const pathList = this._cachedTypeshedThirdPartyPackagePaths.get(strippedFileName);
                                if (pathList) {
                                    pathList.push(innerDirPath);
                                }
                                else {
                                    this._cachedTypeshedThirdPartyPackagePaths.set(strippedFileName, [innerDirPath]);
                                }
                            }
                        }
                    });
                }
            });
        }
        const flattenPaths = Array.from(this._cachedTypeshedThirdPartyPackagePaths.values()).flatMap((v) => v);
        this._cachedTypeshedThirdPartyPackageRoots = Array.from(new Set(flattenPaths)).sort();
    }
    _getCompletionSuggestionsTypeshedPath(sourceFileUri, execEnv, moduleDescriptor, isStdLib, suggestions) {
        const importFailureInfo = [];
        let typeshedPaths;
        if (isStdLib) {
            const path = this._getStdlibTypeshedPath(this._configOptions.typeshedPath, execEnv.pythonVersion, execEnv.pythonPlatform, importFailureInfo, moduleDescriptor);
            if (path) {
                typeshedPaths = [path];
            }
        }
        else {
            typeshedPaths = this._getThirdPartyTypeshedPackagePaths(moduleDescriptor, importFailureInfo, 
            /* includeMatchOnly */ false);
            const typeshedPathEx = this.getTypeshedPathEx(execEnv, importFailureInfo);
            if (typeshedPathEx) {
                typeshedPaths = typeshedPaths !== null && typeshedPaths !== void 0 ? typeshedPaths : [];
                typeshedPaths.push(typeshedPathEx);
            }
        }
        if (!typeshedPaths) {
            return;
        }
        typeshedPaths.forEach((typeshedPath) => {
            if (this.dirExistsCached(typeshedPath)) {
                this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, typeshedPath, moduleDescriptor, suggestions);
            }
        });
    }
    // Returns the directory for a module within the stdlib typeshed directory.
    // If moduleDescriptor is provided, it is filtered based on the VERSIONS
    // file in the typeshed stubs.
    _getStdlibTypeshedPath(customTypeshedPath, pythonVersion, pythonPlatform, importFailureInfo, moduleDescriptor) {
        const subdirectory = this._getTypeshedSubdirectory(/* isStdLib */ true, customTypeshedPath, importFailureInfo);
        if (subdirectory &&
            moduleDescriptor &&
            !this._isStdlibTypeshedStubValidForVersion(moduleDescriptor, customTypeshedPath, pythonVersion, pythonPlatform, importFailureInfo)) {
            return undefined;
        }
        return subdirectory;
    }
    _getThirdPartyTypeshedPath(customTypeshedPath, importFailureInfo) {
        return this._getTypeshedSubdirectory(/* isStdLib */ false, customTypeshedPath, importFailureInfo);
    }
    _isStdlibTypeshedStubValidForVersion(moduleDescriptor, customTypeshedPath, pythonVersion, pythonPlatform, importFailureInfo) {
        if (!this._cachedTypeshedStdLibModuleVersionInfo) {
            this._cachedTypeshedStdLibModuleVersionInfo = this._readTypeshedStdLibVersions(customTypeshedPath, importFailureInfo);
        }
        // Loop through the name parts to make sure the module and submodules
        // referenced in the import statement are valid for this version of Python.
        for (let namePartCount = 1; namePartCount <= moduleDescriptor.nameParts.length; namePartCount++) {
            const namePartsToConsider = moduleDescriptor.nameParts.slice(0, namePartCount);
            const versionInfo = this._cachedTypeshedStdLibModuleVersionInfo.get(namePartsToConsider.join('.'));
            if (versionInfo) {
                if (pythonVersion.isLessThan(versionInfo.min)) {
                    return false;
                }
                if (versionInfo.max !== undefined && pythonVersion.isGreaterThan(versionInfo.max)) {
                    return false;
                }
                if (pythonPlatform !== undefined) {
                    const pythonPlatformLower = pythonPlatform.toLowerCase();
                    if (versionInfo.supportedPlatforms) {
                        if (versionInfo.supportedPlatforms.every((p) => p.toLowerCase() !== pythonPlatformLower)) {
                            return false;
                        }
                    }
                    if (versionInfo.unsupportedPlatforms) {
                        if (versionInfo.unsupportedPlatforms.some((p) => p.toLowerCase() === pythonPlatformLower)) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
    _readTypeshedStdLibVersions(customTypeshedPath, importFailureInfo) {
        const versionRangeMap = new Map();
        // Read the VERSIONS file from typeshed.
        const typeshedStdLibPath = this._getTypeshedSubdirectory(
        /* isStdLib */ true, customTypeshedPath, importFailureInfo);
        if (typeshedStdLibPath) {
            const versionsFilePath = typeshedStdLibPath.combinePaths('VERSIONS');
            try {
                const fileStats = this.fileSystem.statSync(versionsFilePath);
                if (fileStats.size > 0 && fileStats.size < 256 * 1024) {
                    const fileContents = this.fileSystem.readFileSync(versionsFilePath, 'utf8');
                    fileContents.split(/\r?\n/).forEach((line) => {
                        const commentSplit = line.split('#');
                        // Platform-specific information can be specified after a semicolon.
                        const semicolonSplit = commentSplit[0].split(';').map((s) => s.trim());
                        // Version information is found after a colon.
                        const colonSplit = semicolonSplit[0].split(':');
                        if (colonSplit.length !== 2) {
                            return;
                        }
                        const versionSplit = colonSplit[1].split('-');
                        if (versionSplit.length > 2) {
                            return;
                        }
                        const moduleName = colonSplit[0].trim();
                        if (!moduleName) {
                            return;
                        }
                        let minVersionString = versionSplit[0].trim();
                        if (minVersionString.endsWith('+')) {
                            // If the version ends in "+", strip it off.
                            minVersionString = minVersionString.substr(0, minVersionString.length - 1);
                        }
                        let minVersion = pythonVersion_1.PythonVersion.fromString(minVersionString);
                        if (!minVersion) {
                            minVersion = pythonVersion_1.pythonVersion3_0;
                        }
                        let maxVersion;
                        if (versionSplit.length > 1) {
                            maxVersion = pythonVersion_1.PythonVersion.fromString(versionSplit[1].trim());
                        }
                        // A semicolon can be followed by a semicolon-delimited list of other
                        // exclusions. The "platform" exclusion is a comma delimited list platforms
                        // that are supported or not supported.
                        let supportedPlatforms;
                        let unsupportedPlatforms;
                        const platformsHeader = 'platforms=';
                        let platformExclusions = semicolonSplit.slice(1).find((s) => s.startsWith(platformsHeader));
                        if (platformExclusions) {
                            platformExclusions = platformExclusions.trim().substring(platformsHeader.length);
                            const commaSplit = platformExclusions.split(',');
                            for (let platform of commaSplit) {
                                platform = platform.trim();
                                let isUnsupported = false;
                                // Remove the '!' from the start if it's an exclusion.
                                if (platform.startsWith('!')) {
                                    isUnsupported = true;
                                    platform = platform.substring(1);
                                }
                                if (isUnsupported) {
                                    unsupportedPlatforms = unsupportedPlatforms !== null && unsupportedPlatforms !== void 0 ? unsupportedPlatforms : [];
                                    unsupportedPlatforms.push(platform);
                                }
                                else {
                                    supportedPlatforms = supportedPlatforms !== null && supportedPlatforms !== void 0 ? supportedPlatforms : [];
                                    supportedPlatforms.push(platform);
                                }
                            }
                        }
                        versionRangeMap.set(moduleName, {
                            min: minVersion,
                            max: maxVersion,
                            supportedPlatforms,
                            unsupportedPlatforms,
                        });
                    });
                }
                else {
                    importFailureInfo.push(`Typeshed stdlib VERSIONS file is unexpectedly large`);
                }
            }
            catch (e) {
                importFailureInfo.push(`Could not read typeshed stdlib VERSIONS file: '${JSON.stringify(e)}'`);
            }
        }
        return versionRangeMap;
    }
    _getThirdPartyTypeshedPackagePaths(moduleDescriptor, importFailureInfo, includeMatchOnly = true) {
        const typeshedPath = this._getThirdPartyTypeshedPath(this._configOptions.typeshedPath, importFailureInfo);
        if (!this._cachedTypeshedThirdPartyPackagePaths) {
            this._buildTypeshedThirdPartyPackageMap(typeshedPath);
        }
        const firstNamePart = moduleDescriptor.nameParts.length > 0 ? moduleDescriptor.nameParts[0] : '';
        if (includeMatchOnly) {
            return this._cachedTypeshedThirdPartyPackagePaths.get(firstNamePart);
        }
        if (firstNamePart) {
            return (0, collectionUtils_1.flatten)((0, collectionUtils_1.getMapValues)(this._cachedTypeshedThirdPartyPackagePaths, (k) => k.startsWith(firstNamePart)));
        }
        return [];
    }
    _getThirdPartyTypeshedPackageRoots(importFailureInfo) {
        const typeshedPath = this._getThirdPartyTypeshedPath(this._configOptions.typeshedPath, importFailureInfo);
        if (!this._cachedTypeshedThirdPartyPackagePaths) {
            this._buildTypeshedThirdPartyPackageMap(typeshedPath);
        }
        return this._cachedTypeshedThirdPartyPackageRoots;
    }
    _getTypeshedRoot(customTypeshedPath, importFailureInfo) {
        var _a;
        if (this._cachedTypeshedRoot === undefined) {
            let typeshedPath = undefined;
            // Did the user specify a typeshed path? If not, we'll look in the
            // python search paths, then in the typeshed-fallback directory.
            if (customTypeshedPath) {
                if (this.dirExistsCached(customTypeshedPath)) {
                    typeshedPath = customTypeshedPath;
                }
            }
            // If typeshed directory wasn't found in other locations, use the fallback.
            if (!typeshedPath) {
                typeshedPath = (_a = PythonPathUtils.getTypeShedFallbackPath(this.fileSystem)) !== null && _a !== void 0 ? _a : uri_1.Uri.empty();
            }
            this._cachedTypeshedRoot = typeshedPath;
        }
        return this._cachedTypeshedRoot.isEmpty() ? undefined : this._cachedTypeshedRoot;
    }
    _getTypeshedSubdirectory(isStdLib, customTypeshedPath, importFailureInfo) {
        // See if we have it cached.
        if (isStdLib) {
            if (this._cachedTypeshedStdLibPath !== undefined) {
                return this._cachedTypeshedStdLibPath;
            }
        }
        else {
            if (this._cachedTypeshedThirdPartyPath !== undefined) {
                return this._cachedTypeshedThirdPartyPath;
            }
        }
        let typeshedPath = this._getTypeshedRoot(customTypeshedPath, importFailureInfo);
        if (typeshedPath === undefined) {
            return undefined;
        }
        typeshedPath = PythonPathUtils.getTypeshedSubdirectory(typeshedPath, isStdLib);
        if (!this.dirExistsCached(typeshedPath)) {
            return undefined;
        }
        // Cache the results.
        if (isStdLib) {
            this._cachedTypeshedStdLibPath = typeshedPath;
        }
        else {
            this._cachedTypeshedThirdPartyPath = typeshedPath;
        }
        return typeshedPath;
    }
    _resolveRelativeImport(sourceFileUri, execEnv, moduleDescriptor, importName, importFailureInfo) {
        importFailureInfo.push('Attempting to resolve relative import');
        // Determine which search path this file is part of.
        const directory = (0, importStatementUtils_1.getDirectoryLeadingDotsPointsTo)(sourceFileUri.getDirectory(), moduleDescriptor.leadingDots);
        if (!directory) {
            importFailureInfo.push(`Invalid relative path '${importName}'`);
            return undefined;
        }
        // Now try to match the module parts from the current directory location.
        const absImport = this.resolveAbsoluteImport(sourceFileUri, directory, execEnv, moduleDescriptor, importName, importFailureInfo, 
        /* allowPartial */ false, 
        /* allowNativeLib */ true);
        if (absImport && absImport.isStubFile) {
            // If we found a stub for a relative import, only search
            // the same folder for the real module. Otherwise, it will
            // error out on runtime.
            absImport.nonStubImportResult = this.resolveAbsoluteImport(sourceFileUri, directory, execEnv, moduleDescriptor, importName, importFailureInfo, 
            /* allowPartial */ false, 
            /* allowNativeLib */ true, 
            /* useStubPackage */ false, 
            /* allowPyi */ false) || {
                importName,
                isRelative: true,
                isImportFound: false,
                isPartlyResolved: false,
                isNamespacePackage: false,
                isStubPackage: false,
                importFailureInfo,
                resolvedUris: [],
                importType: 2 /* ImportType.Local */,
                isStubFile: false,
                isNativeLib: false,
                implicitImports: [],
                filteredImplicitImports: [],
                nonStubImportResult: undefined,
            };
        }
        return absImport;
    }
    _getCompletionSuggestionsRelative(sourceFileUri, execEnv, moduleDescriptor, suggestions) {
        // Determine which search path this file is part of.
        const directory = (0, importStatementUtils_1.getDirectoryLeadingDotsPointsTo)(sourceFileUri.getDirectory(), moduleDescriptor.leadingDots);
        if (!directory) {
            return;
        }
        // Now try to match the module parts from the current directory location.
        this._getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, directory, moduleDescriptor, suggestions);
    }
    _getFilesInDirectory(dirPath) {
        const cachedValue = this._cachedFilesForPath.get(dirPath.key);
        if (cachedValue) {
            return cachedValue;
        }
        let newCacheValue = [];
        try {
            const entriesInDir = this.readdirEntriesCached(dirPath);
            const filesInDir = entriesInDir.filter((f) => f.isFile());
            // Add any symbolic links that point to files.
            entriesInDir.forEach((f) => {
                var _a;
                if (f.isSymbolicLink() && ((_a = (0, uriUtils_1.tryStat)(this.fileSystem, dirPath.combinePaths(f.name))) === null || _a === void 0 ? void 0 : _a.isFile())) {
                    filesInDir.push(f);
                }
            });
            newCacheValue = filesInDir.map((f) => dirPath.combinePaths(f.name));
        }
        catch {
            newCacheValue = [];
        }
        this._cachedFilesForPath.set(dirPath.key, newCacheValue);
        return newCacheValue;
    }
    _getCompletionSuggestionsAbsolute(sourceFileUri, execEnv, rootPath, moduleDescriptor, suggestions, strictOnly = true) {
        // Starting at the specified path, walk the file system to find the
        // specified module.
        let dirPath = rootPath;
        // Copy the nameParts into a new directory and add an extra empty
        // part if there is a trailing dot.
        const nameParts = moduleDescriptor.nameParts.map((name) => name);
        if (moduleDescriptor.hasTrailingDot) {
            nameParts.push('');
        }
        // We need to track this since a module might be resolvable using relative path
        // but can't resolved by absolute path.
        const leadingDots = moduleDescriptor.leadingDots;
        const parentNameParts = nameParts.slice(0, -1);
        // Handle the case where the user has typed the first
        // dot (or multiple) in a relative path.
        if (nameParts.length === 0) {
            this._addFilteredSuggestionsAbsolute(sourceFileUri, execEnv, dirPath, '', suggestions, leadingDots, parentNameParts, strictOnly);
        }
        else {
            for (let i = 0; i < nameParts.length; i++) {
                // Provide completions only if we're on the last part
                // of the name.
                if (i === nameParts.length - 1) {
                    this._addFilteredSuggestionsAbsolute(sourceFileUri, execEnv, dirPath, nameParts[i], suggestions, leadingDots, parentNameParts, strictOnly);
                }
                dirPath = dirPath.combinePaths(nameParts[i]);
                if (!this.dirExistsCached(dirPath)) {
                    break;
                }
            }
        }
    }
    _addFilteredSuggestionsAbsolute(sourceFileUri, execEnv, currentPath, filter, suggestions, leadingDots, parentNameParts, strictOnly) {
        // Enumerate all of the files and directories in the path, expanding links.
        const entries = (0, uriUtils_1.getFileSystemEntriesFromDirEntries)(this.readdirEntriesCached(currentPath), this.fileSystem, currentPath);
        entries.files.forEach((file) => {
            // Strip multi-dot extensions to handle file names like "foo.cpython-32m.so". We want
            // to detect the ".so" but strip off the entire ".cpython-32m.so" extension.
            const fileWithoutExtension = file.stripAllExtensions().fileName;
            if (ImportResolver.isSupportedImportFile(file)) {
                if (fileWithoutExtension === '__init__') {
                    return;
                }
                if (filter && !StringUtils.isPatternInSymbol(filter, fileWithoutExtension)) {
                    return;
                }
                if (!this._isUniqueValidSuggestion(fileWithoutExtension, suggestions) ||
                    !this._isResolvableSuggestion(fileWithoutExtension, leadingDots, parentNameParts, sourceFileUri, execEnv, strictOnly)) {
                    return;
                }
                suggestions.set(fileWithoutExtension, file);
            }
        });
        entries.directories.forEach((dir) => {
            const dirSuggestion = dir.fileName;
            if (filter && !dirSuggestion.startsWith(filter)) {
                return;
            }
            if (!this._isUniqueValidSuggestion(dirSuggestion, suggestions) ||
                !this._isResolvableSuggestion(dirSuggestion, leadingDots, parentNameParts, sourceFileUri, execEnv, strictOnly)) {
                return;
            }
            const initPyiPath = dir.initPyiUri;
            if (this.fileExistsCached(initPyiPath)) {
                suggestions.set(dirSuggestion, initPyiPath);
                return;
            }
            const initPyPath = dir.initPyUri;
            if (this.fileExistsCached(initPyPath)) {
                suggestions.set(dirSuggestion, initPyPath);
                return;
            }
            // It is a namespace package. there is no corresponding module path.
            suggestions.set(dirSuggestion, uri_1.Uri.empty());
        });
    }
    // Fix for editable installed submodules where the suggested directory was a namespace directory that wouldn't resolve.
    // only used for absolute imports
    _isResolvableSuggestion(name, leadingDots, parentNameParts, sourceFileUri, execEnv, strictOnly) {
        // We always resolve names based on sourceFileUri.
        const moduleDescriptor = {
            leadingDots: leadingDots,
            nameParts: [...parentNameParts, name],
            importedSymbols: new Set(),
        };
        // Make sure we don't use parent folder resolution when checking whether the given name is resolvable.
        let importResult;
        if (strictOnly) {
            const importName = this.formatImportName(moduleDescriptor);
            const importFailureInfo = [];
            importResult = this._resolveImportStrict(importName, sourceFileUri, execEnv, moduleDescriptor, importFailureInfo);
        }
        else {
            importResult = this.resolveImportInternal(sourceFileUri, execEnv, moduleDescriptor);
        }
        if (importResult && importResult.isImportFound) {
            // Check the import isn't for a private or protected module. If it is, then
            // only allow it if there's no py.typed file.
            if (!SymbolNameUtils.isPrivateOrProtectedName(name) || importResult.pyTypedInfo === undefined) {
                return true;
            }
        }
        return false;
    }
    _isUniqueValidSuggestion(suggestionToAdd, suggestions) {
        if (suggestions.has(suggestionToAdd)) {
            return false;
        }
        // Don't add directories with illegal module names.
        if (/[.-]/.test(suggestionToAdd)) {
            return false;
        }
        // Don't add directories with dunder names like "__pycache__".
        if ((0, symbolNameUtils_1.isDunderName)(suggestionToAdd) && suggestionToAdd !== '__future__') {
            return false;
        }
        return true;
    }
    _findImplicitImports(importingModuleName, dirPath, exclusions) {
        const implicitImportMap = new Map();
        // Enumerate all of the files and directories in the path, expanding links.
        const entries = (0, uriUtils_1.getFileSystemEntriesFromDirEntries)(this.readdirEntriesCached(dirPath), this.fileSystem, dirPath);
        // Add implicit file-based modules.
        for (const filePath of entries.files) {
            const fileExt = filePath.lastExtension;
            let strippedFileName;
            let isNativeLib = false;
            if (fileExt === '.py' || fileExt === '.pyi') {
                strippedFileName = (0, pathUtils_1.stripFileExtension)(filePath.fileName);
            }
            else if (this._isNativeModuleFileExtension(fileExt) &&
                !this.fileExistsCached(filePath.packageUri) &&
                !this.fileExistsCached(filePath.packageStubUri)) {
                // Native module.
                strippedFileName = filePath.stripAllExtensions().fileName;
                isNativeLib = true;
            }
            else {
                continue;
            }
            if (!exclusions.find((exclusion) => exclusion.equals(filePath))) {
                const implicitImport = {
                    isStubFile: filePath.hasExtension('.pyi'),
                    isNativeLib,
                    name: strippedFileName,
                    uri: filePath,
                };
                // Always prefer stub files over non-stub files.
                const entry = implicitImportMap.get(implicitImport.name);
                if (!entry || !entry.isStubFile) {
                    // Try resolving resolving native lib to a custom stub.
                    if (isNativeLib) {
                        const nativeLibPath = filePath;
                        const nativeStubPath = this.resolveNativeImportEx(nativeLibPath, `${importingModuleName}.${strippedFileName}`, []);
                        if (nativeStubPath) {
                            implicitImport.uri = nativeStubPath;
                            implicitImport.isNativeLib = false;
                        }
                    }
                    implicitImportMap.set(implicitImport.name, implicitImport);
                }
            }
        }
        // Add implicit directory-based modules.
        for (const dirPath of entries.directories) {
            const pyFilePath = dirPath.initPyUri;
            const pyiFilePath = dirPath.initPyiUri;
            let isStubFile = false;
            let path;
            if (this.fileExistsCached(pyiFilePath)) {
                isStubFile = true;
                path = pyiFilePath;
            }
            else if (this.fileExistsCached(pyFilePath)) {
                path = pyFilePath;
            }
            if (path) {
                if (!exclusions.find((exclusion) => exclusion.equals(path))) {
                    const implicitImport = {
                        isStubFile,
                        isNativeLib: false,
                        name: dirPath.fileName,
                        uri: path,
                        pyTypedInfo: this._getPyTypedInfo(dirPath),
                    };
                    implicitImportMap.set(implicitImport.name, implicitImport);
                }
            }
        }
        return implicitImportMap;
    }
    // Retrieves the pytyped info for a directory if it exists. This is a small perf optimization
    // that allows skipping the search when the pytyped file doesn't exist.
    _getPyTypedInfo(filePath) {
        if (!this.fileExistsCached(filePath.pytypedUri)) {
            return undefined;
        }
        return (0, pyTypedUtils_1.getPyTypedInfoForPyTypedFile)(this.fileSystem, filePath.pytypedUri);
    }
    _resolveNativeModuleStub(nativeLibPath, execEnv, importName, moduleDescriptor, importFailureInfo, resolvedPaths) {
        let moduleFullName = importName;
        if (moduleDescriptor.leadingDots > 0) {
            // Relative path. Convert `.mtrand` to `numpy.random.mtrand` based on search path.
            const info = this.getModuleNameForImport(nativeLibPath, execEnv);
            moduleFullName = info.moduleName.length > 0 ? info.moduleName : moduleFullName;
        }
        const compiledStubPath = this.resolveNativeImportEx(nativeLibPath, moduleFullName, importFailureInfo);
        if (compiledStubPath) {
            importFailureInfo.push(`Resolved native import ${importName} with stub '${compiledStubPath}'`);
            resolvedPaths.push(compiledStubPath);
            return false; // Resolved to a stub.
        }
        importFailureInfo.push(`Resolved import with file '${nativeLibPath}'`);
        resolvedPaths.push(nativeLibPath);
        return true;
    }
    _isNativeModuleFileName(moduleName, fileUri) {
        // Strip off the final file extension and the part of the file name
        // that excludes all (multi-part) file extensions. This allows us to
        // handle file names like "foo.cpython-32m.so".
        const fileExtension = fileUri.lastExtension.toLowerCase();
        const withoutExtension = (0, pathUtils_1.stripFileExtension)(fileUri.fileName, /* multiDotExtension */ true);
        return (this._isNativeModuleFileExtension(fileExtension) &&
            (0, stringUtils_1.equateStringsCaseInsensitive)(moduleName, withoutExtension));
    }
    _isNativeModuleFileExtension(fileExtension) {
        return supportedNativeLibExtensions.some((ext) => ext === fileExtension);
    }
    _tryWalkUp(current) {
        if (!current || current.isEmpty() || current.isRoot()) {
            return undefined;
        }
        // Ensure we don't go around forever even if isRoot returns false.
        const next = current.resolvePaths('..');
        if (next.equals(current)) {
            return undefined;
        }
        return next;
    }
    _shouldWalkUp(current, root, execEnv) {
        return (current &&
            !current.isEmpty() &&
            (current.isChild(root) || (current.equals(root) && (!execEnv.root || execEnv.root.isEmpty()))));
    }
}
exports.ImportResolver = ImportResolver;


/***/ }),

/***/ "../pyright-internal/src/analyzer/importStatementUtils.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/analyzer/importStatementUtils.ts ***!
  \****************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * importStatementUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility routines for summarizing and manipulating
 * import statements in a Python source file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.haveSameParentModule = exports.getResolvedFilePath = exports.getDirectoryLeadingDotsPointsTo = exports.getRelativeModuleName = exports.getTextRangeForImportNameDeletion = exports.getImportGroupFromModuleNameAndType = exports.getAllImportNames = exports.getContainingImportStatement = exports.getTextEditsForAutoImportInsertion = exports.getTextEditsForAutoImportInsertions = exports.getTextEditsForAutoImportSymbolAddition = exports.getTopLevelImports = exports.compareImportStatements = exports.getImportGroup = void 0;
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const stringUtils_1 = __webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const SymbolNameUtils = __importStar(__webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
// Determines which import grouping should be used when sorting imports.
function getImportGroup(statement) {
    if (statement.importResult) {
        if (statement.importResult.importType === 0 /* ImportType.BuiltIn */) {
            return 0 /* ImportGroup.BuiltIn */;
        }
        else if (statement.importResult.importType === 1 /* ImportType.ThirdParty */ ||
            statement.importResult.isLocalTypingsFile) {
            return 1 /* ImportGroup.ThirdParty */;
        }
        if (statement.importResult.isRelative) {
            return 3 /* ImportGroup.LocalRelative */;
        }
        return 2 /* ImportGroup.Local */;
    }
    else {
        return 2 /* ImportGroup.Local */;
    }
}
exports.getImportGroup = getImportGroup;
// Compares sort order of two import statements.
function compareImportStatements(a, b) {
    const aImportGroup = getImportGroup(a);
    const bImportGroup = getImportGroup(b);
    if (aImportGroup < bImportGroup) {
        return -1;
    }
    else if (aImportGroup > bImportGroup) {
        return 1;
    }
    return a.moduleName < b.moduleName ? -1 : 1;
}
exports.compareImportStatements = compareImportStatements;
// Looks for top-level 'import' and 'import from' statements and provides
// an ordered list and a map (by file path).
function getTopLevelImports(parseTree, includeImplicitImports = false) {
    const localImports = {
        orderedImports: [],
        mapByFilePath: new Map(),
    };
    let followsNonImportStatement = false;
    let foundFirstImportStatement = false;
    parseTree.statements.forEach((statement) => {
        if (statement.nodeType === 47 /* ParseNodeType.StatementList */) {
            statement.statements.forEach((subStatement) => {
                if (subStatement.nodeType === 20 /* ParseNodeType.Import */) {
                    foundFirstImportStatement = true;
                    _processImportNode(subStatement, localImports, followsNonImportStatement);
                    followsNonImportStatement = false;
                }
                else if (subStatement.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                    foundFirstImportStatement = true;
                    _processImportFromNode(subStatement, localImports, followsNonImportStatement, includeImplicitImports);
                    followsNonImportStatement = false;
                }
                else {
                    followsNonImportStatement = foundFirstImportStatement;
                }
            });
        }
        else {
            followsNonImportStatement = foundFirstImportStatement;
        }
    });
    return localImports;
}
exports.getTopLevelImports = getTopLevelImports;
// Return import symbol type to allow sorting similar to isort
// CONSTANT_VARIABLE, CamelCaseClass, variable_or_function
function _getImportSymbolNameType(symbolName) {
    if (SymbolNameUtils.isConstantName(symbolName)) {
        return 0;
    }
    if (SymbolNameUtils.isTypeAliasName(symbolName)) {
        return 1;
    }
    return 2;
}
function getTextEditsForAutoImportSymbolAddition(importNameInfo, importStatement, parseFileResults) {
    const additionEdits = [];
    if (!importStatement.node ||
        importStatement.node.nodeType !== 22 /* ParseNodeType.ImportFrom */ ||
        importStatement.node.isWildcardImport) {
        return additionEdits;
    }
    // Make sure we're not attempting to auto-import a symbol that
    // already exists in the import list.
    const importFrom = importStatement.node;
    importNameInfo = (Array.isArray(importNameInfo) ? importNameInfo : [importNameInfo]).filter((info) => !!info.name &&
        !importFrom.imports.some((importAs) => { var _a; return importAs.name.value === info.name && ((_a = importAs.alias) === null || _a === void 0 ? void 0 : _a.value) === info.alias; }));
    if (importNameInfo.length === 0) {
        return additionEdits;
    }
    for (const nameInfo of importNameInfo) {
        additionEdits.push(_getTextEditsForAutoImportSymbolAddition(nameInfo.name, nameInfo.alias, importStatement.node, parseFileResults));
    }
    // Merge edits with the same insertion point.
    const editsMap = (0, collectionUtils_1.createMapFromItems)(additionEdits, (e) => textRange_1.Range.print(e.range));
    const textEditList = [];
    for (const editGroup of editsMap.values()) {
        if (editGroup.length === 1) {
            textEditList.push(editGroup[0]);
        }
        else {
            textEditList.push({
                range: editGroup[0].range,
                replacementText: editGroup
                    .sort((a, b) => _compareImportNames(a.importName, b.importName))
                    .map((e) => e.replacementText)
                    .join(''),
            });
        }
    }
    return textEditList;
}
exports.getTextEditsForAutoImportSymbolAddition = getTextEditsForAutoImportSymbolAddition;
function _compareImportNames(name1, name2) {
    // Compare import name by import symbol type and then alphabetical order.
    // Match isort default behavior.
    const name1Type = _getImportSymbolNameType(name1);
    const name2Type = _getImportSymbolNameType(name2);
    const compare = name1Type - name2Type;
    if (compare !== 0) {
        return compare;
    }
    // isort will prefer '_' over alphanumerical chars
    // This can't be reproduced by a normal string compare in TypeScript, since '_' > 'A'.
    // Replace all '_' with '=' which guarantees '=' < 'A'.
    // Safe to do as '=' is an invalid char in Python names.
    const name1toCompare = name1.replace(/_/g, '=');
    const name2toCompare = name2.replace(/_/g, '=');
    return (0, stringUtils_1.compareStringsCaseSensitive)(name1toCompare, name2toCompare);
}
function _getTextEditsForAutoImportSymbolAddition(importName, alias, node, parseFileResults) {
    // Scan through the import symbols to find the right insertion point,
    // assuming we want to keep the imports alphabetized.
    let priorImport;
    for (const curImport of node.imports) {
        if (_compareImportNames(curImport.name.value, importName) > 0) {
            break;
        }
        priorImport = curImport;
    }
    // Are import symbols formatted one per line or multiple per line? We
    // will honor the existing formatting. We'll use a heuristic to determine
    // whether symbols are one per line or multiple per line.
    //   from x import a, b, c
    // or
    //   from x import (
    //      a
    //   )
    let useOnePerLineFormatting = false;
    let indentText = '';
    if (node.imports.length > 0) {
        const importStatementPos = (0, positionUtils_1.convertOffsetToPosition)(node.start, parseFileResults.tokenizerOutput.lines);
        const firstSymbolPos = (0, positionUtils_1.convertOffsetToPosition)(node.imports[0].start, parseFileResults.tokenizerOutput.lines);
        const secondSymbolPos = node.imports.length > 1
            ? (0, positionUtils_1.convertOffsetToPosition)(node.imports[1].start, parseFileResults.tokenizerOutput.lines)
            : undefined;
        if (firstSymbolPos.line > importStatementPos.line &&
            (secondSymbolPos === undefined || secondSymbolPos.line > firstSymbolPos.line)) {
            const firstSymbolLineRange = parseFileResults.tokenizerOutput.lines.getItemAt(firstSymbolPos.line);
            // Use the same combination of spaces or tabs to match
            // existing formatting.
            indentText = parseFileResults.text.substr(firstSymbolLineRange.start, firstSymbolPos.character);
            // Is the indent text composed of whitespace only?
            if (/^\s*$/.test(indentText)) {
                useOnePerLineFormatting = true;
            }
        }
    }
    const insertionOffset = priorImport
        ? textRange_1.TextRange.getEnd(priorImport)
        : node.imports.length > 0
            ? node.imports[0].start
            : node.start + node.length;
    const insertionPosition = (0, positionUtils_1.convertOffsetToPosition)(insertionOffset, parseFileResults.tokenizerOutput.lines);
    const insertText = alias ? `${importName} as ${alias}` : `${importName}`;
    let replacementText;
    if (useOnePerLineFormatting) {
        const eol = parseFileResults.tokenizerOutput.predominantEndOfLineSequence;
        replacementText = priorImport ? `,${eol}${indentText}${insertText}` : `${insertText},${eol}${indentText}`;
    }
    else {
        replacementText = priorImport ? `, ${insertText}` : `${insertText}, `;
    }
    return {
        range: { start: insertionPosition, end: insertionPosition },
        importName,
        replacementText,
    };
}
function getTextEditsForAutoImportInsertions(importNameInfo, importStatements, parseFileResults, invocationPosition) {
    const insertionEdits = [];
    importNameInfo = Array.isArray(importNameInfo) ? importNameInfo : [importNameInfo];
    if (importNameInfo.length === 0) {
        return [];
    }
    const map = (0, collectionUtils_1.createMapFromItems)(importNameInfo, (i) => { var _a; return `${i.module.moduleName}-${(_a = i.nameForImportFrom) !== null && _a !== void 0 ? _a : ''}`; });
    for (const importInfo of map.values()) {
        (0, collectionUtils_1.appendArray)(insertionEdits, _getInsertionEditsForAutoImportInsertion(importInfo, { name: importInfo[0].module.moduleName, nameForImportFrom: importInfo[0].nameForImportFrom }, importStatements, getImportGroupFromModuleNameAndType(importInfo[0].module), parseFileResults, invocationPosition));
    }
    return _convertInsertionEditsToTextEdits(parseFileResults, insertionEdits);
}
exports.getTextEditsForAutoImportInsertions = getTextEditsForAutoImportInsertions;
function getTextEditsForAutoImportInsertion(importNameInfo, moduleNameInfo, importStatements, importGroup, parseFileResults, invocationPosition) {
    const insertionEdits = _getInsertionEditsForAutoImportInsertion(importNameInfo, moduleNameInfo, importStatements, importGroup, parseFileResults, invocationPosition);
    return _convertInsertionEditsToTextEdits(parseFileResults, insertionEdits);
}
exports.getTextEditsForAutoImportInsertion = getTextEditsForAutoImportInsertion;
function _convertInsertionEditsToTextEdits(parseFileResults, insertionEdits) {
    if (insertionEdits.length < 2) {
        return insertionEdits.map((e) => getTextEdit(e));
    }
    // Merge edits with the same insertion point.
    const editsMap = [...(0, collectionUtils_1.createMapFromItems)(insertionEdits, (e) => `${e.importGroup} ${textRange_1.Range.print(e.range)}`)]
        .sort((a, b) => (0, stringUtils_1.compareStringsCaseSensitive)(a[0], b[0]))
        .map((v) => v[1]);
    const textEditList = [];
    for (const editGroup of editsMap) {
        if (editGroup.length === 1) {
            textEditList.push(getTextEdit(editGroup[0]));
        }
        else {
            textEditList.push({
                range: editGroup[0].range,
                replacementText: editGroup[0].preChange +
                    editGroup
                        .map((e) => e.importStatement)
                        .sort((a, b) => compareImports(a, b))
                        .join(parseFileResults.tokenizerOutput.predominantEndOfLineSequence) +
                    editGroup[0].postChange,
            });
        }
    }
    return textEditList;
    function getTextEdit(edit) {
        return { range: edit.range, replacementText: edit.preChange + edit.importStatement + edit.postChange };
    }
    function compareImports(a, b) {
        const isImport1 = a.startsWith('import');
        const isImport2 = b.startsWith('import');
        if (isImport1 === isImport2) {
            return a < b ? -1 : 1;
        }
        return isImport1 ? -1 : 1;
    }
}
function _getInsertionEditsForAutoImportInsertion(importNameInfo, moduleNameInfo, importStatements, importGroup, parseFileResults, invocationPosition) {
    const insertionEdits = [];
    importNameInfo = Array.isArray(importNameInfo) ? importNameInfo : [importNameInfo];
    if (importNameInfo.length === 0) {
        // This will let "import [moduleName]" to be generated.
        importNameInfo.push({});
    }
    // We need to emit a new 'from import' statement if symbolName is given. otherwise, use 'import' statement.
    const map = (0, collectionUtils_1.createMapFromItems)(importNameInfo, (i) => (i.name ? 'from' : 'import'));
    // Add import statements first.
    const imports = map.get('import');
    if (imports) {
        appendToEdits(imports, (names) => `import ${names.join(', ')}`);
    }
    // Add from import statements next.
    const fromImports = map.get('from');
    if (fromImports) {
        appendToEdits(fromImports, (names) => { var _a; return `from ${(_a = moduleNameInfo.nameForImportFrom) !== null && _a !== void 0 ? _a : moduleNameInfo.name} import ${names.join(', ')}`; });
    }
    return insertionEdits;
    function getImportAsText(nameInfo, moduleName) {
        const importText = nameInfo.name ? nameInfo.name : moduleName;
        return {
            sortText: importText,
            text: nameInfo.alias ? `${importText} as ${nameInfo.alias}` : importText,
        };
    }
    function appendToEdits(importNameInfo, importStatementGetter) {
        const importNames = importNameInfo
            .map((i) => getImportAsText(i, moduleNameInfo.name))
            .sort((a, b) => _compareImportNames(a.sortText, b.sortText))
            .reduce((set, v) => (0, collectionUtils_1.addIfUnique)(set, v.text), []);
        insertionEdits.push(_getInsertionEditForAutoImportInsertion(importStatementGetter(importNames), importStatements, moduleNameInfo.name, importGroup, parseFileResults, invocationPosition));
    }
}
function _getInsertionEditForAutoImportInsertion(importStatement, importStatements, moduleName, importGroup, parseFileResults, invocationPosition) {
    let preChange = '';
    let postChange = '';
    let insertionPosition;
    const invocation = (0, positionUtils_1.convertPositionToOffset)(invocationPosition, parseFileResults.tokenizerOutput.lines);
    if (importStatements.orderedImports.length > 0 && invocation > importStatements.orderedImports[0].node.start) {
        let insertBefore = true;
        let insertionImport = importStatements.orderedImports[0];
        // Find a good spot to insert the new import statement. Follow
        // the PEP8 standard sorting order whereby built-in imports are
        // followed by third-party, which are followed by local.
        let prevImportGroup = 0 /* ImportGroup.BuiltIn */;
        for (const curImport of importStatements.orderedImports) {
            // If the import was resolved, use its import type. If it wasn't
            // resolved, assume that it's the same import type as the previous
            // one.
            const curImportGroup = curImport.importResult ? getImportGroup(curImport) : prevImportGroup;
            if (importGroup < curImportGroup) {
                if (!insertBefore && prevImportGroup < importGroup) {
                    // Add an extra line to create a new group.
                    preChange = parseFileResults.tokenizerOutput.predominantEndOfLineSequence + preChange;
                }
                break;
            }
            if (importGroup === curImportGroup && curImport.moduleName > moduleName) {
                insertBefore = true;
                insertionImport = curImport;
                break;
            }
            // If we're about to hit the end of the import statements, don't go
            // any further.
            if (curImport.followsNonImportStatement) {
                if (importGroup > prevImportGroup) {
                    // Add an extra line to create a new group.
                    preChange = parseFileResults.tokenizerOutput.predominantEndOfLineSequence + preChange;
                }
                break;
            }
            // If this is the last import, see if we need to create a new group.
            if (curImport === importStatements.orderedImports[importStatements.orderedImports.length - 1]) {
                if (importGroup > curImportGroup) {
                    // Add an extra line to create a new group.
                    preChange = parseFileResults.tokenizerOutput.predominantEndOfLineSequence + preChange;
                }
            }
            // Are we starting a new group?
            if (!insertBefore && importGroup < prevImportGroup && importGroup === curImportGroup) {
                insertBefore = true;
            }
            else {
                insertBefore = false;
            }
            prevImportGroup = curImportGroup;
            insertionImport = curImport;
        }
        if (insertionImport) {
            if (insertBefore) {
                postChange = postChange + parseFileResults.tokenizerOutput.predominantEndOfLineSequence;
            }
            else {
                preChange = parseFileResults.tokenizerOutput.predominantEndOfLineSequence + preChange;
            }
            insertionPosition = (0, positionUtils_1.convertOffsetToPosition)(insertBefore ? insertionImport.node.start : textRange_1.TextRange.getEnd(insertionImport.node), parseFileResults.tokenizerOutput.lines);
        }
        else {
            insertionPosition = { line: 0, character: 0 };
        }
    }
    else {
        // Insert at or near the top of the file. See if there's a doc string and
        // copyright notice, etc. at the top. If so, move past those.
        insertionPosition = { line: 0, character: 0 };
        let addNewLineBefore = false;
        for (const statement of parseFileResults.parserOutput.parseTree.statements) {
            let stopHere = true;
            if (statement.nodeType === 47 /* ParseNodeType.StatementList */ && statement.statements.length === 1) {
                const simpleStatement = statement.statements[0];
                if (simpleStatement.nodeType === 48 /* ParseNodeType.StringList */) {
                    // Assume that it's a file header doc string.
                    stopHere = false;
                }
                else if (simpleStatement.nodeType === 3 /* ParseNodeType.Assignment */) {
                    if (simpleStatement.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
                        if (SymbolNameUtils.isDunderName(simpleStatement.leftExpression.value)) {
                            // Assume that it's an assignment of __copyright__, __author__, etc.
                            stopHere = false;
                        }
                    }
                }
            }
            if (stopHere) {
                insertionPosition = (0, positionUtils_1.convertOffsetToPosition)(statement.start, parseFileResults.tokenizerOutput.lines);
                addNewLineBefore = false;
                break;
            }
            else {
                insertionPosition = (0, positionUtils_1.convertOffsetToPosition)(statement.start + statement.length, parseFileResults.tokenizerOutput.lines);
                addNewLineBefore = true;
            }
        }
        postChange =
            postChange +
                parseFileResults.tokenizerOutput.predominantEndOfLineSequence +
                parseFileResults.tokenizerOutput.predominantEndOfLineSequence;
        if (addNewLineBefore) {
            preChange = parseFileResults.tokenizerOutput.predominantEndOfLineSequence + preChange;
        }
        else {
            postChange = postChange + parseFileResults.tokenizerOutput.predominantEndOfLineSequence;
        }
    }
    const range = { start: insertionPosition, end: insertionPosition };
    return { range, preChange, importStatement, postChange, importGroup };
}
function _processImportNode(node, localImports, followsNonImportStatement) {
    node.list.forEach((importAsNode) => {
        const importResult = AnalyzerNodeInfo.getImportInfo(importAsNode.module);
        let resolvedPath;
        if (importResult && importResult.isImportFound) {
            resolvedPath = importResult.resolvedUris[importResult.resolvedUris.length - 1];
        }
        const localImport = {
            node,
            subnode: importAsNode,
            importResult,
            resolvedPath,
            moduleName: _formatModuleName(importAsNode.module),
            followsNonImportStatement,
        };
        localImports.orderedImports.push(localImport);
        // Add it to the map.
        if (resolvedPath && !resolvedPath.isEmpty()) {
            // Don't overwrite existing import or import from statements
            // because we always want to prefer 'import from' over 'import'
            // in the map.
            if (!localImports.mapByFilePath.has(resolvedPath.key)) {
                localImports.mapByFilePath.set(resolvedPath.key, localImport);
            }
        }
    });
}
function _processImportFromNode(node, localImports, followsNonImportStatement, includeImplicitImports) {
    var _a;
    const importResult = AnalyzerNodeInfo.getImportInfo(node.module);
    let resolvedPath;
    if (importResult && importResult.isImportFound) {
        resolvedPath = importResult.resolvedUris[importResult.resolvedUris.length - 1];
    }
    if (includeImplicitImports && importResult) {
        localImports.implicitImports = (_a = localImports.implicitImports) !== null && _a !== void 0 ? _a : new Map();
        for (const implicitImport of importResult.implicitImports.values()) {
            const importFromAs = node.imports.find((i) => i.name.value === implicitImport.name);
            if (importFromAs) {
                localImports.implicitImports.set(implicitImport.uri.key, importFromAs);
            }
        }
    }
    const localImport = {
        node,
        importResult,
        resolvedPath,
        moduleName: _formatModuleName(node.module),
        followsNonImportStatement,
    };
    localImports.orderedImports.push(localImport);
    // Add it to the map.
    if (resolvedPath && !resolvedPath.isEmpty()) {
        const prevEntry = localImports.mapByFilePath.get(resolvedPath.key);
        // Overwrite existing import statements because we always want to prefer
        // 'import from' over 'import'. Also, overwrite existing 'import from' if
        // the module name is shorter.
        if (!prevEntry ||
            prevEntry.node.nodeType === 20 /* ParseNodeType.Import */ ||
            prevEntry.moduleName.length > localImport.moduleName.length) {
            localImports.mapByFilePath.set(resolvedPath.key, localImport);
        }
    }
}
function _formatModuleName(node) {
    let moduleName = '';
    for (let i = 0; i < node.leadingDots; i++) {
        moduleName = moduleName + '.';
    }
    moduleName += node.nameParts.map((part) => part.value).join('.');
    return moduleName;
}
function getContainingImportStatement(node, token) {
    while (node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        if (node.nodeType === 20 /* ParseNodeType.Import */ || node.nodeType === 22 /* ParseNodeType.ImportFrom */) {
            break;
        }
        node = node.parent;
    }
    return node;
}
exports.getContainingImportStatement = getContainingImportStatement;
function getAllImportNames(node) {
    if (node.nodeType === 20 /* ParseNodeType.Import */) {
        const importNode = node;
        return importNode.list;
    }
    const importFromNode = node;
    return importFromNode.imports;
}
exports.getAllImportNames = getAllImportNames;
function getImportGroupFromModuleNameAndType(moduleNameAndType) {
    let importGroup = 2 /* ImportGroup.Local */;
    if (moduleNameAndType.isLocalTypingsFile || moduleNameAndType.importType === 1 /* ImportType.ThirdParty */) {
        importGroup = 1 /* ImportGroup.ThirdParty */;
    }
    else if (moduleNameAndType.importType === 0 /* ImportType.BuiltIn */) {
        importGroup = 0 /* ImportGroup.BuiltIn */;
    }
    return importGroup;
}
exports.getImportGroupFromModuleNameAndType = getImportGroupFromModuleNameAndType;
function getTextRangeForImportNameDeletion(parseFileResults, nameNodes, ...nameNodeIndexToDelete) {
    const editSpans = [];
    for (const pair of getConsecutiveNumberPairs(nameNodeIndexToDelete)) {
        const startNode = nameNodes[pair.start];
        const endNode = nameNodes[pair.end];
        if (pair.start === 0 && nameNodes.length === pair.end + 1) {
            // get span of whole statement. ex) "import [|A|]" or "import [|A, B|]"
            editSpans.push(textRange_1.TextRange.fromBounds(startNode.start, textRange_1.TextRange.getEnd(endNode)));
        }
        else if (pair.end === nameNodes.length - 1) {
            // get span of "import A[|, B|]" or "import A[|, B, C|]"
            const previousNode = nameNodes[pair.start - 1];
            editSpans.push(...getEditsPreservingFirstCommentAfterCommaIfExist(parseFileResults, previousNode, startNode, endNode));
        }
        else {
            // get span of "import [|A, |]B" or "import [|A, B,|] C"
            const start = startNode.start;
            const length = nameNodes[pair.end + 1].start - start;
            editSpans.push({ start, length });
        }
    }
    return editSpans;
}
exports.getTextRangeForImportNameDeletion = getTextRangeForImportNameDeletion;
function getEditsPreservingFirstCommentAfterCommaIfExist(parseFileResults, previousNode, startNode, endNode) {
    const offsetOfPreviousNodeEnd = textRange_1.TextRange.getEnd(previousNode);
    const startingToken = (0, parseTreeUtils_1.getTokenAt)(parseFileResults.tokenizerOutput.tokens, startNode.start);
    if (!startingToken || !startingToken.comments || startingToken.comments.length === 0) {
        const length = textRange_1.TextRange.getEnd(endNode) - offsetOfPreviousNodeEnd;
        return [{ start: offsetOfPreviousNodeEnd, length }];
    }
    const commaToken = (0, parseTreeUtils_1.findTokenAfter)(parseFileResults.tokenizerOutput, textRange_1.TextRange.getEnd(previousNode), (t) => t.type === 12 /* TokenType.Comma */);
    if (!commaToken) {
        const length = textRange_1.TextRange.getEnd(endNode) - offsetOfPreviousNodeEnd;
        return [{ start: offsetOfPreviousNodeEnd, length }];
    }
    // We have code something like
    //  previousNode, #comment
    //  startNode,
    //  endNode
    //
    // Make sure we preserve #comment when deleting start/end nodes so we have
    //  previousNode #comment
    // as final result.
    const lengthToComma = textRange_1.TextRange.getEnd(commaToken) - offsetOfPreviousNodeEnd;
    const offsetToCommentEnd = textRange_1.TextRange.getEnd(startingToken.comments[startingToken.comments.length - 1]);
    const length = textRange_1.TextRange.getEnd(endNode) - offsetToCommentEnd;
    return [
        { start: offsetOfPreviousNodeEnd, length: lengthToComma },
        { start: offsetToCommentEnd, length },
    ];
}
function getConsecutiveNumberPairs(indices) {
    if (indices.length === 0) {
        return [];
    }
    if (indices.length === 1) {
        return [{ start: indices[0], end: indices[0] }];
    }
    const pairs = [];
    let start = indices[0];
    let current = start;
    for (const index of indices) {
        if (current === index) {
            continue;
        }
        if (current + 1 === index) {
            current = index;
            continue;
        }
        pairs.push({ start, end: current });
        start = index;
        current = index;
    }
    pairs.push({ start, end: current });
    return pairs;
}
function getRelativeModuleName(fs, sourcePath, targetPath, configOptions, ignoreFolderStructure = false, sourceIsFile) {
    let srcPath = sourcePath;
    sourceIsFile = sourceIsFile !== undefined ? sourceIsFile : (0, uriUtils_1.isFile)(fs, sourcePath);
    if (sourceIsFile) {
        srcPath = sourcePath.getDirectory();
    }
    let symbolName;
    let destPath = targetPath;
    if ((configOptions.stubPath && destPath.isChild(configOptions.stubPath)) ||
        (configOptions.typeshedPath && destPath.isChild(configOptions.typeshedPath))) {
        // Always use absolute imports for files in these library-like directories.
        return undefined;
    }
    if (sourceIsFile) {
        destPath = targetPath.getDirectory();
        const fileName = targetPath.stripAllExtensions().fileName;
        if (fileName !== '__init__') {
            // ex) src: a.py, dest: b.py -> ".b" will be returned.
            symbolName = fileName;
        }
        else if (ignoreFolderStructure) {
            // ex) src: nested1/nested2/__init__.py, dest: nested1/__init__.py -> "...nested1" will be returned
            //     like how it would return for sibling folder.
            //
            // if folder structure is not ignored, ".." will be returned
            symbolName = destPath.fileName;
            destPath = destPath.getDirectory();
        }
    }
    const relativePaths = srcPath.getRelativePathComponents(destPath);
    // This assumes both file paths are under the same importing root.
    // So this doesn't handle paths pointing to 2 different import roots.
    // ex) user file A to library file B
    let currentPaths = '.';
    for (let i = 0; i < relativePaths.length; i++) {
        const relativePath = relativePaths[i];
        if (relativePath === '..') {
            currentPaths += '.';
        }
        else {
            currentPaths += relativePath;
        }
        if (relativePath !== '..' && i !== relativePaths.length - 1) {
            currentPaths += '.';
        }
    }
    if (symbolName) {
        currentPaths =
            currentPaths[currentPaths.length - 1] === '.' ? currentPaths + symbolName : currentPaths + '.' + symbolName;
    }
    return currentPaths;
}
exports.getRelativeModuleName = getRelativeModuleName;
function getDirectoryLeadingDotsPointsTo(fromDirectory, leadingDots) {
    let currentDirectory = fromDirectory;
    for (let i = 1; i < leadingDots; i++) {
        if (currentDirectory.isRoot()) {
            return undefined;
        }
        currentDirectory = currentDirectory.getDirectory();
    }
    return currentDirectory;
}
exports.getDirectoryLeadingDotsPointsTo = getDirectoryLeadingDotsPointsTo;
function getResolvedFilePath(importResult) {
    if (!importResult || !importResult.isImportFound || importResult.resolvedUris.length === 0) {
        return undefined;
    }
    if (importResult.resolvedUris.length === 1 && importResult.resolvedUris[0].equals(uri_1.Uri.empty())) {
        // Import is resolved to namespace package folder.
        if (importResult.packageDirectory) {
            return importResult.packageDirectory;
        }
        // Absolute import is partially resolved from the path.
        if (importResult.searchPath) {
            return importResult.searchPath;
        }
        return undefined;
    }
    // Regular case.
    return importResult.resolvedUris[importResult.resolvedUris.length - 1];
}
exports.getResolvedFilePath = getResolvedFilePath;
function haveSameParentModule(module1, module2) {
    if (module1.length !== module2.length) {
        return false;
    }
    let i = 0;
    for (i = 0; i < module1.length - 1; i++) {
        if (module1[i] !== module2[i]) {
            break;
        }
    }
    return i === module1.length - 1;
}
exports.haveSameParentModule = haveSameParentModule;


/***/ }),

/***/ "../pyright-internal/src/analyzer/namedTuples.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/analyzer/namedTuples.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * namedTuples.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides special-case logic for the construction of named tuple
 * classes with defined entry names and types.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.updateNamedTupleBaseClass = exports.createNamedTupleType = void 0;
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const tokenizer_1 = __webpack_require__(/*! ../parser/tokenizer */ "../pyright-internal/src/parser/tokenizer.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const staticExpressions_1 = __webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// Creates a new custom tuple factory class with named values.
// Supports both typed and untyped variants.
function createNamedTupleType(evaluator, errorNode, argList, includesTypes) {
    var _a, _b, _c;
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(errorNode);
    let className = 'namedtuple';
    // The "rename" parameter is supported only in the untyped version.
    let allowRename = false;
    if (!includesTypes) {
        const renameArg = argList.find((arg) => { var _a; return arg.argumentCategory === 0 /* ArgumentCategory.Simple */ && ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'rename'; });
        if (renameArg === null || renameArg === void 0 ? void 0 : renameArg.valueExpression) {
            const renameValue = (0, staticExpressions_1.evaluateStaticBoolExpression)(renameArg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
            if (renameValue === true) {
                allowRename = true;
            }
        }
    }
    if (argList.length === 0) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.namedTupleFirstArg(), errorNode);
    }
    else {
        const nameArg = argList[0];
        if (nameArg.argumentCategory !== 0 /* ArgumentCategory.Simple */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.namedTupleFirstArg(), argList[0].valueExpression || errorNode);
        }
        else if (nameArg.valueExpression && nameArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            className = nameArg.valueExpression.strings.map((s) => s.value).join('');
        }
    }
    // Is there is a default arg? If so, is it defined in a way that we
    // can determine its length statically?
    const defaultsArg = argList.find((arg) => { var _a; return ((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'defaults'; });
    let defaultArgCount = 0;
    if (defaultsArg && defaultsArg.valueExpression) {
        const defaultsArgType = evaluator.getTypeOfExpression(defaultsArg.valueExpression).type;
        if ((0, types_1.isClassInstance)(defaultsArgType) &&
            (0, typeUtils_1.isTupleClass)(defaultsArgType) &&
            !(0, typeUtils_1.isUnboundedTupleClass)(defaultsArgType) &&
            defaultsArgType.tupleTypeArguments) {
            defaultArgCount = defaultsArgType.tupleTypeArguments.length;
        }
        else {
            defaultArgCount = undefined;
        }
    }
    const namedTupleType = evaluator.getTypingType(errorNode, 'NamedTuple') || types_1.UnknownType.create();
    const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 33554432 /* ClassTypeFlags.ReadOnlyInstanceVariables */ | 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */, ParseTreeUtils.getTypeSourceId(errorNode), 
    /* declaredMetaclass */ undefined, (0, types_1.isInstantiableClass)(namedTupleType) ? namedTupleType.details.effectiveMetaclass : types_1.UnknownType.create());
    classType.details.baseClasses.push(namedTupleType);
    classType.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(errorNode);
    const classFields = types_1.ClassType.getSymbolTable(classType);
    classFields.set('__class__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 64 /* SymbolFlags.IgnoredForProtocolMatch */, classType));
    const classTypeVar = (0, typeUtils_1.synthesizeTypeVarForSelfCls)(classType, /* isClsParam */ true);
    const constructorType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* FunctionTypeFlags.ConstructorMethod */);
    constructorType.details.declaredReturnType = (0, typeUtils_1.convertToInstance)(classTypeVar);
    constructorType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    if (ParseTreeUtils.isAssignmentToDefaultsFollowingNamedTuple(errorNode)) {
        constructorType.details.flags |= 32 /* FunctionTypeFlags.DisableDefaultChecks */;
    }
    constructorType.details.typeVarScopeId = classType.details.typeVarScopeId;
    types_1.FunctionType.addParameter(constructorType, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'cls',
        type: classTypeVar,
        hasDeclaredType: true,
    });
    const matchArgsNames = [];
    const selfParameter = {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: (0, typeUtils_1.synthesizeTypeVarForSelfCls)(classType, /* isClsParam */ false),
        hasDeclaredType: true,
    };
    let addGenericGetAttribute = false;
    const entryTypes = [];
    if (argList.length < 2) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.namedTupleSecondArg(), errorNode);
        addGenericGetAttribute = true;
    }
    else {
        const entriesArg = argList[1];
        if (entriesArg.argumentCategory !== 0 /* ArgumentCategory.Simple */) {
            addGenericGetAttribute = true;
        }
        else {
            if (!includesTypes &&
                entriesArg.valueExpression &&
                entriesArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                const entries = entriesArg.valueExpression.strings
                    .map((s) => s.value)
                    .join('')
                    .split(/[,\s]+/);
                const firstParamWithDefaultIndex = defaultArgCount === undefined ? 0 : Math.max(0, entries.length - defaultArgCount);
                entries.forEach((entryName, index) => {
                    entryName = entryName.trim();
                    if (entryName) {
                        entryName = renameKeyword(evaluator, entryName, allowRename, entriesArg.valueExpression, index);
                        const entryType = types_1.UnknownType.create();
                        const paramInfo = {
                            category: 0 /* ParameterCategory.Simple */,
                            name: entryName,
                            type: entryType,
                            hasDeclaredType: includesTypes,
                            hasDefault: index >= firstParamWithDefaultIndex,
                        };
                        types_1.FunctionType.addParameter(constructorType, paramInfo);
                        const newSymbol = symbol_1.Symbol.createWithType(8 /* SymbolFlags.InstanceMember */, entryType);
                        matchArgsNames.push(entryName);
                        // We need to associate the declaration with a parse node.
                        // In this case it's just part of a string literal value.
                        // The definition provider won't necessarily take the
                        // user to the exact spot in the string, but it's close enough.
                        const stringNode = entriesArg.valueExpression;
                        const declaration = {
                            type: 1 /* DeclarationType.Variable */,
                            node: stringNode,
                            isRuntimeTypeExpression: true,
                            uri: fileInfo.fileUri,
                            range: (0, positionUtils_1.convertOffsetsToRange)(stringNode.start, textRange_1.TextRange.getEnd(stringNode), fileInfo.lines),
                            moduleName: fileInfo.moduleName,
                            isInExceptSuite: false,
                        };
                        newSymbol.addDeclaration(declaration);
                        classFields.set(entryName, newSymbol);
                        entryTypes.push(entryType);
                    }
                });
            }
            else if (((_a = entriesArg.valueExpression) === null || _a === void 0 ? void 0 : _a.nodeType) === 31 /* ParseNodeType.List */ ||
                ((_b = entriesArg.valueExpression) === null || _b === void 0 ? void 0 : _b.nodeType) === 52 /* ParseNodeType.Tuple */) {
                const entryList = entriesArg.valueExpression;
                const entryMap = new Map();
                const entryExpressions = ((_c = entriesArg.valueExpression) === null || _c === void 0 ? void 0 : _c.nodeType) === 31 /* ParseNodeType.List */
                    ? entriesArg.valueExpression.entries
                    : entriesArg.valueExpression.expressions;
                const firstParamWithDefaultIndex = defaultArgCount === undefined ? 0 : Math.max(0, entryExpressions.length - defaultArgCount);
                entryExpressions.forEach((entry, index) => {
                    let entryTypeNode;
                    let entryType;
                    let entryNameNode;
                    let entryName = '';
                    if (includesTypes) {
                        // Handle the variant that includes name/type tuples.
                        if (entry.nodeType === 52 /* ParseNodeType.Tuple */ && entry.expressions.length === 2) {
                            entryNameNode = entry.expressions[0];
                            entryTypeNode = entry.expressions[1];
                            entryType = (0, typeUtils_1.convertToInstance)(evaluator.getTypeOfExpressionExpectingType(entryTypeNode).type);
                        }
                        else {
                            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.namedTupleNameType(), entry);
                        }
                    }
                    else {
                        entryNameNode = entry;
                        entryType = types_1.UnknownType.create();
                    }
                    if (entryNameNode) {
                        const nameTypeResult = evaluator.getTypeOfExpression(entryNameNode);
                        if ((0, types_1.isClassInstance)(nameTypeResult.type) &&
                            types_1.ClassType.isBuiltIn(nameTypeResult.type, 'str') &&
                            (0, typeUtils_1.isLiteralType)(nameTypeResult.type)) {
                            entryName = nameTypeResult.type.literalValue;
                            if (!entryName) {
                                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.namedTupleEmptyName(), entryNameNode);
                            }
                            else {
                                entryName = renameKeyword(evaluator, entryName, allowRename, entryNameNode, index);
                            }
                        }
                        else {
                            addGenericGetAttribute = true;
                        }
                    }
                    else {
                        addGenericGetAttribute = true;
                    }
                    if (!entryName) {
                        entryName = `_${index.toString()}`;
                    }
                    if (entryMap.has(entryName)) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.namedTupleNameUnique(), entryNameNode || entry);
                    }
                    // Record names in a map to detect duplicates.
                    entryMap.set(entryName, entryName);
                    if (!entryType) {
                        entryType = types_1.UnknownType.create();
                    }
                    const paramInfo = {
                        category: 0 /* ParameterCategory.Simple */,
                        name: entryName,
                        type: entryType,
                        hasDeclaredType: includesTypes,
                        hasDefault: index >= firstParamWithDefaultIndex,
                    };
                    types_1.FunctionType.addParameter(constructorType, paramInfo);
                    entryTypes.push(entryType);
                    matchArgsNames.push(entryName);
                    const newSymbol = symbol_1.Symbol.createWithType(8 /* SymbolFlags.InstanceMember */ | 2048 /* SymbolFlags.NamedTupleMember */, entryType);
                    if (entryNameNode && entryNameNode.nodeType === 48 /* ParseNodeType.StringList */) {
                        const declaration = {
                            type: 1 /* DeclarationType.Variable */,
                            node: entryNameNode,
                            uri: fileInfo.fileUri,
                            typeAnnotationNode: entryTypeNode,
                            range: (0, positionUtils_1.convertOffsetsToRange)(entryNameNode.start, textRange_1.TextRange.getEnd(entryNameNode), fileInfo.lines),
                            moduleName: fileInfo.moduleName,
                            isInExceptSuite: false,
                        };
                        newSymbol.addDeclaration(declaration);
                    }
                    classFields.set(entryName, newSymbol);
                });
                // Set the type in the type cache for the dict node so it
                // doesn't get evaluated again.
                evaluator.setTypeResultForNode(entryList, { type: types_1.UnknownType.create() });
            }
            else {
                // A dynamic expression was used, so we can't evaluate
                // the named tuple statically.
                addGenericGetAttribute = true;
            }
            if (entriesArg.valueExpression && !addGenericGetAttribute) {
                // Set the type of the value expression node to Any so we don't attempt to
                // re-evaluate it later, potentially generating "partially unknown" errors
                // in strict mode.
                evaluator.setTypeResultForNode(entriesArg.valueExpression, { type: types_1.AnyType.create() });
            }
        }
    }
    if (addGenericGetAttribute) {
        constructorType.details.parameters = [];
        types_1.FunctionType.addDefaultParameters(constructorType);
        entryTypes.push(types_1.AnyType.create(/* isEllipsis */ false));
        entryTypes.push(types_1.AnyType.create(/* isEllipsis */ true));
    }
    // Always use generic parameters for __init__.
    const initType = types_1.FunctionType.createSynthesizedInstance('__init__');
    types_1.FunctionType.addParameter(initType, selfParameter);
    types_1.FunctionType.addDefaultParameters(initType);
    initType.details.declaredReturnType = evaluator.getNoneType();
    initType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    classFields.set('__new__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, constructorType));
    classFields.set('__init__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, initType));
    const keysItemType = types_1.FunctionType.createSynthesizedInstance('keys');
    const itemsItemType = types_1.FunctionType.createSynthesizedInstance('items');
    keysItemType.details.declaredReturnType = evaluator.getBuiltInObject(errorNode, 'list', [
        evaluator.getBuiltInObject(errorNode, 'str'),
    ]);
    itemsItemType.details.declaredReturnType = keysItemType.details.declaredReturnType;
    classFields.set('keys', symbol_1.Symbol.createWithType(8 /* SymbolFlags.InstanceMember */, keysItemType));
    classFields.set('items', symbol_1.Symbol.createWithType(8 /* SymbolFlags.InstanceMember */, itemsItemType));
    const lenType = types_1.FunctionType.createSynthesizedInstance('__len__');
    lenType.details.declaredReturnType = evaluator.getBuiltInObject(errorNode, 'int');
    types_1.FunctionType.addParameter(lenType, selfParameter);
    classFields.set('__len__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, lenType));
    if (addGenericGetAttribute) {
        const getAttribType = types_1.FunctionType.createSynthesizedInstance('__getattribute__');
        getAttribType.details.declaredReturnType = types_1.AnyType.create();
        types_1.FunctionType.addParameter(getAttribType, selfParameter);
        types_1.FunctionType.addParameter(getAttribType, {
            category: 0 /* ParameterCategory.Simple */,
            name: 'name',
            type: evaluator.getBuiltInObject(errorNode, 'str'),
        });
        classFields.set('__getattribute__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, getAttribType));
    }
    const tupleClassType = evaluator.getBuiltInType(errorNode, 'tuple');
    // Synthesize the __match_args__ class variable.
    const strType = evaluator.getBuiltInType(errorNode, 'str');
    if (!addGenericGetAttribute &&
        strType &&
        (0, types_1.isInstantiableClass)(strType) &&
        tupleClassType &&
        (0, types_1.isInstantiableClass)(tupleClassType)) {
        const literalTypes = matchArgsNames.map((name) => {
            return { type: types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneWithLiteral(strType, name)), isUnbounded: false };
        });
        const matchArgsType = types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeTupleClass)(tupleClassType, literalTypes));
        classFields.set('__match_args__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, matchArgsType));
    }
    updateNamedTupleBaseClass(classType, entryTypes, !addGenericGetAttribute);
    (0, typeUtils_1.computeMroLinearization)(classType);
    return classType;
}
exports.createNamedTupleType = createNamedTupleType;
function updateNamedTupleBaseClass(classType, typeArgs, isTypeArgumentExplicit) {
    let isUpdateNeeded = false;
    classType.details.baseClasses = classType.details.baseClasses.map((baseClass) => {
        if (!(0, types_1.isInstantiableClass)(baseClass) || !types_1.ClassType.isBuiltIn(baseClass, 'NamedTuple')) {
            return baseClass;
        }
        const tupleTypeArgs = [];
        if (!isTypeArgumentExplicit) {
            tupleTypeArgs.push({
                type: typeArgs.length > 0 ? (0, types_1.combineTypes)(typeArgs) : types_1.UnknownType.create(),
                isUnbounded: true,
            });
        }
        else {
            typeArgs.forEach((t) => {
                tupleTypeArgs.push({ type: t, isUnbounded: false });
            });
        }
        // Create a copy of the NamedTuple class that replaces the tuple base class.
        const clonedNamedTupleClass = types_1.ClassType.cloneForSpecialization(baseClass, 
        /* typeArguments */ undefined, isTypeArgumentExplicit);
        clonedNamedTupleClass.details = { ...clonedNamedTupleClass.details };
        clonedNamedTupleClass.details.baseClasses = clonedNamedTupleClass.details.baseClasses.map((namedTupleBaseClass) => {
            if (!(0, types_1.isInstantiableClass)(namedTupleBaseClass) || !types_1.ClassType.isBuiltIn(namedTupleBaseClass, 'tuple')) {
                return namedTupleBaseClass;
            }
            return (0, typeUtils_1.specializeTupleClass)(namedTupleBaseClass, tupleTypeArgs, isTypeArgumentExplicit);
        });
        (0, typeUtils_1.computeMroLinearization)(clonedNamedTupleClass);
        isUpdateNeeded = true;
        return clonedNamedTupleClass;
    });
    return isUpdateNeeded;
}
exports.updateNamedTupleBaseClass = updateNamedTupleBaseClass;
function renameKeyword(evaluator, name, allowRename, errorNode, index) {
    // Determine whether the name is a keyword in python.
    const isKeyword = tokenizer_1.Tokenizer.isPythonKeyword(name);
    if (!isKeyword) {
        // No rename necessary.
        return name;
    }
    if (allowRename) {
        // Rename based on index.
        return `_${index}`;
    }
    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.namedTupleNameKeyword(), errorNode);
    return name;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/operations.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/operations.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * operations.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides type evaluation logic for unary, binary, augmented assignment,
 * and ternary operators.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getTypeOfTernaryOperation = exports.getTypeOfUnaryOperation = exports.getTypeOfAugmentedAssignment = exports.getTypeOfBinaryOperation = exports.validateBinaryOperation = void 0;
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const scopeUtils_1 = __webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const staticExpressions_1 = __webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// Maps binary operators to the magic methods that implement them.
const binaryOperatorMap = {
    [0 /* OperatorType.Add */]: ['__add__', '__radd__'],
    [33 /* OperatorType.Subtract */]: ['__sub__', '__rsub__'],
    [26 /* OperatorType.Multiply */]: ['__mul__', '__rmul__'],
    [13 /* OperatorType.FloorDivide */]: ['__floordiv__', '__rfloordiv__'],
    [10 /* OperatorType.Divide */]: ['__truediv__', '__rtruediv__'],
    [24 /* OperatorType.Mod */]: ['__mod__', '__rmod__'],
    [29 /* OperatorType.Power */]: ['__pow__', '__rpow__'],
    [22 /* OperatorType.MatrixMultiply */]: ['__matmul__', '__rmatmul__'],
    [3 /* OperatorType.BitwiseAnd */]: ['__and__', '__rand__'],
    [6 /* OperatorType.BitwiseOr */]: ['__or__', '__ror__'],
    [8 /* OperatorType.BitwiseXor */]: ['__xor__', '__rxor__'],
    [17 /* OperatorType.LeftShift */]: ['__lshift__', '__rlshift__'],
    [31 /* OperatorType.RightShift */]: ['__rshift__', '__rrshift__'],
    [12 /* OperatorType.Equals */]: ['__eq__', '__eq__'],
    [28 /* OperatorType.NotEquals */]: ['__ne__', '__ne__'],
    [20 /* OperatorType.LessThan */]: ['__lt__', '__gt__'],
    [21 /* OperatorType.LessThanOrEqual */]: ['__le__', '__ge__'],
    [15 /* OperatorType.GreaterThan */]: ['__gt__', '__lt__'],
    [16 /* OperatorType.GreaterThanOrEqual */]: ['__ge__', '__le__'],
};
// Map of operators that always return a bool result.
const booleanOperatorMap = {
    [36 /* OperatorType.And */]: true,
    [37 /* OperatorType.Or */]: true,
    [39 /* OperatorType.Is */]: true,
    [40 /* OperatorType.IsNot */]: true,
    [41 /* OperatorType.In */]: true,
    [42 /* OperatorType.NotIn */]: true,
};
// If the number of subtypes starts to explode when applying "literal math",
// cut off the literal union and fall back to the non-literal supertype.
const maxLiteralMathSubtypeCount = 64;
function validateBinaryOperation(evaluator, operator, leftTypeResult, rightTypeResult, errorNode, inferenceContext, diag, options) {
    const leftType = leftTypeResult.type;
    const rightType = rightTypeResult.type;
    let type;
    let concreteLeftType = evaluator.makeTopLevelTypeVarsConcrete(leftType);
    if (booleanOperatorMap[operator] !== undefined) {
        // If it's an AND or OR, we need to handle short-circuiting by
        // eliminating any known-truthy or known-falsy types.
        if (operator === 36 /* OperatorType.And */) {
            // If the LHS evaluates to falsy, the And expression will
            // always return the type of the left-hand side.
            if (!evaluator.canBeTruthy(concreteLeftType)) {
                return leftType;
            }
            // If the LHS evaluates to truthy, the And expression will
            // always return the type of the right-hand side.
            if (!evaluator.canBeFalsy(concreteLeftType)) {
                return rightType;
            }
            concreteLeftType = evaluator.removeTruthinessFromType(concreteLeftType);
            if ((0, types_1.isNever)(rightType)) {
                return concreteLeftType;
            }
        }
        else if (operator === 37 /* OperatorType.Or */) {
            // If the LHS evaluates to truthy, the Or expression will
            // always return the type of the left-hand side.
            if (!evaluator.canBeFalsy(concreteLeftType)) {
                return leftType;
            }
            // If the LHS evaluates to falsy, the Or expression will
            // always return the type of the right-hand side.
            if (!evaluator.canBeTruthy(concreteLeftType)) {
                return rightType;
            }
            concreteLeftType = evaluator.removeFalsinessFromType(concreteLeftType);
            if ((0, types_1.isNever)(rightType)) {
                return concreteLeftType;
            }
        }
        if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(rightType)) {
            return types_1.NeverType.createNever();
        }
        // The "in" and "not in" operators make use of the __contains__
        // magic method.
        if (operator === 41 /* OperatorType.In */ || operator === 42 /* OperatorType.NotIn */) {
            type = evaluator.mapSubtypesExpandTypeVars(rightType, 
            /* options */ undefined, (rightSubtypeExpanded, rightSubtypeUnexpanded) => {
                return evaluator.mapSubtypesExpandTypeVars(concreteLeftType, { conditionFilter: (0, typeUtils_1.getTypeCondition)(rightSubtypeExpanded) }, (leftSubtype) => {
                    var _a;
                    if ((0, types_1.isAnyOrUnknown)(leftSubtype) || (0, types_1.isAnyOrUnknown)(rightSubtypeUnexpanded)) {
                        return (0, typeUtils_1.preserveUnknown)(leftSubtype, rightSubtypeExpanded);
                    }
                    let returnType = evaluator.getTypeOfMagicMethodCall(rightSubtypeExpanded, '__contains__', [{ type: leftSubtype, isIncomplete: leftTypeResult.isIncomplete }], errorNode, 
                    /* inferenceContext */ undefined);
                    if (!returnType) {
                        // If __contains__ was not supported, fall back
                        // on an iterable.
                        const iteratorType = (_a = evaluator.getTypeOfIterator({ type: rightSubtypeExpanded, isIncomplete: rightTypeResult.isIncomplete }, 
                        /* isAsync */ false, errorNode, 
                        /* emitNotIterableError */ false)) === null || _a === void 0 ? void 0 : _a.type;
                        if (iteratorType && evaluator.assignType(iteratorType, leftSubtype)) {
                            returnType = evaluator.getBuiltInObject(errorNode, 'bool');
                        }
                    }
                    if (!returnType) {
                        diag.addMessage(localize_1.LocMessage.typeNotSupportBinaryOperator().format({
                            operator: (0, parseTreeUtils_1.printOperator)(operator),
                            leftType: evaluator.printType(leftSubtype),
                            rightType: evaluator.printType(rightSubtypeExpanded),
                        }));
                    }
                    return returnType;
                });
            });
            // Assume that a bool is returned even if the type is unknown
            if (type && !(0, types_1.isNever)(type)) {
                type = evaluator.getBuiltInObject(errorNode, 'bool');
            }
        }
        else {
            type = evaluator.mapSubtypesExpandTypeVars(concreteLeftType, 
            /* options */ undefined, (leftSubtypeExpanded, leftSubtypeUnexpanded) => {
                return evaluator.mapSubtypesExpandTypeVars(rightType, { conditionFilter: (0, typeUtils_1.getTypeCondition)(leftSubtypeExpanded) }, (rightSubtypeExpanded, rightSubtypeUnexpanded) => {
                    // If the operator is an AND or OR, we need to combine the two types.
                    if (operator === 36 /* OperatorType.And */ || operator === 37 /* OperatorType.Or */) {
                        return (0, types_1.combineTypes)([leftSubtypeUnexpanded, rightSubtypeUnexpanded]);
                    }
                    // The other boolean operators always return a bool value.
                    return evaluator.getBuiltInObject(errorNode, 'bool');
                });
            });
        }
    }
    else if (binaryOperatorMap[operator]) {
        if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(rightType)) {
            return types_1.NeverType.createNever();
        }
        // Handle certain operations on certain homogenous literal types
        // using special-case math. For example, Literal[1, 2] + Literal[3, 4]
        // should result in Literal[4, 5, 6].
        if (options.isLiteralMathAllowed) {
            const leftLiteralClassName = (0, typeUtils_1.getLiteralTypeClassName)(leftType);
            if (leftLiteralClassName && !(0, typeUtils_1.getTypeCondition)(leftType)) {
                const rightLiteralClassName = (0, typeUtils_1.getLiteralTypeClassName)(rightType);
                if (leftLiteralClassName === rightLiteralClassName &&
                    !(0, typeUtils_1.getTypeCondition)(rightType) &&
                    (0, typeUtils_1.getUnionSubtypeCount)(leftType) * (0, typeUtils_1.getUnionSubtypeCount)(rightType) < maxLiteralMathSubtypeCount) {
                    if (leftLiteralClassName === 'str' || leftLiteralClassName === 'bytes') {
                        if (operator === 0 /* OperatorType.Add */) {
                            type = (0, typeUtils_1.mapSubtypes)(leftType, (leftSubtype) => {
                                return (0, typeUtils_1.mapSubtypes)(rightType, (rightSubtype) => {
                                    const leftClassSubtype = leftSubtype;
                                    const rightClassSubtype = rightSubtype;
                                    return types_1.ClassType.cloneWithLiteral(leftClassSubtype, (leftClassSubtype.literalValue +
                                        rightClassSubtype.literalValue));
                                });
                            });
                        }
                    }
                    else if (leftLiteralClassName === 'int') {
                        if (operator === 0 /* OperatorType.Add */ ||
                            operator === 33 /* OperatorType.Subtract */ ||
                            operator === 26 /* OperatorType.Multiply */ ||
                            operator === 13 /* OperatorType.FloorDivide */ ||
                            operator === 24 /* OperatorType.Mod */) {
                            let isValidResult = true;
                            type = (0, typeUtils_1.mapSubtypes)(leftType, (leftSubtype) => {
                                return (0, typeUtils_1.mapSubtypes)(rightType, (rightSubtype) => {
                                    try {
                                        const leftClassSubtype = leftSubtype;
                                        const rightClassSubtype = rightSubtype;
                                        const leftLiteralValue = BigInt(leftClassSubtype.literalValue);
                                        const rightLiteralValue = BigInt(rightClassSubtype.literalValue);
                                        let newValue;
                                        if (operator === 0 /* OperatorType.Add */) {
                                            newValue = leftLiteralValue + rightLiteralValue;
                                        }
                                        else if (operator === 33 /* OperatorType.Subtract */) {
                                            newValue = leftLiteralValue - rightLiteralValue;
                                        }
                                        else if (operator === 26 /* OperatorType.Multiply */) {
                                            newValue = leftLiteralValue * rightLiteralValue;
                                        }
                                        else if (operator === 13 /* OperatorType.FloorDivide */) {
                                            if (rightLiteralValue !== BigInt(0)) {
                                                newValue = leftLiteralValue / rightLiteralValue;
                                            }
                                        }
                                        else if (operator === 24 /* OperatorType.Mod */) {
                                            if (rightLiteralValue !== BigInt(0)) {
                                                newValue = leftLiteralValue % rightLiteralValue;
                                            }
                                        }
                                        if (newValue === undefined) {
                                            isValidResult = false;
                                            return undefined;
                                        }
                                        else if (typeof newValue === 'number' && isNaN(newValue)) {
                                            isValidResult = false;
                                            return undefined;
                                        }
                                        else {
                                            // Convert back to a simple number if it fits. Leave as a bigint
                                            // if it doesn't.
                                            if (newValue >= Number.MIN_SAFE_INTEGER &&
                                                newValue <= Number.MAX_SAFE_INTEGER) {
                                                newValue = Number(newValue);
                                            }
                                            return types_1.ClassType.cloneWithLiteral(leftClassSubtype, newValue);
                                        }
                                    }
                                    catch {
                                        isValidResult = false;
                                        return undefined;
                                    }
                                });
                            });
                            if (!isValidResult) {
                                type = undefined;
                            }
                        }
                    }
                }
            }
        }
        if (!type) {
            type = evaluator.mapSubtypesExpandTypeVars(leftType, 
            /* options */ undefined, (leftSubtypeExpanded, leftSubtypeUnexpanded) => {
                return evaluator.mapSubtypesExpandTypeVars(rightType, { conditionFilter: (0, typeUtils_1.getTypeCondition)(leftSubtypeExpanded) }, (rightSubtypeExpanded, rightSubtypeUnexpanded) => {
                    if ((0, types_1.isAnyOrUnknown)(leftSubtypeUnexpanded) || (0, types_1.isAnyOrUnknown)(rightSubtypeUnexpanded)) {
                        return (0, typeUtils_1.preserveUnknown)(leftSubtypeUnexpanded, rightSubtypeUnexpanded);
                    }
                    const tupleClassType = evaluator.getTupleClassType();
                    // Special-case __add__ for tuples when the types for both tuples are known.
                    if (options.isTupleAddAllowed &&
                        operator === 0 /* OperatorType.Add */ &&
                        (0, types_1.isClassInstance)(leftSubtypeExpanded) &&
                        (0, typeUtils_1.isTupleClass)(leftSubtypeExpanded) &&
                        leftSubtypeExpanded.tupleTypeArguments &&
                        (0, types_1.isClassInstance)(rightSubtypeExpanded) &&
                        (0, typeUtils_1.isTupleClass)(rightSubtypeExpanded) &&
                        rightSubtypeExpanded.tupleTypeArguments &&
                        tupleClassType &&
                        (0, types_1.isInstantiableClass)(tupleClassType)) {
                        // If at least one of the tuples is of fixed size, we can
                        // combine them into a precise new type. If both are unbounded
                        // (or contain an unbounded element), we cannot combine them
                        // in this manner because tuples can contain at most one
                        // unbounded element.
                        if (!(0, typeUtils_1.isUnboundedTupleClass)(leftSubtypeExpanded) ||
                            !(0, typeUtils_1.isUnboundedTupleClass)(rightSubtypeExpanded)) {
                            return types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeTupleClass)(tupleClassType, [
                                ...leftSubtypeExpanded.tupleTypeArguments,
                                ...rightSubtypeExpanded.tupleTypeArguments,
                            ]));
                        }
                    }
                    const magicMethodName = binaryOperatorMap[operator][0];
                    let resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, leftSubtypeUnexpanded), magicMethodName, [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }], errorNode, inferenceContext);
                    if (!resultType && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
                        // Try the expanded left type.
                        resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, leftSubtypeExpanded), magicMethodName, [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }], errorNode, inferenceContext);
                    }
                    if (!resultType && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
                        // Try the expanded left and right type.
                        resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, leftSubtypeExpanded), magicMethodName, [{ type: rightSubtypeExpanded, isIncomplete: rightTypeResult.isIncomplete }], errorNode, inferenceContext);
                    }
                    if (!resultType) {
                        // Try the alternate form (swapping right and left).
                        const altMagicMethodName = binaryOperatorMap[operator][1];
                        resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, rightSubtypeUnexpanded), altMagicMethodName, [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }], errorNode, inferenceContext);
                        if (!resultType && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
                            // Try the expanded right type.
                            resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, rightSubtypeExpanded), altMagicMethodName, [
                                {
                                    type: leftSubtypeUnexpanded,
                                    isIncomplete: leftTypeResult.isIncomplete,
                                },
                            ], errorNode, inferenceContext);
                        }
                        if (!resultType && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
                            // Try the expanded right and left type.
                            resultType = evaluator.getTypeOfMagicMethodCall(convertFunctionToObject(evaluator, rightSubtypeExpanded), altMagicMethodName, [{ type: leftSubtypeExpanded, isIncomplete: leftTypeResult.isIncomplete }], errorNode, inferenceContext);
                        }
                    }
                    if (!resultType) {
                        if (inferenceContext) {
                            diag.addMessage(localize_1.LocMessage.typeNotSupportBinaryOperatorBidirectional().format({
                                operator: (0, parseTreeUtils_1.printOperator)(operator),
                                leftType: evaluator.printType(leftSubtypeExpanded),
                                rightType: evaluator.printType(rightSubtypeExpanded),
                                expectedType: evaluator.printType(inferenceContext.expectedType),
                            }));
                        }
                        else {
                            diag.addMessage(localize_1.LocMessage.typeNotSupportBinaryOperator().format({
                                operator: (0, parseTreeUtils_1.printOperator)(operator),
                                leftType: evaluator.printType(leftSubtypeExpanded),
                                rightType: evaluator.printType(rightSubtypeExpanded),
                            }));
                        }
                    }
                    return resultType;
                });
            });
        }
    }
    return type !== null && type !== void 0 ? type : types_1.UnknownType.create();
}
exports.validateBinaryOperation = validateBinaryOperation;
function getTypeOfBinaryOperation(evaluator, node, flags, inferenceContext) {
    const leftExpression = node.leftExpression;
    let rightExpression = node.rightExpression;
    let isIncomplete = false;
    let typeErrors = false;
    // If this is a comparison and the left expression is also a comparison,
    // we need to change the behavior to accommodate python's "chained
    // comparisons" feature.
    if ((0, parseTreeUtils_1.operatorSupportsChaining)(node.operator)) {
        if (rightExpression.nodeType === 7 /* ParseNodeType.BinaryOperation */ &&
            !rightExpression.parenthesized &&
            (0, parseTreeUtils_1.operatorSupportsChaining)(rightExpression.operator)) {
            // Evaluate the right expression so it is type checked.
            getTypeOfBinaryOperation(evaluator, rightExpression, flags, inferenceContext);
            // Use the left side of the right expression for comparison purposes.
            rightExpression = rightExpression.leftExpression;
        }
    }
    // For most binary operations, the "expected type" is applied to the output
    // of the magic method for that operation. However, the "or" and "and" operators
    // have no magic method, so we apply the expected type directly to both operands.
    let expectedOperandType = node.operator === 37 /* OperatorType.Or */ || node.operator === 36 /* OperatorType.And */
        ? inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType
        : undefined;
    // Handle the very special case where the expected type is a list
    // and the operator is a multiply. This comes up in the common case
    // of "x: List[Optional[X]] = [None] * y" where y is an integer literal.
    let expectedLeftOperandType;
    if (node.operator === 26 /* OperatorType.Multiply */ &&
        inferenceContext &&
        (0, types_1.isClassInstance)(inferenceContext.expectedType) &&
        types_1.ClassType.isBuiltIn(inferenceContext.expectedType, 'list') &&
        inferenceContext.expectedType.typeArguments &&
        inferenceContext.expectedType.typeArguments.length >= 1 &&
        node.leftExpression.nodeType === 31 /* ParseNodeType.List */) {
        expectedLeftOperandType = inferenceContext.expectedType;
    }
    const effectiveExpectedType = expectedOperandType !== null && expectedOperandType !== void 0 ? expectedOperandType : expectedLeftOperandType;
    const leftTypeResult = evaluator.getTypeOfExpression(leftExpression, flags, (0, typeUtils_1.makeInferenceContext)(effectiveExpectedType));
    let leftType = leftTypeResult.type;
    if (!expectedOperandType) {
        if (node.operator === 37 /* OperatorType.Or */ || node.operator === 36 /* OperatorType.And */) {
            // For "or" and "and", use the type of the left operand under certain
            // circumstances. This allows us to infer a better type for expressions
            // like `x or []`. Do this only if it's a generic class (like list or dict)
            // or a TypedDict.
            if ((0, typeUtils_1.someSubtypes)(leftType, (subtype) => {
                if (!(0, types_1.isClassInstance)(subtype)) {
                    return false;
                }
                return types_1.ClassType.isTypedDictClass(subtype) || subtype.details.typeParameters.length > 0;
            })) {
                expectedOperandType = leftType;
            }
        }
        else if (node.operator === 0 /* OperatorType.Add */ && node.rightExpression.nodeType === 31 /* ParseNodeType.List */) {
            // For the "+" operator , use this technique only if the right operand is
            // a list expression. This heuristic handles the common case of `my_list + [0]`.
            expectedOperandType = leftType;
        }
        else if (node.operator === 6 /* OperatorType.BitwiseOr */) {
            // If this is a bitwise or ("|"), use the type of the left operand. This allows
            // us to support the case where a TypedDict is being updated with a dict expression.
            if ((0, types_1.isClassInstance)(leftType) && types_1.ClassType.isTypedDictClass(leftType)) {
                expectedOperandType = leftType;
            }
        }
    }
    const rightTypeResult = evaluator.getTypeOfExpression(rightExpression, flags, (0, typeUtils_1.makeInferenceContext)(expectedOperandType));
    let rightType = rightTypeResult.type;
    if (leftTypeResult.isIncomplete || rightTypeResult.isIncomplete) {
        isIncomplete = true;
    }
    // Is this a "|" operator used in a context where it is supposed to be
    // interpreted as a union operator?
    if (node.operator === 6 /* OperatorType.BitwiseOr */ &&
        !customMetaclassSupportsMethod(leftType, '__or__') &&
        !customMetaclassSupportsMethod(rightType, '__ror__')) {
        let adjustedRightType = rightType;
        let adjustedLeftType = leftType;
        if (!(0, typeUtils_1.isNoneInstance)(leftType) && (0, typeUtils_1.isNoneInstance)(rightType)) {
            // Handle the special case where "None" is being added to the union
            // with something else. Even though "None" will normally be interpreted
            // as the None singleton object in contexts where a type annotation isn't
            // assumed, we'll allow it here.
            adjustedRightType = (0, typeUtils_1.convertToInstantiable)(evaluator.getNoneType());
        }
        else if (!(0, typeUtils_1.isNoneInstance)(rightType) && (0, typeUtils_1.isNoneInstance)(leftType)) {
            adjustedLeftType = (0, typeUtils_1.convertToInstantiable)(evaluator.getNoneType());
        }
        if ((0, typeUtils_1.isUnionableType)([adjustedLeftType, adjustedRightType])) {
            const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(node);
            const unionNotationSupported = fileInfo.isStubFile ||
                (flags & 4 /* EvaluatorFlags.AllowForwardReferences */) !== 0 ||
                fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_10);
            if (!unionNotationSupported) {
                // If the left type is Any, we can't say for sure whether this
                // is an illegal syntax or a valid application of the "|" operator.
                if (!(0, types_1.isAnyOrUnknown)(adjustedLeftType)) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unionSyntaxIllegal(), node, node.operatorToken);
                }
            }
            if (!evaluator.validateTypeArg({ ...leftTypeResult, node: leftExpression }, { allowVariadicTypeVar: true, allowUnpackedTuples: true }) ||
                !evaluator.validateTypeArg({ ...rightTypeResult, node: rightExpression }, { allowVariadicTypeVar: true, allowUnpackedTuples: true })) {
                return { type: types_1.UnknownType.create() };
            }
            adjustedLeftType = evaluator.reportMissingTypeArguments(node.leftExpression, adjustedLeftType, flags | 128 /* EvaluatorFlags.ExpectingInstantiableType */);
            adjustedRightType = evaluator.reportMissingTypeArguments(node.rightExpression, adjustedRightType, flags | 128 /* EvaluatorFlags.ExpectingInstantiableType */);
            let newUnion = (0, types_1.combineTypes)([adjustedLeftType, adjustedRightType]);
            const unionClass = evaluator.getUnionClassType();
            if (unionClass && (0, types_1.isInstantiableClass)(unionClass)) {
                newUnion = types_1.TypeBase.cloneAsSpecialForm(newUnion, types_1.ClassType.cloneAsInstance(unionClass));
            }
            // Check for "stringified" forward reference type expressions. The "|" operator
            // doesn't support these except in certain circumstances. Notably, it can't be used
            // with other strings or with types that are not specialized using an index form.
            if (!fileInfo.isStubFile) {
                let stringNode;
                let otherNode;
                let otherType;
                if (leftExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                    stringNode = leftExpression;
                    otherNode = rightExpression;
                    otherType = rightType;
                }
                else if (rightExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                    stringNode = rightExpression;
                    otherNode = leftExpression;
                    otherType = leftType;
                }
                if (stringNode && otherNode && otherType) {
                    let isAllowed = true;
                    if ((0, types_1.isClass)(otherType)) {
                        if (!otherType.isTypeArgumentExplicit || (0, types_1.isClassInstance)(otherType)) {
                            isAllowed = false;
                        }
                    }
                    if (!isAllowed) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unionForwardReferenceNotAllowed(), stringNode);
                    }
                }
            }
            return { type: newUnion };
        }
    }
    if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
        // Exempt "|" because it might be a union operation involving unknowns.
        if (node.operator !== 6 /* OperatorType.BitwiseOr */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.binaryOperationNotAllowed(), node);
            return { type: types_1.UnknownType.create() };
        }
    }
    // Optional checks apply to all operations except for boolean operations.
    let isLeftOptionalType = false;
    if (booleanOperatorMap[node.operator] === undefined) {
        // None is a valid operand for == and != even if the type stub says otherwise.
        if (node.operator === 12 /* OperatorType.Equals */ || node.operator === 28 /* OperatorType.NotEquals */) {
            leftType = (0, typeUtils_1.removeNoneFromUnion)(leftType);
        }
        else {
            isLeftOptionalType = (0, typeUtils_1.isOptionalType)(leftType);
        }
        // None is a valid operand for == and != even if the type stub says otherwise.
        if (node.operator === 12 /* OperatorType.Equals */ || node.operator === 28 /* OperatorType.NotEquals */) {
            rightType = (0, typeUtils_1.removeNoneFromUnion)(rightType);
        }
    }
    const diag = new diagnostic_1.DiagnosticAddendum();
    // Don't use literal math if the operation is within a loop
    // because the literal values may change each time. We also don't want to
    // apply literal math within the body of a lambda because they are often
    // used as callbacks where the value changes each time they are called.
    const isLiteralMathAllowed = !(0, parseTreeUtils_1.isWithinLoop)(node) && !(0, parseTreeUtils_1.getEnclosingLambda)(node);
    // Don't special-case tuple __add__ if the left type is a union. This
    // can result in an infinite loop if we keep creating new tuple types
    // within a loop construct using __add__.
    const isTupleAddAllowed = !(0, types_1.isUnion)(leftType);
    let type = validateBinaryOperation(evaluator, node.operator, { type: leftType, isIncomplete: leftTypeResult.isIncomplete }, { type: rightType, isIncomplete: rightTypeResult.isIncomplete }, node, inferenceContext, diag, { isLiteralMathAllowed, isTupleAddAllowed });
    if (!diag.isEmpty()) {
        typeErrors = true;
        if (!isIncomplete) {
            if (isLeftOptionalType && diag.getMessages().length === 1) {
                // If the left was an optional type and there is just one diagnostic,
                // assume that it was due to a "None" not being supported. Report
                // this as a reportOptionalOperand diagnostic rather than a
                // reportGeneralTypeIssues diagnostic.
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalOperand, localize_1.LocMessage.noneOperator().format({
                    operator: (0, parseTreeUtils_1.printOperator)(node.operator),
                }), node.leftExpression);
            }
            else {
                // If neither the LHS or RHS are unions, don't include a diagnostic addendum
                // because it will be redundant with the main diagnostic message. The addenda
                // are useful only if union expansion was used for one or both operands.
                let diagString = '';
                if ((0, types_1.isUnion)(evaluator.makeTopLevelTypeVarsConcrete(leftType)) ||
                    (0, types_1.isUnion)(evaluator.makeTopLevelTypeVarsConcrete(rightType))) {
                    diagString = diag.getString();
                }
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOperatorIssue, localize_1.LocMessage.typeNotSupportBinaryOperator().format({
                    operator: (0, parseTreeUtils_1.printOperator)(node.operator),
                    leftType: evaluator.printType(leftType),
                    rightType: evaluator.printType(rightType),
                }) + diagString, node);
            }
        }
        type = types_1.UnknownType.create();
    }
    return { type, isIncomplete, typeErrors };
}
exports.getTypeOfBinaryOperation = getTypeOfBinaryOperation;
function getTypeOfAugmentedAssignment(evaluator, node, inferenceContext) {
    const operatorMap = {
        [1 /* OperatorType.AddEqual */]: ['__iadd__', 0 /* OperatorType.Add */],
        [34 /* OperatorType.SubtractEqual */]: ['__isub__', 33 /* OperatorType.Subtract */],
        [27 /* OperatorType.MultiplyEqual */]: ['__imul__', 26 /* OperatorType.Multiply */],
        [14 /* OperatorType.FloorDivideEqual */]: ['__ifloordiv__', 13 /* OperatorType.FloorDivide */],
        [11 /* OperatorType.DivideEqual */]: ['__itruediv__', 10 /* OperatorType.Divide */],
        [25 /* OperatorType.ModEqual */]: ['__imod__', 24 /* OperatorType.Mod */],
        [30 /* OperatorType.PowerEqual */]: ['__ipow__', 29 /* OperatorType.Power */],
        [23 /* OperatorType.MatrixMultiplyEqual */]: ['__imatmul__', 22 /* OperatorType.MatrixMultiply */],
        [4 /* OperatorType.BitwiseAndEqual */]: ['__iand__', 3 /* OperatorType.BitwiseAnd */],
        [7 /* OperatorType.BitwiseOrEqual */]: ['__ior__', 6 /* OperatorType.BitwiseOr */],
        [9 /* OperatorType.BitwiseXorEqual */]: ['__ixor__', 8 /* OperatorType.BitwiseXor */],
        [18 /* OperatorType.LeftShiftEqual */]: ['__ilshift__', 17 /* OperatorType.LeftShift */],
        [32 /* OperatorType.RightShiftEqual */]: ['__irshift__', 31 /* OperatorType.RightShift */],
    };
    let type;
    let typeResult;
    const diag = new diagnostic_1.DiagnosticAddendum();
    const leftTypeResult = evaluator.getTypeOfExpression(node.leftExpression);
    const leftType = leftTypeResult.type;
    let expectedOperandType;
    if (node.operator === 7 /* OperatorType.BitwiseOrEqual */) {
        // If this is a bitwise or ("|="), use the type of the left operand. This allows
        // us to support the case where a TypedDict is being updated with a dict expression.
        expectedOperandType = leftType;
    }
    const rightTypeResult = evaluator.getTypeOfExpression(node.rightExpression, 
    /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedOperandType));
    const rightType = rightTypeResult.type;
    const isIncomplete = !!rightTypeResult.isIncomplete || !!leftTypeResult.isIncomplete;
    if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(rightType)) {
        typeResult = { type: types_1.NeverType.createNever(), isIncomplete };
    }
    else {
        type = evaluator.mapSubtypesExpandTypeVars(leftType, 
        /* options */ undefined, (leftSubtypeExpanded, leftSubtypeUnexpanded) => {
            return evaluator.mapSubtypesExpandTypeVars(rightType, { conditionFilter: (0, typeUtils_1.getTypeCondition)(leftSubtypeExpanded) }, (rightSubtypeExpanded, rightSubtypeUnexpanded) => {
                if ((0, types_1.isAnyOrUnknown)(leftSubtypeUnexpanded) || (0, types_1.isAnyOrUnknown)(rightSubtypeUnexpanded)) {
                    return (0, typeUtils_1.preserveUnknown)(leftSubtypeUnexpanded, rightSubtypeUnexpanded);
                }
                const magicMethodName = operatorMap[node.operator][0];
                let returnType = evaluator.getTypeOfMagicMethodCall(leftSubtypeUnexpanded, magicMethodName, [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }], node, inferenceContext);
                if (!returnType && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
                    // Try with the expanded left type.
                    returnType = evaluator.getTypeOfMagicMethodCall(leftSubtypeExpanded, magicMethodName, [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }], node, inferenceContext);
                }
                if (!returnType && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
                    // Try with the expanded left and right type.
                    returnType = evaluator.getTypeOfMagicMethodCall(leftSubtypeExpanded, magicMethodName, [{ type: rightSubtypeExpanded, isIncomplete: rightTypeResult.isIncomplete }], node, inferenceContext);
                }
                if (!returnType) {
                    // If the LHS class didn't support the magic method for augmented
                    // assignment, fall back on the normal binary expression evaluator.
                    const binaryOperator = operatorMap[node.operator][1];
                    // Don't use literal math if the operation is within a loop
                    // because the literal values may change each time.
                    const isLiteralMathAllowed = !(0, parseTreeUtils_1.isWithinLoop)(node) &&
                        isExpressionLocalVariable(evaluator, node.leftExpression) &&
                        (0, typeUtils_1.getUnionSubtypeCount)(leftType) * (0, typeUtils_1.getUnionSubtypeCount)(rightType) <
                            maxLiteralMathSubtypeCount;
                    // Don't special-case tuple __add__ if the left type is a union. This
                    // can result in an infinite loop if we keep creating new tuple types
                    // within a loop construct using __add__.
                    const isTupleAddAllowed = !(0, types_1.isUnion)(leftType);
                    returnType = validateBinaryOperation(evaluator, binaryOperator, { type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }, { type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }, node, inferenceContext, diag, { isLiteralMathAllowed, isTupleAddAllowed });
                }
                return returnType;
            });
        });
        // If the LHS class didn't support the magic method for augmented
        // assignment, fall back on the normal binary expression evaluator.
        if (!diag.isEmpty() || !type || (0, types_1.isNever)(type)) {
            if (!isIncomplete) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOperatorIssue, localize_1.LocMessage.typeNotSupportBinaryOperator().format({
                    operator: (0, parseTreeUtils_1.printOperator)(node.operator),
                    leftType: evaluator.printType(leftType),
                    rightType: evaluator.printType(rightType),
                }) + diag.getString(), node);
            }
            type = types_1.UnknownType.create();
        }
        typeResult = { type, isIncomplete };
    }
    evaluator.assignTypeToExpression(node.destExpression, typeResult.type, !!typeResult.isIncomplete, node.rightExpression);
    return typeResult;
}
exports.getTypeOfAugmentedAssignment = getTypeOfAugmentedAssignment;
function getTypeOfUnaryOperation(evaluator, node, flags, inferenceContext) {
    if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.unaryOperationNotAllowed(), node);
        return { type: types_1.UnknownType.create() };
    }
    const exprTypeResult = evaluator.getTypeOfExpression(node.expression);
    let exprType = evaluator.makeTopLevelTypeVarsConcrete((0, typeUtils_1.transformPossibleRecursiveTypeAlias)(exprTypeResult.type));
    const isIncomplete = exprTypeResult.isIncomplete;
    if ((0, types_1.isNever)(exprType)) {
        return { type: types_1.NeverType.createNever(), isIncomplete };
    }
    // Map unary operators to magic functions. Note that the bitwise
    // invert has two magic functions that are aliases of each other.
    const unaryOperatorMap = {
        [0 /* OperatorType.Add */]: '__pos__',
        [33 /* OperatorType.Subtract */]: '__neg__',
        [5 /* OperatorType.BitwiseInvert */]: '__invert__',
    };
    let type;
    if (node.operator !== 38 /* OperatorType.Not */) {
        if ((0, typeUtils_1.isOptionalType)(exprType)) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalOperand, localize_1.LocMessage.noneOperator().format({
                operator: (0, parseTreeUtils_1.printOperator)(node.operator),
            }), node.expression);
            exprType = (0, typeUtils_1.removeNoneFromUnion)(exprType);
        }
    }
    // Handle certain operations on certain literal types
    // using special-case math. Do not apply this if the input type
    // is incomplete because we may be evaluating an expression within
    // a loop, so the literal value may change each time.
    if (!exprTypeResult.isIncomplete) {
        const literalClassName = (0, typeUtils_1.getLiteralTypeClassName)(exprType);
        if (literalClassName === 'int') {
            if (node.operator === 0 /* OperatorType.Add */) {
                type = exprType;
            }
            else if (node.operator === 33 /* OperatorType.Subtract */) {
                type = (0, typeUtils_1.mapSubtypes)(exprType, (subtype) => {
                    const classSubtype = subtype;
                    return types_1.ClassType.cloneWithLiteral(classSubtype, -classSubtype.literalValue);
                });
            }
        }
        else if (literalClassName === 'bool') {
            if (node.operator === 38 /* OperatorType.Not */) {
                type = (0, typeUtils_1.mapSubtypes)(exprType, (subtype) => {
                    const classSubtype = subtype;
                    return types_1.ClassType.cloneWithLiteral(classSubtype, !classSubtype.literalValue);
                });
            }
        }
    }
    if (!type) {
        // __not__ always returns a boolean.
        if (node.operator === 38 /* OperatorType.Not */) {
            type = evaluator.getBuiltInObject(node, 'bool');
            if (!type) {
                type = types_1.UnknownType.create();
            }
        }
        else {
            if ((0, types_1.isAnyOrUnknown)(exprType)) {
                type = exprType;
            }
            else {
                const magicMethodName = unaryOperatorMap[node.operator];
                type = evaluator.getTypeOfMagicMethodCall(exprType, magicMethodName, [], node, inferenceContext);
            }
            if (!type) {
                if (!isIncomplete) {
                    if (inferenceContext) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOperatorIssue, localize_1.LocMessage.typeNotSupportUnaryOperatorBidirectional().format({
                            operator: (0, parseTreeUtils_1.printOperator)(node.operator),
                            type: evaluator.printType(exprType),
                            expectedType: evaluator.printType(inferenceContext.expectedType),
                        }), node);
                    }
                    else {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOperatorIssue, localize_1.LocMessage.typeNotSupportUnaryOperator().format({
                            operator: (0, parseTreeUtils_1.printOperator)(node.operator),
                            type: evaluator.printType(exprType),
                        }), node);
                    }
                }
                type = types_1.UnknownType.create();
            }
        }
    }
    return { type, isIncomplete };
}
exports.getTypeOfUnaryOperation = getTypeOfUnaryOperation;
function getTypeOfTernaryOperation(evaluator, node, flags, inferenceContext) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(node);
    if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.ternaryNotAllowed(), node);
        return { type: types_1.UnknownType.create() };
    }
    evaluator.getTypeOfExpression(node.testExpression);
    const typesToCombine = [];
    let isIncomplete = false;
    let typeErrors = false;
    const constExprValue = (0, staticExpressions_1.evaluateStaticBoolExpression)(node.testExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
    if (constExprValue !== false && evaluator.isNodeReachable(node.ifExpression)) {
        const ifType = evaluator.getTypeOfExpression(node.ifExpression, flags, inferenceContext);
        typesToCombine.push(ifType.type);
        if (ifType.isIncomplete) {
            isIncomplete = true;
        }
        if (ifType.typeErrors) {
            typeErrors = true;
        }
    }
    if (constExprValue !== true && evaluator.isNodeReachable(node.elseExpression)) {
        const elseType = evaluator.getTypeOfExpression(node.elseExpression, flags, inferenceContext);
        typesToCombine.push(elseType.type);
        if (elseType.isIncomplete) {
            isIncomplete = true;
        }
        if (elseType.typeErrors) {
            typeErrors = true;
        }
    }
    return { type: (0, types_1.combineTypes)(typesToCombine), isIncomplete, typeErrors };
}
exports.getTypeOfTernaryOperation = getTypeOfTernaryOperation;
function customMetaclassSupportsMethod(type, methodName) {
    if (!(0, types_1.isInstantiableClass)(type)) {
        return false;
    }
    const metaclass = type.details.effectiveMetaclass;
    if (!metaclass || !(0, types_1.isInstantiableClass)(metaclass)) {
        return false;
    }
    if (types_1.ClassType.isBuiltIn(metaclass, 'type')) {
        return false;
    }
    const memberInfo = (0, typeUtils_1.lookUpClassMember)(metaclass, methodName);
    if (!memberInfo) {
        return false;
    }
    // If the metaclass inherits from Any or Unknown, we have to guess
    // whether the method is supported. We'll assume it's not, since this
    // is the most likely case.
    if ((0, types_1.isAnyOrUnknown)(memberInfo.classType)) {
        return false;
    }
    if ((0, types_1.isInstantiableClass)(memberInfo.classType) && types_1.ClassType.isBuiltIn(memberInfo.classType, 'type')) {
        return false;
    }
    return true;
}
// All functions in Python derive from object, so they inherit all
// of the capabilities of an object. This function converts a function
// to an object instance.
function convertFunctionToObject(evaluator, type) {
    if ((0, types_1.isFunction)(type) || (0, types_1.isOverloadedFunction)(type)) {
        return evaluator.getObjectType();
    }
    return type;
}
// Determines whether the expression refers to a variable that
// is defined within the current scope or some outer scope.
function isExpressionLocalVariable(evaluator, node) {
    if (node.nodeType !== 38 /* ParseNodeType.Name */) {
        return false;
    }
    const symbolWithScope = evaluator.lookUpSymbolRecursive(node, node.value, /* honorCodeFlow */ false);
    if (!symbolWithScope) {
        return false;
    }
    const currentScope = (0, scopeUtils_1.getScopeForNode)(node);
    return currentScope === symbolWithScope.scope;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/parameterUtils.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/parameterUtils.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * parameterUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Utility functions for parameters.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isParamSpecKwargsArgument = exports.isParamSpecArgsArgument = exports.getParameterListDetails = exports.firstParametersExcludingSelf = exports.ParameterSource = exports.isTypedKwargs = void 0;
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
function isTypedKwargs(param) {
    return (param.category === 2 /* ParameterCategory.KwargsDict */ &&
        (0, types_1.isClassInstance)(param.type) &&
        (0, types_1.isUnpackedClass)(param.type) &&
        types_1.ClassType.isTypedDictClass(param.type) &&
        !!param.type.details.typedDictEntries);
}
exports.isTypedKwargs = isTypedKwargs;
var ParameterSource;
(function (ParameterSource) {
    ParameterSource[ParameterSource["PositionOnly"] = 0] = "PositionOnly";
    ParameterSource[ParameterSource["PositionOrKeyword"] = 1] = "PositionOrKeyword";
    ParameterSource[ParameterSource["KeywordOnly"] = 2] = "KeywordOnly";
})(ParameterSource || (exports.ParameterSource = ParameterSource = {}));
function firstParametersExcludingSelf(type) {
    return type.details.parameters.find((p) => !((0, types_1.isTypeVar)(p.type) && p.type.details.isSynthesizedSelf));
}
exports.firstParametersExcludingSelf = firstParametersExcludingSelf;
// Examines the input parameters within a function signature and creates a
// "virtual list" of parameters, stripping out any markers and expanding
// any *args with unpacked tuples.
function getParameterListDetails(type) {
    const result = {
        firstPositionOrKeywordIndex: 0,
        positionParamCount: 0,
        positionOnlyParamCount: 0,
        params: [],
        hasUnpackedVariadicTypeVar: false,
        hasUnpackedTypedDict: false,
        paramSpec: type.details.paramSpec,
    };
    let positionOnlyIndex = type.details.parameters.findIndex((p) => (0, types_1.isPositionOnlySeparator)(p));
    // Handle the old (pre Python 3.8) way of specifying positional-only
    // parameters by naming them with "__".
    if (positionOnlyIndex < 0) {
        for (let i = 0; i < type.details.parameters.length; i++) {
            const p = type.details.parameters[i];
            if (p.category !== 0 /* ParameterCategory.Simple */) {
                break;
            }
            if (!p.name) {
                break;
            }
            if ((0, symbolNameUtils_1.isDunderName)(p.name) || !p.name.startsWith('__')) {
                // We exempt "self" and "cls" in class and instance methods.
                if (i > 0 || types_1.FunctionType.isStaticMethod(type)) {
                    break;
                }
                continue;
            }
            positionOnlyIndex = i + 1;
        }
    }
    for (let i = 0; i < positionOnlyIndex; i++) {
        if (type.details.parameters[i].hasDefault) {
            break;
        }
        result.positionOnlyParamCount++;
    }
    let sawKeywordOnlySeparator = false;
    const addVirtualParameter = (param, index, typeOverride, defaultArgTypeOverride, sourceOverride) => {
        if (param.name) {
            let source;
            if (sourceOverride !== undefined) {
                source = sourceOverride;
            }
            else if (param.category === 1 /* ParameterCategory.ArgsList */) {
                source = ParameterSource.PositionOnly;
            }
            else if (sawKeywordOnlySeparator) {
                source = ParameterSource.KeywordOnly;
            }
            else if (positionOnlyIndex >= 0 && index < positionOnlyIndex) {
                source = ParameterSource.PositionOnly;
            }
            else {
                source = ParameterSource.PositionOrKeyword;
            }
            result.params.push({
                param,
                index,
                type: typeOverride !== null && typeOverride !== void 0 ? typeOverride : types_1.FunctionType.getEffectiveParameterType(type, index),
                defaultArgType: defaultArgTypeOverride,
                source,
            });
        }
    };
    type.details.parameters.forEach((param, index) => {
        var _a, _b;
        if (param.category === 1 /* ParameterCategory.ArgsList */) {
            // If this is an unpacked tuple, expand the entries.
            const paramType = types_1.FunctionType.getEffectiveParameterType(type, index);
            if (param.name && (0, types_1.isUnpackedClass)(paramType) && paramType.tupleTypeArguments) {
                const addToPositionalOnly = index < result.positionOnlyParamCount;
                paramType.tupleTypeArguments.forEach((tupleArg, tupleIndex) => {
                    const category = (0, types_1.isVariadicTypeVar)(tupleArg.type) || tupleArg.isUnbounded
                        ? 1 /* ParameterCategory.ArgsList */
                        : 0 /* ParameterCategory.Simple */;
                    if (category === 1 /* ParameterCategory.ArgsList */) {
                        result.argsIndex = result.params.length;
                    }
                    if ((0, types_1.isVariadicTypeVar)(param.type)) {
                        result.hasUnpackedVariadicTypeVar = true;
                    }
                    addVirtualParameter({
                        category,
                        name: `${param.name}[${tupleIndex.toString()}]`,
                        isNameSynthesized: true,
                        type: tupleArg.type,
                        hasDeclaredType: true,
                    }, index, tupleArg.type, 
                    /* defaultArgTypeOverride */ undefined, ParameterSource.PositionOnly);
                    if (category === 0 /* ParameterCategory.Simple */) {
                        result.positionParamCount++;
                    }
                    if (tupleIndex > 0 && addToPositionalOnly) {
                        result.positionOnlyParamCount++;
                    }
                });
                // Normally, a VarArgList parameter (either named or as an unnamed separator)
                // would signify the start of keyword-only parameters. However, we can construct
                // callable signatures that defy this rule by using Callable and TypeVarTuples
                // or unpacked tuples.
                if (!sawKeywordOnlySeparator && (positionOnlyIndex < 0 || index >= positionOnlyIndex)) {
                    result.firstKeywordOnlyIndex = result.params.length;
                    sawKeywordOnlySeparator = true;
                }
            }
            else {
                if (param.name && result.argsIndex === undefined) {
                    result.argsIndex = result.params.length;
                    if ((0, types_1.isVariadicTypeVar)(param.type)) {
                        result.hasUnpackedVariadicTypeVar = true;
                    }
                }
                // Normally, a VarArgList parameter (either named or as an unnamed separator)
                // would signify the start of keyword-only parameters. However, we can construct
                // callable signatures that defy this rule by using Callable and TypeVarTuples
                // or unpacked tuples.
                if (!sawKeywordOnlySeparator && (positionOnlyIndex < 0 || index >= positionOnlyIndex)) {
                    result.firstKeywordOnlyIndex = result.params.length;
                    if (param.name) {
                        result.firstKeywordOnlyIndex++;
                    }
                    sawKeywordOnlySeparator = true;
                }
                addVirtualParameter(param, index);
            }
        }
        else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
            sawKeywordOnlySeparator = true;
            const paramType = types_1.FunctionType.getEffectiveParameterType(type, index);
            // Is this an unpacked TypedDict? If so, expand the entries.
            if ((0, types_1.isClassInstance)(paramType) && (0, types_1.isUnpackedClass)(paramType) && paramType.details.typedDictEntries) {
                if (result.firstKeywordOnlyIndex === undefined) {
                    result.firstKeywordOnlyIndex = result.params.length;
                }
                const typedDictType = paramType;
                paramType.details.typedDictEntries.knownItems.forEach((entry, name) => {
                    const specializedParamType = (0, typeUtils_1.partiallySpecializeType)(entry.valueType, typedDictType);
                    addVirtualParameter({
                        category: 0 /* ParameterCategory.Simple */,
                        name,
                        type: specializedParamType,
                        hasDeclaredType: true,
                        hasDefault: !entry.isRequired,
                    }, index, specializedParamType);
                });
                if (paramType.details.typedDictEntries.extraItems) {
                    addVirtualParameter({
                        category: 2 /* ParameterCategory.KwargsDict */,
                        name: 'kwargs',
                        type: paramType.details.typedDictEntries.extraItems.valueType,
                        hasDeclaredType: true,
                        hasDefault: false,
                    }, index, paramType.details.typedDictEntries.extraItems.valueType);
                    result.kwargsIndex = result.params.length - 1;
                }
                result.hasUnpackedTypedDict = true;
                result.unpackedKwargsTypedDictType = paramType;
            }
            else if (param.name) {
                if (result.kwargsIndex === undefined) {
                    result.kwargsIndex = result.params.length;
                }
                if (result.firstKeywordOnlyIndex === undefined) {
                    result.firstKeywordOnlyIndex = result.params.length;
                }
                addVirtualParameter(param, index);
            }
        }
        else if (param.category === 0 /* ParameterCategory.Simple */) {
            if (param.name && !sawKeywordOnlySeparator) {
                result.positionParamCount++;
            }
            addVirtualParameter(param, index, 
            /* typeOverride */ undefined, ((_a = type.specializedTypes) === null || _a === void 0 ? void 0 : _a.parameterDefaultArgs)
                ? (_b = type.specializedTypes) === null || _b === void 0 ? void 0 : _b.parameterDefaultArgs[index]
                : undefined);
        }
    });
    // If the signature ends in `*args: P.args, **kwargs: P.kwargs`,
    // extract the ParamSpec P.
    if (result.params.length >= 2) {
        const secondLastParam = result.params[result.params.length - 2].param;
        const lastParam = result.params[result.params.length - 1].param;
        if (secondLastParam.category === 1 /* ParameterCategory.ArgsList */ &&
            (0, types_1.isTypeVar)(secondLastParam.type) &&
            secondLastParam.type.paramSpecAccess === 'args' &&
            lastParam.category === 2 /* ParameterCategory.KwargsDict */ &&
            (0, types_1.isTypeVar)(lastParam.type) &&
            lastParam.type.paramSpecAccess === 'kwargs') {
            result.paramSpec = types_1.TypeVarType.cloneForParamSpecAccess(secondLastParam.type, undefined);
        }
    }
    result.firstPositionOrKeywordIndex = result.params.findIndex((p) => p.source !== ParameterSource.PositionOnly);
    if (result.firstPositionOrKeywordIndex < 0) {
        result.firstPositionOrKeywordIndex = result.params.length;
    }
    return result;
}
exports.getParameterListDetails = getParameterListDetails;
// Returns true if the type of the argument type is "*args: P.args" or
// "*args: Any". Both of these match a parameter of type "*args: P.args".
function isParamSpecArgsArgument(paramSpec, argType) {
    let isCompatible = true;
    (0, typeUtils_1.doForEachSubtype)(argType, (argSubtype) => {
        if ((0, types_1.isParamSpec)(argSubtype) &&
            argSubtype.paramSpecAccess === 'args' &&
            (0, types_1.isTypeSame)(argSubtype, paramSpec, { ignoreTypeFlags: true })) {
            return;
        }
        if ((0, types_1.isClassInstance)(argSubtype) &&
            argSubtype.tupleTypeArguments &&
            argSubtype.tupleTypeArguments.length === 1 &&
            argSubtype.tupleTypeArguments[0].isUnbounded &&
            (0, types_1.isAnyOrUnknown)(argSubtype.tupleTypeArguments[0].type)) {
            return;
        }
        if ((0, types_1.isAnyOrUnknown)(argSubtype)) {
            return;
        }
        isCompatible = false;
    });
    return isCompatible;
}
exports.isParamSpecArgsArgument = isParamSpecArgsArgument;
// Returns true if the type of the argument type is "**kwargs: P.kwargs" or
// "*kwargs: Any". Both of these match a parameter of type "*kwargs: P.kwargs".
function isParamSpecKwargsArgument(paramSpec, argType) {
    let isCompatible = true;
    (0, typeUtils_1.doForEachSubtype)(argType, (argSubtype) => {
        if ((0, types_1.isParamSpec)(argSubtype) &&
            argSubtype.paramSpecAccess === 'kwargs' &&
            (0, types_1.isTypeSame)(argSubtype, paramSpec, { ignoreTypeFlags: true })) {
            return;
        }
        if ((0, types_1.isClassInstance)(argSubtype) &&
            types_1.ClassType.isBuiltIn(argSubtype, 'dict') &&
            argSubtype.typeArguments &&
            argSubtype.typeArguments.length === 2 &&
            (0, types_1.isClassInstance)(argSubtype.typeArguments[0]) &&
            types_1.ClassType.isBuiltIn(argSubtype.typeArguments[0], 'str') &&
            (0, types_1.isAnyOrUnknown)(argSubtype.typeArguments[1])) {
            return;
        }
        if ((0, types_1.isAnyOrUnknown)(argSubtype)) {
            return;
        }
        isCompatible = false;
    });
    return isCompatible;
}
exports.isParamSpecKwargsArgument = isParamSpecKwargsArgument;


/***/ }),

/***/ "../pyright-internal/src/analyzer/parentDirectoryCache.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/analyzer/parentDirectoryCache.ts ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * parentDirectoryCache.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Cache to hold parent directory import result to make sure
 * we don't repeatedly search folders.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ParentDirectoryCache = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
class ParentDirectoryCache {
    constructor(_importRootGetter) {
        this._importRootGetter = _importRootGetter;
        this._importChecked = new Map();
        this._cachedResults = new Map();
        this._libPathCache = undefined;
        // empty
    }
    getImportResult(path, importName, importResult) {
        var _a, _b, _c, _d;
        const result = (_a = this._cachedResults.get(importName)) === null || _a === void 0 ? void 0 : _a.get(path.key);
        if (result) {
            // We already checked for the importName at the path.
            // Return the result if succeeded otherwise, return regular import result given.
            return result !== null && result !== void 0 ? result : importResult;
        }
        const checked = (_b = this._importChecked.get(importName)) === null || _b === void 0 ? void 0 : _b.get(path.key);
        if (checked) {
            // We already checked for the importName at the path.
            if (!checked.importPath) {
                return importResult;
            }
            return (_d = (_c = this._cachedResults.get(importName)) === null || _c === void 0 ? void 0 : _c.get(checked.importPath.key)) !== null && _d !== void 0 ? _d : importResult;
        }
        return undefined;
    }
    checkValidPath(fs, sourceFileUri, root) {
        var _a;
        if (!sourceFileUri.startsWith(root)) {
            // We don't search containing folders for libs.
            return false;
        }
        this._libPathCache =
            (_a = this._libPathCache) !== null && _a !== void 0 ? _a : this._importRootGetter()
                .map((r) => fs.realCasePath(r))
                .filter((r) => r !== root)
                .filter((r) => r.startsWith(root));
        if (this._libPathCache.some((p) => sourceFileUri.startsWith(p))) {
            // Make sure it is not lib folders under user code root.
            // ex) .venv folder
            return false;
        }
        return true;
    }
    checked(path, importName, importPath) {
        (0, collectionUtils_1.getOrAdd)(this._importChecked, importName, () => new Map()).set(path.key, importPath);
    }
    add(result) {
        (0, collectionUtils_1.getOrAdd)(this._cachedResults, result.importName, () => new Map()).set(result.path.key, result.importResult);
    }
    reset() {
        this._importChecked.clear();
        this._cachedResults.clear();
        this._libPathCache = undefined;
    }
}
exports.ParentDirectoryCache = ParentDirectoryCache;


/***/ }),

/***/ "../pyright-internal/src/analyzer/parseTreeCleaner.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/analyzer/parseTreeCleaner.ts ***!
  \************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * parseTreeCleaner.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A parse tree walker that's used to clean any analysis
 * information hanging off the parse tree. It's used when
 * dependent files have been modified and the file requires
 * reanalysis. Without this, we'd need to generate a fresh
 * parse tree from scratch.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ParseTreeCleanerWalker = void 0;
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
class ParseTreeCleanerWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(parseTree) {
        super();
        this._parseTree = parseTree;
    }
    clean() {
        this.walk(this._parseTree);
    }
    visitNode(node) {
        AnalyzerNodeInfo.cleanNodeAnalysisInfo(node);
        return super.visitNode(node);
    }
}
exports.ParseTreeCleanerWalker = ParseTreeCleanerWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/parseTreeUtils.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/parseTreeUtils.ts ***!
  \**********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * parseTreeUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility routines for traversing a parse tree.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCallNodeAndActiveParameterIndex = exports.getEnclosingParameter = exports.CallNodeWalker = exports.NameNodeWalker = exports.isAssignmentToDefaultsFollowingNamedTuple = exports.isDocString = exports.getDocString = exports.isWithinAssertExpression = exports.isWithinTryBlock = exports.isWithinLoop = exports.isWithinAnnotationComment = exports.isWithinTypeAnnotation = exports.isWithinDefaultParamInitializer = exports.isPartialMatchingExpression = exports.isMatchingExpression = exports.containsAwaitNode = exports.isSuiteEmpty = exports.isNodeContainedWithinNodeType = exports.getParentAnnotationNode = exports.getParentNodeOfType = exports.isNodeContainedWithin = exports.isRequiredAllowedForAssignmentTarget = exports.isClassVarAllowedForAssignmentTarget = exports.isFinalAllowedForAssignmentTarget = exports.getArgumentsByRuntimeOrder = exports.getTypeAnnotationNode = exports.getExecutionScopeNode = exports.getTypeVarScopeNode = exports.getEvaluationScopeNode = exports.getEvaluationNodeForAssignmentExpression = exports.getEnclosingSuiteOrModule = exports.getEnclosingClassOrFunction = exports.getEnclosingLambda = exports.getEnclosingFunctionEvaluationScope = exports.getEnclosingFunction = exports.getEnclosingClassOrModule = exports.getEnclosingModule = exports.getEnclosingClass = exports.getEnclosingSuite = exports.getDecoratorForName = exports.getCallForName = exports.printOperator = exports.printExpression = exports.printArgument = exports.getTypeSourceId = exports.getClassFullName = exports.isCompliantWithNodeRangeRules = exports.findNodeByOffset = exports.findNodeByPosition = exports.getNodeDepth = void 0;
exports.isSimpleDefault = exports.checkDecorator = exports.getTypeVarScopesForNode = exports.getScopeIdForNode = exports.getVariableDocStringNode = exports.operatorSupportsChaining = exports.isValidLocationForFutureImport = exports.isUnannotatedFunction = exports.isBlankLine = exports.getFullStatementRange = exports.getStringValueRange = exports.getStringNodeValueRange = exports.isLastNameOfDottedName = exports.isFirstNameOfDottedName = exports.getFirstNameOfDottedName = exports.getDottedName = exports.getDecoratorName = exports.getDottedNameWithGivenNodeAsLastName = exports.getFirstAncestorOrSelf = exports.getFirstAncestorOrSelfOfKind = exports.getAncestorsIncludingSelf = exports.isLastNameOfModuleName = exports.isFromImportAlias = exports.isFromImportName = exports.isFromImportModuleName = exports.isImportAlias = exports.isImportModuleName = exports.getTypeAnnotationForParameter = exports.isFunctionSuiteEmpty = exports.getFileInfoFromNode = exports.getModuleNode = exports.isWriteAccess = exports.printParseNodeType = exports.getCommentsAtTokenIndex = exports.findTokenAfter = exports.getIndexOfTokenOverlapping = exports.getTokenOverlapping = exports.getTokenAt = exports.getTokenAtIndex = exports.isWhitespace = exports.getTokenAtLeft = exports.getTokenIndexAtLeft = void 0;
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const textRangeCollection_1 = __webpack_require__(/*! ../common/textRangeCollection */ "../pyright-internal/src/common/textRangeCollection.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
// Returns the depth of the node as measured from the root
// of the parse tree.
function getNodeDepth(node) {
    let depth = 0;
    let curNode = node;
    while (curNode) {
        depth++;
        curNode = curNode.parent;
    }
    return depth;
}
exports.getNodeDepth = getNodeDepth;
// Returns the deepest node that contains the specified position.
function findNodeByPosition(node, position, lines) {
    const offset = (0, positionUtils_1.convertPositionToOffset)(position, lines);
    if (offset === undefined) {
        return undefined;
    }
    return findNodeByOffset(node, offset);
}
exports.findNodeByPosition = findNodeByPosition;
// Returns the deepest node that contains the specified offset.
function findNodeByOffset(node, offset) {
    if (offset < node.start || offset > textRange_1.TextRange.getEnd(node)) {
        return undefined;
    }
    // The range is found within this node. See if we can localize it
    // further by checking its children.
    let children = (0, parseTreeWalker_1.getChildNodes)(node);
    if (isCompliantWithNodeRangeRules(node) && children.length > 20) {
        // Use binary search to find the child to visit. This should be helpful
        // when there are many siblings, such as statements in a module/suite
        // or expressions in a list, etc. Otherwise, we will have to traverse
        // every sibling before finding the correct one.
        const index = (0, textRangeCollection_1.getIndexContaining)(children, offset);
        if (index >= 0) {
            children = [children[index]];
        }
    }
    for (const child of children) {
        if (!child) {
            continue;
        }
        const containingChild = findNodeByOffset(child, offset);
        if (containingChild) {
            // For augmented assignments, prefer the dest expression, which is a clone
            // of the left expression but is used to hold the type of the operation result.
            if (node.nodeType === 5 /* ParseNodeType.AugmentedAssignment */ && containingChild === node.leftExpression) {
                return node.destExpression;
            }
            return containingChild;
        }
    }
    return node;
}
exports.findNodeByOffset = findNodeByOffset;
function isCompliantWithNodeRangeRules(node) {
    // ParseNode range rules are
    // 1. Children are all contained within the parent.
    // 2. Children have non-overlapping ranges.
    // 3. Children are listed in increasing order.
    return node.nodeType !== 3 /* ParseNodeType.Assignment */ && node.nodeType !== 48 /* ParseNodeType.StringList */;
}
exports.isCompliantWithNodeRangeRules = isCompliantWithNodeRangeRules;
function getClassFullName(classNode, moduleName, className) {
    const nameParts = [className];
    let curNode = classNode;
    // Walk the parse tree looking for classes.
    while (curNode) {
        curNode = getEnclosingClass(curNode);
        if (curNode) {
            nameParts.push(curNode.name.value);
        }
    }
    nameParts.push(moduleName);
    return nameParts.reverse().join('.');
}
exports.getClassFullName = getClassFullName;
// Create an ID that is based on the location within the file.
// This allows us to disambiguate between different types that
// don't have unique names (those that are not created with class
// declarations).
function getTypeSourceId(node) {
    return node.start;
}
exports.getTypeSourceId = getTypeSourceId;
function printArgument(node, flags) {
    let argStr = '';
    if (node.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
        argStr = '*';
    }
    else if (node.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */) {
        argStr = '**';
    }
    if (node.name) {
        argStr += node.name.value + '=';
    }
    argStr += printExpression(node.valueExpression, flags);
    return argStr;
}
exports.printArgument = printArgument;
function printExpression(node, flags = 0 /* PrintExpressionFlags.None */) {
    switch (node.nodeType) {
        case 38 /* ParseNodeType.Name */: {
            return node.value;
        }
        case 35 /* ParseNodeType.MemberAccess */: {
            return printExpression(node.leftExpression, flags) + '.' + node.memberName.value;
        }
        case 9 /* ParseNodeType.Call */: {
            let lhs = printExpression(node.leftExpression, flags);
            // Some left-hand expressions must be parenthesized.
            if (node.leftExpression.nodeType !== 35 /* ParseNodeType.MemberAccess */ &&
                node.leftExpression.nodeType !== 38 /* ParseNodeType.Name */ &&
                node.leftExpression.nodeType !== 24 /* ParseNodeType.Index */ &&
                node.leftExpression.nodeType !== 9 /* ParseNodeType.Call */) {
                lhs = `(${lhs})`;
            }
            return lhs + '(' + node.arguments.map((arg) => printArgument(arg, flags)).join(', ') + ')';
        }
        case 24 /* ParseNodeType.Index */: {
            return (printExpression(node.baseExpression, flags) +
                '[' +
                node.items.map((item) => printArgument(item, flags)).join(', ') +
                (node.trailingComma ? ',' : '') +
                ']');
        }
        case 55 /* ParseNodeType.UnaryOperation */: {
            const exprStr = printOperator(node.operator) + printExpression(node.expression, flags);
            return node.parenthesized ? `(${exprStr})` : exprStr;
        }
        case 7 /* ParseNodeType.BinaryOperation */: {
            const exprStr = printExpression(node.leftExpression, flags) +
                ' ' +
                printOperator(node.operator) +
                ' ' +
                printExpression(node.rightExpression, flags);
            return node.parenthesized ? `(${exprStr})` : exprStr;
        }
        case 40 /* ParseNodeType.Number */: {
            let value = node.value.toString();
            // If it's stored as a bigint, strip off the "n".
            if (value.endsWith('n')) {
                value = value.substring(0, value.length - 1);
            }
            if (node.isImaginary) {
                value += 'j';
            }
            return value;
        }
        case 48 /* ParseNodeType.StringList */: {
            if (flags & 1 /* PrintExpressionFlags.ForwardDeclarations */ && node.typeAnnotation) {
                return printExpression(node.typeAnnotation, flags);
            }
            else {
                return node.strings
                    .map((str) => {
                    return printExpression(str, flags);
                })
                    .join(' ');
            }
        }
        case 49 /* ParseNodeType.String */: {
            let exprString = '';
            if (node.token.flags & 8 /* StringTokenFlags.Raw */) {
                exprString += 'r';
            }
            if (node.token.flags & 16 /* StringTokenFlags.Unicode */) {
                exprString += 'u';
            }
            if (node.token.flags & 32 /* StringTokenFlags.Bytes */) {
                exprString += 'b';
            }
            if (node.token.flags & 64 /* StringTokenFlags.Format */) {
                exprString += 'f';
            }
            let escapedString = node.token.escapedValue;
            if ((flags & 2 /* PrintExpressionFlags.DoNotLimitStringLength */) === 0) {
                const maxStringLength = 32;
                escapedString = escapedString.slice(0, maxStringLength);
            }
            if (node.token.flags & 4 /* StringTokenFlags.Triplicate */) {
                if (node.token.flags & 1 /* StringTokenFlags.SingleQuote */) {
                    exprString += `'''${escapedString}'''`;
                }
                else {
                    exprString += `"""${escapedString}"""`;
                }
            }
            else {
                if (node.token.flags & 1 /* StringTokenFlags.SingleQuote */) {
                    exprString += `'${escapedString}'`;
                }
                else {
                    exprString += `"${escapedString}"`;
                }
            }
            return exprString;
        }
        case 27 /* ParseNodeType.FormatString */: {
            let exprString = 'f';
            let escapedString = '';
            const itemsToPrint = [...node.middleTokens, ...node.fieldExpressions].sort((a, b) => a.start - b.start);
            while (itemsToPrint.length > 0) {
                const itemToPrint = itemsToPrint.shift();
                if ('nodeType' in itemToPrint) {
                    escapedString += `{${printExpression(itemToPrint)}}`;
                }
                else {
                    escapedString += itemToPrint.escapedValue;
                }
            }
            if (node.token.flags & 4 /* StringTokenFlags.Triplicate */) {
                if (node.token.flags & 1 /* StringTokenFlags.SingleQuote */) {
                    exprString += `'''${escapedString}'''`;
                }
                else {
                    exprString += `"""${escapedString}"""`;
                }
            }
            else {
                if (node.token.flags & 1 /* StringTokenFlags.SingleQuote */) {
                    exprString += `'${escapedString}'`;
                }
                else {
                    exprString += `"${escapedString}"`;
                }
            }
            return exprString;
        }
        case 3 /* ParseNodeType.Assignment */: {
            return printExpression(node.leftExpression, flags) + ' = ' + printExpression(node.rightExpression, flags);
        }
        case 4 /* ParseNodeType.AssignmentExpression */: {
            return printExpression(node.name, flags) + ' := ' + printExpression(node.rightExpression, flags);
        }
        case 54 /* ParseNodeType.TypeAnnotation */: {
            return printExpression(node.valueExpression, flags) + ': ' + printExpression(node.typeAnnotation, flags);
        }
        case 5 /* ParseNodeType.AugmentedAssignment */: {
            return (printExpression(node.leftExpression, flags) +
                ' ' +
                printOperator(node.operator) +
                ' ' +
                printExpression(node.rightExpression, flags));
        }
        case 6 /* ParseNodeType.Await */: {
            const exprStr = 'await ' + printExpression(node.expression, flags);
            return node.parenthesized ? `(${exprStr})` : exprStr;
        }
        case 51 /* ParseNodeType.Ternary */: {
            return (printExpression(node.ifExpression, flags) +
                ' if ' +
                printExpression(node.testExpression, flags) +
                ' else ' +
                printExpression(node.elseExpression, flags));
        }
        case 31 /* ParseNodeType.List */: {
            const expressions = node.entries.map((expr) => {
                return printExpression(expr, flags);
            });
            return `[${expressions.join(', ')}]`;
        }
        case 56 /* ParseNodeType.Unpack */: {
            return '*' + printExpression(node.expression, flags);
        }
        case 52 /* ParseNodeType.Tuple */: {
            const expressions = node.expressions.map((expr) => {
                return printExpression(expr, flags);
            });
            if (expressions.length === 1) {
                return `(${expressions[0]}, )`;
            }
            return `(${expressions.join(', ')})`;
        }
        case 60 /* ParseNodeType.Yield */: {
            if (node.expression) {
                return 'yield ' + printExpression(node.expression, flags);
            }
            else {
                return 'yield';
            }
        }
        case 61 /* ParseNodeType.YieldFrom */: {
            return 'yield from ' + printExpression(node.expression, flags);
        }
        case 18 /* ParseNodeType.Ellipsis */: {
            return '...';
        }
        case 32 /* ParseNodeType.ListComprehension */: {
            let listStr = '<ListExpression>';
            if ((0, parseNodes_1.isExpressionNode)(node.expression)) {
                listStr = printExpression(node.expression, flags);
            }
            else if (node.expression.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */) {
                const keyStr = printExpression(node.expression.keyExpression, flags);
                const valueStr = printExpression(node.expression.valueExpression, flags);
                listStr = `${keyStr}: ${valueStr}`;
            }
            listStr =
                listStr +
                    ' ' +
                    node.forIfNodes
                        .map((expr) => {
                        if (expr.nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
                            return (`${expr.isAsync ? 'async ' : ''}for ` +
                                printExpression(expr.targetExpression, flags) +
                                ` in ${printExpression(expr.iterableExpression, flags)}`);
                        }
                        else {
                            return `if ${printExpression(expr.testExpression, flags)}`;
                        }
                    })
                        .join(' ');
            return node.isParenthesized ? `(${listStr})` : listStr;
        }
        case 46 /* ParseNodeType.Slice */: {
            let result = '';
            if (node.startValue || node.endValue || node.stepValue) {
                if (node.startValue) {
                    result += printExpression(node.startValue, flags);
                }
                if (node.endValue) {
                    result += ': ' + printExpression(node.endValue, flags);
                }
                if (node.stepValue) {
                    result += ': ' + printExpression(node.stepValue, flags);
                }
            }
            else {
                result += ':';
            }
            return result;
        }
        case 30 /* ParseNodeType.Lambda */: {
            return ('lambda ' +
                node.parameters
                    .map((param) => {
                    let paramStr = '';
                    if (param.category === 1 /* ParameterCategory.ArgsList */) {
                        paramStr += '*';
                    }
                    else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                        paramStr += '**';
                    }
                    if (param.name) {
                        paramStr += param.name.value;
                    }
                    else if (param.category === 0 /* ParameterCategory.Simple */) {
                        paramStr += '/';
                    }
                    if (param.defaultValue) {
                        paramStr += ' = ' + printExpression(param.defaultValue, flags);
                    }
                    return paramStr;
                })
                    .join(', ') +
                ': ' +
                printExpression(node.expression, flags));
        }
        case 11 /* ParseNodeType.Constant */: {
            if (node.constType === 33 /* KeywordType.True */) {
                return 'True';
            }
            else if (node.constType === 15 /* KeywordType.False */) {
                return 'False';
            }
            else if (node.constType === 9 /* KeywordType.Debug */) {
                return '__debug__';
            }
            else if (node.constType === 26 /* KeywordType.None */) {
                return 'None';
            }
            break;
        }
        case 15 /* ParseNodeType.Dictionary */: {
            const dictContents = `${node.entries.map((entry) => {
                if (entry.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */) {
                    return (`${printExpression(entry.keyExpression, flags)}: ` +
                        `${printExpression(entry.valueExpression, flags)}`);
                }
                else if (entry.nodeType === 16 /* ParseNodeType.DictionaryExpandEntry */) {
                    return `**${printExpression(entry.expandExpression, flags)}`;
                }
                else {
                    return printExpression(entry, flags);
                }
            })}`;
            if (dictContents) {
                return `{ ${dictContents} }`;
            }
            return '{}';
        }
        case 45 /* ParseNodeType.Set */: {
            return node.entries.map((entry) => printExpression(entry, flags)).join(', ');
        }
        case 0 /* ParseNodeType.Error */: {
            return '<Parse Error>';
        }
        default: {
            (0, debug_1.assertNever)(node);
        }
    }
    return '<Expression>';
}
exports.printExpression = printExpression;
function printOperator(operator) {
    const operatorMap = {
        [0 /* OperatorType.Add */]: '+',
        [1 /* OperatorType.AddEqual */]: '+=',
        [2 /* OperatorType.Assign */]: '=',
        [3 /* OperatorType.BitwiseAnd */]: '&',
        [4 /* OperatorType.BitwiseAndEqual */]: '&=',
        [5 /* OperatorType.BitwiseInvert */]: '~',
        [6 /* OperatorType.BitwiseOr */]: '|',
        [7 /* OperatorType.BitwiseOrEqual */]: '|=',
        [8 /* OperatorType.BitwiseXor */]: '^',
        [9 /* OperatorType.BitwiseXorEqual */]: '^=',
        [10 /* OperatorType.Divide */]: '/',
        [11 /* OperatorType.DivideEqual */]: '/=',
        [12 /* OperatorType.Equals */]: '==',
        [13 /* OperatorType.FloorDivide */]: '//',
        [14 /* OperatorType.FloorDivideEqual */]: '//=',
        [15 /* OperatorType.GreaterThan */]: '>',
        [16 /* OperatorType.GreaterThanOrEqual */]: '>=',
        [17 /* OperatorType.LeftShift */]: '<<',
        [18 /* OperatorType.LeftShiftEqual */]: '<<=',
        [19 /* OperatorType.LessOrGreaterThan */]: '<>',
        [20 /* OperatorType.LessThan */]: '<',
        [21 /* OperatorType.LessThanOrEqual */]: '<=',
        [22 /* OperatorType.MatrixMultiply */]: '@',
        [23 /* OperatorType.MatrixMultiplyEqual */]: '@=',
        [24 /* OperatorType.Mod */]: '%',
        [25 /* OperatorType.ModEqual */]: '%=',
        [26 /* OperatorType.Multiply */]: '*',
        [27 /* OperatorType.MultiplyEqual */]: '*=',
        [28 /* OperatorType.NotEquals */]: '!=',
        [29 /* OperatorType.Power */]: '**',
        [30 /* OperatorType.PowerEqual */]: '**=',
        [31 /* OperatorType.RightShift */]: '>>',
        [32 /* OperatorType.RightShiftEqual */]: '>>=',
        [33 /* OperatorType.Subtract */]: '-',
        [34 /* OperatorType.SubtractEqual */]: '-=',
        [36 /* OperatorType.And */]: 'and',
        [37 /* OperatorType.Or */]: 'or',
        [38 /* OperatorType.Not */]: 'not ',
        [39 /* OperatorType.Is */]: 'is',
        [40 /* OperatorType.IsNot */]: 'is not',
        [41 /* OperatorType.In */]: 'in',
        [42 /* OperatorType.NotIn */]: 'not in',
    };
    if (operatorMap[operator]) {
        return operatorMap[operator];
    }
    return 'unknown';
}
exports.printOperator = printOperator;
// If the name node is the LHS of a call expression or is a member
// name in the LHS of a call expression, returns the call node.
function getCallForName(node) {
    var _a, _b, _c;
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 9 /* ParseNodeType.Call */ && node.parent.leftExpression === node) {
        return node.parent;
    }
    if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 35 /* ParseNodeType.MemberAccess */ &&
        node.parent.memberName === node &&
        ((_c = node.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 9 /* ParseNodeType.Call */ &&
        node.parent.parent.leftExpression === node.parent) {
        return node.parent.parent;
    }
    return undefined;
}
exports.getCallForName = getCallForName;
function getDecoratorForName(node) {
    var _a, _b, _c;
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 13 /* ParseNodeType.Decorator */ && node.parent.expression === node) {
        return node.parent;
    }
    if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 35 /* ParseNodeType.MemberAccess */ &&
        node.parent.memberName === node &&
        ((_c = node.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 13 /* ParseNodeType.Decorator */ &&
        node.parent.parent.expression === node.parent) {
        return node.parent.parent;
    }
    return undefined;
}
exports.getDecoratorForName = getDecoratorForName;
function getEnclosingSuite(node) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 50 /* ParseNodeType.Suite */) {
            return curNode;
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingSuite = getEnclosingSuite;
function getEnclosingClass(node, stopAtFunction = false) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
            return curNode;
        }
        if (curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return undefined;
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            if (stopAtFunction) {
                return undefined;
            }
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingClass = getEnclosingClass;
function getEnclosingModule(node) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return curNode;
        }
        curNode = curNode.parent;
    }
    (0, debug_1.fail)('Module node not found');
    return undefined;
}
exports.getEnclosingModule = getEnclosingModule;
function getEnclosingClassOrModule(node, stopAtFunction = false) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
            return curNode;
        }
        if (curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return curNode;
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            if (stopAtFunction) {
                return undefined;
            }
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingClassOrModule = getEnclosingClassOrModule;
function getEnclosingFunction(node) {
    let curNode = node.parent;
    let prevNode;
    while (curNode) {
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            // Don't treat a decorator as being "enclosed" in the function.
            if (!curNode.decorators.some((decorator) => decorator === prevNode)) {
                return curNode;
            }
        }
        if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
            return undefined;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingFunction = getEnclosingFunction;
// This is similar to getEnclosingFunction except that it uses evaluation
// scopes rather than the parse tree to determine whether the specified node
// is within the scope. That means if the node is within a class decorator
// (for example), it will be considered part of its parent node rather than
// the class node.
function getEnclosingFunctionEvaluationScope(node) {
    let curNode = getEvaluationScopeNode(node);
    while (curNode) {
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            return curNode;
        }
        if (curNode.nodeType === 10 /* ParseNodeType.Class */ || !curNode.parent) {
            return undefined;
        }
        curNode = getEvaluationScopeNode(curNode.parent);
    }
    return undefined;
}
exports.getEnclosingFunctionEvaluationScope = getEnclosingFunctionEvaluationScope;
function getEnclosingLambda(node) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 30 /* ParseNodeType.Lambda */) {
            return curNode;
        }
        if (curNode.nodeType === 50 /* ParseNodeType.Suite */) {
            return undefined;
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingLambda = getEnclosingLambda;
function getEnclosingClassOrFunction(node) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            return curNode;
        }
        if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
            return curNode;
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingClassOrFunction = getEnclosingClassOrFunction;
function getEnclosingSuiteOrModule(node, stopAtFunction = false, stopAtLambda = true) {
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 50 /* ParseNodeType.Suite */) {
            return curNode;
        }
        if (curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return curNode;
        }
        if (curNode.nodeType === 30 /* ParseNodeType.Lambda */) {
            if (stopAtLambda) {
                return undefined;
            }
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            if (stopAtFunction) {
                return undefined;
            }
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingSuiteOrModule = getEnclosingSuiteOrModule;
function getEvaluationNodeForAssignmentExpression(node) {
    // PEP 572 indicates that the evaluation node for an assignment expression
    // target within a list comprehension is contained within a lambda,
    // function or module, but not a class.
    let sawListComprehension = false;
    let curNode = getEvaluationScopeNode(node);
    while (curNode !== undefined) {
        switch (curNode.nodeType) {
            case 28 /* ParseNodeType.Function */:
            case 30 /* ParseNodeType.Lambda */:
            case 36 /* ParseNodeType.Module */:
                return curNode;
            case 10 /* ParseNodeType.Class */:
                return sawListComprehension ? undefined : curNode;
            case 32 /* ParseNodeType.ListComprehension */:
                sawListComprehension = true;
                curNode = getEvaluationScopeNode(curNode.parent);
                break;
            default:
                return undefined;
        }
    }
    return undefined;
}
exports.getEvaluationNodeForAssignmentExpression = getEvaluationNodeForAssignmentExpression;
// Returns the parse node corresponding to the scope that is used to evaluate
// a symbol referenced in the specified node.
function getEvaluationScopeNode(node) {
    let prevNode;
    let prevPrevNode;
    let curNode = node;
    let isParamNameNode = false;
    while (curNode) {
        if (curNode.nodeType === 41 /* ParseNodeType.Parameter */ && prevNode === curNode.name) {
            // Note that we passed through a parameter name node.
            isParamNameNode = true;
        }
        // We found a scope associated with this node. In most cases,
        // we'll return this scope, but in a few cases we need to return
        // the enclosing scope instead.
        switch (curNode.nodeType) {
            case 28 /* ParseNodeType.Function */: {
                if (curNode.parameters.some((param) => param === prevNode)) {
                    if (isParamNameNode) {
                        if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                            return curNode;
                        }
                    }
                }
                else if (prevNode === curNode.suite) {
                    if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                        return curNode;
                    }
                }
                break;
            }
            case 30 /* ParseNodeType.Lambda */: {
                if (curNode.parameters.some((param) => param === prevNode)) {
                    if (isParamNameNode) {
                        if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                            return curNode;
                        }
                    }
                }
                else if (!prevNode || prevNode === curNode.expression) {
                    if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                        return curNode;
                    }
                }
                break;
            }
            case 10 /* ParseNodeType.Class */: {
                if (prevNode === curNode.suite) {
                    if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                        return curNode;
                    }
                }
                break;
            }
            case 32 /* ParseNodeType.ListComprehension */: {
                if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                    // The iterable expression of the first subnode of a list comprehension
                    // is evaluated within the scope of its parent.
                    const isFirstIterableExpr = prevNode === curNode.forIfNodes[0] &&
                        curNode.forIfNodes[0].nodeType === 33 /* ParseNodeType.ListComprehensionFor */ &&
                        curNode.forIfNodes[0].iterableExpression === prevPrevNode;
                    if (!isFirstIterableExpr) {
                        return curNode;
                    }
                }
                break;
            }
            case 36 /* ParseNodeType.Module */: {
                if ((0, analyzerNodeInfo_1.getScope)(curNode) !== undefined) {
                    return curNode;
                }
                break;
            }
        }
        prevPrevNode = prevNode;
        prevNode = curNode;
        curNode = curNode.parent;
    }
    (0, debug_1.fail)('Did not find evaluation scope');
    return undefined;
}
exports.getEvaluationScopeNode = getEvaluationScopeNode;
// Returns the parse node corresponding to the function, class, or type alias
// that contains the specified typeVar reference.
function getTypeVarScopeNode(node) {
    let prevNode;
    let curNode = node;
    while (curNode) {
        switch (curNode.nodeType) {
            case 28 /* ParseNodeType.Function */: {
                if (!curNode.decorators.some((decorator) => decorator === prevNode)) {
                    return curNode;
                }
                break;
            }
            case 10 /* ParseNodeType.Class */: {
                if (!curNode.decorators.some((decorator) => decorator === prevNode)) {
                    return curNode;
                }
                break;
            }
            case 77 /* ParseNodeType.TypeAlias */: {
                return curNode;
            }
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getTypeVarScopeNode = getTypeVarScopeNode;
// Returns the parse node corresponding to the scope that is used
// for executing the code referenced in the specified node.
function getExecutionScopeNode(node) {
    let evaluationScope = getEvaluationScopeNode(node);
    // Classes are not considered execution scope because they are executed
    // within the context of their containing module or function. Likewise, list
    // comprehensions are executed within their container.
    while (evaluationScope.nodeType === 10 /* ParseNodeType.Class */ ||
        evaluationScope.nodeType === 32 /* ParseNodeType.ListComprehension */) {
        evaluationScope = getEvaluationScopeNode(evaluationScope.parent);
    }
    return evaluationScope;
}
exports.getExecutionScopeNode = getExecutionScopeNode;
// Given a node within a type annotation expression, returns the type annotation
// node that contains it (if applicable).
function getTypeAnnotationNode(node) {
    let prevNode = node;
    let curNode = node.parent;
    while (curNode) {
        if (curNode.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            if (curNode.typeAnnotation === prevNode) {
                return curNode;
            }
            break;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getTypeAnnotationNode = getTypeAnnotationNode;
// In general, arguments passed to a call are evaluated by the runtime in
// left-to-right order. There is one exception, however, when an unpacked
// iterable is used after a keyword argument.
function getArgumentsByRuntimeOrder(node) {
    const positionalArgs = node.arguments.filter((arg) => !arg.name && arg.argumentCategory !== 2 /* ArgumentCategory.UnpackedDictionary */);
    const keywordArgs = node.arguments.filter((arg) => !!arg.name || arg.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */);
    return positionalArgs.concat(keywordArgs);
}
exports.getArgumentsByRuntimeOrder = getArgumentsByRuntimeOrder;
// PEP 591 spells out certain limited cases where an assignment target
// can be annotated with a "Final" annotation. This function determines
// whether Final is allowed for the specified node.
function isFinalAllowedForAssignmentTarget(targetNode) {
    // Simple names always support Final.
    if (targetNode.nodeType === 38 /* ParseNodeType.Name */) {
        return true;
    }
    // Member access expressions like "self.x" are permitted only
    // within __init__ methods.
    if (targetNode.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        if (targetNode.leftExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            return false;
        }
        const classNode = getEnclosingClass(targetNode);
        if (!classNode) {
            return false;
        }
        const methodNode = getEnclosingFunction(targetNode);
        if (!methodNode) {
            return false;
        }
        if (methodNode.name.value !== '__init__') {
            return false;
        }
        return true;
    }
    return false;
}
exports.isFinalAllowedForAssignmentTarget = isFinalAllowedForAssignmentTarget;
function isClassVarAllowedForAssignmentTarget(targetNode) {
    const classNode = getEnclosingClass(targetNode, /* stopAtFunction */ true);
    if (!classNode) {
        return false;
    }
    return true;
}
exports.isClassVarAllowedForAssignmentTarget = isClassVarAllowedForAssignmentTarget;
function isRequiredAllowedForAssignmentTarget(targetNode) {
    const classNode = getEnclosingClass(targetNode, /* stopAtFunction */ true);
    if (!classNode) {
        return false;
    }
    return true;
}
exports.isRequiredAllowedForAssignmentTarget = isRequiredAllowedForAssignmentTarget;
function isNodeContainedWithin(node, potentialContainer) {
    let curNode = node;
    while (curNode) {
        if (curNode === potentialContainer) {
            return true;
        }
        curNode = curNode.parent;
    }
    return false;
}
exports.isNodeContainedWithin = isNodeContainedWithin;
function getParentNodeOfType(node, containerType) {
    let curNode = node;
    while (curNode) {
        if (curNode.nodeType === containerType) {
            return curNode;
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getParentNodeOfType = getParentNodeOfType;
// If the specified node is contained within an expression that is intended to be
// interpreted as a type annotation, this function returns the annotation node.
function getParentAnnotationNode(node) {
    let curNode = node;
    let prevNode;
    while (curNode) {
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            if (prevNode === curNode.returnTypeAnnotation) {
                return prevNode;
            }
            return undefined;
        }
        if (curNode.nodeType === 41 /* ParseNodeType.Parameter */) {
            if (prevNode === curNode.typeAnnotation || prevNode === curNode.typeAnnotationComment) {
                return prevNode;
            }
            return undefined;
        }
        if (curNode.nodeType === 3 /* ParseNodeType.Assignment */) {
            if (prevNode === curNode.typeAnnotationComment) {
                return prevNode;
            }
            return undefined;
        }
        if (curNode.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            if (prevNode === curNode.typeAnnotation) {
                return prevNode;
            }
            return undefined;
        }
        if (curNode.nodeType === 62 /* ParseNodeType.FunctionAnnotation */) {
            if (prevNode === curNode.returnTypeAnnotation || curNode.paramTypeAnnotations.some((p) => p === prevNode)) {
                (0, debug_1.assert)(!prevNode || (0, parseNodes_1.isExpressionNode)(prevNode));
                return prevNode;
            }
            return undefined;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getParentAnnotationNode = getParentAnnotationNode;
function isNodeContainedWithinNodeType(node, containerType) {
    return getParentNodeOfType(node, containerType) !== undefined;
}
exports.isNodeContainedWithinNodeType = isNodeContainedWithinNodeType;
function isSuiteEmpty(node) {
    let sawEllipsis = false;
    for (const statement of node.statements) {
        if (statement.nodeType === 47 /* ParseNodeType.StatementList */) {
            for (const substatement of statement.statements) {
                if (substatement.nodeType === 18 /* ParseNodeType.Ellipsis */) {
                    // Allow an ellipsis
                    sawEllipsis = true;
                }
                else if (substatement.nodeType === 48 /* ParseNodeType.StringList */) {
                    // Allow doc strings
                }
                else {
                    return false;
                }
            }
        }
        else {
            return false;
        }
    }
    return sawEllipsis;
}
exports.isSuiteEmpty = isSuiteEmpty;
function containsAwaitNode(node) {
    let foundAwait = false;
    class AwaitNodeWalker extends parseTreeWalker_1.ParseTreeWalker {
        visitAwait(node) {
            foundAwait = true;
            return false;
        }
    }
    const walker = new AwaitNodeWalker();
    walker.walk(node);
    return foundAwait;
}
exports.containsAwaitNode = containsAwaitNode;
function isMatchingExpression(reference, expression) {
    if (reference.nodeType === 38 /* ParseNodeType.Name */) {
        if (expression.nodeType === 38 /* ParseNodeType.Name */) {
            return reference.value === expression.value;
        }
        else if (expression.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
            return reference.value === expression.name.value;
        }
        return false;
    }
    else if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
        expression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        return (isMatchingExpression(reference.leftExpression, expression.leftExpression) &&
            reference.memberName.value === expression.memberName.value);
    }
    else if (reference.nodeType === 24 /* ParseNodeType.Index */ && expression.nodeType === 24 /* ParseNodeType.Index */) {
        if (!isMatchingExpression(reference.baseExpression, expression.baseExpression)) {
            return false;
        }
        if (expression.items.length !== 1 ||
            expression.trailingComma ||
            expression.items[0].name ||
            expression.items[0].argumentCategory !== 0 /* ArgumentCategory.Simple */) {
            return false;
        }
        const expr = reference.items[0].valueExpression;
        if (expr.nodeType === 40 /* ParseNodeType.Number */) {
            const subscriptNode = expression.items[0].valueExpression;
            if (subscriptNode.nodeType !== 40 /* ParseNodeType.Number */ ||
                subscriptNode.isImaginary ||
                !subscriptNode.isInteger) {
                return false;
            }
            return expr.value === subscriptNode.value;
        }
        if (expr.nodeType === 55 /* ParseNodeType.UnaryOperation */ &&
            expr.operator === 33 /* OperatorType.Subtract */ &&
            expr.expression.nodeType === 40 /* ParseNodeType.Number */) {
            const subscriptNode = expression.items[0].valueExpression;
            if (subscriptNode.nodeType !== 55 /* ParseNodeType.UnaryOperation */ ||
                subscriptNode.operator !== 33 /* OperatorType.Subtract */ ||
                subscriptNode.expression.nodeType !== 40 /* ParseNodeType.Number */ ||
                subscriptNode.expression.isImaginary ||
                !subscriptNode.expression.isInteger) {
                return false;
            }
            return expr.expression.value === subscriptNode.expression.value;
        }
        if (expr.nodeType === 48 /* ParseNodeType.StringList */) {
            const referenceStringListNode = expr;
            const subscriptNode = expression.items[0].valueExpression;
            if (referenceStringListNode.strings.length === 1 &&
                referenceStringListNode.strings[0].nodeType === 49 /* ParseNodeType.String */ &&
                subscriptNode.nodeType === 48 /* ParseNodeType.StringList */ &&
                subscriptNode.strings.length === 1 &&
                subscriptNode.strings[0].nodeType === 49 /* ParseNodeType.String */) {
                return referenceStringListNode.strings[0].value === subscriptNode.strings[0].value;
            }
        }
        return false;
    }
    return false;
}
exports.isMatchingExpression = isMatchingExpression;
function isPartialMatchingExpression(reference, expression) {
    if (reference.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        return (isMatchingExpression(reference.leftExpression, expression) ||
            isPartialMatchingExpression(reference.leftExpression, expression));
    }
    else if (reference.nodeType === 24 /* ParseNodeType.Index */) {
        return (isMatchingExpression(reference.baseExpression, expression) ||
            isPartialMatchingExpression(reference.baseExpression, expression));
    }
    return false;
}
exports.isPartialMatchingExpression = isPartialMatchingExpression;
function isWithinDefaultParamInitializer(node) {
    let curNode = node;
    let prevNode;
    while (curNode) {
        if (curNode.nodeType === 41 /* ParseNodeType.Parameter */ && prevNode === curNode.defaultValue) {
            return true;
        }
        if (curNode.nodeType === 30 /* ParseNodeType.Lambda */ ||
            curNode.nodeType === 28 /* ParseNodeType.Function */ ||
            curNode.nodeType === 10 /* ParseNodeType.Class */ ||
            curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return false;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinDefaultParamInitializer = isWithinDefaultParamInitializer;
function isWithinTypeAnnotation(node, requireQuotedAnnotation) {
    let curNode = node;
    let prevNode;
    let isQuoted = false;
    while (curNode) {
        if (curNode.nodeType === 41 /* ParseNodeType.Parameter */ &&
            (prevNode === curNode.typeAnnotation || prevNode === curNode.typeAnnotationComment)) {
            return isQuoted || !requireQuotedAnnotation;
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */ && prevNode === curNode.returnTypeAnnotation) {
            return isQuoted || !requireQuotedAnnotation;
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */ && prevNode === curNode.functionAnnotationComment) {
            // Type comments are always considered forward declarations even though
            // they're not "quoted".
            return true;
        }
        if (curNode.nodeType === 54 /* ParseNodeType.TypeAnnotation */ && prevNode === curNode.typeAnnotation) {
            return isQuoted || !requireQuotedAnnotation;
        }
        if (curNode.nodeType === 3 /* ParseNodeType.Assignment */ && prevNode === curNode.typeAnnotationComment) {
            // Type comments are always considered forward declarations even though
            // they're not "quoted".
            return true;
        }
        if (curNode.nodeType === 48 /* ParseNodeType.StringList */ && prevNode === curNode.typeAnnotation) {
            isQuoted = true;
        }
        if (curNode.nodeType === 30 /* ParseNodeType.Lambda */ ||
            curNode.nodeType === 28 /* ParseNodeType.Function */ ||
            curNode.nodeType === 10 /* ParseNodeType.Class */ ||
            curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return false;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinTypeAnnotation = isWithinTypeAnnotation;
function isWithinAnnotationComment(node) {
    let curNode = node;
    let prevNode;
    while (curNode) {
        if (curNode.nodeType === 28 /* ParseNodeType.Function */ && prevNode === curNode.functionAnnotationComment) {
            // Type comments are always considered forward declarations even though
            // they're not "quoted".
            return true;
        }
        if (curNode.nodeType === 3 /* ParseNodeType.Assignment */ && prevNode === curNode.typeAnnotationComment) {
            // Type comments are always considered forward declarations even though
            // they're not "quoted".
            return true;
        }
        if (curNode.nodeType === 30 /* ParseNodeType.Lambda */ ||
            curNode.nodeType === 28 /* ParseNodeType.Function */ ||
            curNode.nodeType === 10 /* ParseNodeType.Class */ ||
            curNode.nodeType === 36 /* ParseNodeType.Module */) {
            return false;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinAnnotationComment = isWithinAnnotationComment;
function isWithinLoop(node) {
    let curNode = node;
    while (curNode) {
        switch (curNode.nodeType) {
            case 26 /* ParseNodeType.For */:
            case 57 /* ParseNodeType.While */: {
                return true;
            }
            case 36 /* ParseNodeType.Module */: {
                break;
            }
        }
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinLoop = isWithinLoop;
function isWithinTryBlock(node, treatWithAsTryBlock = false) {
    let curNode = node;
    let prevNode;
    while (curNode) {
        switch (curNode.nodeType) {
            case 53 /* ParseNodeType.Try */: {
                return curNode.trySuite === prevNode;
            }
            case 58 /* ParseNodeType.With */: {
                if (treatWithAsTryBlock && curNode.suite === prevNode) {
                    return true;
                }
                break;
            }
            case 28 /* ParseNodeType.Function */:
            case 36 /* ParseNodeType.Module */:
            case 10 /* ParseNodeType.Class */: {
                return false;
            }
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinTryBlock = isWithinTryBlock;
function isWithinAssertExpression(node) {
    let curNode = node;
    let prevNode;
    while (curNode) {
        switch (curNode.nodeType) {
            case 2 /* ParseNodeType.Assert */: {
                return curNode.testExpression === prevNode;
            }
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWithinAssertExpression = isWithinAssertExpression;
function getDocString(statements) {
    // See if the first statement in the suite is a triple-quote string.
    if (statements.length === 0) {
        return undefined;
    }
    if (statements[0].nodeType !== 47 /* ParseNodeType.StatementList */) {
        return undefined;
    }
    if (!isDocString(statements[0])) {
        return undefined;
    }
    // It's up to the user to convert normalize/convert this as needed.
    const strings = statements[0].statements[0].strings;
    if (strings.length === 1) {
        return strings[0].value;
    }
    return strings.map((s) => s.value).join('');
}
exports.getDocString = getDocString;
function isDocString(statementList) {
    // If the first statement in the suite isn't a StringNode,
    // assume there is no docString.
    if (statementList.statements.length === 0 || statementList.statements[0].nodeType !== 48 /* ParseNodeType.StringList */) {
        return false;
    }
    // A docstring can consist of multiple joined strings in a single expression.
    const strings = statementList.statements[0].strings;
    if (strings.length === 0) {
        return false;
    }
    // Any f-strings invalidate the entire docstring.
    if (strings.some((n) => n.nodeType === 27 /* ParseNodeType.FormatString */)) {
        return false;
    }
    // It's up to the user to convert normalize/convert this as needed.
    return true;
}
exports.isDocString = isDocString;
// Sometimes a NamedTuple assignment statement is followed by a statement
// that looks like the following:
//    MyNamedTuple.__new__.__defaults__ = ...
// This pattern is commonly used to set the default values that are
// not specified in the original list.
function isAssignmentToDefaultsFollowingNamedTuple(callNode) {
    var _a, _b;
    if (callNode.nodeType !== 9 /* ParseNodeType.Call */ ||
        !callNode.parent ||
        callNode.parent.nodeType !== 3 /* ParseNodeType.Assignment */ ||
        callNode.parent.leftExpression.nodeType !== 38 /* ParseNodeType.Name */ ||
        !callNode.parent.parent ||
        callNode.parent.parent.nodeType !== 47 /* ParseNodeType.StatementList */) {
        return false;
    }
    const namedTupleAssignedName = callNode.parent.leftExpression.value;
    const statementList = callNode.parent.parent;
    if (statementList.statements[0] !== callNode.parent ||
        !statementList.parent ||
        !(statementList.parent.nodeType === 36 /* ParseNodeType.Module */ ||
            statementList.parent.nodeType === 50 /* ParseNodeType.Suite */)) {
        return false;
    }
    const moduleOrSuite = statementList.parent;
    let statementIndex = moduleOrSuite.statements.findIndex((s) => s === statementList);
    if (statementIndex < 0) {
        return false;
    }
    statementIndex++;
    while (statementIndex < moduleOrSuite.statements.length) {
        const nextStatement = moduleOrSuite.statements[statementIndex];
        if (nextStatement.nodeType !== 47 /* ParseNodeType.StatementList */) {
            break;
        }
        if (((_a = nextStatement.statements[0]) === null || _a === void 0 ? void 0 : _a.nodeType) === 48 /* ParseNodeType.StringList */) {
            // Skip over comments
            statementIndex++;
            continue;
        }
        if (((_b = nextStatement.statements[0]) === null || _b === void 0 ? void 0 : _b.nodeType) === 3 /* ParseNodeType.Assignment */) {
            const assignNode = nextStatement.statements[0];
            if (assignNode.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                assignNode.leftExpression.memberName.value === '__defaults__') {
                const defaultTarget = assignNode.leftExpression.leftExpression;
                if (defaultTarget.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                    defaultTarget.memberName.value === '__new__' &&
                    defaultTarget.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                    defaultTarget.leftExpression.value === namedTupleAssignedName) {
                    return true;
                }
            }
        }
        break;
    }
    return false;
}
exports.isAssignmentToDefaultsFollowingNamedTuple = isAssignmentToDefaultsFollowingNamedTuple;
// This simple parse tree walker calls a callback function
// for each NameNode it encounters.
class NameNodeWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_callback) {
        super();
        this._callback = _callback;
    }
    visitName(node) {
        this._callback(node, this._subscriptIndex, this._baseExpression);
        return true;
    }
    visitIndex(node) {
        this.walk(node.baseExpression);
        const prevSubscriptIndex = this._subscriptIndex;
        const prevBaseExpression = this._baseExpression;
        this._baseExpression = node.baseExpression;
        node.items.forEach((item, index) => {
            this._subscriptIndex = index;
            this.walk(item);
        });
        this._subscriptIndex = prevSubscriptIndex;
        this._baseExpression = prevBaseExpression;
        return false;
    }
}
exports.NameNodeWalker = NameNodeWalker;
class CallNodeWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_callback) {
        super();
        this._callback = _callback;
    }
    visitCall(node) {
        this._callback(node);
        return true;
    }
}
exports.CallNodeWalker = CallNodeWalker;
function getEnclosingParameter(node) {
    let curNode = node;
    while (curNode) {
        if (curNode.nodeType === 41 /* ParseNodeType.Parameter */) {
            return curNode;
        }
        if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
            return undefined;
        }
        curNode = curNode.parent;
    }
    return undefined;
}
exports.getEnclosingParameter = getEnclosingParameter;
function getCallNodeAndActiveParameterIndex(node, insertionOffset, tokens) {
    // Find the call node that contains the specified node.
    let curNode = node;
    let callNode;
    while (curNode !== undefined) {
        // make sure we only look at callNodes when we are inside their arguments
        if (curNode.nodeType === 9 /* ParseNodeType.Call */) {
            if (isOffsetInsideCallArgs(tokens, curNode, insertionOffset)) {
                callNode = curNode;
                break;
            }
        }
        curNode = curNode.parent;
    }
    if (!callNode || !callNode.arguments) {
        return undefined;
    }
    const endPosition = textRange_1.TextRange.getEnd(callNode);
    if (insertionOffset > endPosition) {
        return undefined;
    }
    const tokenAtEnd = getTokenAt(tokens, endPosition - 1);
    if (insertionOffset === endPosition && (tokenAtEnd === null || tokenAtEnd === void 0 ? void 0 : tokenAtEnd.type) === 14 /* TokenType.CloseParenthesis */) {
        return undefined;
    }
    let addedActive = false;
    let activeIndex = -1;
    let activeOrFake = false;
    callNode.arguments.forEach((arg, index) => {
        if (addedActive) {
            return;
        }
        // Calculate the argument's bounds including whitespace and colons.
        let start = arg.start;
        const startTokenIndex = tokens.getItemAtPosition(start);
        if (startTokenIndex >= 0) {
            start = textRange_1.TextRange.getEnd(tokens.getItemAt(startTokenIndex - 1));
        }
        let end = textRange_1.TextRange.getEnd(arg);
        const endTokenIndex = tokens.getItemAtPosition(end);
        if (endTokenIndex >= 0) {
            // Find the true end of the argument by searching for the
            // terminating comma or parenthesis.
            for (let i = endTokenIndex; i < tokens.count; i++) {
                const tok = tokens.getItemAt(i);
                switch (tok.type) {
                    case 12 /* TokenType.Comma */:
                    case 14 /* TokenType.CloseParenthesis */:
                        break;
                    default:
                        continue;
                }
                end = textRange_1.TextRange.getEnd(tok);
                break;
            }
        }
        if (insertionOffset < end) {
            activeIndex = index;
            activeOrFake = insertionOffset >= start;
            addedActive = true;
        }
    });
    if (!addedActive) {
        activeIndex = callNode.arguments.length + 1;
    }
    return {
        callNode,
        activeIndex,
        activeOrFake,
    };
    function isOffsetInsideCallArgs(tokens, node, offset) {
        const argumentStart = node.leftExpression.length > 0 ? textRange_1.TextRange.getEnd(node.leftExpression) - 1 : node.leftExpression.start;
        // Handle obvious case first.
        const callEndOffset = textRange_1.TextRange.getEnd(node);
        if (offset < argumentStart || callEndOffset < offset) {
            return false;
        }
        if (node.arguments.length > 0) {
            const start = node.arguments[0].start;
            const end = textRange_1.TextRange.getEnd(node.arguments[node.arguments.length - 1]);
            if (start <= offset && offset < end) {
                return true;
            }
        }
        const index = tokens.getItemAtPosition(argumentStart);
        if (index < 0 || tokens.count <= index) {
            return true;
        }
        const nextToken = tokens.getItemAt(index + 1);
        if (nextToken.type === 13 /* TokenType.OpenParenthesis */ && offset < textRange_1.TextRange.getEnd(nextToken)) {
            // Position must be after '('.
            return false;
        }
        return true;
    }
}
exports.getCallNodeAndActiveParameterIndex = getCallNodeAndActiveParameterIndex;
function getTokenIndexAtLeft(tokens, position, includeWhitespace = false, includeZeroLengthToken = false) {
    const index = tokens.getItemAtPosition(position);
    if (index < 0) {
        return -1;
    }
    for (let i = index; i >= 0; i--) {
        const token = tokens.getItemAt(i);
        if (!includeZeroLengthToken && token.length === 0) {
            continue;
        }
        if (!includeWhitespace && isWhitespace(token)) {
            continue;
        }
        if (textRange_1.TextRange.getEnd(token) <= position) {
            return i;
        }
    }
    return -1;
}
exports.getTokenIndexAtLeft = getTokenIndexAtLeft;
function getTokenAtLeft(tokens, position, includeWhitespace = false, includeZeroLengthToken = false) {
    const index = getTokenIndexAtLeft(tokens, position, includeWhitespace, includeZeroLengthToken);
    if (index < 0) {
        return undefined;
    }
    return tokens.getItemAt(index);
}
exports.getTokenAtLeft = getTokenAtLeft;
function isWhitespace(token) {
    return token.type === 2 /* TokenType.NewLine */ || token.type === 3 /* TokenType.Indent */ || token.type === 4 /* TokenType.Dedent */;
}
exports.isWhitespace = isWhitespace;
function getTokenAtIndex(tokens, index) {
    if (index < 0) {
        return undefined;
    }
    return tokens.getItemAt(index);
}
exports.getTokenAtIndex = getTokenAtIndex;
function getTokenAt(tokens, position) {
    return getTokenAtIndex(tokens, tokens.getItemAtPosition(position));
}
exports.getTokenAt = getTokenAt;
function getTokenOverlapping(tokens, position) {
    const index = getIndexOfTokenOverlapping(tokens, position);
    return getTokenAtIndex(tokens, index);
}
exports.getTokenOverlapping = getTokenOverlapping;
function getIndexOfTokenOverlapping(tokens, position) {
    const index = tokens.getItemAtPosition(position);
    if (index < 0) {
        return -1;
    }
    const token = tokens.getItemAt(index);
    return textRange_1.TextRange.overlaps(token, position) ? index : -1;
}
exports.getIndexOfTokenOverlapping = getIndexOfTokenOverlapping;
function findTokenAfter(tokenizerOutput, offset, predicate) {
    const tokens = tokenizerOutput.tokens;
    const index = tokens.getItemAtPosition(offset);
    if (index < 0) {
        return undefined;
    }
    for (let i = index; i < tokens.length; i++) {
        const token = tokens.getItemAt(i);
        if (predicate(token)) {
            return token;
        }
    }
    return undefined;
}
exports.findTokenAfter = findTokenAfter;
function getCommentsAtTokenIndex(tokens, index) {
    let token = getTokenAtIndex(tokens, index);
    if (!token) {
        return undefined;
    }
    // If the preceding token has the same start offset
    // (in other words, when tokens have zero length and they're piled on top of each other)
    // look back through the tokens until we find the first token with that start offset.
    // That's where the comments (if any) will be.
    for (let precedingIndex = index - 1; precedingIndex >= 0; --precedingIndex) {
        const precedingToken = getTokenAtIndex(tokens, precedingIndex);
        if (precedingToken && precedingToken.start === token.start) {
            token = precedingToken;
        }
        else {
            break;
        }
    }
    return token.comments;
}
exports.getCommentsAtTokenIndex = getCommentsAtTokenIndex;
function printParseNodeType(type) {
    switch (type) {
        case 0 /* ParseNodeType.Error */:
            return 'Error';
        case 1 /* ParseNodeType.Argument */:
            return 'Argument';
        case 2 /* ParseNodeType.Assert */:
            return 'Assert';
        case 3 /* ParseNodeType.Assignment */:
            return 'Assignment';
        case 4 /* ParseNodeType.AssignmentExpression */:
            return 'AssignmentExpression';
        case 5 /* ParseNodeType.AugmentedAssignment */:
            return 'AugmentedAssignment';
        case 6 /* ParseNodeType.Await */:
            return 'Await';
        case 7 /* ParseNodeType.BinaryOperation */:
            return 'BinaryOperation';
        case 8 /* ParseNodeType.Break */:
            return 'Break';
        case 9 /* ParseNodeType.Call */:
            return 'Call';
        case 10 /* ParseNodeType.Class */:
            return 'Class';
        case 11 /* ParseNodeType.Constant */:
            return 'Constant';
        case 12 /* ParseNodeType.Continue */:
            return 'Continue';
        case 13 /* ParseNodeType.Decorator */:
            return 'Decorator';
        case 14 /* ParseNodeType.Del */:
            return 'Del';
        case 15 /* ParseNodeType.Dictionary */:
            return 'Dictionary';
        case 16 /* ParseNodeType.DictionaryExpandEntry */:
            return 'DictionaryExpandEntry';
        case 17 /* ParseNodeType.DictionaryKeyEntry */:
            return 'DictionaryKeyEntry';
        case 18 /* ParseNodeType.Ellipsis */:
            return 'Ellipsis';
        case 19 /* ParseNodeType.If */:
            return 'If';
        case 20 /* ParseNodeType.Import */:
            return 'Import';
        case 21 /* ParseNodeType.ImportAs */:
            return 'ImportAs';
        case 22 /* ParseNodeType.ImportFrom */:
            return 'ImportFrom';
        case 23 /* ParseNodeType.ImportFromAs */:
            return 'ImportFromAs';
        case 24 /* ParseNodeType.Index */:
            return 'Index';
        case 25 /* ParseNodeType.Except */:
            return 'Except';
        case 26 /* ParseNodeType.For */:
            return 'For';
        case 27 /* ParseNodeType.FormatString */:
            return 'FormatString';
        case 28 /* ParseNodeType.Function */:
            return 'Function';
        case 29 /* ParseNodeType.Global */:
            return 'Global';
        case 30 /* ParseNodeType.Lambda */:
            return 'Lambda';
        case 31 /* ParseNodeType.List */:
            return 'List';
        case 32 /* ParseNodeType.ListComprehension */:
            return 'ListComprehension';
        case 33 /* ParseNodeType.ListComprehensionFor */:
            return 'ListComprehensionFor';
        case 34 /* ParseNodeType.ListComprehensionIf */:
            return 'ListComprehensionIf';
        case 35 /* ParseNodeType.MemberAccess */:
            return 'MemberAccess';
        case 36 /* ParseNodeType.Module */:
            return 'Module';
        case 37 /* ParseNodeType.ModuleName */:
            return 'ModuleName';
        case 38 /* ParseNodeType.Name */:
            return 'Name';
        case 39 /* ParseNodeType.Nonlocal */:
            return 'Nonlocal';
        case 40 /* ParseNodeType.Number */:
            return 'Number';
        case 41 /* ParseNodeType.Parameter */:
            return 'Parameter';
        case 42 /* ParseNodeType.Pass */:
            return 'Pass';
        case 43 /* ParseNodeType.Raise */:
            return 'Raise';
        case 44 /* ParseNodeType.Return */:
            return 'Return';
        case 45 /* ParseNodeType.Set */:
            return 'Set';
        case 46 /* ParseNodeType.Slice */:
            return 'Slice';
        case 47 /* ParseNodeType.StatementList */:
            return 'StatementList';
        case 48 /* ParseNodeType.StringList */:
            return 'StringList';
        case 49 /* ParseNodeType.String */:
            return 'String';
        case 50 /* ParseNodeType.Suite */:
            return 'Suite';
        case 51 /* ParseNodeType.Ternary */:
            return 'Ternary';
        case 52 /* ParseNodeType.Tuple */:
            return 'Tuple';
        case 53 /* ParseNodeType.Try */:
            return 'Try';
        case 54 /* ParseNodeType.TypeAnnotation */:
            return 'TypeAnnotation';
        case 55 /* ParseNodeType.UnaryOperation */:
            return 'UnaryOperation';
        case 56 /* ParseNodeType.Unpack */:
            return 'Unpack';
        case 57 /* ParseNodeType.While */:
            return 'While';
        case 58 /* ParseNodeType.With */:
            return 'With';
        case 59 /* ParseNodeType.WithItem */:
            return 'WithItem';
        case 60 /* ParseNodeType.Yield */:
            return 'Yield';
        case 61 /* ParseNodeType.YieldFrom */:
            return 'YieldFrom';
        case 62 /* ParseNodeType.FunctionAnnotation */:
            return 'FunctionAnnotation';
        case 63 /* ParseNodeType.Match */:
            return 'Match';
        case 64 /* ParseNodeType.Case */:
            return 'Case';
        case 65 /* ParseNodeType.PatternSequence */:
            return 'PatternSequence';
        case 66 /* ParseNodeType.PatternAs */:
            return 'PatternAs';
        case 67 /* ParseNodeType.PatternLiteral */:
            return 'PatternLiteral';
        case 68 /* ParseNodeType.PatternClass */:
            return 'PatternClass';
        case 69 /* ParseNodeType.PatternCapture */:
            return 'PatternCapture';
        case 70 /* ParseNodeType.PatternMapping */:
            return 'PatternMapping';
        case 71 /* ParseNodeType.PatternMappingKeyEntry */:
            return 'PatternMappingKeyEntry';
        case 72 /* ParseNodeType.PatternMappingExpandEntry */:
            return 'PatternMappingExpandEntry';
        case 73 /* ParseNodeType.PatternValue */:
            return 'PatternValue';
        case 74 /* ParseNodeType.PatternClassArgument */:
            return 'PatternClassArgument';
        case 75 /* ParseNodeType.TypeParameter */:
            return 'TypeParameter';
        case 76 /* ParseNodeType.TypeParameterList */:
            return 'TypeParameterList';
        case 77 /* ParseNodeType.TypeAlias */:
            return 'TypeAlias';
    }
    (0, debug_1.assertNever)(type);
}
exports.printParseNodeType = printParseNodeType;
function isWriteAccess(node) {
    let prevNode = node;
    let curNode = prevNode.parent;
    while (curNode) {
        switch (curNode.nodeType) {
            case 3 /* ParseNodeType.Assignment */: {
                return prevNode === curNode.leftExpression;
            }
            case 5 /* ParseNodeType.AugmentedAssignment */: {
                return prevNode === curNode.leftExpression;
            }
            case 4 /* ParseNodeType.AssignmentExpression */: {
                return prevNode === curNode.name;
            }
            case 14 /* ParseNodeType.Del */: {
                return true;
            }
            case 26 /* ParseNodeType.For */: {
                return prevNode === curNode.targetExpression;
            }
            case 21 /* ParseNodeType.ImportAs */: {
                return (prevNode === curNode.alias ||
                    (curNode.module.nameParts.length > 0 && prevNode === curNode.module.nameParts[0]));
            }
            case 23 /* ParseNodeType.ImportFromAs */: {
                return prevNode === curNode.alias || (!curNode.alias && prevNode === curNode.name);
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                if (prevNode !== curNode.memberName) {
                    return false;
                }
                break;
            }
            case 25 /* ParseNodeType.Except */: {
                return prevNode === curNode.name;
            }
            case 58 /* ParseNodeType.With */: {
                return curNode.withItems.some((item) => item === prevNode);
            }
            case 33 /* ParseNodeType.ListComprehensionFor */: {
                return prevNode === curNode.targetExpression;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                if (prevNode === curNode.typeAnnotation) {
                    return false;
                }
                break;
            }
            case 28 /* ParseNodeType.Function */:
            case 10 /* ParseNodeType.Class */:
            case 36 /* ParseNodeType.Module */: {
                return false;
            }
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return false;
}
exports.isWriteAccess = isWriteAccess;
function getModuleNode(node) {
    let current = node;
    while (current && current.nodeType !== 36 /* ParseNodeType.Module */) {
        current = current.parent;
    }
    return current;
}
exports.getModuleNode = getModuleNode;
function getFileInfoFromNode(node) {
    const current = getModuleNode(node);
    return current ? AnalyzerNodeInfo.getFileInfo(current) : undefined;
}
exports.getFileInfoFromNode = getFileInfoFromNode;
function isFunctionSuiteEmpty(node) {
    let isEmpty = true;
    node.suite.statements.forEach((statement) => {
        if (statement.nodeType === 0 /* ParseNodeType.Error */) {
            return;
        }
        else if (statement.nodeType === 47 /* ParseNodeType.StatementList */) {
            statement.statements.forEach((subStatement) => {
                // Allow docstrings, ellipsis, and pass statements.
                if (subStatement.nodeType !== 18 /* ParseNodeType.Ellipsis */ &&
                    subStatement.nodeType !== 48 /* ParseNodeType.StringList */ &&
                    subStatement.nodeType !== 42 /* ParseNodeType.Pass */) {
                    isEmpty = false;
                }
            });
        }
        else {
            isEmpty = false;
        }
    });
    return isEmpty;
}
exports.isFunctionSuiteEmpty = isFunctionSuiteEmpty;
function getTypeAnnotationForParameter(node, paramIndex) {
    if (paramIndex >= node.parameters.length) {
        return undefined;
    }
    const param = node.parameters[paramIndex];
    if (param.typeAnnotation) {
        return param.typeAnnotation;
    }
    else if (param.typeAnnotationComment) {
        return param.typeAnnotationComment;
    }
    if (!node.functionAnnotationComment || node.functionAnnotationComment.isParamListEllipsis) {
        return undefined;
    }
    let firstCommentAnnotationIndex = 0;
    const paramAnnotations = node.functionAnnotationComment.paramTypeAnnotations;
    if (paramAnnotations.length < node.parameters.length) {
        firstCommentAnnotationIndex = 1;
    }
    const adjIndex = paramIndex - firstCommentAnnotationIndex;
    if (adjIndex < 0 || adjIndex >= paramAnnotations.length) {
        return undefined;
    }
    return paramAnnotations[adjIndex];
}
exports.getTypeAnnotationForParameter = getTypeAnnotationForParameter;
function isImportModuleName(node) {
    var _a, _b;
    return ((_b = (_a = getFirstAncestorOrSelfOfKind(node, 37 /* ParseNodeType.ModuleName */)) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 21 /* ParseNodeType.ImportAs */;
}
exports.isImportModuleName = isImportModuleName;
function isImportAlias(node) {
    var _a;
    return ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 21 /* ParseNodeType.ImportAs */ && node.parent.alias === node;
}
exports.isImportAlias = isImportAlias;
function isFromImportModuleName(node) {
    var _a, _b;
    return ((_b = (_a = getFirstAncestorOrSelfOfKind(node, 37 /* ParseNodeType.ModuleName */)) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 22 /* ParseNodeType.ImportFrom */;
}
exports.isFromImportModuleName = isFromImportModuleName;
function isFromImportName(node) {
    var _a;
    return ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 23 /* ParseNodeType.ImportFromAs */ && node.parent.name === node;
}
exports.isFromImportName = isFromImportName;
function isFromImportAlias(node) {
    var _a;
    return ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 23 /* ParseNodeType.ImportFromAs */ && node.parent.alias === node;
}
exports.isFromImportAlias = isFromImportAlias;
function isLastNameOfModuleName(node) {
    var _a;
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 37 /* ParseNodeType.ModuleName */) {
        return false;
    }
    const module = node.parent;
    if (module.nameParts.length === 0) {
        return false;
    }
    return module.nameParts[module.nameParts.length - 1] === node;
}
exports.isLastNameOfModuleName = isLastNameOfModuleName;
function* getAncestorsIncludingSelf(node) {
    while (node !== undefined) {
        yield node;
        node = node.parent;
    }
}
exports.getAncestorsIncludingSelf = getAncestorsIncludingSelf;
function getFirstAncestorOrSelfOfKind(node, type) {
    return getFirstAncestorOrSelf(node, (n) => n.nodeType === type);
}
exports.getFirstAncestorOrSelfOfKind = getFirstAncestorOrSelfOfKind;
function getFirstAncestorOrSelf(node, predicate) {
    for (const current of getAncestorsIncludingSelf(node)) {
        if (predicate(current)) {
            return current;
        }
    }
    return undefined;
}
exports.getFirstAncestorOrSelf = getFirstAncestorOrSelf;
function getDottedNameWithGivenNodeAsLastName(node) {
    var _a;
    // Shape of dotted name is
    //    MemberAccess (ex, a.b)
    //  Name        Name
    // or
    //           MemberAccess (ex, a.b.c)
    //    MemberAccess     Name
    //  Name       Name
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 35 /* ParseNodeType.MemberAccess */) {
        return node;
    }
    if (node.parent.leftExpression === node) {
        return node;
    }
    return node.parent;
}
exports.getDottedNameWithGivenNodeAsLastName = getDottedNameWithGivenNodeAsLastName;
//
// Returns the dotted name that makes up the expression for the decorator.
// Example:
// @pytest.fixture()
// def my_fixture():
//    pass
//
// would return `pytest.fixture`
function getDecoratorName(decorator) {
    function getExpressionName(node) {
        var _a;
        if (node.nodeType === 38 /* ParseNodeType.Name */ || node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            return (_a = getDottedName(node)) === null || _a === void 0 ? void 0 : _a.map((n) => n.value).join('.');
        }
        if (node.nodeType === 9 /* ParseNodeType.Call */) {
            return getExpressionName(node.leftExpression);
        }
        return undefined;
    }
    return getExpressionName(decorator.expression);
}
exports.getDecoratorName = getDecoratorName;
function getDottedName(node) {
    // ex) [a] or [a].b
    // simple case, [a]
    if (node.nodeType === 38 /* ParseNodeType.Name */) {
        return [node];
    }
    // dotted name case.
    const names = [];
    if (_getDottedName(node, names)) {
        return names.reverse();
    }
    return undefined;
    function _getDottedName(node, names) {
        if (node.nodeType === 38 /* ParseNodeType.Name */) {
            names.push(node);
            return true;
        }
        names.push(node.memberName);
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ ||
            node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            return _getDottedName(node.leftExpression, names);
        }
        return false;
    }
}
exports.getDottedName = getDottedName;
function getFirstNameOfDottedName(node) {
    // ex) [a] or [a].b
    if (node.nodeType === 38 /* ParseNodeType.Name */) {
        return node;
    }
    if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ ||
        node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        return getFirstNameOfDottedName(node.leftExpression);
    }
    return undefined;
}
exports.getFirstNameOfDottedName = getFirstNameOfDottedName;
function isFirstNameOfDottedName(node) {
    var _a;
    // ex) [A] or [A].B.C.D
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 35 /* ParseNodeType.MemberAccess */) {
        return true;
    }
    if (node.parent.leftExpression === node) {
        return true;
    }
    return false;
}
exports.isFirstNameOfDottedName = isFirstNameOfDottedName;
function isLastNameOfDottedName(node) {
    var _a, _b;
    // ex) A or D.C.B.[A]
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 35 /* ParseNodeType.MemberAccess */) {
        return true;
    }
    if (node.parent.leftExpression.nodeType !== 38 /* ParseNodeType.Name */ &&
        node.parent.leftExpression.nodeType !== 35 /* ParseNodeType.MemberAccess */) {
        return false;
    }
    if (node.parent.leftExpression === node) {
        return false;
    }
    return ((_b = node.parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) !== 35 /* ParseNodeType.MemberAccess */;
}
exports.isLastNameOfDottedName = isLastNameOfDottedName;
function getStringNodeValueRange(node) {
    return getStringValueRange(node.token);
}
exports.getStringNodeValueRange = getStringNodeValueRange;
function getStringValueRange(token) {
    const length = token.quoteMarkLength;
    const hasEnding = !(token.flags & 65536 /* StringTokenFlags.Unterminated */);
    return textRange_1.TextRange.create(token.start + length, token.length - length - (hasEnding ? length : 0));
}
exports.getStringValueRange = getStringValueRange;
function getFullStatementRange(statementNode, parseFileResults, options) {
    var _a;
    const range = (0, positionUtils_1.convertTextRangeToRange)(statementNode, parseFileResults.tokenizerOutput.lines);
    const start = (_a = _getStartPositionIfMultipleStatementsAreOnSameLine(range, statementNode.start, parseFileResults.tokenizerOutput)) !== null && _a !== void 0 ? _a : {
        line: range.start.line,
        character: 0,
    };
    // First, see whether there are other tokens except semicolon or new line on the same line.
    const end = _getEndPositionIfMultipleStatementsAreOnSameLine(range, textRange_1.TextRange.getEnd(statementNode), parseFileResults.tokenizerOutput);
    if (end) {
        return { start, end };
    }
    // If not, delete the whole line.
    if (range.end.line === parseFileResults.tokenizerOutput.lines.count - 1) {
        return { start, end: range.end };
    }
    let lineDeltaToAdd = 1;
    if (options) {
        if (options.includeTrailingBlankLines) {
            for (let i = lineDeltaToAdd; range.end.line + i < parseFileResults.tokenizerOutput.lines.count; i++) {
                if (!isBlankLine(parseFileResults.tokenizerOutput, parseFileResults.text, range.end.line + i)) {
                    lineDeltaToAdd = i;
                    break;
                }
            }
        }
    }
    return { start, end: { line: range.end.line + lineDeltaToAdd, character: 0 } };
}
exports.getFullStatementRange = getFullStatementRange;
function isBlankLine(tokenizerOutput, text, line) {
    const span = tokenizerOutput.lines.getItemAt(line);
    return (0, core_1.containsOnlyWhitespace)(text, span);
}
exports.isBlankLine = isBlankLine;
function isUnannotatedFunction(node) {
    return (node.returnTypeAnnotation === undefined &&
        node.parameters.every((param) => param.typeAnnotation === undefined && param.typeAnnotationComment === undefined));
}
exports.isUnannotatedFunction = isUnannotatedFunction;
// Verifies that an import of the form "from __future__ import x"
// occurs only at the top of a file. This mirrors the algorithm used
// in the CPython interpreter.
function isValidLocationForFutureImport(node) {
    const module = getModuleNode(node);
    (0, debug_1.assert)(module);
    let sawDocString = false;
    for (const statement of module.statements) {
        if (statement.nodeType !== 47 /* ParseNodeType.StatementList */) {
            return false;
        }
        for (const simpleStatement of statement.statements) {
            if (simpleStatement === node) {
                return true;
            }
            if (simpleStatement.nodeType === 48 /* ParseNodeType.StringList */) {
                if (sawDocString) {
                    return false;
                }
                sawDocString = true;
            }
            else if (simpleStatement.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                if (simpleStatement.module.leadingDots !== 0 ||
                    simpleStatement.module.nameParts.length !== 1 ||
                    simpleStatement.module.nameParts[0].value !== '__future__') {
                    return false;
                }
            }
            else {
                return false;
            }
        }
    }
    return false;
}
exports.isValidLocationForFutureImport = isValidLocationForFutureImport;
// "Chaining" is when binary operators can be chained together
// as a shorthand. For example, "a < b < c" is shorthand for
// "a < b and b < c".
function operatorSupportsChaining(op) {
    switch (op) {
        case 12 /* OperatorType.Equals */:
        case 28 /* OperatorType.NotEquals */:
        case 20 /* OperatorType.LessThan */:
        case 21 /* OperatorType.LessThanOrEqual */:
        case 15 /* OperatorType.GreaterThan */:
        case 16 /* OperatorType.GreaterThanOrEqual */:
        case 39 /* OperatorType.Is */:
        case 40 /* OperatorType.IsNot */:
        case 41 /* OperatorType.In */:
        case 42 /* OperatorType.NotIn */:
            return true;
    }
    return false;
}
exports.operatorSupportsChaining = operatorSupportsChaining;
// If the statement is a part of multiple statements on the same line
// and the statement is not the first statement on the line, then it will return
// appropriate start position. otherwise, return undefined.
// ex) a = 1; [|b = 1|]
function _getStartPositionIfMultipleStatementsAreOnSameLine(range, tokenPosition, tokenizerOutput) {
    const tokenIndex = tokenizerOutput.tokens.getItemAtPosition(tokenPosition);
    if (tokenIndex < 0) {
        return undefined;
    }
    // Find the last token index on the previous line or the first token.
    let currentIndex = tokenIndex;
    for (; currentIndex > 0; currentIndex--) {
        const token = tokenizerOutput.tokens.getItemAt(currentIndex);
        const tokenRange = (0, positionUtils_1.convertTextRangeToRange)(token, tokenizerOutput.lines);
        if (tokenRange.end.line !== range.start.line) {
            break;
        }
    }
    // Find the previous token of the first token of the statement.
    for (let index = tokenIndex - 1; index > currentIndex; index--) {
        const token = tokenizerOutput.tokens.getItemAt(index);
        // Eat up indentation
        if (token.type === 3 /* TokenType.Indent */ || token.type === 4 /* TokenType.Dedent */) {
            continue;
        }
        // If previous token is new line, use default.
        if (token.type === 2 /* TokenType.NewLine */) {
            return undefined;
        }
        // Anything else (ex, semicolon), use statement start as it is.
        return range.start;
    }
    return undefined;
}
// If the statement is a part of multiple statements on the same line
// and the statement is not the last statement on the line, then it will return
// appropriate end position. otherwise, return undefined.
// ex) [|a = 1|]; b = 1
function _getEndPositionIfMultipleStatementsAreOnSameLine(range, tokenPosition, tokenizerOutput) {
    const tokenIndex = tokenizerOutput.tokens.getItemAtPosition(tokenPosition);
    if (tokenIndex < 0) {
        return undefined;
    }
    // Find the first token index on the next line or the last token.
    let currentIndex = tokenIndex;
    for (; currentIndex < tokenizerOutput.tokens.count; currentIndex++) {
        const token = tokenizerOutput.tokens.getItemAt(currentIndex);
        const tokenRange = (0, positionUtils_1.convertTextRangeToRange)(token, tokenizerOutput.lines);
        if (range.end.line !== tokenRange.start.line) {
            break;
        }
    }
    // Find the next token of the last token of the statement.
    let foundStatementEnd = false;
    for (let index = tokenIndex; index < currentIndex; index++) {
        const token = tokenizerOutput.tokens.getItemAt(index);
        // Eat up semicolon or new line.
        if (token.type === 11 /* TokenType.Semicolon */ || token.type === 2 /* TokenType.NewLine */) {
            foundStatementEnd = true;
            continue;
        }
        if (!foundStatementEnd) {
            continue;
        }
        const tokenRange = (0, positionUtils_1.convertTextRangeToRange)(token, tokenizerOutput.lines);
        return tokenRange.start;
    }
    return undefined;
}
function getVariableDocStringNode(node) {
    var _a, _b, _c, _d;
    // Walk up the parse tree to find an assignment or type alias statement.
    let curNode = node;
    let annotationNode;
    while (curNode) {
        if (curNode.nodeType === 3 /* ParseNodeType.Assignment */) {
            break;
        }
        if (curNode.nodeType === 77 /* ParseNodeType.TypeAlias */) {
            break;
        }
        if (curNode.nodeType === 54 /* ParseNodeType.TypeAnnotation */ && !annotationNode) {
            annotationNode = curNode;
        }
        curNode = curNode.parent;
    }
    if ((curNode === null || curNode === void 0 ? void 0 : curNode.nodeType) !== 3 /* ParseNodeType.Assignment */ && (curNode === null || curNode === void 0 ? void 0 : curNode.nodeType) !== 77 /* ParseNodeType.TypeAlias */) {
        // Allow a simple annotation statement to have a docstring even
        // though PEP 258 doesn't mention this case. This PEP pre-dated
        // PEP 526, so it didn't contemplate this situation.
        if (annotationNode) {
            curNode = annotationNode;
        }
        else {
            return undefined;
        }
    }
    const parentNode = curNode.parent;
    if ((parentNode === null || parentNode === void 0 ? void 0 : parentNode.nodeType) !== 47 /* ParseNodeType.StatementList */) {
        return undefined;
    }
    const suiteOrModule = parentNode.parent;
    if (!suiteOrModule ||
        (suiteOrModule.nodeType !== 36 /* ParseNodeType.Module */ && suiteOrModule.nodeType !== 50 /* ParseNodeType.Suite */)) {
        return undefined;
    }
    const assignmentIndex = suiteOrModule.statements.findIndex((node) => node === parentNode);
    if (assignmentIndex < 0 || assignmentIndex === suiteOrModule.statements.length - 1) {
        return undefined;
    }
    const nextStatement = suiteOrModule.statements[assignmentIndex + 1];
    if (nextStatement.nodeType !== 47 /* ParseNodeType.StatementList */ || !isDocString(nextStatement)) {
        return undefined;
    }
    // See if the assignment is within one of the contexts specified in PEP 258.
    let isValidContext = false;
    if (((_a = parentNode === null || parentNode === void 0 ? void 0 : parentNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 36 /* ParseNodeType.Module */) {
        // If we're at the top level of a module, the attribute docstring is valid.
        isValidContext = true;
    }
    else if (((_b = parentNode === null || parentNode === void 0 ? void 0 : parentNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 50 /* ParseNodeType.Suite */ &&
        ((_d = (_c = parentNode === null || parentNode === void 0 ? void 0 : parentNode.parent) === null || _c === void 0 ? void 0 : _c.parent) === null || _d === void 0 ? void 0 : _d.nodeType) === 10 /* ParseNodeType.Class */) {
        // If we're at the top level of a class, the attribute docstring is valid.
        isValidContext = true;
    }
    else {
        const func = getEnclosingFunction(parentNode);
        // If we're within an __init__ method, the attribute docstring is valid.
        if (func && func.name.value === '__init__' && getEnclosingClass(func, /* stopAtFunction */ true)) {
            isValidContext = true;
        }
    }
    if (!isValidContext) {
        return undefined;
    }
    // A docstring can consist of multiple joined strings in a single expression.
    return nextStatement.statements[0];
}
exports.getVariableDocStringNode = getVariableDocStringNode;
// Creates an ID that identifies this parse node in a way that will
// not change each time the file is parsed (unless, of course, the
// file contents change).
function getScopeIdForNode(node) {
    let name = '';
    if (node.nodeType === 10 /* ParseNodeType.Class */) {
        name = node.name.value;
    }
    else if (node.nodeType === 28 /* ParseNodeType.Function */) {
        name = node.name.value;
    }
    const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
    return `${fileInfo.fileUri.key}.${node.start.toString()}-${name}`;
}
exports.getScopeIdForNode = getScopeIdForNode;
// Walks up the parse tree and finds all scopes that can provide
// a context for a TypeVar and returns the scope ID for each.
function getTypeVarScopesForNode(node) {
    const scopeIds = [];
    let curNode = node;
    while (curNode) {
        curNode = getTypeVarScopeNode(curNode);
        if (!curNode) {
            break;
        }
        scopeIds.push(getScopeIdForNode(curNode));
        curNode = curNode.parent;
    }
    return scopeIds;
}
exports.getTypeVarScopesForNode = getTypeVarScopesForNode;
function checkDecorator(node, value) {
    return node.expression.nodeType === 38 /* ParseNodeType.Name */ && node.expression.value === value;
}
exports.checkDecorator = checkDecorator;
function isSimpleDefault(node) {
    switch (node.nodeType) {
        case 40 /* ParseNodeType.Number */:
        case 11 /* ParseNodeType.Constant */:
        case 35 /* ParseNodeType.MemberAccess */:
            return true;
        case 49 /* ParseNodeType.String */:
            return (node.token.flags & 64 /* StringTokenFlags.Format */) === 0;
        case 48 /* ParseNodeType.StringList */:
            return node.strings.every(isSimpleDefault);
        case 55 /* ParseNodeType.UnaryOperation */:
            return isSimpleDefault(node.expression);
        case 7 /* ParseNodeType.BinaryOperation */:
            return isSimpleDefault(node.leftExpression) && isSimpleDefault(node.rightExpression);
        default:
            return false;
    }
}
exports.isSimpleDefault = isSimpleDefault;


/***/ }),

/***/ "../pyright-internal/src/analyzer/parseTreeWalker.ts":
/*!***********************************************************!*\
  !*** ../pyright-internal/src/analyzer/parseTreeWalker.ts ***!
  \***********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * parseTreeWalker.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that traverses a parse tree.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ParseTreeWalker = exports.ParseTreeVisitor = exports.getChildNodes = void 0;
const debug = __importStar(__webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts"));
// Get child nodes of the given node.
function getChildNodes(node) {
    var _a, _b;
    switch (node.nodeType) {
        case 0 /* ParseNodeType.Error */:
            return [node.child, ...((_a = node.decorators) !== null && _a !== void 0 ? _a : [])];
        case 1 /* ParseNodeType.Argument */:
            return [node.name, node.valueExpression];
        case 2 /* ParseNodeType.Assert */:
            return [node.testExpression, node.exceptionExpression];
        case 4 /* ParseNodeType.AssignmentExpression */:
            return [node.name, node.rightExpression];
        case 3 /* ParseNodeType.Assignment */:
            return [node.leftExpression, node.rightExpression, node.typeAnnotationComment];
        case 5 /* ParseNodeType.AugmentedAssignment */:
            return [node.leftExpression, node.rightExpression];
        case 6 /* ParseNodeType.Await */:
            return [node.expression];
        case 7 /* ParseNodeType.BinaryOperation */:
            return [node.leftExpression, node.rightExpression];
        case 8 /* ParseNodeType.Break */:
            return [];
        case 9 /* ParseNodeType.Call */:
            return [node.leftExpression, ...node.arguments];
        case 64 /* ParseNodeType.Case */:
            return [node.pattern, node.guardExpression, node.suite];
        case 10 /* ParseNodeType.Class */:
            return [...node.decorators, node.name, node.typeParameters, ...node.arguments, node.suite];
        case 11 /* ParseNodeType.Constant */:
            return [];
        case 12 /* ParseNodeType.Continue */:
            return [];
        case 13 /* ParseNodeType.Decorator */:
            return [node.expression];
        case 14 /* ParseNodeType.Del */:
            return node.expressions;
        case 15 /* ParseNodeType.Dictionary */:
            return node.entries;
        case 16 /* ParseNodeType.DictionaryExpandEntry */:
            return [node.expandExpression];
        case 17 /* ParseNodeType.DictionaryKeyEntry */:
            return [node.keyExpression, node.valueExpression];
        case 18 /* ParseNodeType.Ellipsis */:
            return [];
        case 19 /* ParseNodeType.If */:
            return [node.testExpression, node.ifSuite, node.elseSuite];
        case 20 /* ParseNodeType.Import */:
            return node.list;
        case 21 /* ParseNodeType.ImportAs */:
            return [node.module, node.alias];
        case 22 /* ParseNodeType.ImportFrom */:
            return [node.module, ...node.imports];
        case 23 /* ParseNodeType.ImportFromAs */:
            return [node.name, node.alias];
        case 24 /* ParseNodeType.Index */:
            return [node.baseExpression, ...node.items];
        case 25 /* ParseNodeType.Except */:
            return [node.typeExpression, node.name, node.exceptSuite];
        case 26 /* ParseNodeType.For */:
            return [node.targetExpression, node.iterableExpression, node.forSuite, node.elseSuite];
        case 27 /* ParseNodeType.FormatString */:
            return [...node.fieldExpressions, ...((_b = node.formatExpressions) !== null && _b !== void 0 ? _b : [])];
        case 28 /* ParseNodeType.Function */:
            return [
                ...node.decorators,
                node.name,
                node.typeParameters,
                ...node.parameters,
                node.returnTypeAnnotation,
                node.functionAnnotationComment,
                node.suite,
            ];
        case 62 /* ParseNodeType.FunctionAnnotation */:
            return [...node.paramTypeAnnotations, node.returnTypeAnnotation];
        case 29 /* ParseNodeType.Global */:
            return node.nameList;
        case 30 /* ParseNodeType.Lambda */:
            return [...node.parameters, node.expression];
        case 31 /* ParseNodeType.List */:
            return node.entries;
        case 32 /* ParseNodeType.ListComprehension */:
            return [node.expression, ...node.forIfNodes];
        case 33 /* ParseNodeType.ListComprehensionFor */:
            return [node.targetExpression, node.iterableExpression];
        case 34 /* ParseNodeType.ListComprehensionIf */:
            return [node.testExpression];
        case 63 /* ParseNodeType.Match */:
            return [node.subjectExpression, ...node.cases];
        case 35 /* ParseNodeType.MemberAccess */:
            return [node.leftExpression, node.memberName];
        case 37 /* ParseNodeType.ModuleName */:
            return node.nameParts;
        case 36 /* ParseNodeType.Module */:
            return [...node.statements];
        case 38 /* ParseNodeType.Name */:
            return [];
        case 39 /* ParseNodeType.Nonlocal */:
            return node.nameList;
        case 40 /* ParseNodeType.Number */:
            return [];
        case 41 /* ParseNodeType.Parameter */:
            return [node.name, node.typeAnnotation, node.typeAnnotationComment, node.defaultValue];
        case 42 /* ParseNodeType.Pass */:
            return [];
        case 66 /* ParseNodeType.PatternAs */:
            return [...node.orPatterns, node.target];
        case 68 /* ParseNodeType.PatternClass */:
            return [node.className, ...node.arguments];
        case 74 /* ParseNodeType.PatternClassArgument */:
            return [node.name, node.pattern];
        case 69 /* ParseNodeType.PatternCapture */:
            return [node.target];
        case 67 /* ParseNodeType.PatternLiteral */:
            return [node.expression];
        case 72 /* ParseNodeType.PatternMappingExpandEntry */:
            return [node.target];
        case 71 /* ParseNodeType.PatternMappingKeyEntry */:
            return [node.keyPattern, node.valuePattern];
        case 70 /* ParseNodeType.PatternMapping */:
            return [...node.entries];
        case 65 /* ParseNodeType.PatternSequence */:
            return [...node.entries];
        case 73 /* ParseNodeType.PatternValue */:
            return [node.expression];
        case 43 /* ParseNodeType.Raise */:
            return [node.typeExpression, node.valueExpression, node.tracebackExpression];
        case 44 /* ParseNodeType.Return */:
            return [node.returnExpression];
        case 45 /* ParseNodeType.Set */:
            return node.entries;
        case 46 /* ParseNodeType.Slice */:
            return [node.startValue, node.endValue, node.stepValue];
        case 47 /* ParseNodeType.StatementList */:
            return node.statements;
        case 48 /* ParseNodeType.StringList */:
            return [node.typeAnnotation, ...node.strings];
        case 49 /* ParseNodeType.String */:
            return [];
        case 50 /* ParseNodeType.Suite */:
            return [...node.statements];
        case 51 /* ParseNodeType.Ternary */:
            return [node.ifExpression, node.testExpression, node.elseExpression];
        case 52 /* ParseNodeType.Tuple */:
            return node.expressions;
        case 53 /* ParseNodeType.Try */:
            return [node.trySuite, ...node.exceptClauses, node.elseSuite, node.finallySuite];
        case 77 /* ParseNodeType.TypeAlias */:
            return [node.name, node.typeParameters, node.expression];
        case 54 /* ParseNodeType.TypeAnnotation */:
            return [node.valueExpression, node.typeAnnotation];
        case 75 /* ParseNodeType.TypeParameter */:
            return [node.name, node.boundExpression, node.defaultExpression];
        case 76 /* ParseNodeType.TypeParameterList */:
            return [...node.parameters];
        case 55 /* ParseNodeType.UnaryOperation */:
            return [node.expression];
        case 56 /* ParseNodeType.Unpack */:
            return [node.expression];
        case 57 /* ParseNodeType.While */:
            return [node.testExpression, node.whileSuite, node.elseSuite];
        case 58 /* ParseNodeType.With */:
            return [...node.withItems, node.suite];
        case 59 /* ParseNodeType.WithItem */:
            return [node.expression, node.target];
        case 60 /* ParseNodeType.Yield */:
            return [node.expression];
        case 61 /* ParseNodeType.YieldFrom */:
            return [node.expression];
        default:
            debug.assertNever(node, `Unknown node type ${node}`);
    }
}
exports.getChildNodes = getChildNodes;
// To use this class, create a subclass and override the
// visitXXX methods that you want to handle.
class ParseTreeVisitor {
    constructor(_default) {
        this._default = _default;
        // empty
    }
    visit(node) {
        switch (node.nodeType) {
            case 0 /* ParseNodeType.Error */:
                return this.visitError(node);
            case 1 /* ParseNodeType.Argument */:
                return this.visitArgument(node);
            case 2 /* ParseNodeType.Assert */:
                return this.visitAssert(node);
            case 4 /* ParseNodeType.AssignmentExpression */:
                return this.visitAssignmentExpression(node);
            case 3 /* ParseNodeType.Assignment */:
                return this.visitAssignment(node);
            case 5 /* ParseNodeType.AugmentedAssignment */:
                return this.visitAugmentedAssignment(node);
            case 6 /* ParseNodeType.Await */:
                return this.visitAwait(node);
            case 7 /* ParseNodeType.BinaryOperation */:
                return this.visitBinaryOperation(node);
            case 8 /* ParseNodeType.Break */:
                return this.visitBreak(node);
            case 9 /* ParseNodeType.Call */:
                return this.visitCall(node);
            case 64 /* ParseNodeType.Case */:
                return this.visitCase(node);
            case 10 /* ParseNodeType.Class */:
                return this.visitClass(node);
            case 11 /* ParseNodeType.Constant */:
                return this.visitConstant(node);
            case 12 /* ParseNodeType.Continue */:
                return this.visitContinue(node);
            case 13 /* ParseNodeType.Decorator */:
                return this.visitDecorator(node);
            case 14 /* ParseNodeType.Del */:
                return this.visitDel(node);
            case 15 /* ParseNodeType.Dictionary */:
                return this.visitDictionary(node);
            case 16 /* ParseNodeType.DictionaryExpandEntry */:
                return this.visitDictionaryExpandEntry(node);
            case 17 /* ParseNodeType.DictionaryKeyEntry */:
                return this.visitDictionaryKeyEntry(node);
            case 18 /* ParseNodeType.Ellipsis */:
                return this.visitEllipsis(node);
            case 19 /* ParseNodeType.If */:
                return this.visitIf(node);
            case 20 /* ParseNodeType.Import */:
                return this.visitImport(node);
            case 21 /* ParseNodeType.ImportAs */:
                return this.visitImportAs(node);
            case 22 /* ParseNodeType.ImportFrom */:
                return this.visitImportFrom(node);
            case 23 /* ParseNodeType.ImportFromAs */:
                return this.visitImportFromAs(node);
            case 24 /* ParseNodeType.Index */:
                return this.visitIndex(node);
            case 25 /* ParseNodeType.Except */:
                return this.visitExcept(node);
            case 26 /* ParseNodeType.For */:
                return this.visitFor(node);
            case 27 /* ParseNodeType.FormatString */:
                return this.visitFormatString(node);
            case 28 /* ParseNodeType.Function */:
                return this.visitFunction(node);
            case 62 /* ParseNodeType.FunctionAnnotation */:
                return this.visitFunctionAnnotation(node);
            case 29 /* ParseNodeType.Global */:
                return this.visitGlobal(node);
            case 30 /* ParseNodeType.Lambda */:
                return this.visitLambda(node);
            case 31 /* ParseNodeType.List */:
                return this.visitList(node);
            case 32 /* ParseNodeType.ListComprehension */:
                return this.visitListComprehension(node);
            case 33 /* ParseNodeType.ListComprehensionFor */:
                return this.visitListComprehensionFor(node);
            case 34 /* ParseNodeType.ListComprehensionIf */:
                return this.visitListComprehensionIf(node);
            case 63 /* ParseNodeType.Match */:
                return this.visitMatch(node);
            case 35 /* ParseNodeType.MemberAccess */:
                return this.visitMemberAccess(node);
            case 37 /* ParseNodeType.ModuleName */:
                return this.visitModuleName(node);
            case 36 /* ParseNodeType.Module */:
                return this.visitModule(node);
            case 38 /* ParseNodeType.Name */:
                return this.visitName(node);
            case 39 /* ParseNodeType.Nonlocal */:
                return this.visitNonlocal(node);
            case 40 /* ParseNodeType.Number */:
                return this.visitNumber(node);
            case 41 /* ParseNodeType.Parameter */:
                return this.visitParameter(node);
            case 42 /* ParseNodeType.Pass */:
                return this.visitPass(node);
            case 66 /* ParseNodeType.PatternAs */:
                return this.visitPatternAs(node);
            case 68 /* ParseNodeType.PatternClass */:
                return this.visitPatternClass(node);
            case 74 /* ParseNodeType.PatternClassArgument */:
                return this.visitPatternClassArgument(node);
            case 69 /* ParseNodeType.PatternCapture */:
                return this.visitPatternCapture(node);
            case 67 /* ParseNodeType.PatternLiteral */:
                return this.visitPatternLiteral(node);
            case 72 /* ParseNodeType.PatternMappingExpandEntry */:
                return this.visitPatternMappingExpandEntry(node);
            case 71 /* ParseNodeType.PatternMappingKeyEntry */:
                return this.visitPatternMappingKeyEntry(node);
            case 70 /* ParseNodeType.PatternMapping */:
                return this.visitPatternMapping(node);
            case 65 /* ParseNodeType.PatternSequence */:
                return this.visitPatternSequence(node);
            case 73 /* ParseNodeType.PatternValue */:
                return this.visitPatternValue(node);
            case 43 /* ParseNodeType.Raise */:
                return this.visitRaise(node);
            case 44 /* ParseNodeType.Return */:
                return this.visitReturn(node);
            case 45 /* ParseNodeType.Set */:
                return this.visitSet(node);
            case 46 /* ParseNodeType.Slice */:
                return this.visitSlice(node);
            case 47 /* ParseNodeType.StatementList */:
                return this.visitStatementList(node);
            case 48 /* ParseNodeType.StringList */:
                return this.visitStringList(node);
            case 49 /* ParseNodeType.String */:
                return this.visitString(node);
            case 50 /* ParseNodeType.Suite */:
                return this.visitSuite(node);
            case 51 /* ParseNodeType.Ternary */:
                return this.visitTernary(node);
            case 52 /* ParseNodeType.Tuple */:
                return this.visitTuple(node);
            case 53 /* ParseNodeType.Try */:
                return this.visitTry(node);
            case 77 /* ParseNodeType.TypeAlias */:
                return this.visitTypeAlias(node);
            case 54 /* ParseNodeType.TypeAnnotation */:
                return this.visitTypeAnnotation(node);
            case 75 /* ParseNodeType.TypeParameter */:
                return this.visitTypeParameter(node);
            case 76 /* ParseNodeType.TypeParameterList */:
                return this.visitTypeParameterList(node);
            case 55 /* ParseNodeType.UnaryOperation */:
                return this.visitUnaryOperation(node);
            case 56 /* ParseNodeType.Unpack */:
                return this.visitUnpack(node);
            case 57 /* ParseNodeType.While */:
                return this.visitWhile(node);
            case 58 /* ParseNodeType.With */:
                return this.visitWith(node);
            case 59 /* ParseNodeType.WithItem */:
                return this.visitWithItem(node);
            case 60 /* ParseNodeType.Yield */:
                return this.visitYield(node);
            case 61 /* ParseNodeType.YieldFrom */:
                return this.visitYieldFrom(node);
            default:
                debug.assertNever(node, `Unknown node type ${node}`);
        }
    }
    // Override these methods as necessary.
    visitArgument(node) {
        return this._default;
    }
    visitAssert(node) {
        return this._default;
    }
    visitAssignment(node) {
        return this._default;
    }
    visitAssignmentExpression(node) {
        return this._default;
    }
    visitAugmentedAssignment(node) {
        return this._default;
    }
    visitAwait(node) {
        return this._default;
    }
    visitBinaryOperation(node) {
        return this._default;
    }
    visitBreak(node) {
        return this._default;
    }
    visitCall(node) {
        return this._default;
    }
    visitCase(node) {
        return this._default;
    }
    visitClass(node) {
        return this._default;
    }
    visitTernary(node) {
        return this._default;
    }
    visitContinue(node) {
        return this._default;
    }
    visitConstant(node) {
        return this._default;
    }
    visitDecorator(node) {
        return this._default;
    }
    visitDel(node) {
        return this._default;
    }
    visitDictionary(node) {
        return this._default;
    }
    visitDictionaryKeyEntry(node) {
        return this._default;
    }
    visitDictionaryExpandEntry(node) {
        return this._default;
    }
    visitError(node) {
        return this._default;
    }
    visitEllipsis(node) {
        return this._default;
    }
    visitIf(node) {
        return this._default;
    }
    visitImport(node) {
        return this._default;
    }
    visitImportAs(node) {
        return this._default;
    }
    visitImportFrom(node) {
        return this._default;
    }
    visitImportFromAs(node) {
        return this._default;
    }
    visitIndex(node) {
        return this._default;
    }
    visitExcept(node) {
        return this._default;
    }
    visitFor(node) {
        return this._default;
    }
    visitFormatString(node) {
        return this._default;
    }
    visitFunction(node) {
        return this._default;
    }
    visitFunctionAnnotation(node) {
        return this._default;
    }
    visitGlobal(node) {
        return this._default;
    }
    visitLambda(node) {
        return this._default;
    }
    visitList(node) {
        return this._default;
    }
    visitListComprehension(node) {
        return this._default;
    }
    visitListComprehensionFor(node) {
        return this._default;
    }
    visitListComprehensionIf(node) {
        return this._default;
    }
    visitMatch(node) {
        return this._default;
    }
    visitMemberAccess(node) {
        return this._default;
    }
    visitModule(node) {
        return this._default;
    }
    visitModuleName(node) {
        return this._default;
    }
    visitName(node) {
        return this._default;
    }
    visitNonlocal(node) {
        return this._default;
    }
    visitNumber(node) {
        return this._default;
    }
    visitParameter(node) {
        return this._default;
    }
    visitPass(node) {
        return this._default;
    }
    visitPatternCapture(node) {
        return this._default;
    }
    visitPatternClass(node) {
        return this._default;
    }
    visitPatternClassArgument(node) {
        return this._default;
    }
    visitPatternAs(node) {
        return this._default;
    }
    visitPatternLiteral(node) {
        return this._default;
    }
    visitPatternMappingExpandEntry(node) {
        return this._default;
    }
    visitPatternSequence(node) {
        return this._default;
    }
    visitPatternValue(node) {
        return this._default;
    }
    visitPatternMappingKeyEntry(node) {
        return this._default;
    }
    visitPatternMapping(node) {
        return this._default;
    }
    visitRaise(node) {
        return this._default;
    }
    visitReturn(node) {
        return this._default;
    }
    visitSet(node) {
        return this._default;
    }
    visitSlice(node) {
        return this._default;
    }
    visitStatementList(node) {
        return this._default;
    }
    visitString(node) {
        return this._default;
    }
    visitStringList(node) {
        return this._default;
    }
    visitSuite(node) {
        return this._default;
    }
    visitTuple(node) {
        return this._default;
    }
    visitTry(node) {
        return this._default;
    }
    visitTypeAlias(node) {
        return this._default;
    }
    visitTypeAnnotation(node) {
        return this._default;
    }
    visitTypeParameter(node) {
        return this._default;
    }
    visitTypeParameterList(node) {
        return this._default;
    }
    visitUnaryOperation(node) {
        return this._default;
    }
    visitUnpack(node) {
        return this._default;
    }
    visitWhile(node) {
        return this._default;
    }
    visitWith(node) {
        return this._default;
    }
    visitWithItem(node) {
        return this._default;
    }
    visitYield(node) {
        return this._default;
    }
    visitYieldFrom(node) {
        return this._default;
    }
}
exports.ParseTreeVisitor = ParseTreeVisitor;
// To use this class, create a subclass and override the
// visitXXX methods that you want to handle.
class ParseTreeWalker extends ParseTreeVisitor {
    constructor() {
        super(/* default */ true);
    }
    walk(node) {
        const childrenToWalk = this.visitNode(node);
        if (childrenToWalk.length > 0) {
            this.walkMultiple(childrenToWalk);
        }
    }
    walkMultiple(nodes) {
        nodes.forEach((node) => {
            if (node) {
                this.walk(node);
            }
        });
    }
    // If this.visit(node) returns true, all child nodes for the node are returned.
    // If the method returns false, we assume that the handler has already handled the
    // child nodes, so an empty list is returned.
    visitNode(node) {
        return this.visit(node) ? getChildNodes(node) : [];
    }
}
exports.ParseTreeWalker = ParseTreeWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/patternMatching.ts":
/*!***********************************************************!*\
  !*** ../pyright-internal/src/analyzer/patternMatching.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * patternMatching.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Type evaluation logic for evaluating and narrowing types
 * related to "match" and "case" statements as documented in
 * PEP 634.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getPatternSubtypeNarrowingCallback = exports.validateClassPattern = exports.assignTypeToPatternTargets = exports.checkForUnusedPattern = exports.narrowTypeBasedOnPattern = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const constraintSolver_1 = __webpack_require__(/*! ./constraintSolver */ "../pyright-internal/src/analyzer/constraintSolver.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const typedDicts_1 = __webpack_require__(/*! ./typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const typeGuards_1 = __webpack_require__(/*! ./typeGuards */ "../pyright-internal/src/analyzer/typeGuards.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
// PEP 634 indicates that several built-in classes are handled differently
// when used with class pattern matching.
const classPatternSpecialCases = [
    'builtins.bool',
    'builtins.bytearray',
    'builtins.bytes',
    'builtins.dict',
    'builtins.float',
    'builtins.frozenset',
    'builtins.int',
    'builtins.list',
    'builtins.set',
    'builtins.str',
    'builtins.tuple',
];
function narrowTypeBasedOnPattern(evaluator, type, pattern, isPositiveTest) {
    switch (pattern.nodeType) {
        case 65 /* ParseNodeType.PatternSequence */: {
            return narrowTypeBasedOnSequencePattern(evaluator, type, pattern, isPositiveTest);
        }
        case 67 /* ParseNodeType.PatternLiteral */: {
            return narrowTypeBasedOnLiteralPattern(evaluator, type, pattern, isPositiveTest);
        }
        case 68 /* ParseNodeType.PatternClass */: {
            return narrowTypeBasedOnClassPattern(evaluator, type, pattern, isPositiveTest);
        }
        case 66 /* ParseNodeType.PatternAs */: {
            return narrowTypeBasedOnAsPattern(evaluator, type, pattern, isPositiveTest);
        }
        case 70 /* ParseNodeType.PatternMapping */: {
            return narrowTypeBasedOnMappingPattern(evaluator, type, pattern, isPositiveTest);
        }
        case 73 /* ParseNodeType.PatternValue */: {
            return narrowTypeBasedOnValuePattern(evaluator, type, pattern, isPositiveTest);
        }
        case 69 /* ParseNodeType.PatternCapture */: {
            // A capture captures everything, so nothing remains in the negative case.
            return isPositiveTest ? type : types_1.NeverType.createNever();
        }
        case 0 /* ParseNodeType.Error */: {
            return type;
        }
    }
}
exports.narrowTypeBasedOnPattern = narrowTypeBasedOnPattern;
// Determines whether this pattern (or part of the pattern) in
// this case statement will never be matched.
function checkForUnusedPattern(evaluator, pattern, subjectType) {
    if ((0, types_1.isNever)(subjectType)) {
        reportUnnecessaryPattern(evaluator, pattern, subjectType);
    }
    else if (pattern.nodeType === 66 /* ParseNodeType.PatternAs */ && pattern.orPatterns.length > 1) {
        // Check each of the or patterns separately.
        pattern.orPatterns.forEach((orPattern) => {
            const subjectTypeMatch = narrowTypeBasedOnPattern(evaluator, subjectType, orPattern, 
            /* isPositiveTest */ true);
            if ((0, types_1.isNever)(subjectTypeMatch)) {
                reportUnnecessaryPattern(evaluator, orPattern, subjectType);
            }
            subjectType = narrowTypeBasedOnPattern(evaluator, subjectType, orPattern, /* isPositiveTest */ false);
        });
    }
    else {
        const subjectTypeMatch = narrowTypeBasedOnPattern(evaluator, subjectType, pattern, /* isPositiveTest */ true);
        if ((0, types_1.isNever)(subjectTypeMatch)) {
            reportUnnecessaryPattern(evaluator, pattern, subjectType);
        }
    }
}
exports.checkForUnusedPattern = checkForUnusedPattern;
function narrowTypeBasedOnSequencePattern(evaluator, type, pattern, isPositiveTest) {
    type = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(type);
    let sequenceInfo = getSequencePatternInfo(evaluator, pattern, type);
    // Further narrow based on pattern entry types.
    sequenceInfo = sequenceInfo.filter((entry) => {
        var _a;
        if (entry.isDefiniteNoMatch) {
            if (isPositiveTest) {
                return false;
            }
            else {
                return true;
            }
        }
        let isPlausibleMatch = true;
        let isDefiniteMatch = true;
        const narrowedEntryTypes = [];
        let canNarrowTuple = entry.isTuple;
        // Don't attempt to narrow tuples in the negative case if the subject
        // contains indeterminate-length entries.
        if (!isPositiveTest && entry.isIndeterminateLength) {
            canNarrowTuple = false;
        }
        // If the subject has an indeterminate length but the pattern does not accept
        // an arbitrary number of entries or accepts at least one non-star entry,
        // we can't prove that it's a definite match.
        if (entry.isIndeterminateLength) {
            if (pattern.entries.length !== 1 || pattern.starEntryIndex !== 0) {
                isDefiniteMatch = false;
            }
        }
        let negativeEntriesNarrowed = 0;
        pattern.entries.forEach((sequenceEntry, index) => {
            const entryType = getTypeOfPatternSequenceEntry(evaluator, pattern, entry, index, pattern.entries.length, pattern.starEntryIndex, 
            /* unpackStarEntry */ true);
            const narrowedEntryType = narrowTypeBasedOnPattern(evaluator, entryType, sequenceEntry, isPositiveTest);
            if (isPositiveTest) {
                if (index === pattern.starEntryIndex) {
                    if ((0, types_1.isClassInstance)(narrowedEntryType) &&
                        narrowedEntryType.tupleTypeArguments &&
                        !(0, typeUtils_1.isUnboundedTupleClass)(narrowedEntryType) &&
                        narrowedEntryType.tupleTypeArguments) {
                        (0, collectionUtils_1.appendArray)(narrowedEntryTypes, narrowedEntryType.tupleTypeArguments.map((t) => t.type));
                    }
                    else {
                        narrowedEntryTypes.push(narrowedEntryType);
                        canNarrowTuple = false;
                    }
                }
                else {
                    narrowedEntryTypes.push(narrowedEntryType);
                    if ((0, types_1.isNever)(narrowedEntryType)) {
                        isPlausibleMatch = false;
                    }
                }
            }
            else {
                if (entry.isPotentialNoMatch) {
                    isDefiniteMatch = false;
                }
                if (!(0, types_1.isNever)(narrowedEntryType)) {
                    isDefiniteMatch = false;
                    // Record the number of entries that were narrowed in the negative
                    // case. We can apply the tuple narrowing only if exactly one entry
                    // is narrowed.
                    negativeEntriesNarrowed++;
                    narrowedEntryTypes.push(narrowedEntryType);
                }
                else {
                    narrowedEntryTypes.push(entryType);
                }
                if (index === pattern.starEntryIndex) {
                    canNarrowTuple = false;
                }
            }
        });
        // If the pattern is an empty sequence, use the entry types.
        if (pattern.entries.length === 0 && entry.entryTypes.length > 0) {
            narrowedEntryTypes.push((0, types_1.combineTypes)(entry.entryTypes));
        }
        if (!isPositiveTest) {
            // If the positive case is a definite match, the negative case can
            // eliminate this subtype entirely.
            if (isDefiniteMatch) {
                return false;
            }
            // Can we narrow a tuple?
            if (canNarrowTuple && negativeEntriesNarrowed === 1) {
                const tupleClassType = evaluator.getBuiltInType(pattern, 'tuple');
                if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                    entry.subtype = types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeTupleClass)(tupleClassType, narrowedEntryTypes.map((t) => {
                        return { type: t, isUnbounded: false };
                    })));
                }
            }
            return true;
        }
        if (isPlausibleMatch) {
            // If this is a tuple, we can narrow it to a specific tuple type.
            // Other sequences cannot be narrowed because we don't know if they
            // are immutable (covariant).
            if (canNarrowTuple) {
                const tupleClassType = evaluator.getBuiltInType(pattern, 'tuple');
                if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                    entry.subtype = types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeTupleClass)(tupleClassType, narrowedEntryTypes.map((t) => {
                        return { type: t, isUnbounded: false };
                    })));
                }
            }
            // If this is a supertype of Sequence, we can narrow it to a Sequence type.
            if (entry.isPotentialNoMatch && !entry.isTuple) {
                const sequenceType = evaluator.getTypingType(pattern, 'Sequence');
                if (sequenceType && (0, types_1.isInstantiableClass)(sequenceType)) {
                    let typeArgType = evaluator.stripLiteralValue((0, types_1.combineTypes)(narrowedEntryTypes));
                    // If the type is a union that contains Any or Unknown, remove the other types
                    // before wrapping it in a Sequence.
                    typeArgType = (_a = (0, typeUtils_1.containsAnyOrUnknown)(typeArgType, /* recurse */ false)) !== null && _a !== void 0 ? _a : typeArgType;
                    entry.subtype = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(sequenceType, [typeArgType], /* isTypeArgumentExplicit */ true));
                }
            }
        }
        return isPlausibleMatch;
    });
    return (0, types_1.combineTypes)(sequenceInfo.map((entry) => entry.subtype));
}
function narrowTypeBasedOnAsPattern(evaluator, type, pattern, isPositiveTest) {
    let remainingType = type;
    if (!isPositiveTest) {
        pattern.orPatterns.forEach((subpattern) => {
            remainingType = narrowTypeBasedOnPattern(evaluator, remainingType, subpattern, /* isPositiveTest */ false);
        });
        return remainingType;
    }
    const narrowedTypes = pattern.orPatterns.map((subpattern) => {
        const narrowedSubtype = narrowTypeBasedOnPattern(evaluator, remainingType, subpattern, 
        /* isPositiveTest */ true);
        remainingType = narrowTypeBasedOnPattern(evaluator, remainingType, subpattern, /* isPositiveTest */ false);
        return narrowedSubtype;
    });
    return (0, types_1.combineTypes)(narrowedTypes);
}
function narrowTypeBasedOnMappingPattern(evaluator, type, pattern, isPositiveTest) {
    type = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(type);
    if (!isPositiveTest) {
        // Our ability to narrow in the negative case for mapping patterns is
        // limited, but we can do it if the type is a union that includes a
        // TypedDict with a field discriminated by a literal.
        if (pattern.entries.length !== 1 || pattern.entries[0].nodeType !== 71 /* ParseNodeType.PatternMappingKeyEntry */) {
            return type;
        }
        const keyPattern = pattern.entries[0].keyPattern;
        const valuePattern = pattern.entries[0].valuePattern;
        if (keyPattern.nodeType !== 67 /* ParseNodeType.PatternLiteral */ ||
            valuePattern.nodeType !== 66 /* ParseNodeType.PatternAs */ ||
            !valuePattern.orPatterns.every((orPattern) => orPattern.nodeType === 67 /* ParseNodeType.PatternLiteral */)) {
            return type;
        }
        const keyType = evaluator.getTypeOfExpression(keyPattern.expression).type;
        // The key type must be a str literal.
        if (!(0, types_1.isClassInstance)(keyType) || !types_1.ClassType.isBuiltIn(keyType, 'str') || keyType.literalValue === undefined) {
            return type;
        }
        const keyValue = keyType.literalValue;
        const valueTypes = valuePattern.orPatterns.map((orPattern) => evaluator.getTypeOfExpression(orPattern.expression).type);
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
                const typedDictMembers = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, subtype, /* allowNarrowed */ true);
                const member = typedDictMembers.knownItems.get(keyValue);
                if (member && (member.isRequired || member.isProvided) && (0, types_1.isClassInstance)(member.valueType)) {
                    const memberValueType = member.valueType;
                    // If there's at least one literal value pattern that matches
                    // the literal type of the member, we can eliminate this type.
                    if (valueTypes.some((valueType) => (0, types_1.isClassInstance)(valueType) &&
                        types_1.ClassType.isSameGenericClass(valueType, memberValueType) &&
                        valueType.literalValue === memberValueType.literalValue)) {
                        return undefined;
                    }
                }
            }
            return subtype;
        });
    }
    let mappingInfo = getMappingPatternInfo(evaluator, type, pattern);
    // Further narrow based on pattern entry types.
    mappingInfo = mappingInfo.filter((mappingSubtypeInfo) => {
        let isPlausibleMatch = true;
        pattern.entries.forEach((mappingEntry) => {
            if (mappingSubtypeInfo.typedDict) {
                if (mappingEntry.nodeType === 71 /* ParseNodeType.PatternMappingKeyEntry */) {
                    const narrowedKeyType = narrowTypeBasedOnPattern(evaluator, evaluator.getBuiltInObject(pattern, 'str'), mappingEntry.keyPattern, isPositiveTest);
                    if ((0, types_1.isNever)(narrowedKeyType)) {
                        isPlausibleMatch = false;
                    }
                    const valueType = (0, typeUtils_1.mapSubtypes)(narrowedKeyType, (keySubtype) => {
                        var _a;
                        if ((0, types_1.isAnyOrUnknown)(keySubtype)) {
                            return keySubtype;
                        }
                        if ((0, types_1.isClassInstance)(keySubtype) && types_1.ClassType.isBuiltIn(keySubtype, 'str')) {
                            if (!(0, typeUtils_1.isLiteralType)(keySubtype)) {
                                return types_1.UnknownType.create();
                            }
                            const tdEntries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, mappingSubtypeInfo.typedDict);
                            const valueEntry = tdEntries.knownItems.get(keySubtype.literalValue);
                            if (valueEntry) {
                                const narrowedValueType = narrowTypeBasedOnPattern(evaluator, valueEntry.valueType, mappingEntry.valuePattern, 
                                /* isPositiveTest */ true);
                                if (!(0, types_1.isNever)(narrowedValueType)) {
                                    // If this is a "NotRequired" entry that has not yet been demonstrated
                                    // to be present, we can mark it as "provided" at this point.
                                    if (!valueEntry.isRequired &&
                                        !valueEntry.isProvided &&
                                        (0, types_1.isTypeSame)(mappingSubtypeInfo.subtype, mappingSubtypeInfo.typedDict)) {
                                        const newNarrowedEntriesMap = new Map((_a = mappingSubtypeInfo.typedDict.typedDictNarrowedEntries) !== null && _a !== void 0 ? _a : []);
                                        newNarrowedEntriesMap.set(keySubtype.literalValue, {
                                            valueType: valueEntry.valueType,
                                            isReadOnly: valueEntry.isReadOnly,
                                            isRequired: false,
                                            isProvided: true,
                                        });
                                        // Clone the TypedDict object with the new entries.
                                        mappingSubtypeInfo.subtype = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForNarrowedTypedDictEntries(types_1.ClassType.cloneAsInstantiable(mappingSubtypeInfo.typedDict), newNarrowedEntriesMap));
                                        mappingSubtypeInfo.typedDict = mappingSubtypeInfo.subtype;
                                    }
                                    return narrowedValueType;
                                }
                            }
                        }
                        return undefined;
                    });
                    if ((0, types_1.isNever)(valueType)) {
                        isPlausibleMatch = false;
                    }
                }
            }
            else if (mappingSubtypeInfo.dictTypeArgs) {
                if (mappingEntry.nodeType === 71 /* ParseNodeType.PatternMappingKeyEntry */) {
                    const narrowedKeyType = narrowTypeBasedOnPattern(evaluator, mappingSubtypeInfo.dictTypeArgs.key, mappingEntry.keyPattern, isPositiveTest);
                    const narrowedValueType = narrowTypeBasedOnPattern(evaluator, mappingSubtypeInfo.dictTypeArgs.value, mappingEntry.valuePattern, isPositiveTest);
                    if ((0, types_1.isNever)(narrowedKeyType) || (0, types_1.isNever)(narrowedValueType)) {
                        isPlausibleMatch = false;
                    }
                }
            }
        });
        return isPlausibleMatch;
    });
    return (0, types_1.combineTypes)(mappingInfo.map((entry) => entry.subtype));
}
// Looks up the "__match_args__" class member to determine the names of
// the attributes used for class pattern matching.
function getPositionalMatchArgNames(evaluator, type) {
    const matchArgsMemberInfo = (0, typeUtils_1.lookUpClassMember)(type, '__match_args__');
    if (matchArgsMemberInfo) {
        const matchArgsType = evaluator.getTypeOfMember(matchArgsMemberInfo);
        if ((0, types_1.isClassInstance)(matchArgsType) &&
            (0, typeUtils_1.isTupleClass)(matchArgsType) &&
            !(0, typeUtils_1.isUnboundedTupleClass)(matchArgsType) &&
            matchArgsType.tupleTypeArguments) {
            const tupleArgs = matchArgsType.tupleTypeArguments;
            // Are all the args string literals?
            if (tupleArgs.every((arg) => (0, types_1.isClassInstance)(arg.type) && types_1.ClassType.isBuiltIn(arg.type, 'str') && (0, typeUtils_1.isLiteralType)(arg.type))) {
                return tupleArgs.map((arg) => arg.type.literalValue);
            }
        }
    }
    return [];
}
function narrowTypeBasedOnLiteralPattern(evaluator, type, pattern, isPositiveTest) {
    const literalType = evaluator.getTypeOfExpression(pattern.expression).type;
    if (!isPositiveTest) {
        return evaluator.mapSubtypesExpandTypeVars(type, 
        /* options */ undefined, (expandedSubtype, unexpandedSubtype) => {
            if ((0, types_1.isClassInstance)(literalType) &&
                (0, typeUtils_1.isLiteralType)(literalType) &&
                (0, types_1.isClassInstance)(expandedSubtype) &&
                (0, typeUtils_1.isLiteralType)(expandedSubtype) &&
                evaluator.assignType(literalType, expandedSubtype)) {
                return undefined;
            }
            if ((0, typeUtils_1.isNoneInstance)(expandedSubtype) && (0, typeUtils_1.isNoneInstance)(literalType)) {
                return undefined;
            }
            // Narrow a non-literal bool based on a literal bool pattern.
            if ((0, types_1.isClassInstance)(expandedSubtype) &&
                types_1.ClassType.isBuiltIn(expandedSubtype, 'bool') &&
                expandedSubtype.literalValue === undefined &&
                (0, types_1.isClassInstance)(literalType) &&
                types_1.ClassType.isBuiltIn(literalType, 'bool') &&
                literalType.literalValue !== undefined) {
                return types_1.ClassType.cloneWithLiteral(literalType, !literalType.literalValue);
            }
            return expandedSubtype;
        });
    }
    return evaluator.mapSubtypesExpandTypeVars(type, /* options */ undefined, (expandedSubtype, unexpandedSubtype) => {
        if (evaluator.assignType(expandedSubtype, literalType)) {
            return literalType;
        }
        // See if the subtype is a subclass of the literal's class. For example,
        // if it's a literal str, see if the subtype is subclass of str.
        if ((0, types_1.isClassInstance)(literalType) &&
            (0, typeUtils_1.isLiteralType)(literalType) &&
            (0, types_1.isClassInstance)(expandedSubtype) &&
            !(0, typeUtils_1.isLiteralType)(expandedSubtype)) {
            if (evaluator.assignType(types_1.ClassType.cloneWithLiteral(literalType, /* value */ undefined), expandedSubtype)) {
                return expandedSubtype;
            }
        }
        return undefined;
    });
}
function narrowTypeBasedOnClassPattern(evaluator, type, pattern, isPositiveTest) {
    let exprType = evaluator.getTypeOfExpression(pattern.className, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
    // If this is a class (but not a type alias that refers to a class),
    // specialize it with Unknown type arguments.
    if ((0, types_1.isClass)(exprType) && !exprType.typeAliasInfo) {
        exprType = types_1.ClassType.cloneRemoveTypePromotions(exprType);
        exprType = (0, typeUtils_1.specializeClassType)(exprType);
    }
    // Are there any positional arguments? If so, try to get the mappings for
    // these arguments by fetching the __match_args__ symbol from the class.
    let positionalArgNames = [];
    if (pattern.arguments.some((arg) => !arg.name) && (0, types_1.isInstantiableClass)(exprType)) {
        positionalArgNames = getPositionalMatchArgNames(evaluator, exprType);
    }
    if (!isPositiveTest) {
        // Don't attempt to narrow if the class type is a more complex type (e.g. a TypeVar or union).
        if (!(0, types_1.isInstantiableClass)(exprType)) {
            return type;
        }
        let classType = exprType;
        if (classType.details.typeParameters.length > 0) {
            classType = types_1.ClassType.cloneForSpecialization(classType, 
            /* typeArguments */ undefined, 
            /* isTypeArgumentExplicit */ false);
        }
        const classInstance = (0, typeUtils_1.convertToInstance)(classType);
        const isPatternMetaclass = (0, typeUtils_1.isMetaclassInstance)(classInstance);
        return evaluator.mapSubtypesExpandTypeVars(type, {
            expandCallback: (type) => evaluator.expandPromotionTypes(pattern, type),
        }, (subjectSubtypeExpanded, subjectSubtypeUnexpanded) => {
            var _a;
            // Handle the case where the class pattern references type() or a subtype thereof
            // and the subject type is an instantiable class itself.
            if (isPatternMetaclass && (0, types_1.isInstantiableClass)(subjectSubtypeExpanded)) {
                const metaclass = (_a = subjectSubtypeExpanded.details.effectiveMetaclass) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
                if ((0, types_1.isInstantiableClass)(classType) && evaluator.assignType(classType, metaclass)) {
                    return undefined;
                }
                return subjectSubtypeExpanded;
            }
            if (!(0, typeUtils_1.isNoneInstance)(subjectSubtypeExpanded) && !(0, types_1.isClassInstance)(subjectSubtypeExpanded)) {
                return subjectSubtypeUnexpanded;
            }
            if ((0, typeUtils_1.isNoneInstance)(subjectSubtypeExpanded) &&
                (0, types_1.isInstantiableClass)(classType) &&
                types_1.ClassType.isBuiltIn(classType, 'NoneType')) {
                return undefined;
            }
            if (!evaluator.assignType(classInstance, subjectSubtypeExpanded)) {
                return subjectSubtypeExpanded;
            }
            if (pattern.arguments.length === 0) {
                if ((0, types_1.isClass)(classInstance) && (0, types_1.isClass)(subjectSubtypeExpanded)) {
                    if (types_1.ClassType.isDerivedFrom(subjectSubtypeExpanded, classInstance)) {
                        // We know that this match will always succeed, so we can
                        // eliminate this subtype.
                        return undefined;
                    }
                    // Handle LiteralString as a special case.
                    if (types_1.ClassType.isBuiltIn(classInstance, 'str') &&
                        types_1.ClassType.isBuiltIn(subjectSubtypeExpanded, 'LiteralString')) {
                        return undefined;
                    }
                }
                return subjectSubtypeExpanded;
            }
            // We might be able to narrow further based on arguments, but only
            // if the types match exactly, the subject subtype is a final class (and
            // therefore cannot be subclassed), or the pattern class is a protocol
            // class.
            if (!evaluator.assignType(subjectSubtypeExpanded, classInstance)) {
                if ((0, types_1.isClass)(subjectSubtypeExpanded) &&
                    !types_1.ClassType.isFinal(subjectSubtypeExpanded) &&
                    !types_1.ClassType.isProtocolClass(classInstance)) {
                    return subjectSubtypeExpanded;
                }
            }
            for (let index = 0; index < pattern.arguments.length; index++) {
                const narrowedArgType = narrowTypeOfClassPatternArgument(evaluator, pattern.arguments[index], index, positionalArgNames, subjectSubtypeExpanded, isPositiveTest);
                if (!(0, types_1.isNever)(narrowedArgType)) {
                    return subjectSubtypeUnexpanded;
                }
            }
            // We've completely eliminated the type based on the arguments.
            return undefined;
        });
    }
    if (!types_1.TypeBase.isInstantiable(exprType) && !(0, types_1.isNever)(exprType)) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocAddendum.typeNotClass().format({ type: evaluator.printType(exprType) }), pattern.className);
        return types_1.NeverType.createNever();
    }
    else if ((0, types_1.isInstantiableClass)(exprType) &&
        types_1.ClassType.isProtocolClass(exprType) &&
        !types_1.ClassType.isRuntimeCheckable(exprType)) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocAddendum.protocolRequiresRuntimeCheckable(), pattern.className);
    }
    return evaluator.mapSubtypesExpandTypeVars(exprType, 
    /* options */ undefined, (expandedSubtype, unexpandedSubtype) => {
        if ((0, types_1.isAnyOrUnknown)(expandedSubtype)) {
            return unexpandedSubtype;
        }
        if ((0, types_1.isInstantiableClass)(expandedSubtype)) {
            const expandedSubtypeInstance = (0, typeUtils_1.convertToInstance)(expandedSubtype);
            const isPatternMetaclass = (0, typeUtils_1.isMetaclassInstance)(expandedSubtypeInstance);
            return evaluator.mapSubtypesExpandTypeVars(type, /* options */ undefined, (subjectSubtypeExpanded) => {
                var _a;
                if ((0, types_1.isAnyOrUnknown)(subjectSubtypeExpanded)) {
                    return (0, typeUtils_1.convertToInstance)(unexpandedSubtype);
                }
                // Handle the case where the class pattern references type() or a subtype thereof
                // and the subject type is a class itself.
                if (isPatternMetaclass && (0, types_1.isInstantiableClass)(subjectSubtypeExpanded)) {
                    const metaclass = (_a = subjectSubtypeExpanded.details.effectiveMetaclass) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
                    if (evaluator.assignType(expandedSubtype, metaclass) ||
                        evaluator.assignType(metaclass, expandedSubtype)) {
                        return subjectSubtypeExpanded;
                    }
                    return undefined;
                }
                // Handle NoneType specially.
                if ((0, typeUtils_1.isNoneInstance)(subjectSubtypeExpanded) &&
                    (0, types_1.isInstantiableClass)(expandedSubtype) &&
                    types_1.ClassType.isBuiltIn(expandedSubtype, 'NoneType')) {
                    return subjectSubtypeExpanded;
                }
                // Handle Callable specially.
                if ((0, types_1.isInstantiableClass)(expandedSubtype) && types_1.ClassType.isBuiltIn(expandedSubtype, 'Callable')) {
                    const callableType = (0, typeUtils_1.getUnknownTypeForCallable)();
                    if (evaluator.assignType(callableType, subjectSubtypeExpanded)) {
                        return subjectSubtypeExpanded;
                    }
                    const subjObjType = (0, typeUtils_1.convertToInstance)(subjectSubtypeExpanded);
                    if (evaluator.assignType(subjObjType, callableType)) {
                        return callableType;
                    }
                    return undefined;
                }
                if ((0, types_1.isClassInstance)(subjectSubtypeExpanded)) {
                    let resultType;
                    if (evaluator.assignType(types_1.ClassType.cloneAsInstance(expandedSubtype), subjectSubtypeExpanded)) {
                        resultType = subjectSubtypeExpanded;
                    }
                    else if (evaluator.assignType(subjectSubtypeExpanded, types_1.ClassType.cloneAsInstance(expandedSubtype))) {
                        resultType = (0, typeUtils_1.addConditionToType)((0, typeUtils_1.convertToInstance)(unexpandedSubtype), (0, typeUtils_1.getTypeCondition)(subjectSubtypeExpanded));
                        // Try to retain the type arguments for the pattern class type.
                        if ((0, types_1.isInstantiableClass)(unexpandedSubtype) && (0, types_1.isClassInstance)(subjectSubtypeExpanded)) {
                            if (types_1.ClassType.isSpecialBuiltIn(unexpandedSubtype) ||
                                unexpandedSubtype.details.typeParameters.length > 0) {
                                const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(unexpandedSubtype));
                                const unspecializedMatchType = types_1.ClassType.cloneForSpecialization(unexpandedSubtype, 
                                /* typeArguments */ undefined, 
                                /* isTypeArgumentExplicit */ false);
                                const matchTypeInstance = types_1.ClassType.cloneAsInstance(unspecializedMatchType);
                                if ((0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluator, matchTypeInstance, subjectSubtypeExpanded, typeVarContext, 
                                /* liveTypeVarScopes */ undefined, 
                                /* usageOffset */ undefined)) {
                                    resultType = (0, typeUtils_1.applySolvedTypeVars)(matchTypeInstance, typeVarContext, {
                                        unknownIfNotFound: true,
                                    });
                                }
                            }
                        }
                    }
                    else {
                        return undefined;
                    }
                    // Are there any positional arguments? If so, try to get the mappings for
                    // these arguments by fetching the __match_args__ symbol from the class.
                    let positionalArgNames = [];
                    if (pattern.arguments.some((arg) => !arg.name)) {
                        positionalArgNames = getPositionalMatchArgNames(evaluator, expandedSubtype);
                    }
                    let isMatchValid = true;
                    pattern.arguments.forEach((arg, index) => {
                        // Narrow the arg pattern. It's possible that the actual type of the object
                        // being matched is a subtype of the resultType, so it might contain additional
                        // attributes that we don't know about.
                        const narrowedArgType = narrowTypeOfClassPatternArgument(evaluator, arg, index, positionalArgNames, resultType, isPositiveTest);
                        if ((0, types_1.isNever)(narrowedArgType)) {
                            isMatchValid = false;
                        }
                    });
                    if (isMatchValid) {
                        return resultType;
                    }
                }
                return undefined;
            });
        }
        return undefined;
    });
}
// Some built-in classes are treated as special cases for the class pattern
// if a positional argument is used.
function isClassSpecialCaseForClassPattern(classType) {
    if (classPatternSpecialCases.some((className) => classType.details.fullName === className)) {
        return true;
    }
    // If the class supplies its own `__match_args__`, it's not a special case.
    const matchArgsMemberInfo = (0, typeUtils_1.lookUpClassMember)(classType, '__match_args__');
    if (matchArgsMemberInfo) {
        return false;
    }
    // If the class derives from a built-in class, it is considered a special case.
    for (const mroClass of classType.details.mro) {
        if ((0, types_1.isClass)(mroClass) &&
            classPatternSpecialCases.some((className) => mroClass.details.fullName === className)) {
            return true;
        }
    }
    return false;
}
// Narrows the pattern provided for a class pattern argument.
function narrowTypeOfClassPatternArgument(evaluator, arg, argIndex, positionalArgNames, matchType, isPositiveTest) {
    var _a;
    let argName;
    if (arg.name) {
        argName = arg.name.value;
    }
    else if (argIndex < positionalArgNames.length) {
        argName = positionalArgNames[argIndex];
    }
    if ((0, types_1.isAnyOrUnknown)(matchType)) {
        return matchType;
    }
    if (!(0, types_1.isClass)(matchType)) {
        return types_1.UnknownType.create();
    }
    // According to PEP 634, some built-in types use themselves as the subject
    // for the first positional argument to a class pattern. Although the PEP does
    // state so explicitly, this is true of subclasses of these built-in classes
    // if the subclass doesn't define its own __match_args__.
    let useSelfForPattern = false;
    let selfForPatternType = matchType;
    if (!arg.name && (0, types_1.isClass)(matchType) && argIndex === 0) {
        if (isClassSpecialCaseForClassPattern(matchType)) {
            useSelfForPattern = true;
        }
        else if (positionalArgNames.length === 0) {
            matchType.details.mro.forEach((mroClass) => {
                if ((0, types_1.isClass)(mroClass) && isClassSpecialCaseForClassPattern(mroClass)) {
                    selfForPatternType = mroClass;
                    useSelfForPattern = true;
                }
            });
        }
    }
    let argType;
    if (useSelfForPattern) {
        argType = types_1.ClassType.cloneAsInstance(selfForPatternType);
    }
    else {
        if (argName) {
            argType = (_a = evaluator.useSpeculativeMode(arg, () => 
            // We need to apply a rather ugly cast here because PatternClassArgumentNode is
            // not technically an ExpressionNode, but it is OK to use it in this context.
            evaluator.getTypeOfBoundMember(arg, types_1.ClassType.cloneAsInstance(matchType), argName))) === null || _a === void 0 ? void 0 : _a.type;
        }
        if (!argType) {
            if (!isPositiveTest) {
                return matchType;
            }
            // If the class type in question is "final", we know that no additional
            // attributes can be added by subtypes, so it's safe to eliminate this
            // type entirely.
            if (types_1.ClassType.isFinal(matchType)) {
                return types_1.NeverType.createNever();
            }
            argType = types_1.UnknownType.create();
        }
    }
    return narrowTypeBasedOnPattern(evaluator, argType, arg.pattern, isPositiveTest);
}
function narrowTypeBasedOnValuePattern(evaluator, subjectType, pattern, isPositiveTest) {
    const valueType = evaluator.getTypeOfExpression(pattern.expression).type;
    const narrowedSubtypes = [];
    evaluator.mapSubtypesExpandTypeVars(valueType, 
    /* options */ undefined, (valueSubtypeExpanded, valueSubtypeUnexpanded) => {
        narrowedSubtypes.push(evaluator.mapSubtypesExpandTypeVars(subjectType, { conditionFilter: (0, typeUtils_1.getTypeCondition)(valueSubtypeExpanded) }, (subjectSubtypeExpanded) => {
            // If this is a negative test, see if it's an enum value.
            if (!isPositiveTest) {
                if ((0, types_1.isClassInstance)(subjectSubtypeExpanded) &&
                    types_1.ClassType.isEnumClass(subjectSubtypeExpanded) &&
                    !(0, typeUtils_1.isLiteralType)(subjectSubtypeExpanded) &&
                    (0, types_1.isClassInstance)(valueSubtypeExpanded) &&
                    (0, types_1.isSameWithoutLiteralValue)(subjectSubtypeExpanded, valueSubtypeExpanded) &&
                    (0, typeUtils_1.isLiteralType)(valueSubtypeExpanded)) {
                    const allEnumTypes = (0, typeGuards_1.enumerateLiteralsForType)(evaluator, subjectSubtypeExpanded);
                    if (allEnumTypes) {
                        return (0, types_1.combineTypes)(allEnumTypes.filter((enumType) => !types_1.ClassType.isLiteralValueSame(valueSubtypeExpanded, enumType)));
                    }
                }
                else if ((0, types_1.isClassInstance)(subjectSubtypeExpanded) &&
                    (0, types_1.isClassInstance)(valueSubtypeExpanded) &&
                    (0, typeUtils_1.isLiteralType)(subjectSubtypeExpanded) &&
                    types_1.ClassType.isLiteralValueSame(valueSubtypeExpanded, subjectSubtypeExpanded)) {
                    return undefined;
                }
                return subjectSubtypeExpanded;
            }
            if ((0, types_1.isNever)(valueSubtypeExpanded) || (0, types_1.isNever)(subjectSubtypeExpanded)) {
                return types_1.NeverType.createNever();
            }
            if ((0, types_1.isAnyOrUnknown)(valueSubtypeExpanded) || (0, types_1.isAnyOrUnknown)(subjectSubtypeExpanded)) {
                // If either type is "Unknown" (versus Any), propagate the Unknown.
                return (0, types_1.isUnknown)(valueSubtypeExpanded) || (0, types_1.isUnknown)(subjectSubtypeExpanded)
                    ? (0, typeUtils_1.preserveUnknown)(valueSubtypeExpanded, subjectSubtypeExpanded)
                    : types_1.AnyType.create();
            }
            // If both types are literals, we can compare the literal values directly.
            if ((0, types_1.isClassInstance)(subjectSubtypeExpanded) &&
                (0, typeUtils_1.isLiteralType)(subjectSubtypeExpanded) &&
                (0, types_1.isClassInstance)(valueSubtypeExpanded) &&
                (0, typeUtils_1.isLiteralType)(valueSubtypeExpanded)) {
                return types_1.ClassType.isLiteralValueSame(valueSubtypeExpanded, subjectSubtypeExpanded)
                    ? valueSubtypeUnexpanded
                    : undefined;
            }
            // Determine if assignment is supported for this combination of
            // value subtype and matching subtype.
            const returnType = evaluator.useSpeculativeMode(pattern.expression, () => evaluator.getTypeOfMagicMethodCall(valueSubtypeExpanded, '__eq__', [{ type: subjectSubtypeExpanded }], pattern.expression, 
            /* expectedType */ undefined));
            return returnType ? valueSubtypeUnexpanded : undefined;
        }));
        return undefined;
    });
    return (0, types_1.combineTypes)(narrowedSubtypes);
}
// Returns information about all subtypes that match the definition of a "mapping" as
// specified in PEP 634.
function getMappingPatternInfo(evaluator, type, node) {
    const mappingInfo = [];
    (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
        const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
        if ((0, types_1.isAnyOrUnknown)(concreteSubtype)) {
            mappingInfo.push({
                subtype,
                dictTypeArgs: {
                    key: concreteSubtype,
                    value: concreteSubtype,
                },
            });
            return;
        }
        if ((0, types_1.isClassInstance)(concreteSubtype)) {
            // Is it a TypedDict?
            if (types_1.ClassType.isTypedDictClass(concreteSubtype)) {
                mappingInfo.push({
                    subtype,
                    typedDict: concreteSubtype,
                });
                return;
            }
            // Is it a subclass of Mapping?
            let mroClassToSpecialize;
            for (const mroClass of concreteSubtype.details.mro) {
                if ((0, types_1.isInstantiableClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, 'Mapping')) {
                    mroClassToSpecialize = mroClass;
                    break;
                }
            }
            if (mroClassToSpecialize) {
                const specializedMapping = (0, typeUtils_1.partiallySpecializeType)(mroClassToSpecialize, concreteSubtype);
                if (specializedMapping.typeArguments && specializedMapping.typeArguments.length >= 2) {
                    mappingInfo.push({
                        subtype,
                        dictTypeArgs: {
                            key: specializedMapping.typeArguments[0],
                            value: specializedMapping.typeArguments[1],
                        },
                    });
                }
                return;
            }
            // Is it a superclass of Mapping?
            const mappingType = evaluator.getTypingType(node, 'Mapping');
            if (mappingType && (0, types_1.isInstantiableClass)(mappingType)) {
                const mappingObject = types_1.ClassType.cloneAsInstance(mappingType);
                if (evaluator.assignType(type, mappingObject)) {
                    mappingInfo.push({
                        subtype,
                        dictTypeArgs: {
                            key: types_1.UnknownType.create(),
                            value: types_1.UnknownType.create(),
                        },
                    });
                }
            }
        }
    });
    return mappingInfo;
}
// Returns information about all subtypes that match the definition of a "sequence" as
// specified in PEP 634. For types that are not sequences or sequences that are not of
// sufficient length, it sets definiteNoMatch to true.
function getSequencePatternInfo(evaluator, pattern, type) {
    const patternEntryCount = pattern.entries.length;
    const patternStarEntryIndex = pattern.starEntryIndex;
    const sequenceInfo = [];
    (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
        var _a;
        const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
        let mroClassToSpecialize;
        let pushedEntry = false;
        if ((0, types_1.isClassInstance)(concreteSubtype)) {
            for (const mroClass of concreteSubtype.details.mro) {
                if (!(0, types_1.isInstantiableClass)(mroClass)) {
                    break;
                }
                // Strings, bytes, and bytearray are explicitly excluded.
                if (types_1.ClassType.isBuiltIn(mroClass, 'str') ||
                    types_1.ClassType.isBuiltIn(mroClass, 'bytes') ||
                    types_1.ClassType.isBuiltIn(mroClass, 'bytearray')) {
                    // This is definitely not a match.
                    sequenceInfo.push({
                        subtype,
                        entryTypes: [],
                        isIndeterminateLength: true,
                        isDefiniteNoMatch: true,
                    });
                    return;
                }
                if (types_1.ClassType.isBuiltIn(mroClass, 'Sequence')) {
                    mroClassToSpecialize = mroClass;
                    break;
                }
                if ((0, typeUtils_1.isTupleClass)(mroClass)) {
                    mroClassToSpecialize = mroClass;
                    break;
                }
            }
            if (mroClassToSpecialize) {
                const specializedSequence = (0, typeUtils_1.partiallySpecializeType)(mroClassToSpecialize, concreteSubtype);
                if ((0, typeUtils_1.isTupleClass)(specializedSequence)) {
                    const typeArgs = (_a = specializedSequence.tupleTypeArguments) !== null && _a !== void 0 ? _a : [
                        { type: types_1.UnknownType.create(), isUnbounded: true },
                    ];
                    const tupleIndeterminateIndex = typeArgs.findIndex((t) => t.isUnbounded || (0, types_1.isUnpackedVariadicTypeVar)(t.type));
                    // If the tuple contains an indeterminate entry, expand or remove that
                    // entry to match the length of the pattern if possible.
                    if (tupleIndeterminateIndex >= 0) {
                        while (typeArgs.length < patternEntryCount) {
                            typeArgs.splice(tupleIndeterminateIndex, 0, typeArgs[tupleIndeterminateIndex]);
                        }
                        if (typeArgs.length > patternEntryCount && patternStarEntryIndex === undefined) {
                            typeArgs.splice(tupleIndeterminateIndex, 1);
                        }
                    }
                    // If the pattern contains a star entry and there are too many entries
                    // in the tuple, we can collapse some of them into the star entry.
                    if (patternStarEntryIndex !== undefined &&
                        typeArgs.length >= 2 &&
                        typeArgs.length > patternEntryCount) {
                        const entriesToCombine = typeArgs.length - patternEntryCount + 1;
                        const removedEntries = typeArgs.splice(patternStarEntryIndex, entriesToCombine);
                        typeArgs.splice(patternStarEntryIndex, 0, {
                            type: (0, types_1.combineTypes)(removedEntries.map((t) => t.type)),
                            isUnbounded: removedEntries.every((t) => t.isUnbounded || (0, types_1.isUnpackedVariadicTypeVar)(t.type)),
                        });
                    }
                    if (typeArgs.length === patternEntryCount) {
                        let isDefiniteNoMatch = false;
                        let isPotentialNoMatch = tupleIndeterminateIndex >= 0;
                        if (patternStarEntryIndex !== undefined && patternEntryCount === 1) {
                            isPotentialNoMatch = false;
                        }
                        for (let i = 0; i < patternEntryCount; i++) {
                            const subPattern = pattern.entries[i];
                            const typeArg = typeArgs[i].type;
                            const narrowedType = narrowTypeBasedOnPattern(evaluator, typeArg, subPattern, 
                            /* isPositiveTest */ true);
                            if ((0, types_1.isNever)(narrowedType)) {
                                isDefiniteNoMatch = true;
                            }
                        }
                        sequenceInfo.push({
                            subtype,
                            entryTypes: isDefiniteNoMatch ? [] : typeArgs.map((t) => t.type),
                            isIndeterminateLength: false,
                            isTuple: true,
                            isDefiniteNoMatch,
                            isPotentialNoMatch,
                        });
                        pushedEntry = true;
                    }
                    // If the pattern contains a star entry and the pattern associated with
                    // the star entry is unbounded, we can remove it completely under the
                    // assumption that the star pattern will capture nothing.
                    if (patternStarEntryIndex !== undefined) {
                        let tryMatchStarSequence = false;
                        if (typeArgs.length === patternEntryCount - 1) {
                            tryMatchStarSequence = true;
                            typeArgs.splice(patternStarEntryIndex, 0, {
                                type: types_1.AnyType.create(),
                                isUnbounded: true,
                            });
                        }
                        else if (typeArgs.length === patternEntryCount &&
                            typeArgs[patternStarEntryIndex].isUnbounded) {
                            tryMatchStarSequence = true;
                        }
                        if (tryMatchStarSequence) {
                            let isDefiniteNoMatch = false;
                            for (let i = 0; i < patternEntryCount; i++) {
                                if (i === patternStarEntryIndex) {
                                    continue;
                                }
                                const subPattern = pattern.entries[i];
                                const typeArg = typeArgs[i].type;
                                const narrowedType = narrowTypeBasedOnPattern(evaluator, typeArg, subPattern, 
                                /* isPositiveTest */ true);
                                if ((0, types_1.isNever)(narrowedType)) {
                                    isDefiniteNoMatch = true;
                                }
                            }
                            sequenceInfo.push({
                                subtype,
                                entryTypes: isDefiniteNoMatch ? [] : typeArgs.map((t) => t.type),
                                isIndeterminateLength: false,
                                isTuple: true,
                                isDefiniteNoMatch,
                            });
                            pushedEntry = true;
                        }
                    }
                }
                else {
                    sequenceInfo.push({
                        subtype,
                        entryTypes: [
                            specializedSequence.typeArguments && specializedSequence.typeArguments.length > 0
                                ? specializedSequence.typeArguments[0]
                                : types_1.UnknownType.create(),
                        ],
                        isIndeterminateLength: true,
                        isDefiniteNoMatch: false,
                    });
                    pushedEntry = true;
                }
            }
        }
        if (!pushedEntry) {
            // If it wasn't a subtype of Sequence, see if it's a supertype.
            const sequenceType = evaluator.getTypingType(pattern, 'Sequence');
            if (sequenceType && (0, types_1.isInstantiableClass)(sequenceType)) {
                const sequenceTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(sequenceType));
                if ((0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluator, types_1.ClassType.cloneAsInstance(sequenceType), subtype, sequenceTypeVarContext, (0, parseTreeUtils_1.getTypeVarScopesForNode)(pattern), pattern.start)) {
                    const specializedSequence = (0, typeUtils_1.applySolvedTypeVars)(types_1.ClassType.cloneAsInstantiable(sequenceType), sequenceTypeVarContext);
                    if (specializedSequence.typeArguments && specializedSequence.typeArguments.length > 0) {
                        sequenceInfo.push({
                            subtype,
                            entryTypes: [specializedSequence.typeArguments[0]],
                            isIndeterminateLength: true,
                            isDefiniteNoMatch: false,
                            isPotentialNoMatch: true,
                        });
                        return;
                    }
                }
                if (evaluator.assignType(subtype, types_1.ClassType.cloneForSpecialization(types_1.ClassType.cloneAsInstance(sequenceType), [types_1.UnknownType.create()], 
                /* isTypeArgumentExplicit */ true))) {
                    sequenceInfo.push({
                        subtype,
                        entryTypes: [types_1.UnknownType.create()],
                        isIndeterminateLength: true,
                        isDefiniteNoMatch: false,
                        isPotentialNoMatch: true,
                    });
                    return;
                }
            }
            // Push an entry that indicates that this is definitely not a match.
            sequenceInfo.push({
                subtype,
                entryTypes: [],
                isIndeterminateLength: true,
                isDefiniteNoMatch: true,
            });
        }
    });
    return sequenceInfo;
}
function getTypeOfPatternSequenceEntry(evaluator, node, sequenceInfo, entryIndex, entryCount, starEntryIndex, unpackStarEntry) {
    if (sequenceInfo.isIndeterminateLength) {
        let entryType = sequenceInfo.entryTypes[0];
        if (!unpackStarEntry && entryIndex === starEntryIndex && !(0, types_1.isNever)(entryType)) {
            entryType = wrapTypeInList(evaluator, node, entryType);
        }
        return entryType;
    }
    if (starEntryIndex === undefined || entryIndex < starEntryIndex) {
        return sequenceInfo.entryTypes[entryIndex];
    }
    if (entryIndex === starEntryIndex) {
        // Create a list out of the entries that map to the star entry.
        // Note that we strip literal types here.
        const starEntryTypes = sequenceInfo.entryTypes
            .slice(starEntryIndex, starEntryIndex + sequenceInfo.entryTypes.length - entryCount + 1)
            .map((type) => evaluator.stripLiteralValue(type));
        let entryType = (0, types_1.combineTypes)(starEntryTypes);
        if (!unpackStarEntry) {
            entryType = wrapTypeInList(evaluator, node, entryType);
        }
        return entryType;
    }
    // The entry index is past the index of the star entry, so we need
    // to index from the end of the sequence rather than the start.
    const itemIndex = sequenceInfo.entryTypes.length - (entryCount - entryIndex);
    (0, debug_1.assert)(itemIndex >= 0 && itemIndex < sequenceInfo.entryTypes.length);
    return sequenceInfo.entryTypes[itemIndex];
}
// Recursively assigns the specified type to the pattern and any capture
// nodes within it. It returns the narrowed type, as dictated by the pattern.
function assignTypeToPatternTargets(evaluator, type, isTypeIncomplete, pattern) {
    // Further narrow the type based on this pattern.
    const narrowedType = narrowTypeBasedOnPattern(evaluator, type, pattern, /* positiveTest */ true);
    switch (pattern.nodeType) {
        case 65 /* ParseNodeType.PatternSequence */: {
            const sequenceInfo = getSequencePatternInfo(evaluator, pattern, narrowedType).filter((seqInfo) => !seqInfo.isDefiniteNoMatch);
            pattern.entries.forEach((entry, index) => {
                const entryType = (0, types_1.combineTypes)(sequenceInfo.map((info) => getTypeOfPatternSequenceEntry(evaluator, pattern, info, index, pattern.entries.length, pattern.starEntryIndex, 
                /* unpackStarEntry */ false)));
                assignTypeToPatternTargets(evaluator, entryType, isTypeIncomplete, entry);
            });
            break;
        }
        case 66 /* ParseNodeType.PatternAs */: {
            if (pattern.target) {
                evaluator.assignTypeToExpression(pattern.target, narrowedType, isTypeIncomplete, pattern.target);
            }
            let runningNarrowedType = narrowedType;
            pattern.orPatterns.forEach((orPattern) => {
                assignTypeToPatternTargets(evaluator, runningNarrowedType, isTypeIncomplete, orPattern);
                // OR patterns are evaluated left to right, so we can narrow
                // the type as we go.
                runningNarrowedType = narrowTypeBasedOnPattern(evaluator, runningNarrowedType, orPattern, 
                /* positiveTest */ false);
            });
            break;
        }
        case 69 /* ParseNodeType.PatternCapture */: {
            if (pattern.isWildcard) {
                if (!isTypeIncomplete) {
                    if ((0, types_1.isUnknown)(narrowedType)) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, localize_1.LocMessage.wildcardPatternTypeUnknown(), pattern.target);
                    }
                    else if ((0, typeUtils_1.isPartlyUnknown)(narrowedType)) {
                        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                        diagAddendum.addMessage(localize_1.LocAddendum.typeOfSymbol().format({
                            name: '_',
                            type: evaluator.printType(narrowedType, { expandTypeAlias: true }),
                        }));
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, localize_1.LocMessage.wildcardPatternTypePartiallyUnknown() + diagAddendum.getString(), pattern.target);
                    }
                    else if ((0, types_1.isAny)(narrowedType)) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.wildcardPatternTypeAny(), pattern.target);
                    }
                }
            }
            else {
                evaluator.assignTypeToExpression(pattern.target, narrowedType, isTypeIncomplete, pattern.target);
            }
            break;
        }
        case 70 /* ParseNodeType.PatternMapping */: {
            const mappingInfo = getMappingPatternInfo(evaluator, narrowedType, pattern);
            pattern.entries.forEach((mappingEntry) => {
                const keyTypes = [];
                const valueTypes = [];
                mappingInfo.forEach((mappingSubtypeInfo) => {
                    if (mappingSubtypeInfo.typedDict) {
                        if (mappingEntry.nodeType === 71 /* ParseNodeType.PatternMappingKeyEntry */) {
                            const keyType = narrowTypeBasedOnPattern(evaluator, evaluator.getBuiltInObject(pattern, 'str'), mappingEntry.keyPattern, 
                            /* isPositiveTest */ true);
                            keyTypes.push(keyType);
                            (0, typeUtils_1.doForEachSubtype)(keyType, (keySubtype) => {
                                if ((0, types_1.isClassInstance)(keySubtype) &&
                                    types_1.ClassType.isBuiltIn(keySubtype, 'str') &&
                                    (0, typeUtils_1.isLiteralType)(keySubtype)) {
                                    const tdEntries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, mappingSubtypeInfo.typedDict);
                                    const valueInfo = tdEntries.knownItems.get(keySubtype.literalValue);
                                    valueTypes.push(valueInfo ? valueInfo.valueType : types_1.UnknownType.create());
                                }
                                else {
                                    valueTypes.push(types_1.UnknownType.create());
                                }
                            });
                        }
                        else if (mappingEntry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */) {
                            keyTypes.push(evaluator.getBuiltInObject(pattern, 'str'));
                            valueTypes.push(types_1.UnknownType.create());
                        }
                    }
                    else if (mappingSubtypeInfo.dictTypeArgs) {
                        if (mappingEntry.nodeType === 71 /* ParseNodeType.PatternMappingKeyEntry */) {
                            const keyType = narrowTypeBasedOnPattern(evaluator, mappingSubtypeInfo.dictTypeArgs.key, mappingEntry.keyPattern, 
                            /* isPositiveTest */ true);
                            keyTypes.push(keyType);
                            valueTypes.push(narrowTypeBasedOnPattern(evaluator, mappingSubtypeInfo.dictTypeArgs.value, mappingEntry.valuePattern, 
                            /* isPositiveTest */ true));
                        }
                        else if (mappingEntry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */) {
                            keyTypes.push(mappingSubtypeInfo.dictTypeArgs.key);
                            valueTypes.push(mappingSubtypeInfo.dictTypeArgs.value);
                        }
                    }
                });
                const keyType = (0, types_1.combineTypes)(keyTypes);
                const valueType = (0, types_1.combineTypes)(valueTypes);
                if (mappingEntry.nodeType === 71 /* ParseNodeType.PatternMappingKeyEntry */) {
                    assignTypeToPatternTargets(evaluator, keyType, isTypeIncomplete, mappingEntry.keyPattern);
                    assignTypeToPatternTargets(evaluator, valueType, isTypeIncomplete, mappingEntry.valuePattern);
                }
                else if (mappingEntry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */) {
                    const dictClass = evaluator.getBuiltInType(pattern, 'dict');
                    const strType = evaluator.getBuiltInObject(pattern, 'str');
                    const dictType = dictClass && (0, types_1.isInstantiableClass)(dictClass) && (0, types_1.isClassInstance)(strType)
                        ? types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictClass, [keyType, valueType], 
                        /* isTypeArgumentExplicit */ true))
                        : types_1.UnknownType.create();
                    evaluator.assignTypeToExpression(mappingEntry.target, dictType, isTypeIncomplete, mappingEntry.target);
                }
            });
            break;
        }
        case 68 /* ParseNodeType.PatternClass */: {
            const argTypes = pattern.arguments.map((arg) => []);
            evaluator.mapSubtypesExpandTypeVars(narrowedType, /* options */ undefined, (expandedSubtype) => {
                if ((0, types_1.isClassInstance)(expandedSubtype)) {
                    (0, typeUtils_1.doForEachSubtype)(narrowedType, (subjectSubtype) => {
                        const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subjectSubtype);
                        if ((0, types_1.isAnyOrUnknown)(concreteSubtype)) {
                            pattern.arguments.forEach((arg, index) => {
                                argTypes[index].push(concreteSubtype);
                            });
                        }
                        else if ((0, types_1.isClassInstance)(concreteSubtype)) {
                            // Are there any positional arguments? If so, try to get the mappings for
                            // these arguments by fetching the __match_args__ symbol from the class.
                            let positionalArgNames = [];
                            if (pattern.arguments.some((arg) => !arg.name)) {
                                positionalArgNames = getPositionalMatchArgNames(evaluator, types_1.ClassType.cloneAsInstantiable(expandedSubtype));
                            }
                            pattern.arguments.forEach((arg, index) => {
                                const narrowedArgType = narrowTypeOfClassPatternArgument(evaluator, arg, index, positionalArgNames, types_1.ClassType.cloneAsInstantiable(expandedSubtype), 
                                /* isPositiveTest */ true);
                                argTypes[index].push(narrowedArgType);
                            });
                        }
                    });
                }
                else {
                    pattern.arguments.forEach((arg, index) => {
                        argTypes[index].push(types_1.UnknownType.create());
                    });
                }
                return undefined;
            });
            pattern.arguments.forEach((arg, index) => {
                assignTypeToPatternTargets(evaluator, (0, types_1.combineTypes)(argTypes[index]), isTypeIncomplete, arg.pattern);
            });
            break;
        }
        case 67 /* ParseNodeType.PatternLiteral */:
        case 73 /* ParseNodeType.PatternValue */:
        case 0 /* ParseNodeType.Error */: {
            // Nothing to do here.
            break;
        }
    }
    return narrowedType;
}
exports.assignTypeToPatternTargets = assignTypeToPatternTargets;
function wrapTypeInList(evaluator, node, type) {
    var _a;
    if ((0, types_1.isNever)(type)) {
        return type;
    }
    const listObjectType = (0, typeUtils_1.convertToInstance)(evaluator.getBuiltInObject(node, 'list'));
    if (listObjectType && (0, types_1.isClassInstance)(listObjectType)) {
        // If the type is a union that contains an Any or Unknown, eliminate the other
        // types before wrapping it in a list.
        type = (_a = (0, typeUtils_1.containsAnyOrUnknown)(type, /* recurse */ false)) !== null && _a !== void 0 ? _a : type;
        return types_1.ClassType.cloneForSpecialization(listObjectType, [type], /* isTypeArgumentExplicit */ true);
    }
    return types_1.UnknownType.create();
}
function validateClassPattern(evaluator, pattern) {
    let exprType = evaluator.getTypeOfExpression(pattern.className, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
    // If the expression is a type alias or other special form, treat it
    // as the special form rather than the class.
    if (exprType.specialForm) {
        exprType = exprType.specialForm;
    }
    if ((0, types_1.isAnyOrUnknown)(exprType)) {
        return;
    }
    // Check for certain uses of type aliases that generate runtime exceptions.
    if (exprType.typeAliasInfo &&
        (0, types_1.isInstantiableClass)(exprType) &&
        exprType.typeArguments &&
        exprType.isTypeArgumentExplicit) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.classPatternTypeAlias().format({ type: evaluator.printType(exprType) }), pattern.className);
    }
    else if (!(0, types_1.isInstantiableClass)(exprType)) {
        if (!(0, types_1.isNever)(exprType)) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocAddendum.typeNotClass().format({ type: evaluator.printType(exprType) }), pattern.className);
        }
    }
    else {
        const isBuiltIn = isClassSpecialCaseForClassPattern(exprType);
        // If it's a special-case builtin class, only positional arguments are allowed.
        if (isBuiltIn) {
            if (pattern.arguments.length === 1 && pattern.arguments[0].name) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.classPatternBuiltInArgPositional(), pattern.arguments[0].name);
            }
        }
        // Emits an error if the supplied number of positional patterns is less than
        // expected for the given subject type.
        let positionalPatternCount = pattern.arguments.findIndex((arg) => arg.name !== undefined);
        if (positionalPatternCount < 0) {
            positionalPatternCount = pattern.arguments.length;
        }
        let expectedPatternCount = 1;
        if (!isBuiltIn) {
            let positionalArgNames = [];
            if (pattern.arguments.some((arg) => !arg.name)) {
                positionalArgNames = getPositionalMatchArgNames(evaluator, exprType);
            }
            expectedPatternCount = positionalArgNames.length;
        }
        if (positionalPatternCount > expectedPatternCount) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.classPatternPositionalArgCount().format({
                type: exprType.details.name,
                expected: expectedPatternCount,
                received: positionalPatternCount,
            }), pattern.arguments[expectedPatternCount]);
        }
    }
}
exports.validateClassPattern = validateClassPattern;
// Determines whether the reference expression has a relationship to the subject expression
// in such a way that the type of the reference expression can be narrowed based
// on the narrowed type of the subject expression.
function getPatternSubtypeNarrowingCallback(evaluator, reference, subjectExpression) {
    // Look for a subject expression of the form <reference>[<literal>] where
    // <literal> is either a str (for TypedDict discrimination) or an int
    // (for tuple discrimination).
    if (subjectExpression.nodeType === 24 /* ParseNodeType.Index */ &&
        subjectExpression.items.length === 1 &&
        !subjectExpression.trailingComma &&
        subjectExpression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
        (0, parseTreeUtils_1.isMatchingExpression)(reference, subjectExpression.baseExpression)) {
        const indexTypeResult = evaluator.getTypeOfExpression(subjectExpression.items[0].valueExpression);
        const indexType = indexTypeResult.type;
        if ((0, types_1.isClassInstance)(indexType) && (0, typeUtils_1.isLiteralType)(indexType)) {
            if (types_1.ClassType.isBuiltIn(indexType, ['int', 'str'])) {
                const unnarrowedReferenceTypeResult = evaluator.getTypeOfExpression(subjectExpression.baseExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const unnarrowedReferenceType = unnarrowedReferenceTypeResult.type;
                return (narrowedSubjectType) => {
                    let canNarrow = true;
                    const typesToCombine = [];
                    (0, typeUtils_1.doForEachSubtype)(narrowedSubjectType, (subtype) => {
                        subtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
                        if ((0, types_1.isClassInstance)(subtype) && subtype.literalValue !== undefined) {
                            if (types_1.ClassType.isBuiltIn(indexType, 'str')) {
                                typesToCombine.push((0, typeGuards_1.narrowTypeForDiscriminatedDictEntryComparison)(evaluator, unnarrowedReferenceType, indexType, subtype, 
                                /* isPositiveTest */ true));
                            }
                            else {
                                typesToCombine.push((0, typeGuards_1.narrowTypeForDiscriminatedTupleComparison)(evaluator, unnarrowedReferenceType, indexType, subtype, 
                                /* isPositiveTest */ true));
                            }
                        }
                        else if (!(0, types_1.isNever)(subtype)) {
                            // We don't know how to narrow in this case.
                            canNarrow = false;
                        }
                    });
                    if (!canNarrow) {
                        return undefined;
                    }
                    return {
                        type: (0, types_1.combineTypes)(typesToCombine),
                        isIncomplete: indexTypeResult.isIncomplete || unnarrowedReferenceTypeResult.isIncomplete,
                    };
                };
            }
        }
    }
    // Look for a subject expression that contains the reference
    // expression as an entry in a tuple.
    if (subjectExpression.nodeType === 52 /* ParseNodeType.Tuple */) {
        const matchingEntryIndex = subjectExpression.expressions.findIndex((expr) => (0, parseTreeUtils_1.isMatchingExpression)(reference, expr));
        if (matchingEntryIndex >= 0) {
            const typeResult = evaluator.getTypeOfExpression(subjectExpression.expressions[matchingEntryIndex]);
            return (narrowedSubjectType) => {
                let canNarrow = true;
                const narrowedSubtypes = [];
                (0, typeUtils_1.doForEachSubtype)(narrowedSubjectType, (subtype) => {
                    if ((0, types_1.isClassInstance)(subtype) &&
                        types_1.ClassType.isBuiltIn(subtype, 'tuple') &&
                        subtype.tupleTypeArguments &&
                        matchingEntryIndex < subtype.tupleTypeArguments.length &&
                        subtype.tupleTypeArguments.every((e) => !e.isUnbounded)) {
                        narrowedSubtypes.push(subtype.tupleTypeArguments[matchingEntryIndex].type);
                    }
                    else if ((0, types_1.isNever)(narrowedSubjectType)) {
                        narrowedSubtypes.push(narrowedSubjectType);
                    }
                    else {
                        canNarrow = false;
                    }
                });
                return canNarrow
                    ? { type: (0, types_1.combineTypes)(narrowedSubtypes), isIncomplete: typeResult.isIncomplete }
                    : undefined;
            };
        }
    }
    // Look for a subject expression of the form "a.b" where "b" is an attribute
    // that is annotated with a literal type.
    if (subjectExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
        (0, parseTreeUtils_1.isMatchingExpression)(reference, subjectExpression.leftExpression)) {
        const unnarrowedReferenceTypeResult = evaluator.getTypeOfExpression(subjectExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
        const unnarrowedReferenceType = unnarrowedReferenceTypeResult.type;
        return (narrowedSubjectType) => {
            if ((0, types_1.isNever)(narrowedSubjectType)) {
                return { type: types_1.NeverType.createNever() };
            }
            if (!(0, typeUtils_1.isLiteralTypeOrUnion)(narrowedSubjectType)) {
                return undefined;
            }
            const resultType = (0, typeUtils_1.mapSubtypes)(narrowedSubjectType, (literalSubtype) => {
                (0, debug_1.assert)((0, types_1.isClassInstance)(literalSubtype) && literalSubtype.literalValue !== undefined);
                return (0, typeGuards_1.narrowTypeForDiscriminatedLiteralFieldComparison)(evaluator, unnarrowedReferenceType, subjectExpression.memberName.value, literalSubtype, 
                /* isPositiveTest */ true);
            });
            return {
                type: resultType,
            };
        };
    }
    return undefined;
}
exports.getPatternSubtypeNarrowingCallback = getPatternSubtypeNarrowingCallback;
function reportUnnecessaryPattern(evaluator, pattern, subjectType) {
    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison, localize_1.LocMessage.patternNeverMatches().format({ type: evaluator.printType(subjectType) }), pattern);
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/program.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/analyzer/program.ts ***!
  \***************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * program.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * An object that tracks all of the source files being analyzed
 * and all of their recursive imports.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Program = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const vscode_languageserver_textdocument_1 = __webpack_require__(/*! vscode-languageserver-textdocument */ "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/main.js");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ../common/console */ "../pyright-internal/src/common/console.ts");
const debug = __importStar(__webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts"));
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const logTracker_1 = __webpack_require__(/*! ../common/logTracker */ "../pyright-internal/src/common/logTracker.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
__webpack_require__(/*! ../common/serviceProviderExtensions */ "../pyright-internal/src/common/serviceProviderExtensions.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const cacheManager_1 = __webpack_require__(/*! ./cacheManager */ "../pyright-internal/src/analyzer/cacheManager.ts");
const circularDependency_1 = __webpack_require__(/*! ./circularDependency */ "../pyright-internal/src/analyzer/circularDependency.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const sourceFile_1 = __webpack_require__(/*! ./sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const sourceFileInfo_1 = __webpack_require__(/*! ./sourceFileInfo */ "../pyright-internal/src/analyzer/sourceFileInfo.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ./sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const sourceMapper_1 = __webpack_require__(/*! ./sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const tracePrinter_1 = __webpack_require__(/*! ./tracePrinter */ "../pyright-internal/src/analyzer/tracePrinter.ts");
const typeEvaluatorWithTracker_1 = __webpack_require__(/*! ./typeEvaluatorWithTracker */ "../pyright-internal/src/analyzer/typeEvaluatorWithTracker.ts");
const typeStubWriter_1 = __webpack_require__(/*! ./typeStubWriter */ "../pyright-internal/src/analyzer/typeStubWriter.ts");
const _maxImportDepth = 256;
// Track edit mode related information.
class EditModeTracker {
    constructor() {
        this._isEditMode = false;
        this._mutatedFiles = [];
    }
    get isEditMode() {
        return this._isEditMode;
    }
    addMutatedFiles(file) {
        this._mutatedFiles.push(file);
    }
    enable() {
        this._isEditMode = true;
        this._mutatedFiles = [];
    }
    disable() {
        this._isEditMode = false;
        const files = this._mutatedFiles;
        this._mutatedFiles = [];
        return files;
    }
}
// Container for all of the files that are being analyzed. Files
// can fall into one or more of the following categories:
//  Tracked - specified by the config options
//  Referenced - part of the transitive closure
//  Opened - temporarily opened in the editor
//  Shadowed - implementation file that shadows a type stub file
class Program {
    constructor(initialImportResolver, initialConfigOptions, serviceProvider, logTracker, _disableChecker, id) {
        var _a;
        this.serviceProvider = serviceProvider;
        this._disableChecker = _disableChecker;
        this._sourceFileList = [];
        this._sourceFileMap = new Map();
        this._parsedFileCount = 0;
        this._editModeTracker = new EditModeTracker();
        this._lookUpImport = (fileUriOrModule, options) => {
            var _a;
            let sourceFileInfo;
            if (uri_1.Uri.is(fileUriOrModule)) {
                sourceFileInfo = this.getSourceFileInfo(fileUriOrModule);
            }
            else {
                // Resolve the import.
                const importResult = this._importResolver.resolveImport(fileUriOrModule.importingFileUri, this._configOptions.findExecEnvironment(fileUriOrModule.importingFileUri), {
                    leadingDots: 0,
                    nameParts: fileUriOrModule.nameParts,
                    importedSymbols: undefined,
                });
                if (importResult.isImportFound && !importResult.isNativeLib && importResult.resolvedUris.length > 0) {
                    const resolvedPath = importResult.resolvedUris[importResult.resolvedUris.length - 1];
                    if (!resolvedPath.isEmpty()) {
                        // See if the source file already exists in the program.
                        sourceFileInfo = this.getSourceFileInfo(resolvedPath);
                        if (!sourceFileInfo) {
                            // Start tracking the source file.
                            this.addTrackedFile(resolvedPath);
                            sourceFileInfo = this.getSourceFileInfo(resolvedPath);
                        }
                    }
                }
            }
            if (!sourceFileInfo) {
                return undefined;
            }
            if (options === null || options === void 0 ? void 0 : options.skipParsing) {
                // Return dummy information if the caller has indicated that parsing is
                // unnecessary. This is used in cases where the caller simply wants to
                // know if the source file exists but is not interested in the contents.
                return {
                    symbolTable: new Map(),
                    dunderAllNames: undefined,
                    usesUnsupportedDunderAllForm: false,
                    get docString() {
                        return undefined;
                    },
                    isInPyTypedPackage: false,
                };
            }
            if (sourceFileInfo.sourceFile.isBindingRequired()) {
                // Bind the file if it's not already bound. Don't count this time
                // against the type checker.
                timing_1.timingStats.typeCheckerTime.subtractFromTime(() => {
                    this._bindFile(sourceFileInfo, /* content */ undefined, options === null || options === void 0 ? void 0 : options.skipFileNeededCheck);
                });
            }
            const symbolTable = sourceFileInfo.sourceFile.getModuleSymbolTable();
            if (!symbolTable) {
                return undefined;
            }
            const parseResults = sourceFileInfo.sourceFile.getParserOutput();
            const moduleNode = parseResults.parseTree;
            const fileInfo = AnalyzerNodeInfo.getFileInfo(moduleNode);
            const dunderAllInfo = AnalyzerNodeInfo.getDunderAllInfo(parseResults.parseTree);
            return {
                symbolTable,
                dunderAllNames: dunderAllInfo === null || dunderAllInfo === void 0 ? void 0 : dunderAllInfo.names,
                usesUnsupportedDunderAllForm: (_a = dunderAllInfo === null || dunderAllInfo === void 0 ? void 0 : dunderAllInfo.usesUnsupportedDunderAllForm) !== null && _a !== void 0 ? _a : false,
                get docString() {
                    return (0, parseTreeUtils_1.getDocString)(moduleNode.statements);
                },
                isInPyTypedPackage: fileInfo.isInPyTypedPackage,
            };
        };
        this._console = serviceProvider.tryGet(serviceKeys_1.ServiceKeys.console) || new console_1.StandardConsole();
        this._logTracker = logTracker !== null && logTracker !== void 0 ? logTracker : new logTracker_1.LogTracker(this._console, 'FG');
        this._importResolver = initialImportResolver;
        this._configOptions = initialConfigOptions;
        this._sourceFileFactory = serviceProvider.sourceFileFactory();
        this._cacheManager = (_a = serviceProvider.tryGet(serviceKeys_1.ServiceKeys.cacheManager)) !== null && _a !== void 0 ? _a : new cacheManager_1.CacheManager();
        this._cacheManager.registerCacheOwner(this);
        this._createNewEvaluator();
        this._id = id !== null && id !== void 0 ? id : `Prog_${Program._nextId}`;
        Program._nextId += 1;
    }
    get id() {
        return this._id;
    }
    get console() {
        return this._console;
    }
    get rootPath() {
        return this._configOptions.projectRoot;
    }
    get evaluator() {
        return this._evaluator;
    }
    get configOptions() {
        return this._configOptions;
    }
    get importResolver() {
        return this._importResolver;
    }
    get fileSystem() {
        return this._importResolver.fileSystem;
    }
    dispose() {
        this._cacheManager.unregisterCacheOwner(this);
    }
    enterEditMode() {
        this._editModeTracker.enable();
    }
    exitEditMode() {
        // Stop applying edit mode to new source files.
        const mutatedFiles = this._editModeTracker.disable();
        const filesToDelete = new Set();
        const edits = [];
        // Tell all source files we're no longer in edit mode. Gather
        // up all of their edits and find files that no longer needed.
        mutatedFiles.forEach((fileInfo) => {
            if (fileInfo.isCreatedInEditMode) {
                filesToDelete.add(fileInfo);
            }
            const newContents = fileInfo.restore();
            if (newContents) {
                // Create a text document so we can compute the edits.
                const textDocument = vscode_languageserver_textdocument_1.TextDocument.create(fileInfo.sourceFile.getUri().toString(), 'python', 1, fileInfo.sourceFile.getFileContent() || '');
                // Add an edit action to the list.
                edits.push({
                    fileUri: fileInfo.sourceFile.getUri(),
                    range: {
                        start: { line: 0, character: 0 },
                        end: { line: textDocument.lineCount, character: 0 },
                    },
                    replacementText: newContents,
                });
            }
        });
        // Delete files added while in edit mode
        if (filesToDelete.size > 0) {
            // delete from the back to make sure index is valid.
            for (let i = this._sourceFileList.length - 1; i >= 0; i--) {
                const v = this._sourceFileList[i];
                if (filesToDelete.has(v)) {
                    // We don't need to care about file diagnostics since in edit mode
                    // checker won't run.
                    v.sourceFile.prepareForClose();
                    this._removeSourceFileFromListAndMap(v.sourceFile.getUri(), i);
                }
            }
        }
        if (mutatedFiles.length > 0) {
            // All cache is invalid now.
            this._createNewEvaluator();
        }
        return edits;
    }
    setConfigOptions(configOptions) {
        this._configOptions = configOptions;
        this._importResolver.setConfigOptions(configOptions);
        // Create a new evaluator with the updated config options.
        this._createNewEvaluator();
    }
    setImportResolver(importResolver) {
        this._importResolver = importResolver;
        // Create a new evaluator with the updated import resolver.
        // Otherwise, lookup import passed to type evaluator might use
        // older import resolver when resolving imports after parsing.
        this._createNewEvaluator();
    }
    // Sets the list of tracked files that make up the program.
    setTrackedFiles(fileUris) {
        if (this._sourceFileList.length > 0) {
            // We need to determine which files to remove from the existing file list.
            const newFileMap = new Map();
            fileUris.forEach((path) => {
                newFileMap.set(path.key, path);
            });
            // Files that are not in the tracked file list are
            // marked as no longer tracked.
            this._sourceFileList.forEach((oldFile) => {
                const fileUri = oldFile.sourceFile.getUri();
                if (!newFileMap.has(fileUri.key)) {
                    oldFile.isTracked = false;
                }
            });
        }
        // Add the new files. Only the new items will be added.
        this.addTrackedFiles(fileUris);
        return this._removeUnneededFiles();
    }
    // Allows a caller to set a callback that is called right before
    // a source file is type checked. It is intended for testing only.
    setPreCheckCallback(preCheckCallback) {
        this._preCheckCallback = preCheckCallback;
    }
    // By default, no third-party imports are allowed. This enables
    // third-party imports for a specified import and its children.
    // For example, if importNames is ['tensorflow'], then third-party
    // (absolute) imports are allowed for 'import tensorflow',
    // 'import tensorflow.optimizers', etc.
    setAllowedThirdPartyImports(importNames) {
        this._allowedThirdPartyImports = importNames;
    }
    addTrackedFiles(fileUris, isThirdPartyImport = false, isInPyTypedPackage = false) {
        fileUris.forEach((fileUri) => {
            this.addTrackedFile(fileUri, isThirdPartyImport, isInPyTypedPackage);
        });
    }
    addInterimFile(fileUri) {
        // Double check not already there.
        let fileInfo = this.getSourceFileInfo(fileUri);
        if (!fileInfo) {
            fileInfo = this._createInterimFileInfo(fileUri);
            this._addToSourceFileListAndMap(fileInfo);
        }
        return fileInfo;
    }
    addTrackedFile(fileUri, isThirdPartyImport = false, isInPyTypedPackage = false) {
        let sourceFileInfo = this.getSourceFileInfo(fileUri);
        const moduleImportInfo = this._getModuleImportInfoForFile(fileUri);
        const importName = moduleImportInfo.moduleName;
        if (sourceFileInfo) {
            // The module name may have changed based on updates to the
            // search paths, so update it here.
            sourceFileInfo.sourceFile.setModuleName(importName);
            sourceFileInfo.isTracked = true;
            return sourceFileInfo.sourceFile;
        }
        const sourceFile = this._sourceFileFactory.createSourceFile(this.serviceProvider, fileUri, importName, isThirdPartyImport, isInPyTypedPackage, this._editModeTracker, this._console, this._logTracker);
        sourceFileInfo = new sourceFileInfo_1.SourceFileInfo(sourceFile, 
        /* isTypeshedFile */ false, isThirdPartyImport, isInPyTypedPackage, this._editModeTracker, {
            isTracked: true,
        });
        this._addToSourceFileListAndMap(sourceFileInfo);
        return sourceFile;
    }
    setFileOpened(fileUri, version, contents, options) {
        var _a, _b;
        let sourceFileInfo = this.getSourceFileInfo(fileUri);
        if (!sourceFileInfo) {
            const moduleImportInfo = this._getModuleImportInfoForFile(fileUri);
            const sourceFile = this._sourceFileFactory.createSourceFile(this.serviceProvider, fileUri, moduleImportInfo.moduleName, 
            /* isThirdPartyImport */ false, moduleImportInfo.isThirdPartyPyTypedPresent, this._editModeTracker, this._console, this._logTracker, (_a = options === null || options === void 0 ? void 0 : options.ipythonMode) !== null && _a !== void 0 ? _a : sourceFile_1.IPythonMode.None);
            const chainedFilePath = options === null || options === void 0 ? void 0 : options.chainedFileUri;
            sourceFileInfo = new sourceFileInfo_1.SourceFileInfo(sourceFile, 
            /* isTypeshedFile */ false, 
            /* isThirdPartyImport */ false, 
            /* isThirdPartyPyTypedPresent */ false, this._editModeTracker, {
                isTracked: (_b = options === null || options === void 0 ? void 0 : options.isTracked) !== null && _b !== void 0 ? _b : false,
                chainedSourceFile: chainedFilePath ? this.getSourceFileInfo(chainedFilePath) : undefined,
                isOpenByClient: true,
            });
            this._addToSourceFileListAndMap(sourceFileInfo);
        }
        else {
            sourceFileInfo.isOpenByClient = true;
            // Reset the diagnostic version so we force an update to the
            // diagnostics, which can change based on whether the file is open.
            // We do not set the version to undefined here because that implies
            // there are no diagnostics currently reported for this file.
            sourceFileInfo.diagnosticsVersion = 0;
        }
        (0, sourceFileInfoUtils_1.verifyNoCyclesInChainedFiles)(this, sourceFileInfo);
        sourceFileInfo.sourceFile.setClientVersion(version, contents);
    }
    getChainedUri(fileUri) {
        var _a;
        const sourceFileInfo = this.getSourceFileInfo(fileUri);
        return (_a = sourceFileInfo === null || sourceFileInfo === void 0 ? void 0 : sourceFileInfo.chainedSourceFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getUri();
    }
    updateChainedUri(fileUri, chainedFileUri) {
        const sourceFileInfo = this.getSourceFileInfo(fileUri);
        if (!sourceFileInfo) {
            return;
        }
        sourceFileInfo.chainedSourceFile = chainedFileUri ? this.getSourceFileInfo(chainedFileUri) : undefined;
        sourceFileInfo.sourceFile.markDirty();
        this._markFileDirtyRecursive(sourceFileInfo, new Set());
        (0, sourceFileInfoUtils_1.verifyNoCyclesInChainedFiles)(this, sourceFileInfo);
    }
    setFileClosed(fileUri, isTracked) {
        const sourceFileInfo = this.getSourceFileInfo(fileUri);
        if (sourceFileInfo) {
            sourceFileInfo.isOpenByClient = false;
            sourceFileInfo.isTracked = isTracked !== null && isTracked !== void 0 ? isTracked : sourceFileInfo.isTracked;
            sourceFileInfo.sourceFile.setClientVersion(null, '');
            // There is no guarantee that content is saved before the file is closed.
            // We need to mark the file dirty so we can re-analyze next time.
            // This won't matter much for OpenFileOnly users, but it will matter for
            // people who use diagnosticMode Workspace.
            if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) {
                sourceFileInfo.sourceFile.markDirty();
                this._markFileDirtyRecursive(sourceFileInfo, new Set());
            }
        }
        return this._removeUnneededFiles();
    }
    markAllFilesDirty(evenIfContentsAreSame) {
        const markDirtySet = new Set();
        this._sourceFileList.forEach((sourceFileInfo) => {
            if (evenIfContentsAreSame) {
                sourceFileInfo.sourceFile.markDirty();
            }
            else if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) {
                sourceFileInfo.sourceFile.markDirty();
                // Mark any files that depend on this file as dirty
                // also. This will retrigger analysis of these other files.
                this._markFileDirtyRecursive(sourceFileInfo, markDirtySet);
            }
        });
        if (markDirtySet.size > 0) {
            this._createNewEvaluator();
        }
    }
    markFilesDirty(fileUris, evenIfContentsAreSame) {
        const markDirtySet = new Set();
        fileUris.forEach((fileUri) => {
            const sourceFileInfo = this.getSourceFileInfo(fileUri);
            if (sourceFileInfo) {
                const fileName = fileUri.fileName;
                // Handle builtins and __builtins__ specially. They are implicitly
                // included by all source files.
                if (fileName === 'builtins.pyi' || fileName === '__builtins__.pyi') {
                    this.markAllFilesDirty(evenIfContentsAreSame);
                    return;
                }
                // If !evenIfContentsAreSame, see if the on-disk contents have
                // changed. If the file is open, the on-disk contents don't matter
                // because we'll receive updates directly from the client.
                if (evenIfContentsAreSame ||
                    (!sourceFileInfo.isOpenByClient && sourceFileInfo.sourceFile.didContentsChangeOnDisk())) {
                    sourceFileInfo.sourceFile.markDirty();
                    // Mark any files that depend on this file as dirty
                    // also. This will retrigger analysis of these other files.
                    this._markFileDirtyRecursive(sourceFileInfo, markDirtySet);
                }
            }
        });
        if (markDirtySet.size > 0) {
            this._createNewEvaluator();
        }
    }
    getFileCount(userFileOnly = true) {
        if (userFileOnly) {
            return this._sourceFileList.filter((f) => (0, sourceFileInfoUtils_1.isUserCode)(f)).length;
        }
        return this._sourceFileList.length;
    }
    // Returns the number of files that are considered "user" files and therefore
    // are checked.
    getUserFileCount() {
        return this._sourceFileList.filter((s) => (0, sourceFileInfoUtils_1.isUserCode)(s)).length;
    }
    getUserFiles() {
        return this._sourceFileList.filter((s) => (0, sourceFileInfoUtils_1.isUserCode)(s));
    }
    getOpened() {
        return this._sourceFileList.filter((s) => s.isOpenByClient);
    }
    getFilesToAnalyzeCount() {
        let sourceFileCount = 0;
        if (this._disableChecker) {
            return sourceFileCount;
        }
        this._sourceFileList.forEach((fileInfo) => {
            if (fileInfo.sourceFile.isCheckingRequired()) {
                if (this._shouldCheckFile(fileInfo)) {
                    sourceFileCount++;
                }
            }
        });
        return sourceFileCount;
    }
    isCheckingOnlyOpenFiles() {
        return this._configOptions.checkOnlyOpenFiles || false;
    }
    functionSignatureDisplay() {
        return this._configOptions.functionSignatureDisplay;
    }
    containsSourceFileIn(folder) {
        for (const normalizedSourceFilePath of this._sourceFileMap.values()) {
            if (normalizedSourceFilePath.sourceFile.getUri().startsWith(folder)) {
                return true;
            }
        }
        return false;
    }
    owns(uri) {
        const fileInfo = this.getSourceFileInfo(uri);
        if (fileInfo) {
            // If we already determined whether the file is tracked or not, don't do it again.
            // This will make sure we have consistent look at the state once it is loaded to the memory.
            return fileInfo.isTracked;
        }
        return (0, configOptions_1.matchFileSpecs)(this._configOptions, uri);
    }
    getSourceFile(uri) {
        const sourceFileInfo = this.getSourceFileInfo(uri);
        if (!sourceFileInfo) {
            return undefined;
        }
        return sourceFileInfo.sourceFile;
    }
    getBoundSourceFile(uri) {
        var _a;
        return (_a = this.getBoundSourceFileInfo(uri)) === null || _a === void 0 ? void 0 : _a.sourceFile;
    }
    getSourceFileInfoList() {
        return this._sourceFileList;
    }
    getSourceFileInfo(uri) {
        if (!uri.isEmpty()) {
            return this._sourceFileMap.get(uri.key);
        }
        return undefined;
    }
    getBoundSourceFileInfo(uri, content, force) {
        const sourceFileInfo = this.getSourceFileInfo(uri);
        if (!sourceFileInfo) {
            return undefined;
        }
        this._bindFile(sourceFileInfo, content, force);
        return sourceFileInfo;
    }
    // Performs parsing and analysis of any source files in the program
    // that require it. If a limit time is specified, the operation
    // is interrupted when the time expires. The return value indicates
    // whether the method needs to be called again to complete the
    // analysis. In interactive mode, the timeout is always limited
    // to the smaller value to maintain responsiveness.
    analyze(maxTime, token = vscode_languageserver_1.CancellationToken.None) {
        return this._runEvaluatorWithCancellationToken(token, () => {
            const elapsedTime = new timing_1.Duration();
            const openFiles = this._sourceFileList.filter((sf) => sf.isOpenByClient && sf.sourceFile.isCheckingRequired());
            if (openFiles.length > 0) {
                const effectiveMaxTime = maxTime ? maxTime.openFilesTimeInMs : Number.MAX_VALUE;
                // Check the open files.
                for (const sourceFileInfo of openFiles) {
                    if (this._checkTypes(sourceFileInfo, token)) {
                        if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) {
                            return true;
                        }
                    }
                }
                // If the caller specified a maxTime, return at this point
                // since we've finalized all open files. We want to get
                // the results to the user as quickly as possible.
                if (maxTime !== undefined) {
                    return true;
                }
            }
            if (!this._configOptions.checkOnlyOpenFiles) {
                const effectiveMaxTime = maxTime ? maxTime.noOpenFilesTimeInMs : Number.MAX_VALUE;
                // Now do type parsing and analysis of the remaining.
                for (const sourceFileInfo of this._sourceFileList) {
                    if (!(0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo)) {
                        continue;
                    }
                    if (this._checkTypes(sourceFileInfo, token)) {
                        if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) {
                            return true;
                        }
                    }
                }
            }
            return false;
        });
    }
    // Performs parsing and analysis of a single file in the program. If the file is not part of
    // the program returns false to indicate analysis was not performed.
    analyzeFile(fileUri, token = vscode_languageserver_1.CancellationToken.None) {
        return this._runEvaluatorWithCancellationToken(token, () => {
            const sourceFileInfo = this.getSourceFileInfo(fileUri);
            if (sourceFileInfo && this._checkTypes(sourceFileInfo, token)) {
                return true;
            }
            return false;
        });
    }
    // This will allow the callback to execute a type evaluator with an associated
    // cancellation token and provide a read-only program.
    run(callback, token) {
        return this._runEvaluatorWithCancellationToken(token, () => callback(this));
    }
    // This will allow the callback to execute a type evaluator with an associated
    // cancellation token and provide a mutable program. Should already be in edit mode when called.
    runEditMode(callback, token) {
        if (this._editModeTracker.isEditMode) {
            return this._runEvaluatorWithCancellationToken(token, () => callback(this));
        }
    }
    getSourceMapper(fileUri, token, mapCompiled, preferStubs) {
        const sourceFileInfo = this.getSourceFileInfo(fileUri);
        const execEnv = this._configOptions.findExecEnvironment(fileUri);
        return this._createSourceMapper(execEnv, token, sourceFileInfo, mapCompiled, preferStubs);
    }
    getParserOutput(fileUri) {
        var _a;
        return (_a = this.getBoundSourceFileInfo(fileUri, 
        /* content */ undefined, 
        /* force */ true)) === null || _a === void 0 ? void 0 : _a.sourceFile.getParserOutput();
    }
    getParseResults(fileUri) {
        var _a;
        return (_a = this.getBoundSourceFileInfo(fileUri, 
        /* content */ undefined, 
        /* force */ true)) === null || _a === void 0 ? void 0 : _a.sourceFile.getParseResults();
    }
    handleMemoryHighUsage() {
        this._handleMemoryHighUsage();
    }
    // Prints a detailed list of files that have been checked and the times associated
    // with each of them, sorted greatest to least.
    printDetailedAnalysisTimes() {
        const sortedFiles = this._sourceFileList
            .filter((s) => s.sourceFile.getCheckTime() !== undefined)
            .sort((a, b) => {
            return b.sourceFile.getCheckTime() - a.sourceFile.getCheckTime();
        });
        this._console.info('');
        this._console.info('Analysis time by file');
        sortedFiles.forEach((sfInfo) => {
            const checkTimeInMs = sfInfo.sourceFile.getCheckTime();
            this._console.info(`${checkTimeInMs}ms: ${sfInfo.sourceFile.getUri()}`);
        });
    }
    // Prints import dependency information for each of the files in
    // the program, skipping any typeshed files.
    printDependencies(projectRootDir, verbose) {
        const fs = this._importResolver.fileSystem;
        const sortedFiles = this._sourceFileList
            .filter((s) => !s.isTypeshedFile)
            .sort((a, b) => {
            return fs.getOriginalUri(a.sourceFile.getUri()) < fs.getOriginalUri(b.sourceFile.getUri()) ? 1 : -1;
        });
        const zeroImportFiles = [];
        sortedFiles.forEach((sfInfo) => {
            this._console.info('');
            const fileUri = fs.getOriginalUri(sfInfo.sourceFile.getUri());
            let fileString = fileUri.toString();
            const relPath = projectRootDir.getRelativePathComponents(fileUri);
            if (relPath) {
                fileString = relPath.join('/');
            }
            this._console.info(`${fileString}`);
            this._console.info(` Imports     ${sfInfo.imports.length} ` + `file${sfInfo.imports.length === 1 ? '' : 's'}`);
            if (verbose) {
                sfInfo.imports.forEach((importInfo) => {
                    this._console.info(`    ${fs.getOriginalUri(importInfo.sourceFile.getUri())}`);
                });
            }
            this._console.info(` Imported by ${sfInfo.importedBy.length} ` + `file${sfInfo.importedBy.length === 1 ? '' : 's'}`);
            if (verbose) {
                sfInfo.importedBy.forEach((importInfo) => {
                    this._console.info(`    ${fs.getOriginalUri(importInfo.sourceFile.getUri())}`);
                });
            }
            if (sfInfo.importedBy.length === 0) {
                zeroImportFiles.push(sfInfo.sourceFile);
            }
        });
        if (zeroImportFiles.length > 0) {
            this._console.info('');
            this._console.info(`${zeroImportFiles.length} file${zeroImportFiles.length === 1 ? '' : 's'}` + ` not explicitly imported`);
            zeroImportFiles.forEach((importFile) => {
                this._console.info(`    ${fs.getOriginalUri(importFile.getUri())}`);
            });
        }
    }
    writeTypeStub(targetImportPath, targetIsSingleFile, stubPath, token) {
        for (const sourceFileInfo of this._sourceFileList) {
            (0, cancellationUtils_1.throwIfCancellationRequested)(token);
            const fileUri = sourceFileInfo.sourceFile.getUri();
            // Generate type stubs only for the files within the target path,
            // not any files that the target module happened to import.
            const relativePath = targetImportPath.getRelativePath(fileUri);
            if (relativePath !== undefined) {
                let typeStubPath = stubPath.resolvePaths(relativePath);
                // If the target is a single file implementation, as opposed to
                // a package in a directory, transform the name of the type stub
                // to __init__.pyi because we're placing it in a directory.
                if (targetIsSingleFile) {
                    typeStubPath = typeStubPath.getDirectory().initPyiUri;
                }
                else {
                    typeStubPath = typeStubPath.replaceExtension('.pyi');
                }
                const typeStubDir = typeStubPath.getDirectory();
                try {
                    (0, uriUtils_1.makeDirectories)(this.fileSystem, typeStubDir, stubPath);
                }
                catch (e) {
                    const errMsg = `Could not create directory for '${typeStubDir}'`;
                    throw new Error(errMsg);
                }
                this._bindFile(sourceFileInfo);
                this._runEvaluatorWithCancellationToken(token, () => {
                    const writer = new typeStubWriter_1.TypeStubWriter(typeStubPath, sourceFileInfo.sourceFile, this._evaluator);
                    writer.write();
                });
                // This operation can consume significant memory, so check
                // for situations where we need to discard the type cache.
                this._handleMemoryHighUsage();
            }
        }
    }
    getTypeOfSymbol(symbol) {
        this._handleMemoryHighUsage();
        const evaluator = this._evaluator || this._createNewEvaluator();
        return evaluator.getEffectiveTypeOfSymbol(symbol);
    }
    printType(type, options) {
        this._handleMemoryHighUsage();
        const evaluator = this._evaluator || this._createNewEvaluator();
        return evaluator.printType(type, options);
    }
    getTextOnRange(fileUri, range, token) {
        const sourceFileInfo = this.getSourceFileInfo(fileUri);
        if (!sourceFileInfo) {
            return undefined;
        }
        const sourceFile = sourceFileInfo.sourceFile;
        const fileContents = sourceFile.getOpenFileContents();
        if (fileContents === undefined) {
            // this only works with opened file
            return undefined;
        }
        return this._runEvaluatorWithCancellationToken(token, () => {
            this._parseFile(sourceFileInfo);
            const parseResults = sourceFile.getParseResults();
            const textRange = (0, positionUtils_1.convertRangeToTextRange)(range, parseResults.tokenizerOutput.lines);
            if (!textRange) {
                return undefined;
            }
            return fileContents.substr(textRange.start, textRange.length);
        });
    }
    getDiagnostics(options, reportDeltasOnly = true) {
        const fileDiagnostics = this._removeUnneededFiles();
        this._sourceFileList.forEach((sourceFileInfo) => {
            if (this._shouldCheckFile(sourceFileInfo)) {
                let diagnostics = sourceFileInfo.sourceFile.getDiagnostics(options, reportDeltasOnly ? sourceFileInfo.diagnosticsVersion : undefined);
                if (diagnostics !== undefined) {
                    // Filter out all categories that are translated to tagged hints?
                    if (options.disableTaggedHints) {
                        diagnostics = diagnostics.filter((diag) => diag.category !== 4 /* DiagnosticCategory.UnreachableCode */ &&
                            diag.category !== 3 /* DiagnosticCategory.UnusedCode */ &&
                            diag.category !== 5 /* DiagnosticCategory.Deprecated */);
                    }
                    fileDiagnostics.push({
                        fileUri: sourceFileInfo.sourceFile.getUri(),
                        version: sourceFileInfo.sourceFile.getClientVersion(),
                        diagnostics,
                    });
                    // Update the cached diagnosticsVersion so we can determine
                    // whether there are any updates next time we call getDiagnostics.
                    sourceFileInfo.diagnosticsVersion = sourceFileInfo.sourceFile.getDiagnosticVersion();
                }
            }
            else if (!sourceFileInfo.isOpenByClient &&
                options.checkOnlyOpenFiles &&
                sourceFileInfo.diagnosticsVersion !== undefined) {
                // This condition occurs when the user switches from workspace to
                // "open files only" mode. Clear all diagnostics for this file.
                fileDiagnostics.push({
                    fileUri: sourceFileInfo.sourceFile.getUri(),
                    version: sourceFileInfo.sourceFile.getClientVersion(),
                    diagnostics: [],
                });
                sourceFileInfo.diagnosticsVersion = undefined;
            }
        });
        return fileDiagnostics;
    }
    getDiagnosticsForRange(fileUri, range) {
        const sourceFile = this.getSourceFile(fileUri);
        if (!sourceFile) {
            return [];
        }
        const unfilteredDiagnostics = sourceFile.getDiagnostics(this._configOptions);
        if (!unfilteredDiagnostics) {
            return [];
        }
        return unfilteredDiagnostics.filter((diag) => {
            return (0, textRange_1.doRangesIntersect)(diag.range, range);
        });
    }
    clone() {
        var _a, _b;
        const program = new Program(this._importResolver, this._configOptions, this.serviceProvider, new logTracker_1.LogTracker(this._console, 'Cloned'));
        // Cloned program will use whatever user files the program currently has.
        const userFiles = this.getUserFiles();
        program.setTrackedFiles(userFiles.map((i) => i.sourceFile.getUri()));
        program.markAllFilesDirty(/* evenIfContentsAreSame */ true);
        // Make sure we keep editor content (open file) which could be different than one in the file system.
        for (const fileInfo of this.getOpened()) {
            const version = fileInfo.sourceFile.getClientVersion();
            if (version === undefined) {
                continue;
            }
            program.setFileOpened(fileInfo.sourceFile.getUri(), version, (_a = fileInfo.sourceFile.getOpenFileContents()) !== null && _a !== void 0 ? _a : '', {
                chainedFileUri: (_b = fileInfo.chainedSourceFile) === null || _b === void 0 ? void 0 : _b.sourceFile.getUri(),
                ipythonMode: fileInfo.sourceFile.getIPythonMode(),
                isTracked: fileInfo.isTracked,
            });
        }
        return program;
    }
    // Returns a value from 0 to 1 (or more) indicating how "full" the cache is
    // relative to some predetermined high-water mark. We'll compute this value
    // based on two easy-to-compute metrics: the number of entries in the type
    // cache and the number of parsed files.
    getCacheUsage() {
        const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
        const entryCountRatio = typeCacheEntryCount / 750000;
        const fileCountRatio = this._parsedFileCount / 1000;
        return Math.max(entryCountRatio, fileCountRatio);
    }
    // Discards any cached information associated with this program.
    emptyCache() {
        var _a;
        this._createNewEvaluator();
        this._discardCachedParseResults();
        this._parsedFileCount = 0;
        (_a = this.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.stateMutationListeners)) === null || _a === void 0 ? void 0 : _a.forEach((l) => { var _a; return (_a = l.onClearCache) === null || _a === void 0 ? void 0 : _a.call(l); });
    }
    _handleMemoryHighUsage() {
        const cacheUsage = this._cacheManager.getCacheUsage();
        const usedHeapRatio = this._cacheManager.getUsedHeapRatio(this._configOptions.verboseOutput ? this._console : undefined);
        // If the total cache has exceeded 75%, determine whether we should empty
        // the cache. If the usedHeapRatio has exceeded 90%, we should definitely
        // empty the cache. This can happen before the cacheUsage maxes out because
        // we might be on the background thread and a bunch of the cacheUsage is on the main
        // thread.
        if (cacheUsage > 0.75 || usedHeapRatio > 0.9) {
            // The type cache uses a Map, which has an absolute limit of 2^24 entries
            // before it will fail. If we cross the 95% mark, we'll empty the cache.
            const absoluteMaxCacheEntryCount = (1 << 24) * 0.9;
            const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
            // If we use more than 90% of the heap size limit, avoid a crash
            // by emptying the type cache.
            if (typeCacheEntryCount > absoluteMaxCacheEntryCount || usedHeapRatio > 0.9) {
                this._cacheManager.emptyCache(this._console);
            }
        }
    }
    // Discards all cached parse results and file contents to free up memory.
    // It does not discard cached index results or diagnostics for files.
    _discardCachedParseResults() {
        for (const sourceFileInfo of this._sourceFileList) {
            sourceFileInfo.sourceFile.dropParseAndBindInfo();
        }
    }
    // Wrapper function that should be used when invoking this._evaluator
    // with a cancellation token. It handles cancellation exceptions and
    // any other unexpected exceptions.
    _runEvaluatorWithCancellationToken(token, callback) {
        try {
            if (token) {
                return this._evaluator.runWithCancellationToken(token, callback);
            }
            else {
                return callback();
            }
        }
        catch (e) {
            // An unexpected exception occurred, potentially leaving the current evaluator
            // in an inconsistent state. Discard it and replace it with a fresh one. It is
            // Cancellation exceptions are known to handle this correctly.
            if (!cancellationUtils_1.OperationCanceledException.is(e) || e.isTypeCacheInvalid) {
                this._createNewEvaluator();
            }
            throw e;
        }
    }
    // Returns a list of empty file diagnostic entries for the files
    // that have been removed. This is needed to clear out the
    // errors for files that have been deleted or closed.
    _removeUnneededFiles() {
        const fileDiagnostics = [];
        // If a file is no longer tracked, opened or shadowed, it can
        // be removed from the program.
        for (let i = 0; i < this._sourceFileList.length;) {
            const fileInfo = this._sourceFileList[i];
            if (!this._isFileNeeded(fileInfo)) {
                // Clear only if there are any errors for this file.
                if (fileInfo.diagnosticsVersion !== undefined) {
                    fileDiagnostics.push({
                        fileUri: fileInfo.sourceFile.getUri(),
                        version: fileInfo.sourceFile.getClientVersion(),
                        diagnostics: [],
                    });
                }
                fileInfo.sourceFile.prepareForClose();
                this._removeSourceFileFromListAndMap(fileInfo.sourceFile.getUri(), i);
                // Unlink any imports and remove them from the list if
                // they are no longer referenced.
                fileInfo.imports.forEach((importedFile) => {
                    const indexToRemove = importedFile.importedBy.findIndex((fi) => fi === fileInfo);
                    if (indexToRemove < 0) {
                        return;
                    }
                    importedFile.mutate((s) => s.importedBy.splice(indexToRemove, 1));
                    // See if we need to remove the imported file because it
                    // is no longer needed. If its index is >= i, it will be
                    // removed when we get to it.
                    if (!this._isFileNeeded(importedFile)) {
                        const indexToRemove = this._sourceFileList.findIndex((fi) => fi === importedFile);
                        if (indexToRemove >= 0 && indexToRemove < i) {
                            // Clear if there are any errors for this import.
                            if (importedFile.diagnosticsVersion !== undefined) {
                                fileDiagnostics.push({
                                    fileUri: importedFile.sourceFile.getUri(),
                                    version: importedFile.sourceFile.getClientVersion(),
                                    diagnostics: [],
                                });
                            }
                            importedFile.sourceFile.prepareForClose();
                            this._removeSourceFileFromListAndMap(importedFile.sourceFile.getUri(), indexToRemove);
                            i--;
                        }
                    }
                });
                // Remove any shadowed files corresponding to this file.
                fileInfo.shadowedBy.forEach((shadowedFile) => {
                    shadowedFile.mutate((s) => (s.shadows = s.shadows.filter((f) => f !== fileInfo)));
                });
                fileInfo.mutate((s) => (s.shadowedBy = []));
            }
            else {
                // If we're showing the user errors only for open files, clear
                // out the errors for the now-closed file.
                if (!this._shouldCheckFile(fileInfo) && fileInfo.diagnosticsVersion !== undefined) {
                    fileDiagnostics.push({
                        fileUri: fileInfo.sourceFile.getUri(),
                        version: fileInfo.sourceFile.getClientVersion(),
                        diagnostics: [],
                    });
                    fileInfo.diagnosticsVersion = undefined;
                }
                i++;
            }
        }
        return fileDiagnostics;
    }
    _isFileNeeded(fileInfo, skipFileNeededCheck) {
        if (fileInfo.sourceFile.isFileDeleted()) {
            return false;
        }
        if (!!skipFileNeededCheck || fileInfo.isTracked || fileInfo.isOpenByClient) {
            return true;
        }
        if (fileInfo.shadows.length > 0) {
            return true;
        }
        if (fileInfo.importedBy.length === 0) {
            return false;
        }
        // It's possible for a cycle of files to be imported
        // by a tracked file but then abandoned. The import cycle
        // will keep the entire group "alive" if we don't detect
        // the condition and garbage collect them.
        return this._isImportNeededRecursive(fileInfo, new Set());
    }
    _isImportNeededRecursive(fileInfo, recursionSet) {
        if (fileInfo.isTracked || fileInfo.isOpenByClient || fileInfo.shadows.length > 0) {
            return true;
        }
        const fileUri = fileInfo.sourceFile.getUri();
        // Avoid infinite recursion.
        if (recursionSet.has(fileUri.key)) {
            return false;
        }
        recursionSet.add(fileUri.key);
        for (const importerInfo of fileInfo.importedBy) {
            if (this._isImportNeededRecursive(importerInfo, recursionSet)) {
                return true;
            }
        }
        return false;
    }
    _createSourceMapper(execEnv, token, from, mapCompiled, preferStubs) {
        const sourceMapper = new sourceMapper_1.SourceMapper(this._importResolver, execEnv, this._evaluator, (stubFileUri, implFileUri) => {
            let stubFileInfo = this.getSourceFileInfo(stubFileUri);
            if (!stubFileInfo) {
                // make sure uri exits before adding interimFile
                if (!this.fileSystem.existsSync(stubFileUri)) {
                    return undefined;
                }
                // Special case for import statement like "import X.Y". The SourceFile
                // for X might not be in memory since import `X.Y` only brings in Y.
                stubFileInfo = this.addInterimFile(stubFileUri);
            }
            this._addShadowedFile(stubFileInfo, implFileUri);
            return this.getBoundSourceFile(implFileUri);
        }, (f) => {
            let fileInfo = this.getBoundSourceFileInfo(f);
            if (!fileInfo) {
                // make sure uri exits before adding interimFile
                if (!this.fileSystem.existsSync(f)) {
                    return undefined;
                }
                // Special case for import statement like "import X.Y". The SourceFile
                // for X might not be in memory since import `X.Y` only brings in Y.
                fileInfo = this.addInterimFile(f);
                // Even though this file is not referenced by anything, make sure
                // we have a parse tree for the doc string.
                this._parseFile(fileInfo, /* content */ undefined, /* force */ true);
            }
            return fileInfo;
        }, mapCompiled !== null && mapCompiled !== void 0 ? mapCompiled : false, preferStubs !== null && preferStubs !== void 0 ? preferStubs : false, from, token);
        return sourceMapper;
    }
    _isImportAllowed(importer, importResult, isImportStubFile) {
        // Don't import native libs. We don't want to track these files,
        // and we definitely don't want to attempt to parse them.
        if (importResult.isNativeLib) {
            return false;
        }
        let thirdPartyImportAllowed = this._configOptions.useLibraryCodeForTypes ||
            (importResult.importType === 1 /* ImportType.ThirdParty */ && !!importResult.pyTypedInfo) ||
            (importResult.importType === 2 /* ImportType.Local */ && importer.isThirdPartyPyTypedPresent);
        if (importResult.importType === 1 /* ImportType.ThirdParty */ ||
            (importer.isThirdPartyImport && importResult.importType === 2 /* ImportType.Local */)) {
            if (this._allowedThirdPartyImports) {
                if (importResult.isRelative) {
                    // If it's a relative import, we'll allow it because the
                    // importer was already deemed to be allowed.
                    thirdPartyImportAllowed = true;
                }
                else if (this._allowedThirdPartyImports.some((importName) => {
                    // If this import name is the one that was explicitly
                    // allowed or is a child of that import name,
                    // it's considered allowed.
                    if (importResult.importName === importName) {
                        return true;
                    }
                    if (importResult.importName.startsWith(importName + '.')) {
                        return true;
                    }
                    return false;
                })) {
                    thirdPartyImportAllowed = true;
                }
            }
            else if (importer.isThirdPartyImport && this._configOptions.useLibraryCodeForTypes) {
                // If the importing file is a third-party import, allow importing of
                // additional third-party imports. This supports the case where the importer
                // is in a py.typed library but is importing from another non-py.typed
                // library. It also supports the case where someone explicitly opens a
                // library source file in their editor.
                thirdPartyImportAllowed = true;
            }
            else if (importResult.isNamespacePackage &&
                Array.from(importResult.filteredImplicitImports.values()).some((implicitImport) => !!implicitImport.pyTypedInfo)) {
                // Handle the case where the import targets a namespace package, and a
                // submodule contained within it has a py.typed marker.
                thirdPartyImportAllowed = true;
            }
            // Some libraries ship with stub files that import from non-stubs. Don't
            // explore those.
            // Don't explore any third-party files unless they're type stub files
            // or we've been told explicitly that third-party imports are OK.
            if (!isImportStubFile) {
                return thirdPartyImportAllowed;
            }
        }
        return true;
    }
    _getSourceFileInfoFromKey(key) {
        return this._sourceFileMap.get(key);
    }
    _updateSourceFileImports(sourceFileInfo, options) {
        const filesAdded = [];
        // Get the new list of imports and see if it changed from the last
        // list of imports for this file.
        const imports = sourceFileInfo.sourceFile.getImports();
        // Create a local function that determines whether the import should
        // be considered a "third-party import" and whether it is coming from
        // a third-party package that claims to be typed. An import is
        // considered third-party if it is external to the importer
        // or is internal but the importer is itself a third-party package.
        const getThirdPartyImportInfo = (importResult) => {
            let isThirdPartyImport = false;
            let isPyTypedPresent = false;
            if (importResult.importType === 1 /* ImportType.ThirdParty */) {
                isThirdPartyImport = true;
                if (importResult.pyTypedInfo) {
                    isPyTypedPresent = true;
                }
            }
            else if (sourceFileInfo.isThirdPartyImport && importResult.importType === 2 /* ImportType.Local */) {
                isThirdPartyImport = true;
                if (sourceFileInfo.isThirdPartyPyTypedPresent) {
                    isPyTypedPresent = true;
                }
            }
            return {
                isThirdPartyImport,
                isPyTypedPresent,
            };
        };
        // Create a map of unique imports, since imports can appear more than once.
        const newImportPathMap = new Map();
        // Add chained source file as import if it exists.
        if (sourceFileInfo.chainedSourceFile) {
            if (sourceFileInfo.chainedSourceFile.sourceFile.isFileDeleted()) {
                sourceFileInfo.chainedSourceFile = undefined;
            }
            else {
                const fileUri = sourceFileInfo.chainedSourceFile.sourceFile.getUri();
                newImportPathMap.set(fileUri.key, {
                    path: fileUri,
                    isTypeshedFile: false,
                    isThirdPartyImport: false,
                    isPyTypedPresent: false,
                });
            }
        }
        imports.forEach((importResult) => {
            if (importResult.isImportFound) {
                if (this._isImportAllowed(sourceFileInfo, importResult, importResult.isStubFile)) {
                    if (importResult.resolvedUris.length > 0) {
                        const fileUri = importResult.resolvedUris[importResult.resolvedUris.length - 1];
                        if (!fileUri.isEmpty()) {
                            const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
                            newImportPathMap.set(fileUri.key, {
                                path: fileUri,
                                isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
                                isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
                                isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
                            });
                        }
                    }
                }
                importResult.filteredImplicitImports.forEach((implicitImport) => {
                    if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) {
                        if (!implicitImport.isNativeLib) {
                            const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
                            newImportPathMap.set(implicitImport.uri.key, {
                                path: implicitImport.uri,
                                isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
                                isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
                                isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
                            });
                        }
                    }
                });
                // If the stub was found but the non-stub (source) file was not, dump
                // the failure to the log for diagnostic purposes.
                if (importResult.nonStubImportResult && !importResult.nonStubImportResult.isImportFound) {
                    // We'll skip this for imports from within stub files and imports that target
                    // stdlib typeshed stubs because many of these are known to not have
                    // associated source files, and we don't want to fill the logs with noise.
                    if (!sourceFileInfo.sourceFile.isStubFile() && !importResult.isStdlibTypeshedFile) {
                        if (options.verboseOutput) {
                            this._console.info(`Could not resolve source for '${importResult.importName}' ` +
                                `in file '${sourceFileInfo.sourceFile.getUri().toUserVisibleString()}'`);
                            if (importResult.nonStubImportResult.importFailureInfo) {
                                importResult.nonStubImportResult.importFailureInfo.forEach((diag) => {
                                    this._console.info(`  ${diag}`);
                                });
                            }
                        }
                    }
                }
            }
            else if (options.verboseOutput) {
                this._console.info(`Could not import '${importResult.importName}' ` +
                    `in file '${sourceFileInfo.sourceFile.getUri().toUserVisibleString()}'`);
                if (importResult.importFailureInfo) {
                    importResult.importFailureInfo.forEach((diag) => {
                        this._console.info(`  ${diag}`);
                    });
                }
            }
        });
        const updatedImportMap = new Map();
        sourceFileInfo.imports.forEach((importInfo) => {
            const oldFilePath = importInfo.sourceFile.getUri();
            // A previous import was removed.
            if (!newImportPathMap.has(oldFilePath.key)) {
                importInfo.mutate((s) => {
                    s.importedBy = s.importedBy.filter((fi) => !fi.sourceFile.getUri().equals(sourceFileInfo.sourceFile.getUri()));
                });
            }
            else {
                updatedImportMap.set(oldFilePath.key, importInfo);
            }
        });
        // See if there are any new imports to be added.
        newImportPathMap.forEach((importInfo, normalizedImportPath) => {
            if (!updatedImportMap.has(normalizedImportPath)) {
                // We found a new import to add. See if it's already part
                // of the program.
                let importedFileInfo = this.getSourceFileInfo(importInfo.path);
                if (!importedFileInfo) {
                    const moduleImportInfo = this._getModuleImportInfoForFile(importInfo.path);
                    const sourceFile = this._sourceFileFactory.createSourceFile(this.serviceProvider, importInfo.path, moduleImportInfo.moduleName, importInfo.isThirdPartyImport, importInfo.isPyTypedPresent, this._editModeTracker, this._console, this._logTracker);
                    importedFileInfo = new sourceFileInfo_1.SourceFileInfo(sourceFile, importInfo.isTypeshedFile, importInfo.isThirdPartyImport, importInfo.isPyTypedPresent, this._editModeTracker);
                    this._addToSourceFileListAndMap(importedFileInfo);
                    filesAdded.push(importedFileInfo);
                }
                importedFileInfo.mutate((s) => s.importedBy.push(sourceFileInfo));
                updatedImportMap.set(normalizedImportPath, importedFileInfo);
            }
        });
        // Update the imports list. It should now map the set of imports
        // specified by the source file.
        sourceFileInfo.mutate((s) => (s.imports = []));
        newImportPathMap.forEach((_, key) => {
            if (this._getSourceFileInfoFromKey(key)) {
                sourceFileInfo.mutate((s) => s.imports.push(this._getSourceFileInfoFromKey(key)));
            }
        });
        // Resolve the builtins import for the file. This needs to be
        // analyzed before the file can be analyzed.
        sourceFileInfo.builtinsImport = undefined;
        const builtinsImport = sourceFileInfo.sourceFile.getBuiltinsImport();
        if (builtinsImport && builtinsImport.isImportFound) {
            const resolvedBuiltinsPath = builtinsImport.resolvedUris[builtinsImport.resolvedUris.length - 1];
            sourceFileInfo.builtinsImport = this.getSourceFileInfo(resolvedBuiltinsPath);
        }
        return filesAdded;
    }
    _removeSourceFileFromListAndMap(fileUri, indexToRemove) {
        this._sourceFileMap.delete(fileUri.key);
        this._sourceFileList.splice(indexToRemove, 1);
    }
    _addToSourceFileListAndMap(fileInfo) {
        const fileUri = fileInfo.sourceFile.getUri();
        // We should never add a file with the same path twice.
        (0, debug_1.assert)(!this._sourceFileMap.has(fileUri.key));
        // We should never have an empty URI for a source file.
        (0, debug_1.assert)(!fileInfo.sourceFile.getUri().isEmpty());
        this._sourceFileList.push(fileInfo);
        this._sourceFileMap.set(fileUri.key, fileInfo);
    }
    static _getPrintTypeFlags(configOptions) {
        let flags = 0 /* PrintTypeFlags.None */;
        if (configOptions.diagnosticRuleSet.printUnknownAsAny) {
            flags |= 1 /* PrintTypeFlags.PrintUnknownWithAny */;
        }
        if (configOptions.diagnosticRuleSet.omitConditionalConstraint) {
            flags |= 64 /* PrintTypeFlags.OmitConditionalConstraint */;
        }
        if (configOptions.diagnosticRuleSet.omitTypeArgsIfUnknown) {
            flags |= 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */;
        }
        if (configOptions.diagnosticRuleSet.omitUnannotatedParamType) {
            flags |= 4 /* PrintTypeFlags.OmitUnannotatedParamType */;
        }
        if (configOptions.diagnosticRuleSet.pep604Printing) {
            flags |= 8 /* PrintTypeFlags.PEP604 */;
        }
        return flags;
    }
    _getModuleImportInfoForFile(fileUri) {
        // We allow illegal module names (e.g. names that include "-" in them)
        // because we want a unique name for each module even if it cannot be
        // imported through an "import" statement. It's important to have a
        // unique name in case two modules declare types with the same local
        // name. The type checker uses the fully-qualified (unique) module name
        // to differentiate between such types.
        const moduleNameAndType = this._importResolver.getModuleNameForImport(fileUri, this._configOptions.getDefaultExecEnvironment(), 
        /* allowIllegalModuleName */ true, 
        /* detectPyTyped */ true);
        return moduleNameAndType;
    }
    // A "shadowed" file is a python source file that has been added to the program because
    // it "shadows" a type stub file for purposes of finding doc strings and definitions.
    // We need to track the relationship so if the original type stub is removed from the
    // program, we can remove the corresponding shadowed file and any files it imports.
    _addShadowedFile(stubFile, shadowImplPath) {
        let shadowFileInfo = this.getSourceFileInfo(shadowImplPath);
        if (!shadowFileInfo) {
            shadowFileInfo = this.addInterimFile(shadowImplPath);
        }
        if (!shadowFileInfo.shadows.includes(stubFile)) {
            shadowFileInfo.mutate((s) => s.shadows.push(stubFile));
        }
        if (!stubFile.shadowedBy.includes(shadowFileInfo)) {
            stubFile.mutate((s) => s.shadowedBy.push(shadowFileInfo));
        }
        return shadowFileInfo.sourceFile;
    }
    _createInterimFileInfo(fileUri) {
        const moduleImportInfo = this._getModuleImportInfoForFile(fileUri);
        const sourceFile = this._sourceFileFactory.createSourceFile(this.serviceProvider, fileUri, moduleImportInfo.moduleName, 
        /* isThirdPartyImport */ false, 
        /* isInPyTypedPackage */ false, this._editModeTracker, this._console, this._logTracker);
        const sourceFileInfo = new sourceFileInfo_1.SourceFileInfo(sourceFile, 
        /* isTypeshedFile */ false, 
        /* isThirdPartyImport */ false, 
        /* isThirdPartyPyTypedPresent */ false, this._editModeTracker);
        return sourceFileInfo;
    }
    _createNewEvaluator() {
        if (this._evaluator) {
            // We shouldn't need to call this, but there appears to be a bug
            // in the v8 garbage collector where it's unable to resolve orphaned
            // objects without us giving it some assistance.
            this._evaluator.disposeEvaluator();
        }
        this._evaluator = (0, typeEvaluatorWithTracker_1.createTypeEvaluatorWithTracker)(this._lookUpImport, {
            printTypeFlags: Program._getPrintTypeFlags(this._configOptions),
            logCalls: this._configOptions.logTypeEvaluationTime,
            minimumLoggingThreshold: this._configOptions.typeEvaluationTimeThreshold,
            evaluateUnknownImportsAsAny: !!this._configOptions.evaluateUnknownImportsAsAny,
            verifyTypeCacheEvaluatorFlags: !!this._configOptions.internalTestMode,
        }, this._logTracker, this._configOptions.logTypeEvaluationTime
            ? (0, tracePrinter_1.createTracePrinter)(this._importResolver.getImportRoots(this._configOptions.findExecEnvironment(this._configOptions.projectRoot)))
            : undefined);
        return this._evaluator;
    }
    _parseFile(fileToParse, content, skipFileNeededCheck) {
        if (!this._isFileNeeded(fileToParse, skipFileNeededCheck) || !fileToParse.sourceFile.isParseRequired()) {
            return;
        }
        // SourceFile.parse should only be called here in the program, as calling it
        // elsewhere could break the entire dependency graph maintained by the program.
        // Other parts of the program should use _parseFile to create ParseResults from
        // the sourceFile. For standalone parseResults, use parseFile or the Parser directly.
        if (fileToParse.sourceFile.parse(this._configOptions, this._importResolver, content)) {
            this._parsedFileCount++;
            this._updateSourceFileImports(fileToParse, this._configOptions);
        }
        if (fileToParse.sourceFile.isFileDeleted()) {
            fileToParse.isTracked = false;
            // Mark any files that depend on this file as dirty
            // also. This will retrigger analysis of these other files.
            const markDirtySet = new Set();
            this._markFileDirtyRecursive(fileToParse, markDirtySet);
            // Invalidate the import resolver's cache as well.
            this._importResolver.invalidateCache();
        }
    }
    _getImplicitImports(file) {
        var _a;
        // If file is not parsed, then chainedSourceFile,
        // builtinsImport might not exist or incorrect.
        // They will be added when _parseFile is called and _updateSourceFileImports ran.
        if (file.builtinsImport === file) {
            return undefined;
        }
        const tryReturn = (input) => {
            if (!input || input.sourceFile.isFileDeleted()) {
                return undefined;
            }
            return input;
        };
        return (_a = tryReturn(file.chainedSourceFile)) !== null && _a !== void 0 ? _a : file.builtinsImport;
    }
    _bindImplicitImports(fileToAnalyze, skipFileNeededCheck) {
        var _a, _b;
        // Get all of the potential imports for this file.
        const implicitImports = [];
        const implicitSet = new Set();
        let nextImplicitImport = this._getImplicitImports(fileToAnalyze);
        while (nextImplicitImport) {
            const implicitPath = nextImplicitImport.sourceFile.getUri();
            if (implicitSet.has(implicitPath.key)) {
                // We've found a cycle. Break out of the loop.
                debug.fail((_b = (_a = this.serviceProvider
                    .tryGet(serviceKeys_1.ServiceKeys.debugInfoInspector)) === null || _a === void 0 ? void 0 : _a.getCycleDetail(this, nextImplicitImport)) !== null && _b !== void 0 ? _b : `Found a cycle in implicit imports files`);
            }
            implicitSet.add(implicitPath.key);
            implicitImports.push(nextImplicitImport);
            this._parseFile(nextImplicitImport, /* content */ undefined, skipFileNeededCheck);
            nextImplicitImport = this._getImplicitImports(nextImplicitImport);
        }
        if (implicitImports.length === 0) {
            return;
        }
        // Go in reverse order (so top of chain is first).
        let implicitImport = implicitImports.pop();
        while (implicitImport) {
            // Bind this file, but don't recurse into its imports.
            this._bindFile(implicitImport, undefined, skipFileNeededCheck, /* isImplicitImport */ true);
            implicitImport = implicitImports.pop();
        }
    }
    // Binds the specified file and all of its dependencies, recursively.
    // Returns true if the file was bound or it didn't need to be bound.
    _bindFile(fileToAnalyze, content, skipFileNeededCheck, isImplicitImport) {
        var _a;
        if (!this._isFileNeeded(fileToAnalyze, skipFileNeededCheck) || !fileToAnalyze.sourceFile.isBindingRequired()) {
            return !fileToAnalyze.sourceFile.isBindingRequired();
        }
        this._parseFile(fileToAnalyze, content, skipFileNeededCheck);
        // Create a function to get the scope info.
        const getScopeIfAvailable = (fileInfo) => {
            if (!fileInfo || fileInfo === fileToAnalyze) {
                return undefined;
            }
            // If the file was deleted, there's no scope to return.
            if (fileInfo.sourceFile.isFileDeleted()) {
                return undefined;
            }
            const parseResults = fileInfo.sourceFile.getParserOutput();
            if (!parseResults) {
                return undefined;
            }
            // File should already be bound because of the chained file binding above.
            const scope = AnalyzerNodeInfo.getScope(parseResults.parseTree);
            return scope;
        };
        let builtinsScope;
        if (fileToAnalyze.builtinsImport && fileToAnalyze.builtinsImport !== fileToAnalyze) {
            // Bind all of the implicit imports first. So we don't recurse into them.
            if (!isImplicitImport) {
                this._bindImplicitImports(fileToAnalyze);
            }
            // If it is not builtin module itself, we need to parse and bind
            // the builtin module.
            builtinsScope =
                (_a = getScopeIfAvailable(fileToAnalyze.chainedSourceFile)) !== null && _a !== void 0 ? _a : getScopeIfAvailable(fileToAnalyze.builtinsImport);
        }
        let futureImports = fileToAnalyze.sourceFile.getParserOutput().futureImports;
        if (fileToAnalyze.chainedSourceFile) {
            futureImports = this._getEffectiveFutureImports(futureImports, fileToAnalyze.chainedSourceFile);
        }
        fileToAnalyze.effectiveFutureImports = futureImports.size > 0 ? futureImports : undefined;
        fileToAnalyze.sourceFile.bind(this._configOptions, this._lookUpImport, builtinsScope, futureImports);
        return true;
    }
    _getEffectiveFutureImports(futureImports, chainedSourceFile) {
        var _a;
        const effectiveFutureImports = new Set(futureImports);
        (_a = chainedSourceFile.effectiveFutureImports) === null || _a === void 0 ? void 0 : _a.forEach((value) => {
            effectiveFutureImports.add(value);
        });
        return effectiveFutureImports;
    }
    _shouldCheckFile(fileInfo) {
        // Always do a full checking for a file that's open in the editor.
        if (fileInfo.isOpenByClient) {
            return true;
        }
        // If the file isn't currently open, only perform full checking for
        // files that are tracked, and only if the checkOnlyOpenFiles is disabled.
        if (!this._configOptions.checkOnlyOpenFiles && fileInfo.isTracked) {
            return true;
        }
        return false;
    }
    _checkTypes(fileToCheck, token, chainedByList) {
        return this._logTracker.log(`analyzing: ${fileToCheck.sourceFile.getUri()}`, (logState) => {
            // If the file isn't needed because it was eliminated from the
            // transitive closure or deleted, skip the file rather than wasting
            // time on it.
            if (!this._isFileNeeded(fileToCheck)) {
                logState.suppress();
                return false;
            }
            if (!fileToCheck.sourceFile.isCheckingRequired()) {
                logState.suppress();
                return false;
            }
            if (!this._shouldCheckFile(fileToCheck)) {
                logState.suppress();
                return false;
            }
            // Bind the file if necessary even if we're not going to run the checker.
            // disableChecker means disable semantic errors, not syntax errors. We need to bind again
            // in order to generate syntax errors.
            const boundFile = this._bindFile(fileToCheck, undefined, 
            // If binding is required we want to make sure to bind the file, otherwise
            // the sourceFile.check below will fail.
            /* skipFileNeededCheck */ fileToCheck.sourceFile.isBindingRequired());
            if (!this._disableChecker) {
                // For ipython, make sure we check all its dependent files first since
                // their results can affect this file's result.
                const dependentFiles = this._checkDependentFiles(fileToCheck, chainedByList, token);
                if (this._preCheckCallback) {
                    const parseResults = fileToCheck.sourceFile.getParserOutput();
                    if (parseResults) {
                        this._preCheckCallback(parseResults, this._evaluator);
                    }
                }
                if (boundFile) {
                    const execEnv = this._configOptions.findExecEnvironment(fileToCheck.sourceFile.getUri());
                    fileToCheck.sourceFile.check(this.configOptions, this._importResolver, this._evaluator, this._createSourceMapper(execEnv, token, fileToCheck), dependentFiles);
                }
            }
            // For very large programs, we may need to discard the evaluator and
            // its cached types to avoid running out of heap space.
            this._handleMemoryHighUsage();
            // Detect import cycles that involve the file.
            if (this._configOptions.diagnosticRuleSet.reportImportCycles !== 'none') {
                // Don't detect import cycles when doing type stub generation. Some
                // third-party modules are pretty convoluted.
                // Or if the file is the notebook cell. notebook cell can't have cycles.
                if (!this._allowedThirdPartyImports &&
                    fileToCheck.sourceFile.getIPythonMode() !== sourceFile_1.IPythonMode.CellDocs) {
                    // We need to force all of the files to be parsed and build
                    // a closure map for the files.
                    const closureMap = new Map();
                    this._getImportsRecursive(fileToCheck, closureMap, 0);
                    closureMap.forEach((file) => {
                        timing_1.timingStats.cycleDetectionTime.timeOperation(() => {
                            const filesVisitedMap = new Map();
                            if (!this._detectAndReportImportCycles(file, filesVisitedMap)) {
                                // If no cycles were found in any of the files we visited,
                                // set a flag to indicates that we don't need to visit them again
                                // on subsequent cycle checks.
                                filesVisitedMap.forEach((sourceFileInfo) => {
                                    sourceFileInfo.sourceFile.setNoCircularDependencyConfirmed();
                                });
                            }
                        });
                    });
                }
            }
            return true;
        });
    }
    _checkDependentFiles(fileToCheck, chainedByList, token) {
        if (fileToCheck.sourceFile.getIPythonMode() !== sourceFile_1.IPythonMode.CellDocs) {
            return undefined;
        }
        // If we don't have chainedByList, it means none of them are checked yet.
        const needToRunChecker = !chainedByList;
        chainedByList = chainedByList !== null && chainedByList !== void 0 ? chainedByList : (0, sourceFileInfoUtils_1.createChainedByList)(this, fileToCheck);
        const index = chainedByList.findIndex((v) => v === fileToCheck);
        if (index < 0) {
            return undefined;
        }
        const startIndex = index + 1;
        if (startIndex >= chainedByList.length) {
            return undefined;
        }
        if (needToRunChecker) {
            // If the file is already analyzed, it will be no op.
            // And make sure we don't dump parse tree and etc while
            // calling checker. Otherwise, checkType can dump parse
            // tree required by outer check.
            const handle = this._cacheManager.pauseTracking();
            try {
                for (let i = chainedByList.length - 1; i >= startIndex; i--) {
                    this._checkTypes(chainedByList[i], token, chainedByList);
                }
            }
            finally {
                handle.dispose();
            }
        }
        const dependentFiles = [];
        for (let i = startIndex; i < chainedByList.length; i++) {
            const file = chainedByList[i];
            const parseResults = file === null || file === void 0 ? void 0 : file.sourceFile.getParserOutput();
            if (!parseResults) {
                continue;
            }
            // We might not have the file info if binding failed for whatever reasons.
            const fileInfo = AnalyzerNodeInfo.getFileInfo(parseResults.parseTree);
            if (fileInfo && fileInfo.accessedSymbolSet) {
                dependentFiles.push(parseResults);
            }
        }
        return dependentFiles;
    }
    // Builds a map of files that includes the specified file and all of the files
    // it imports (recursively) and ensures that all such files. If any of these files
    // have already been checked (they and their recursive imports have completed the
    // check phase), they are not included in the results.
    _getImportsRecursive(file, closureMap, recursionCount) {
        // If the file is already in the closure map, we found a cyclical
        // dependency. Don't recur further.
        const fileUri = file.sourceFile.getUri();
        if (closureMap.has(fileUri.key)) {
            return;
        }
        // If the import chain is too long, emit an error. Otherwise we
        // risk blowing the stack.
        if (recursionCount > _maxImportDepth) {
            file.sourceFile.setHitMaxImportDepth(_maxImportDepth);
            return;
        }
        // Add the file to the closure map.
        closureMap.set(fileUri.key, file);
        // If this file hasn't already been parsed, parse it now. This will
        // discover any files it imports. Skip this if the file is part
        // of a library. We'll assume that no cycles will be generated from
        // library code or typeshed stubs.
        if ((0, sourceFileInfoUtils_1.isUserCode)(file)) {
            this._parseFile(file);
        }
        // Recursively add the file's imports.
        for (const importedFileInfo of file.imports) {
            this._getImportsRecursive(importedFileInfo, closureMap, recursionCount + 1);
        }
    }
    _detectAndReportImportCycles(sourceFileInfo, filesVisited, dependencyChain = [], dependencyMap = new Map()) {
        // Don't bother checking for typestub files or third-party files.
        if (sourceFileInfo.sourceFile.isStubFile() || sourceFileInfo.isThirdPartyImport) {
            return false;
        }
        // If we've already confirmed that this source file isn't part of a
        // cycle, we can skip it entirely.
        if (sourceFileInfo.sourceFile.isNoCircularDependencyConfirmed()) {
            return false;
        }
        const fileUri = sourceFileInfo.sourceFile.getUri();
        filesVisited.set(fileUri.key, sourceFileInfo);
        let detectedCycle = false;
        if (dependencyMap.has(fileUri.key)) {
            // We detect a cycle (partial or full). A full cycle is one that is
            // rooted in the file at the start of our dependency chain. A partial
            // cycle loops back on some other file in the dependency chain. We
            // will report only full cycles here and leave the reporting of
            // partial cycles to other passes.
            detectedCycle = true;
            // Look for chains at least two in length. A file that contains
            // an "import . from X" will technically create a cycle with
            // itself, but those are not interesting to report.
            if (dependencyChain.length > 1 && sourceFileInfo === dependencyChain[0]) {
                this._logImportCycle(dependencyChain);
            }
        }
        else {
            // If we've already checked this dependency along
            // some other path, we can skip it.
            if (dependencyMap.has(fileUri.key)) {
                return false;
            }
            // We use both a map (for fast lookups) and a list
            // (for ordering information). Set the dependency map
            // entry to true to indicate that we're actively exploring
            // that dependency.
            dependencyMap.set(fileUri.key, true);
            dependencyChain.push(sourceFileInfo);
            for (const imp of sourceFileInfo.imports) {
                if (this._detectAndReportImportCycles(imp, filesVisited, dependencyChain, dependencyMap)) {
                    detectedCycle = true;
                }
            }
            // Set the dependencyMap entry to false to indicate that we have
            // already explored this file and don't need to explore it again.
            dependencyMap.set(fileUri.key, false);
            dependencyChain.pop();
        }
        return detectedCycle;
    }
    _logImportCycle(dependencyChain) {
        const circDep = new circularDependency_1.CircularDependency();
        dependencyChain.forEach((sourceFileInfo) => {
            circDep.appendPath(sourceFileInfo.sourceFile.getUri());
        });
        circDep.normalizeOrder();
        const firstFilePath = circDep.getPaths()[0];
        const firstSourceFile = this.getSourceFileInfo(firstFilePath);
        (0, debug_1.assert)(firstSourceFile !== undefined);
        firstSourceFile.sourceFile.addCircularDependency(this.configOptions, circDep);
    }
    _markFileDirtyRecursive(sourceFileInfo, markSet, forceRebinding = false) {
        const fileUri = sourceFileInfo.sourceFile.getUri();
        // Don't mark it again if it's already been visited.
        if (markSet.has(fileUri.key)) {
            return;
        }
        sourceFileInfo.sourceFile.markReanalysisRequired(forceRebinding);
        markSet.add(fileUri.key);
        sourceFileInfo.importedBy.forEach((dep) => {
            // Changes on chained source file can change symbols in the symbol table and
            // dependencies on the dependent file. Force rebinding.
            const forceRebinding = dep.chainedSourceFile === sourceFileInfo;
            this._markFileDirtyRecursive(dep, markSet, forceRebinding);
        });
        // Change in the current file could impact checker result of chainedSourceFile such as unused symbols.
        let reevaluationRequired = false;
        let chainedSourceFile = sourceFileInfo.chainedSourceFile;
        while (chainedSourceFile) {
            if (chainedSourceFile.sourceFile.isCheckingRequired()) {
                // If the file is marked for checking, its chained one should be marked
                // as well. Stop here.
                return;
            }
            reevaluationRequired = true;
            chainedSourceFile.sourceFile.markReanalysisRequired(/* forceRebinding */ false);
            chainedSourceFile = chainedSourceFile.chainedSourceFile;
        }
        // If the checker is going to run again, we have to recreate the type evaluator so
        // that it actually reevaluates all the nodes (instead of using the cache).
        // This is necessary because the original file change may not recreate the TypeEvaluator.
        // For example, it might be a file delete.
        if (reevaluationRequired) {
            this._createNewEvaluator();
        }
    }
}
exports.Program = Program;
Program._nextId = 0;


/***/ }),

/***/ "../pyright-internal/src/analyzer/programTypes.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/programTypes.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ISourceFileFactory = void 0;
var ISourceFileFactory;
(function (ISourceFileFactory) {
    function is(obj) {
        return obj.createSourceFile !== undefined;
    }
    ISourceFileFactory.is = is;
})(ISourceFileFactory || (exports.ISourceFileFactory = ISourceFileFactory = {}));


/***/ }),

/***/ "../pyright-internal/src/analyzer/properties.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/properties.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * properties.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides type evaluation logic that is specific to properties.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.assignProperty = exports.clonePropertyWithDeleter = exports.clonePropertyWithSetter = exports.createProperty = exports.validatePropertyMethod = void 0;
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
function validatePropertyMethod(evaluator, method, errorNode) {
    if (types_1.FunctionType.isStaticMethod(method)) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.propertyStaticMethod(), errorNode);
    }
}
exports.validatePropertyMethod = validatePropertyMethod;
function createProperty(evaluator, decoratorNode, decoratorType, fget) {
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(decoratorNode);
    const typeMetaclass = evaluator.getBuiltInType(decoratorNode, 'type');
    const typeSourceId = types_1.ClassType.isBuiltIn(decoratorType, 'property')
        ? (0, parseTreeUtils_1.getTypeSourceId)(decoratorNode)
        : decoratorType.details.typeSourceId;
    const propertyClass = types_1.ClassType.createInstantiable(decoratorType.details.name, (0, parseTreeUtils_1.getClassFullName)(decoratorNode, fileInfo.moduleName, `__property_${fget.details.name}`), fileInfo.moduleName, fileInfo.fileUri, 4096 /* ClassTypeFlags.PropertyClass */ | 1 /* ClassTypeFlags.BuiltInClass */, typeSourceId, 
    /* declaredMetaclass */ undefined, (0, types_1.isInstantiableClass)(typeMetaclass) ? typeMetaclass : types_1.UnknownType.create());
    propertyClass.details.declaration = decoratorType.details.declaration;
    propertyClass.details.typeVarScopeId = decoratorType.details.typeVarScopeId;
    const objectType = evaluator.getBuiltInType(decoratorNode, 'object');
    propertyClass.details.baseClasses.push((0, types_1.isInstantiableClass)(objectType) ? objectType : types_1.UnknownType.create());
    (0, typeUtils_1.computeMroLinearization)(propertyClass);
    // Clone the symbol table of the old class type.
    const fields = types_1.ClassType.getSymbolTable(propertyClass);
    types_1.ClassType.getSymbolTable(decoratorType).forEach((symbol, name) => {
        const ignoredMethods = ['__get__', '__set__', '__delete__'];
        if (!symbol.isIgnoredForProtocolMatch()) {
            if (!ignoredMethods.some((m) => m === name)) {
                fields.set(name, symbol);
            }
        }
    });
    const propertyObject = types_1.ClassType.cloneAsInstance(propertyClass);
    propertyClass.isAsymmetricDescriptor = false;
    // Update the __set__ and __delete__ methods if present.
    updateGetSetDelMethodForClonedProperty(evaluator, propertyObject);
    // Fill in the fget method.
    propertyObject.fgetInfo = {
        methodType: types_1.FunctionType.cloneWithNewFlags(fget, fget.details.flags | 4 /* FunctionTypeFlags.StaticMethod */),
        classType: fget.details.methodClass,
    };
    if (types_1.FunctionType.isClassMethod(fget)) {
        propertyClass.details.flags |= 8388608 /* ClassTypeFlags.ClassProperty */;
    }
    // Fill in the __get__ method with an overload.
    addGetMethodToPropertySymbolTable(evaluator, propertyObject, fget);
    // Fill in the getter, setter and deleter methods.
    addDecoratorMethodsToPropertySymbolTable(propertyObject);
    return propertyObject;
}
exports.createProperty = createProperty;
function clonePropertyWithSetter(evaluator, prop, fset, errorNode) {
    if (!(0, typeUtils_1.isProperty)(prop)) {
        return prop;
    }
    const classType = prop;
    const flagsToClone = classType.details.flags;
    let isAsymmetricDescriptor = !!classType.isAsymmetricDescriptor;
    // Verify parameters for fset.
    // We'll skip this test if the diagnostic rule is disabled because it
    // can be somewhat expensive, especially in code that is not annotated.
    const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(errorNode);
    if (errorNode.parameters.length >= 2) {
        const typeAnnotation = (0, parseTreeUtils_1.getTypeAnnotationForParameter)(errorNode, 1);
        if (typeAnnotation) {
            // Verify consistency of the type.
            const fgetType = evaluator.getGetterTypeFromProperty(classType, /* inferTypeIfNeeded */ false);
            if (fgetType && !(0, types_1.isAnyOrUnknown)(fgetType)) {
                const fsetType = evaluator.getTypeOfAnnotation(typeAnnotation, {
                    associateTypeVarsWithScope: true,
                });
                // The setter type should be assignable to the getter type.
                if (fileInfo.diagnosticRuleSet.reportPropertyTypeMismatch !== 'none') {
                    const diag = new diagnostic_1.DiagnosticAddendum();
                    if (!evaluator.assignType(fgetType, fsetType, diag)) {
                        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPropertyTypeMismatch, localize_1.LocMessage.setterGetterTypeMismatch() + diag.getString(), typeAnnotation);
                    }
                }
                if (!(0, types_1.isTypeSame)(fgetType, fsetType)) {
                    isAsymmetricDescriptor = true;
                }
            }
        }
    }
    const propertyClass = types_1.ClassType.createInstantiable(classType.details.name, classType.details.fullName, classType.details.moduleName, (0, analyzerNodeInfo_1.getFileInfo)(errorNode).fileUri, flagsToClone, classType.details.typeSourceId, classType.details.declaredMetaclass, classType.details.effectiveMetaclass);
    propertyClass.details.declaration = classType.details.declaration;
    propertyClass.details.typeVarScopeId = classType.details.typeVarScopeId;
    const objectType = evaluator.getBuiltInType(errorNode, 'object');
    propertyClass.details.baseClasses.push((0, types_1.isInstantiableClass)(objectType) ? objectType : types_1.UnknownType.create());
    (0, typeUtils_1.computeMroLinearization)(propertyClass);
    propertyClass.fgetInfo = classType.fgetInfo;
    propertyClass.fdelInfo = classType.fdelInfo;
    propertyClass.isAsymmetricDescriptor = isAsymmetricDescriptor;
    const propertyObject = types_1.ClassType.cloneAsInstance(propertyClass);
    // Clone the symbol table of the old class type.
    const fields = types_1.ClassType.getSymbolTable(propertyClass);
    types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
        if (!symbol.isIgnoredForProtocolMatch()) {
            fields.set(name, symbol);
        }
    });
    // Update the __get__ and __delete__ methods if present.
    updateGetSetDelMethodForClonedProperty(evaluator, propertyObject);
    // Fill in the new fset method.
    propertyObject.fsetInfo = {
        methodType: types_1.FunctionType.cloneWithNewFlags(fset, fset.details.flags | 4 /* FunctionTypeFlags.StaticMethod */),
        classType: fset.details.methodClass,
    };
    // Fill in the __set__ method.
    addSetMethodToPropertySymbolTable(evaluator, propertyObject, fset);
    // Fill in the getter, setter and deleter methods.
    addDecoratorMethodsToPropertySymbolTable(propertyObject);
    return propertyObject;
}
exports.clonePropertyWithSetter = clonePropertyWithSetter;
function clonePropertyWithDeleter(evaluator, prop, fdel, errorNode) {
    var _a;
    if (!(0, typeUtils_1.isProperty)(prop)) {
        return prop;
    }
    const classType = prop;
    const propertyClass = types_1.ClassType.createInstantiable(classType.details.name, classType.details.fullName, classType.details.moduleName, (0, analyzerNodeInfo_1.getFileInfo)(errorNode).fileUri, classType.details.flags, classType.details.typeSourceId, classType.details.declaredMetaclass, classType.details.effectiveMetaclass);
    propertyClass.details.declaration = classType.details.declaration;
    propertyClass.details.typeVarScopeId = classType.details.typeVarScopeId;
    const objectType = evaluator.getBuiltInType(errorNode, 'object');
    propertyClass.details.baseClasses.push((0, types_1.isInstantiableClass)(objectType) ? objectType : types_1.UnknownType.create());
    (0, typeUtils_1.computeMroLinearization)(propertyClass);
    propertyClass.fgetInfo = classType.fgetInfo;
    propertyClass.fsetInfo = classType.fsetInfo;
    const propertyObject = types_1.ClassType.cloneAsInstance(propertyClass);
    propertyClass.isAsymmetricDescriptor = (_a = classType.isAsymmetricDescriptor) !== null && _a !== void 0 ? _a : false;
    // Clone the symbol table of the old class type.
    const fields = types_1.ClassType.getSymbolTable(propertyClass);
    types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
        if (!symbol.isIgnoredForProtocolMatch()) {
            fields.set(name, symbol);
        }
    });
    // Update the __get__ and __set__ methods if present.
    updateGetSetDelMethodForClonedProperty(evaluator, propertyObject);
    // Fill in the fdel method.
    propertyObject.fdelInfo = {
        methodType: types_1.FunctionType.cloneWithNewFlags(fdel, fdel.details.flags | 4 /* FunctionTypeFlags.StaticMethod */),
        classType: fdel.details.methodClass,
    };
    // Fill in the __delete__ method.
    addDelMethodToPropertySymbolTable(evaluator, propertyObject, fdel);
    // Fill in the getter, setter and deleter methods.
    addDecoratorMethodsToPropertySymbolTable(propertyObject);
    return propertyObject;
}
exports.clonePropertyWithDeleter = clonePropertyWithDeleter;
function addGetMethodToPropertySymbolTable(evaluator, propertyObject, fget) {
    const fields = types_1.ClassType.getSymbolTable(propertyObject);
    // The first overload is for accesses through a class object (where
    // the instance argument is None).
    const getFunction1 = types_1.FunctionType.createSynthesizedInstance('__get__', 256 /* FunctionTypeFlags.Overloaded */);
    types_1.FunctionType.addParameter(getFunction1, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(getFunction1, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: evaluator.getNoneType(),
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(getFunction1, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'objtype',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
        hasDefault: true,
        defaultType: types_1.AnyType.create(),
    });
    getFunction1.details.declaredReturnType = types_1.FunctionType.isClassMethod(fget)
        ? types_1.FunctionType.getSpecializedReturnType(fget)
        : propertyObject;
    getFunction1.details.declaration = fget.details.declaration;
    getFunction1.details.deprecatedMessage = fget.details.deprecatedMessage;
    // Override the scope ID since we're using parameter types from the
    // decorated function.
    getFunction1.details.typeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(fget);
    // The second overload is for accesses through a class instance.
    const getFunction2 = types_1.FunctionType.createSynthesizedInstance('__get__', 256 /* FunctionTypeFlags.Overloaded */);
    types_1.FunctionType.addParameter(getFunction2, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    const objType = fget.details.parameters.length > 0 ? fget.details.parameters[0].type : types_1.AnyType.create();
    types_1.FunctionType.addParameter(getFunction2, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: objType,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addParameter(getFunction2, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'objtype',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
        hasDefault: true,
        defaultType: types_1.AnyType.create(),
    });
    getFunction2.details.declaredReturnType = types_1.FunctionType.getSpecializedReturnType(fget);
    getFunction2.details.declaration = fget.details.declaration;
    getFunction2.details.deprecatedMessage = fget.details.deprecatedMessage;
    // Override the scope ID since we're using parameter types from the
    // decorated function.
    getFunction2.details.typeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(fget);
    // We previously placed getFunction1 before getFunction2, but this creates
    // problems specifically for the `NoneType` class because None.__class__
    // is a property, and both overloads match in this case because None
    // is passed for the "obj" parameter.
    const getFunctionOverload = types_1.OverloadedFunctionType.create([getFunction2, getFunction1]);
    const getSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, getFunctionOverload);
    fields.set('__get__', getSymbol);
}
function addSetMethodToPropertySymbolTable(evaluator, propertyObject, fset) {
    const fields = types_1.ClassType.getSymbolTable(propertyObject);
    const setFunction = types_1.FunctionType.createSynthesizedInstance('__set__');
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    let objType = fset.details.parameters.length > 0 ? fset.details.parameters[0].type : types_1.AnyType.create();
    if ((0, types_1.isTypeVar)(objType) && objType.details.isSynthesizedSelf) {
        objType = evaluator.makeTopLevelTypeVarsConcrete(objType);
    }
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: (0, types_1.combineTypes)([objType, evaluator.getNoneType()]),
        hasDeclaredType: true,
    });
    setFunction.details.declaredReturnType = evaluator.getNoneType();
    // Adopt the TypeVarScopeId of the fset function in case it has any
    // TypeVars that need to be solved.
    setFunction.details.typeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(fset);
    setFunction.details.deprecatedMessage = fset.details.deprecatedMessage;
    let setParamType = types_1.UnknownType.create();
    if (fset.details.parameters.length >= 2 &&
        fset.details.parameters[1].category === 0 /* ParameterCategory.Simple */ &&
        fset.details.parameters[1].name) {
        setParamType = fset.details.parameters[1].type;
    }
    types_1.FunctionType.addParameter(setFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'value',
        type: setParamType,
        hasDeclaredType: true,
    });
    const setSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, setFunction);
    fields.set('__set__', setSymbol);
}
function addDelMethodToPropertySymbolTable(evaluator, propertyObject, fdel) {
    const fields = types_1.ClassType.getSymbolTable(propertyObject);
    const delFunction = types_1.FunctionType.createSynthesizedInstance('__delete__');
    types_1.FunctionType.addParameter(delFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.AnyType.create(),
        hasDeclaredType: true,
    });
    // Adopt the TypeVarScopeId of the fdel function in case it has any
    // TypeVars that need to be solved.
    delFunction.details.typeVarScopeId = (0, typeUtils_1.getTypeVarScopeId)(fdel);
    delFunction.details.deprecatedMessage = fdel.details.deprecatedMessage;
    let objType = fdel.details.parameters.length > 0 ? fdel.details.parameters[0].type : types_1.AnyType.create();
    if ((0, types_1.isTypeVar)(objType) && objType.details.isSynthesizedSelf) {
        objType = evaluator.makeTopLevelTypeVarsConcrete(objType);
    }
    types_1.FunctionType.addParameter(delFunction, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'obj',
        type: (0, types_1.combineTypes)([objType, evaluator.getNoneType()]),
        hasDeclaredType: true,
    });
    delFunction.details.declaredReturnType = evaluator.getNoneType();
    const delSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, delFunction);
    fields.set('__delete__', delSymbol);
}
function updateGetSetDelMethodForClonedProperty(evaluator, propertyObject) {
    const fgetInfo = propertyObject.fgetInfo;
    if (fgetInfo && (0, types_1.isFunction)(fgetInfo.methodType)) {
        addGetMethodToPropertySymbolTable(evaluator, propertyObject, fgetInfo.methodType);
    }
    const fsetInfo = propertyObject.fsetInfo;
    if (fsetInfo && (0, types_1.isFunction)(fsetInfo.methodType)) {
        addSetMethodToPropertySymbolTable(evaluator, propertyObject, fsetInfo.methodType);
    }
    const fdelInfo = propertyObject.fdelInfo;
    if (fdelInfo && (0, types_1.isFunction)(fdelInfo.methodType)) {
        addDelMethodToPropertySymbolTable(evaluator, propertyObject, fdelInfo.methodType);
    }
}
function addDecoratorMethodsToPropertySymbolTable(propertyObject) {
    const fields = types_1.ClassType.getSymbolTable(propertyObject);
    // Fill in the getter, setter and deleter methods.
    ['getter', 'setter', 'deleter'].forEach((accessorName) => {
        const accessorFunction = types_1.FunctionType.createSynthesizedInstance(accessorName);
        types_1.FunctionType.addParameter(accessorFunction, {
            category: 0 /* ParameterCategory.Simple */,
            name: 'self',
            type: types_1.AnyType.create(),
            hasDeclaredType: true,
        });
        types_1.FunctionType.addParameter(accessorFunction, {
            category: 0 /* ParameterCategory.Simple */,
            name: 'accessor',
            type: types_1.AnyType.create(),
            hasDeclaredType: true,
        });
        accessorFunction.details.declaredReturnType = propertyObject;
        const accessorSymbol = symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, accessorFunction);
        fields.set(accessorName, accessorSymbol);
    });
}
function assignProperty(evaluator, destPropertyType, srcPropertyType, destClass, srcClass, diag, typeVarContext, selfTypeVarContext, recursionCount = 0) {
    const srcObjectToBind = (0, types_1.isClass)(srcClass) ? types_1.ClassType.cloneAsInstance(srcClass) : undefined;
    const destObjectToBind = types_1.ClassType.cloneAsInstance(destClass);
    let isAssignable = true;
    const accessors = [
        {
            getFunction: (c) => { var _a; return (_a = c.fgetInfo) === null || _a === void 0 ? void 0 : _a.methodType; },
            missingDiagMsg: localize_1.LocAddendum.missingGetter,
            incompatibleDiagMsg: localize_1.LocAddendum.incompatibleGetter,
        },
        {
            getFunction: (c) => { var _a; return (_a = c.fsetInfo) === null || _a === void 0 ? void 0 : _a.methodType; },
            missingDiagMsg: localize_1.LocAddendum.missingSetter,
            incompatibleDiagMsg: localize_1.LocAddendum.incompatibleSetter,
        },
        {
            getFunction: (c) => { var _a; return (_a = c.fdelInfo) === null || _a === void 0 ? void 0 : _a.methodType; },
            missingDiagMsg: localize_1.LocAddendum.missingDeleter,
            incompatibleDiagMsg: localize_1.LocAddendum.incompatibleDeleter,
        },
    ];
    accessors.forEach((accessorInfo) => {
        let destAccessType = accessorInfo.getFunction(destPropertyType);
        if (destAccessType && (0, types_1.isFunction)(destAccessType)) {
            let srcAccessType = accessorInfo.getFunction(srcPropertyType);
            if (!srcAccessType || !(0, types_1.isFunction)(srcAccessType)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(accessorInfo.missingDiagMsg());
                isAssignable = false;
                return;
            }
            evaluator.inferReturnTypeIfNecessary(srcAccessType);
            evaluator.inferReturnTypeIfNecessary(destAccessType);
            // If the caller provided a "self" TypeVar context, replace any Self types.
            // This is needed during protocol matching.
            if (selfTypeVarContext) {
                destAccessType = (0, typeUtils_1.applySolvedTypeVars)(destAccessType, selfTypeVarContext);
            }
            // The access methods of fget, fset and fdel are modeled as static
            // variables because they do not bind go the "property" class that
            // contains them, but we'll turn it back into a non-static method
            // here and bind them to the associated objects.
            destAccessType = types_1.FunctionType.cloneWithNewFlags(destAccessType, destAccessType.details.flags & ~4 /* FunctionTypeFlags.StaticMethod */);
            srcAccessType = types_1.FunctionType.cloneWithNewFlags(srcAccessType, srcAccessType.details.flags & ~4 /* FunctionTypeFlags.StaticMethod */);
            const boundDestAccessType = evaluator.bindFunctionToClassOrObject(destObjectToBind, destAccessType, 
            /* memberClass */ undefined, 
            /* treatConstructorAsClassMethod */ undefined, 
            /* firstParamType */ undefined, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), recursionCount);
            const boundSrcAccessType = evaluator.bindFunctionToClassOrObject(srcObjectToBind, srcAccessType, 
            /* memberClass */ undefined, 
            /* treatConstructorAsClassMethod */ undefined, 
            /* firstParamType */ undefined, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), recursionCount);
            if (!boundDestAccessType ||
                !boundSrcAccessType ||
                !evaluator.assignType(boundDestAccessType, boundSrcAccessType, diag, typeVarContext, 
                /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
                isAssignable = false;
            }
        }
    });
    return isAssignable;
}
exports.assignProperty = assignProperty;


/***/ }),

/***/ "../pyright-internal/src/analyzer/protocols.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/analyzer/protocols.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * protocols.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides type evaluation logic that is specific to protocol
 * (structural subtyping) classes.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isProtocolUnsafeOverlap = exports.isMethodOnlyProtocol = exports.assignModuleToProtocol = exports.assignClassToProtocol = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const constraintSolver_1 = __webpack_require__(/*! ./constraintSolver */ "../pyright-internal/src/analyzer/constraintSolver.ts");
const properties_1 = __webpack_require__(/*! ./properties */ "../pyright-internal/src/analyzer/properties.ts");
const symbolUtils_1 = __webpack_require__(/*! ./symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
const protocolAssignmentStack = [];
// Maximum number of different types that are cached with a protocol.
const maxProtocolCompatibilityCacheEntries = 32;
function assignClassToProtocol(evaluator, destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
    // We assume that destType is an instantiable class that is a protocol. The
    // srcType can be an instantiable class or a class instance.
    (0, debug_1.assert)((0, types_1.isInstantiableClass)(destType) && types_1.ClassType.isProtocolClass(destType));
    const enforceInvariance = (flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0;
    // Use a stack of pending protocol class evaluations to detect recursion.
    // This can happen when a protocol class refers to itself.
    if (protocolAssignmentStack.some((entry) => {
        return (0, types_1.isTypeSame)(entry.srcType, srcType) && (0, types_1.isTypeSame)(entry.destType, destType);
    })) {
        return !enforceInvariance;
    }
    // See if we've already determined that this class is compatible with this protocol.
    if (!enforceInvariance) {
        const compatibility = getProtocolCompatibility(destType, srcType, flags, destTypeVarContext);
        if (compatibility !== undefined) {
            if (compatibility) {
                // If the caller has provided a destination type var context,
                // we can't use the cached value unless the dest has no type
                // parameters to solve.
                if (!destTypeVarContext || destType.details.typeParameters.length === 0) {
                    return true;
                }
            }
            // If it's known not to be compatible and the caller hasn't requested
            // any detailed diagnostic information, we can return false immediately.
            if (!compatibility && !diag) {
                return false;
            }
        }
    }
    protocolAssignmentStack.push({ srcType, destType });
    let isCompatible = true;
    const clonedTypeVarContext = destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.clone();
    try {
        isCompatible = assignClassToProtocolInternal(evaluator, destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
    }
    catch (e) {
        // We'd normally use "finally" here, but the TS debugger does such
        // a poor job dealing with finally, we'll use a catch instead.
        protocolAssignmentStack.pop();
        throw e;
    }
    protocolAssignmentStack.pop();
    // Cache the results for next time.
    setProtocolCompatibility(destType, srcType, flags, clonedTypeVarContext, isCompatible);
    return isCompatible;
}
exports.assignClassToProtocol = assignClassToProtocol;
function assignModuleToProtocol(evaluator, destType, srcType, diag, destTypeVarContext, flags, recursionCount) {
    return assignClassToProtocolInternal(evaluator, destType, srcType, diag, destTypeVarContext, 
    /* srcTypeVarContext */ undefined, flags, recursionCount);
}
exports.assignModuleToProtocol = assignModuleToProtocol;
// Determines whether the specified class is a protocol class that has
// only methods, no other symbol types like variables.
function isMethodOnlyProtocol(classType) {
    if (!types_1.ClassType.isProtocolClass(classType)) {
        return false;
    }
    // First check for data members in any protocol base classes.
    for (const baseClass of classType.details.baseClasses) {
        if ((0, types_1.isClass)(baseClass) && types_1.ClassType.isProtocolClass(baseClass) && !isMethodOnlyProtocol(baseClass)) {
            return false;
        }
    }
    for (const [, symbol] of types_1.ClassType.getSymbolTable(classType)) {
        if (symbol.isIgnoredForProtocolMatch()) {
            continue;
        }
        if (symbol.getDeclarations().some((decl) => decl.type !== 5 /* DeclarationType.Function */)) {
            return false;
        }
    }
    return true;
}
exports.isMethodOnlyProtocol = isMethodOnlyProtocol;
// Determines whether the classType has "unsafe overlap" with a runtime checkable protocol.
// This can occur because the runtime doesn't do full type comparisons. It simply looks at
// the presence of specific attributes.
function isProtocolUnsafeOverlap(evaluator, protocol, classType) {
    // If the classType is compatible with the protocol, then it doesn't overlap unsafely.
    if (evaluator.assignType(protocol, classType)) {
        return false;
    }
    let isUnsafeOverlap = true;
    protocol.details.mro.forEach((mroClass) => {
        if (!isUnsafeOverlap || !(0, types_1.isInstantiableClass)(mroClass) || !types_1.ClassType.isProtocolClass(mroClass)) {
            return;
        }
        types_1.ClassType.getSymbolTable(mroClass).forEach((destSymbol, name) => {
            if (!isUnsafeOverlap || !destSymbol.isClassMember() || destSymbol.isIgnoredForProtocolMatch()) {
                return;
            }
            // Does the classType have a member with the same name?
            const srcMemberInfo = (0, typeUtils_1.lookUpClassMember)(classType, name);
            if (!srcMemberInfo) {
                isUnsafeOverlap = false;
            }
        });
    });
    return isUnsafeOverlap;
}
exports.isProtocolUnsafeOverlap = isProtocolUnsafeOverlap;
// Looks up the protocol compatibility in the cache. If it's not found,
// return undefined.
function getProtocolCompatibility(destType, srcType, flags, typeVarContext) {
    const map = srcType.details.protocolCompatibility;
    const entries = map === null || map === void 0 ? void 0 : map.get(destType.details.fullName);
    if (entries === undefined) {
        return undefined;
    }
    const entry = entries.find((entry) => {
        return ((0, types_1.isTypeSame)(entry.destType, destType) &&
            (0, types_1.isTypeSame)(entry.srcType, srcType) &&
            entry.flags === flags &&
            isTypeVarContextSame(typeVarContext, entry.typeVarContext));
    });
    return entry === null || entry === void 0 ? void 0 : entry.isCompatible;
}
function setProtocolCompatibility(destType, srcType, flags, typeVarContext, isCompatible) {
    let map = srcType.details.protocolCompatibility;
    if (!map) {
        map = new Map();
        srcType.details.protocolCompatibility = map;
    }
    let entries = map.get(destType.details.fullName);
    if (!entries) {
        entries = [];
        map.set(destType.details.fullName, entries);
    }
    entries.push({
        destType,
        srcType,
        flags,
        typeVarContext,
        isCompatible,
    });
    if (entries.length > maxProtocolCompatibilityCacheEntries) {
        entries.shift();
    }
}
function isTypeVarContextSame(context1, context2) {
    if (!context1 || !context2) {
        return context1 === context2;
    }
    return context1.isSame(context2);
}
function assignClassToProtocolInternal(evaluator, destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
    var _a;
    if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
        return (0, types_1.isTypeSame)(destType, srcType);
    }
    const sourceIsClassObject = (0, types_1.isClass)(srcType) && types_1.TypeBase.isInstantiable(srcType);
    const protocolTypeVarContext = createProtocolTypeVarContext(evaluator, destType, destTypeVarContext);
    const selfTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(destType));
    let selfType;
    if ((0, types_1.isClass)(srcType)) {
        // If the srcType is conditioned on "self", use "Self" as the selfType.
        // Otherwise use the class type for selfType.
        if ((_a = srcType.condition) === null || _a === void 0 ? void 0 : _a.some((c) => c.typeVar.details.isSynthesizedSelf)) {
            selfType = (0, typeUtils_1.synthesizeTypeVarForSelfCls)(types_1.TypeBase.cloneForCondition(srcType, undefined), 
            /* isClsType */ false);
        }
        else {
            selfType = srcType;
        }
        (0, typeUtils_1.populateTypeVarContextForSelfType)(selfTypeVarContext, destType, selfType);
    }
    // If the source is a TypedDict, use the _TypedDict placeholder class
    // instead. We don't want to use the TypedDict members for protocol
    // comparison.
    if ((0, types_1.isClass)(srcType) && types_1.ClassType.isTypedDictClass(srcType)) {
        const typedDictClassType = evaluator.getTypedDictClassType();
        if (typedDictClassType && (0, types_1.isInstantiableClass)(typedDictClassType)) {
            srcType = typedDictClassType;
        }
    }
    let typesAreConsistent = true;
    const checkedSymbolSet = new Set();
    let assignTypeFlags = flags & (16 /* AssignTypeFlags.OverloadOverlapCheck */ | 32 /* AssignTypeFlags.PartialOverloadOverlapCheck */);
    assignTypeFlags |= (0, typeUtils_1.containsLiteralType)(srcType, /* includeTypeArgs */ true)
        ? 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */
        : 0 /* AssignTypeFlags.Default */;
    destType.details.mro.forEach((mroClass) => {
        if (!(0, types_1.isInstantiableClass)(mroClass) || !types_1.ClassType.isProtocolClass(mroClass)) {
            return;
        }
        // If we've already determined that the types are not consistent and the caller
        // hasn't requested detailed diagnostic output, we can shortcut the remainder.
        if (!typesAreConsistent && !diag) {
            return;
        }
        types_1.ClassType.getSymbolTable(mroClass).forEach((destSymbol, name) => {
            var _a;
            // If we've already determined that the types are not consistent and the caller
            // hasn't requested detailed diagnostic output, we can shortcut the remainder.
            if (!typesAreConsistent && !diag) {
                return;
            }
            if (!destSymbol.isClassMember() || destSymbol.isIgnoredForProtocolMatch() || checkedSymbolSet.has(name)) {
                return;
            }
            let isMemberFromMetaclass = false;
            let srcMemberInfo;
            let srcSymbol;
            // Special-case the `__class_getitem__` for normal protocol comparison.
            // This is a convention agreed upon by typeshed maintainers.
            if (!sourceIsClassObject && name === '__class_getitem__') {
                return;
            }
            // Special-case the `__slots__` entry for all protocol comparisons.
            // This is a convention agreed upon by typeshed maintainers.
            if (name === '__slots__') {
                return;
            }
            // Note that we've already checked this symbol. It doesn't need to
            // be checked again even if it is declared by a subclass.
            checkedSymbolSet.add(name);
            let destMemberType = (_a = evaluator.getDeclaredTypeOfSymbol(destSymbol)) === null || _a === void 0 ? void 0 : _a.type;
            if (!destMemberType) {
                return;
            }
            let srcMemberType;
            let isSrcReadOnly = false;
            if ((0, types_1.isClass)(srcType)) {
                // Look in the metaclass first if we're treating the source as an instantiable class.
                if (sourceIsClassObject &&
                    srcType.details.effectiveMetaclass &&
                    (0, types_1.isInstantiableClass)(srcType.details.effectiveMetaclass)) {
                    srcMemberInfo = (0, typeUtils_1.lookUpClassMember)(srcType.details.effectiveMetaclass, name);
                    if (srcMemberInfo) {
                        isMemberFromMetaclass = true;
                    }
                }
                if (!srcMemberInfo) {
                    srcMemberInfo = (0, typeUtils_1.lookUpClassMember)(srcType, name);
                }
                if (!srcMemberInfo) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.protocolMemberMissing().format({ name }));
                    typesAreConsistent = false;
                    return;
                }
                srcSymbol = srcMemberInfo.symbol;
                // Partially specialize the type of the symbol based on the MRO class.
                // We can skip this if it's the dest class because it is already
                // specialized.
                if (!types_1.ClassType.isSameGenericClass(mroClass, destType)) {
                    destMemberType = (0, typeUtils_1.partiallySpecializeType)(destMemberType, mroClass, selfType);
                }
                if ((0, types_1.isInstantiableClass)(srcMemberInfo.classType)) {
                    const symbolType = evaluator.getEffectiveTypeOfSymbol(srcMemberInfo.symbol);
                    // If this is a function, infer its return type prior to specializing it.
                    if ((0, types_1.isFunction)(symbolType)) {
                        evaluator.inferReturnTypeIfNecessary(symbolType);
                    }
                    srcMemberType = (0, typeUtils_1.partiallySpecializeType)(symbolType, srcMemberInfo.classType, selfType);
                }
                else {
                    srcMemberType = types_1.UnknownType.create();
                }
                // If the source is a method, bind it.
                if ((0, types_1.isFunction)(srcMemberType) || (0, types_1.isOverloadedFunction)(srcMemberType)) {
                    if (isMemberFromMetaclass || (0, types_1.isInstantiableClass)(srcMemberInfo.classType)) {
                        const boundSrcFunction = evaluator.bindFunctionToClassOrObject(sourceIsClassObject && !isMemberFromMetaclass
                            ? srcType
                            : types_1.ClassType.cloneAsInstance(srcType), srcMemberType, isMemberFromMetaclass ? undefined : srcMemberInfo.classType, 
                        /* treatConstructorAsClassMethod */ undefined, isMemberFromMetaclass ? srcType : selfType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), recursionCount);
                        if (boundSrcFunction) {
                            srcMemberType = (0, typeUtils_1.removeParamSpecVariadicsFromSignature)(boundSrcFunction);
                        }
                        else {
                            typesAreConsistent = false;
                            return;
                        }
                    }
                }
                // Frozen dataclasses and named tuples should be treated as read-only.
                if (types_1.ClassType.isFrozenDataClass(srcType) || types_1.ClassType.isReadOnlyInstanceVariables(srcType)) {
                    isSrcReadOnly = true;
                }
            }
            else {
                srcSymbol = srcType.fields.get(name);
                if (!srcSymbol) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.protocolMemberMissing().format({ name }));
                    typesAreConsistent = false;
                    return;
                }
                srcMemberType = evaluator.getEffectiveTypeOfSymbol(srcSymbol);
            }
            // Replace any "Self" TypeVar within the dest with the source type.
            destMemberType = (0, typeUtils_1.applySolvedTypeVars)(destMemberType, selfTypeVarContext);
            // If the dest is a method, bind it.
            if ((0, types_1.isFunction)(destMemberType) || (0, types_1.isOverloadedFunction)(destMemberType)) {
                let boundDeclaredType;
                if ((0, types_1.isClass)(srcType)) {
                    (0, debug_1.assert)(srcMemberInfo);
                    if (isMemberFromMetaclass || (0, types_1.isInstantiableClass)(srcMemberInfo.classType)) {
                        boundDeclaredType = evaluator.bindFunctionToClassOrObject(types_1.ClassType.cloneAsInstance(srcType), destMemberType, isMemberFromMetaclass ? undefined : srcMemberInfo.classType, 
                        /* treatConstructorAsClassMethod */ undefined, isMemberFromMetaclass ? srcType : selfType, diag, recursionCount);
                    }
                }
                else {
                    boundDeclaredType = evaluator.bindFunctionToClassOrObject(types_1.ClassType.cloneAsInstance(destType), destMemberType, destType, 
                    /* treatConstructorAsClassMethod */ undefined, 
                    /* firstParamType */ undefined, diag, recursionCount);
                }
                if (boundDeclaredType) {
                    destMemberType = (0, typeUtils_1.removeParamSpecVariadicsFromSignature)(boundDeclaredType);
                }
                else {
                    typesAreConsistent = false;
                    return;
                }
            }
            const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
            // Properties require special processing.
            if ((0, types_1.isClassInstance)(destMemberType) && types_1.ClassType.isPropertyClass(destMemberType)) {
                if ((0, types_1.isClassInstance)(srcMemberType) &&
                    types_1.ClassType.isPropertyClass(srcMemberType) &&
                    !sourceIsClassObject) {
                    if (!(0, properties_1.assignProperty)(evaluator, types_1.ClassType.cloneAsInstantiable(destMemberType), types_1.ClassType.cloneAsInstantiable(srcMemberType), mroClass, srcType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), protocolTypeVarContext, selfTypeVarContext, recursionCount)) {
                        if (subDiag) {
                            subDiag.addMessage(localize_1.LocAddendum.memberTypeMismatch().format({ name }));
                        }
                        typesAreConsistent = false;
                    }
                }
                else {
                    // Extract the property type from the property class.
                    let getterType = evaluator.getGetterTypeFromProperty(destMemberType, /* inferTypeIfNeeded */ true);
                    if (getterType) {
                        getterType = (0, typeUtils_1.partiallySpecializeType)(getterType, mroClass);
                    }
                    if (!getterType ||
                        !evaluator.assignType(getterType, srcMemberType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), protocolTypeVarContext, 
                        /* srcTypeVarContext */ undefined, assignTypeFlags, recursionCount)) {
                        if (subDiag) {
                            subDiag.addMessage(localize_1.LocAddendum.memberTypeMismatch().format({ name }));
                        }
                        typesAreConsistent = false;
                    }
                    if (isSrcReadOnly) {
                        // The source attribute is read-only. Make sure the setter
                        // is not defined in the dest property.
                        if ((0, typeUtils_1.lookUpClassMember)(destMemberType, '__set__', 16 /* MemberAccessFlags.SkipInstanceMembers */)) {
                            if (subDiag) {
                                subDiag.addMessage(localize_1.LocAddendum.memberIsWritableInProtocol().format({ name }));
                            }
                            typesAreConsistent = false;
                        }
                    }
                }
            }
            else {
                // Class and instance variables that are mutable need to enforce invariance.
                const primaryDecl = destSymbol.getDeclarations()[0];
                const isInvariant = (primaryDecl === null || primaryDecl === void 0 ? void 0 : primaryDecl.type) === 1 /* DeclarationType.Variable */ && !primaryDecl.isFinal;
                // Temporarily add the TypeVar scope ID for this method to handle method-scoped TypeVars.
                const protocolTypeVarContextClone = protocolTypeVarContext.clone();
                protocolTypeVarContextClone.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(destMemberType));
                if (!evaluator.assignType(destMemberType, srcMemberType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), protocolTypeVarContextClone, 
                /* srcTypeVarContext */ undefined, isInvariant ? assignTypeFlags | 1 /* AssignTypeFlags.EnforceInvariance */ : assignTypeFlags, recursionCount)) {
                    if (subDiag) {
                        if (isInvariant) {
                            subDiag.addMessage(localize_1.LocAddendum.memberIsInvariant().format({ name }));
                        }
                        subDiag.addMessage(localize_1.LocAddendum.memberTypeMismatch().format({ name }));
                    }
                    typesAreConsistent = false;
                }
                else {
                    protocolTypeVarContext.copyFromClone(protocolTypeVarContextClone);
                }
            }
            const isDestFinal = destSymbol
                .getTypedDeclarations()
                .some((decl) => decl.type === 1 /* DeclarationType.Variable */ && !!decl.isFinal);
            const isSrcFinal = srcSymbol
                .getTypedDeclarations()
                .some((decl) => decl.type === 1 /* DeclarationType.Variable */ && !!decl.isFinal);
            if (isDestFinal !== isSrcFinal) {
                if (isDestFinal) {
                    if (subDiag) {
                        subDiag.addMessage(localize_1.LocAddendum.memberIsFinalInProtocol().format({ name }));
                    }
                }
                else {
                    if (subDiag) {
                        subDiag.addMessage(localize_1.LocAddendum.memberIsNotFinalInProtocol().format({ name }));
                    }
                }
                typesAreConsistent = false;
            }
            const isDestClassVar = (0, symbolUtils_1.isEffectivelyClassVar)(destSymbol, /* isDataclass */ false);
            const isSrcClassVar = (0, symbolUtils_1.isEffectivelyClassVar)(srcSymbol, /* isDataclass */ false);
            const isSrcVariable = srcSymbol.getDeclarations().some((decl) => decl.type === 1 /* DeclarationType.Variable */);
            if (sourceIsClassObject) {
                // If the source is not marked as a ClassVar or the dest (the protocol) is,
                // the types are not consistent given that the source is a class object.
                if (isDestClassVar) {
                    subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberIsClassVarInProtocol().format({ name }));
                    typesAreConsistent = false;
                }
                else if (isSrcVariable && !isSrcClassVar) {
                    if (!isMemberFromMetaclass) {
                        subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberIsNotClassVarInClass().format({ name }));
                        typesAreConsistent = false;
                    }
                }
            }
            else {
                // If the source is marked as a ClassVar but the dest (the protocol) is not,
                // or vice versa, the types are not consistent.
                if (isDestClassVar !== isSrcClassVar) {
                    if (isDestClassVar) {
                        subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberIsClassVarInProtocol().format({ name }));
                    }
                    else {
                        subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberIsNotClassVarInProtocol().format({ name }));
                    }
                    typesAreConsistent = false;
                }
            }
            const destPrimaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(destSymbol);
            const srcPrimaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(srcSymbol);
            if ((destPrimaryDecl === null || destPrimaryDecl === void 0 ? void 0 : destPrimaryDecl.type) === 1 /* DeclarationType.Variable */ &&
                (srcPrimaryDecl === null || srcPrimaryDecl === void 0 ? void 0 : srcPrimaryDecl.type) === 1 /* DeclarationType.Variable */) {
                const isDestReadOnly = !!destPrimaryDecl.isConstant;
                let isSrcReadOnly = !!srcPrimaryDecl.isConstant;
                if (srcMemberInfo && (0, types_1.isClass)(srcMemberInfo.classType)) {
                    if (types_1.ClassType.isReadOnlyInstanceVariables(srcMemberInfo.classType) ||
                        types_1.ClassType.isFrozenDataClass(srcMemberInfo.classType)) {
                        isSrcReadOnly = true;
                    }
                }
                if (!isDestReadOnly && isSrcReadOnly) {
                    if (subDiag) {
                        subDiag.addMessage(localize_1.LocAddendum.memberIsWritableInProtocol().format({ name }));
                    }
                    typesAreConsistent = false;
                }
            }
        });
    });
    // If the dest protocol has type parameters, make sure the source type arguments match.
    if (typesAreConsistent && destType.details.typeParameters.length > 0) {
        // Create a specialized version of the protocol defined by the dest and
        // make sure the resulting type args can be assigned.
        const genericProtocolType = types_1.ClassType.cloneForSpecialization(destType, undefined, 
        /* isTypeArgumentExplicit */ false);
        const specializedProtocolType = (0, typeUtils_1.applySolvedTypeVars)(genericProtocolType, protocolTypeVarContext);
        if (destType.typeArguments) {
            if (!evaluator.assignTypeArguments(destType, specializedProtocolType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                typesAreConsistent = false;
            }
        }
        else if (destTypeVarContext && !destTypeVarContext.isLocked()) {
            for (const typeParam of destType.details.typeParameters) {
                const typeArgEntry = protocolTypeVarContext.getPrimarySignature().getTypeVar(typeParam);
                if (typeArgEntry) {
                    destTypeVarContext.setTypeVarType(typeParam, typeArgEntry === null || typeArgEntry === void 0 ? void 0 : typeArgEntry.narrowBound, typeArgEntry === null || typeArgEntry === void 0 ? void 0 : typeArgEntry.narrowBoundNoLiterals, typeArgEntry === null || typeArgEntry === void 0 ? void 0 : typeArgEntry.wideBound);
                }
            }
        }
    }
    return typesAreConsistent;
}
// Given a (possibly-specialized) destType and an optional typeVarContext, creates
// a new typeVarContext that combines the constraints from both the destType and
// the destTypeVarContext.
function createProtocolTypeVarContext(evaluator, destType, destTypeVarContext) {
    const protocolTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(destType));
    destType.details.typeParameters.forEach((typeParam, index) => {
        const entry = destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.getPrimarySignature().getTypeVar(typeParam);
        if (entry) {
            protocolTypeVarContext.setTypeVarType(typeParam, entry.narrowBound, entry.narrowBoundNoLiterals, entry.wideBound);
        }
        else if (destType.typeArguments && index < destType.typeArguments.length) {
            let typeArg = destType.typeArguments[index];
            let flags = 2048 /* AssignTypeFlags.PopulatingExpectedType */;
            let hasUnsolvedTypeVars = (0, typeUtils_1.requiresSpecialization)(typeArg);
            // If the type argument has unsolved TypeVars, see if they have
            // solved values in the destTypeVarContext.
            if (hasUnsolvedTypeVars && destTypeVarContext) {
                typeArg = (0, typeUtils_1.applySolvedTypeVars)(typeArg, destTypeVarContext, { useNarrowBoundOnly: true });
                flags = 0 /* AssignTypeFlags.Default */;
                hasUnsolvedTypeVars = (0, typeUtils_1.requiresSpecialization)(typeArg);
            }
            if (!hasUnsolvedTypeVars) {
                (0, constraintSolver_1.assignTypeToTypeVar)(evaluator, typeParam, typeArg, /* diag */ undefined, protocolTypeVarContext, flags);
            }
        }
    });
    return protocolTypeVarContext;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/pyTypedUtils.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/pyTypedUtils.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * pyTypedUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Parser for py.typed files.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getPyTypedInfoForPyTypedFile = exports.getPyTypedInfo = void 0;
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
//
// Retrieves information about a py.typed file, if it exists, under the given path.
//
function getPyTypedInfo(fileSystem, dirPath) {
    if (!fileSystem.existsSync(dirPath) || !(0, uriUtils_1.isDirectory)(fileSystem, dirPath)) {
        return undefined;
    }
    const pyTypedPath = dirPath.pytypedUri;
    if (!fileSystem.existsSync(pyTypedPath) || !(0, uriUtils_1.isFile)(fileSystem, pyTypedPath)) {
        return undefined;
    }
    return getPyTypedInfoForPyTypedFile(fileSystem, pyTypedPath);
}
exports.getPyTypedInfo = getPyTypedInfo;
//
// Retrieves information about a py.typed file. The pyTypedPath provided must be a valid path.
//
function getPyTypedInfoForPyTypedFile(fileSystem, pyTypedPath) {
    // This function intentionally doesn't check whether the given py.typed path exists or not,
    // as filesystem access is expensive if done repeatedly.
    // The caller should verify the file's validity before calling this method and use a cache if possible
    // to avoid high filesystem access costs.
    let isPartiallyTyped = false;
    // Read the contents of the file as text.
    const fileStats = fileSystem.statSync(pyTypedPath);
    // Do a quick sanity check on the size before we attempt to read it. This
    // file should always be really small - typically zero bytes in length.
    if (fileStats.size > 0 && fileStats.size < 64 * 1024) {
        const pyTypedContents = fileSystem.readFileSync(pyTypedPath, 'utf8');
        // PEP 561 doesn't specify the format of "py.typed" in any detail other than
        // to say that "If a stub package is partial it MUST include partial\n in a top
        // level py.typed file."
        if (pyTypedContents.match(/partial\n/) || pyTypedContents.match(/partial\r\n/)) {
            isPartiallyTyped = true;
        }
    }
    return {
        pyTypedPath,
        isPartiallyTyped,
    };
}
exports.getPyTypedInfoForPyTypedFile = getPyTypedInfoForPyTypedFile;


/***/ }),

/***/ "../pyright-internal/src/analyzer/pythonPathUtils.ts":
/*!***********************************************************!*\
  !*** ../pyright-internal/src/analyzer/pythonPathUtils.ts ***!
  \***********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * pythonPathUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility routines used to resolve various paths in Python.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getPathsFromPthFiles = exports.isPythonBinary = exports.findPythonSearchPaths = exports.getTypeshedSubdirectory = exports.getTypeShedFallbackPath = exports.thirdPartyFolderName = exports.stdLibFolderName = void 0;
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const pathConsts = __importStar(__webpack_require__(/*! ../common/pathConsts */ "../pyright-internal/src/common/pathConsts.ts"));
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
exports.stdLibFolderName = 'stdlib';
exports.thirdPartyFolderName = 'stubs';
function getTypeShedFallbackPath(fs) {
    const moduleDirectory = fs.getModulePath();
    if (!moduleDirectory || moduleDirectory.isEmpty()) {
        return undefined;
    }
    const typeshedPath = moduleDirectory.combinePaths(pathConsts.typeshedFallback);
    if (fs.existsSync(typeshedPath)) {
        return fs.realCasePath(typeshedPath);
    }
    // In the debug version of Pyright, the code is one level
    // deeper, so we need to look one level up for the typeshed fallback.
    const debugTypeshedPath = moduleDirectory.getDirectory().combinePaths(pathConsts.typeshedFallback);
    if (fs.existsSync(debugTypeshedPath)) {
        return fs.realCasePath(debugTypeshedPath);
    }
    return undefined;
}
exports.getTypeShedFallbackPath = getTypeShedFallbackPath;
function getTypeshedSubdirectory(typeshedPath, isStdLib) {
    return typeshedPath.combinePaths(isStdLib ? exports.stdLibFolderName : exports.thirdPartyFolderName);
}
exports.getTypeshedSubdirectory = getTypeshedSubdirectory;
function findPythonSearchPaths(fs, configOptions, host, importFailureInfo, includeWatchPathsOnly, workspaceRoot) {
    importFailureInfo.push('Finding python search paths');
    if (configOptions.venvPath !== undefined && configOptions.venv) {
        const venvDir = configOptions.venv;
        const venvPath = configOptions.venvPath.combinePaths(venvDir);
        const foundPaths = [];
        const sitePackagesPaths = [];
        [pathConsts.lib, pathConsts.lib64, pathConsts.libAlternate].forEach((libPath) => {
            const sitePackagesPath = findSitePackagesPath(fs, venvPath.combinePaths(libPath), configOptions.defaultPythonVersion, importFailureInfo);
            if (sitePackagesPath) {
                addPathIfUnique(foundPaths, sitePackagesPath);
                sitePackagesPaths.push(fs.realCasePath(sitePackagesPath));
            }
        });
        // Now add paths from ".pth" files located in each of the site packages folders.
        sitePackagesPaths.forEach((sitePackagesPath) => {
            const pthPaths = getPathsFromPthFiles(fs, sitePackagesPath);
            pthPaths.forEach((path) => {
                addPathIfUnique(foundPaths, path);
            });
        });
        if (foundPaths.length > 0) {
            importFailureInfo.push(`Found the following '${pathConsts.sitePackages}' dirs`);
            foundPaths.forEach((path) => {
                importFailureInfo.push(`  ${path}`);
            });
            return foundPaths;
        }
        importFailureInfo.push(`Did not find any '${pathConsts.sitePackages}' dirs. Falling back on python interpreter.`);
    }
    // Fall back on the python interpreter.
    const pathResult = host.getPythonSearchPaths(configOptions.pythonPath, importFailureInfo);
    if (includeWatchPathsOnly && workspaceRoot) {
        const paths = pathResult.paths
            .filter((p) => !p.startsWith(workspaceRoot) || p.startsWith(pathResult.prefix))
            .map((p) => fs.realCasePath(p));
        return paths;
    }
    return pathResult.paths.map((p) => fs.realCasePath(p));
}
exports.findPythonSearchPaths = findPythonSearchPaths;
function isPythonBinary(p) {
    p = p.trim();
    return p === 'python' || p === 'python3';
}
exports.isPythonBinary = isPythonBinary;
function findSitePackagesPath(fs, libPath, pythonVersion, importFailureInfo) {
    if (fs.existsSync(libPath)) {
        importFailureInfo.push(`Found path '${libPath}'; looking for ${pathConsts.sitePackages}`);
    }
    else {
        importFailureInfo.push(`Did not find '${libPath}'`);
        return undefined;
    }
    const sitePackagesPath = libPath.combinePaths(pathConsts.sitePackages);
    if (fs.existsSync(sitePackagesPath)) {
        importFailureInfo.push(`Found path '${sitePackagesPath}'`);
        return sitePackagesPath;
    }
    else {
        importFailureInfo.push(`Did not find '${sitePackagesPath}', so looking for python subdirectory`);
    }
    // We didn't find a site-packages directory directly in the lib
    // directory. Scan for a "python3.X" directory instead.
    const entries = (0, uriUtils_1.getFileSystemEntries)(fs, libPath);
    // Candidate directories start with "python3.".
    const candidateDirs = entries.directories.filter((dirName) => {
        if (dirName.fileName.startsWith('python3.')) {
            const dirPath = dirName.combinePaths(pathConsts.sitePackages);
            return fs.existsSync(dirPath);
        }
        return false;
    });
    // If there is a python3.X directory (where 3.X matches the configured python
    // version), prefer that over other python directories.
    if (pythonVersion) {
        const preferredDir = candidateDirs.find((dirName) => dirName.fileName === `python${pythonVersion.toMajorMinorString()}`);
        if (preferredDir) {
            const dirPath = preferredDir.combinePaths(pathConsts.sitePackages);
            importFailureInfo.push(`Found path '${dirPath}'`);
            return dirPath;
        }
    }
    // If there was no python version or we didn't find an exact match, use the
    // first directory that starts with "python". Most of the time, there will be
    // only one.
    if (candidateDirs.length > 0) {
        const dirPath = candidateDirs[0].combinePaths(pathConsts.sitePackages);
        importFailureInfo.push(`Found path '${dirPath}'`);
        return dirPath;
    }
    return undefined;
}
function getPathsFromPthFiles(fs, parentDir) {
    const searchPaths = [];
    // Get a list of all *.pth files within the specified directory.
    const pthFiles = fs
        .readdirEntriesSync(parentDir)
        .filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith('.pth'))
        .sort((a, b) => (0, core_1.compareComparableValues)(a.name, b.name));
    pthFiles.forEach((pthFile) => {
        const filePath = fs.realCasePath(parentDir.combinePaths(pthFile.name));
        const fileStats = (0, uriUtils_1.tryStat)(fs, filePath);
        // Skip all files that are much larger than expected.
        if ((fileStats === null || fileStats === void 0 ? void 0 : fileStats.isFile()) && fileStats.size > 0 && fileStats.size < 64 * 1024) {
            const data = fs.readFileSync(filePath, 'utf8');
            const lines = data.split(/\r?\n/);
            lines.forEach((line) => {
                const trimmedLine = line.trim();
                if (trimmedLine.length > 0 && !trimmedLine.startsWith('#') && !trimmedLine.match(/^import\s/)) {
                    const pthPath = parentDir.combinePaths(trimmedLine);
                    if (fs.existsSync(pthPath) && (0, uriUtils_1.isDirectory)(fs, pthPath)) {
                        searchPaths.push(fs.realCasePath(pthPath));
                    }
                }
            });
        }
    });
    return searchPaths;
}
exports.getPathsFromPthFiles = getPathsFromPthFiles;
function addPathIfUnique(pathList, pathToAdd) {
    if (!pathList.some((path) => path.key === pathToAdd.key)) {
        pathList.push(pathToAdd);
        return true;
    }
    return false;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/scope.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/analyzer/scope.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * scope.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Represents an evaluation scope and its defined symbols.
 * It also contains a link to a parent scope (except for the
 * top-most built-in scope).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Scope = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
class Scope {
    constructor(type, parent) {
        // Association between names and symbols.
        this.symbolTable = new Map();
        // Names within this scope that are bound to other scopes
        // (either nonlocal or global).
        this.notLocalBindings = new Map();
        this.type = type;
        this.parent = parent;
    }
    getGlobalScope() {
        let curScope = this;
        let isBeyondExecutionScope = false;
        while (curScope) {
            if (curScope.type === 3 /* ScopeType.Module */ || curScope.type === 4 /* ScopeType.Builtin */) {
                return { scope: curScope, isBeyondExecutionScope };
            }
            if (curScope.type === 1 /* ScopeType.Function */) {
                isBeyondExecutionScope = true;
            }
            curScope = curScope.parent;
        }
        (0, debug_1.fail)('failed to find scope');
        return { scope: this, isBeyondExecutionScope };
    }
    // Independently-executable scopes are those that are executed independently
    // of their parent scopes. Classes are executed in the context of their parent
    // scope, so they don't fit this category.
    isIndependentlyExecutable() {
        return this.type === 3 /* ScopeType.Module */ || this.type === 1 /* ScopeType.Function */;
    }
    lookUpSymbol(name) {
        return this.symbolTable.get(name);
    }
    lookUpSymbolRecursive(name, isOutsideCallerModule = false, isBeyondExecutionScope = false) {
        const symbol = this.symbolTable.get(name);
        if (symbol) {
            // If we're searching outside of the original caller's module (global) scope,
            // hide any names that are not meant to be visible to importers.
            if (isOutsideCallerModule && symbol.isExternallyHidden()) {
                return undefined;
            }
            // If the symbol is a class variable that is defined only in terms of
            // member accesses, it is not accessible directly by name, so hide it.
            const decls = symbol.getDeclarations();
            if (decls.length === 0 ||
                decls.some((decl) => decl.type !== 1 /* DeclarationType.Variable */ || !decl.isDefinedByMemberAccess)) {
                return {
                    symbol,
                    isOutsideCallerModule,
                    isBeyondExecutionScope,
                    scope: this,
                };
            }
        }
        let parentScope;
        let isNextScopeBeyondExecutionScope = isBeyondExecutionScope || this.isIndependentlyExecutable();
        if (this.notLocalBindings.get(name) === 1 /* NameBindingType.Global */) {
            const globalScopeResult = this.getGlobalScope();
            if (globalScopeResult.scope !== this) {
                parentScope = globalScopeResult.scope;
                if (globalScopeResult.isBeyondExecutionScope) {
                    isNextScopeBeyondExecutionScope = true;
                }
            }
        }
        else {
            parentScope = this.parent;
        }
        if (parentScope) {
            // If our recursion is about to take us outside the scope of the current
            // module (i.e. into a built-in scope), indicate as such with the second
            // parameter.
            return parentScope.lookUpSymbolRecursive(name, isOutsideCallerModule || this.type === 3 /* ScopeType.Module */, isNextScopeBeyondExecutionScope);
        }
        return undefined;
    }
    addSymbol(name, flags) {
        const symbol = new symbol_1.Symbol(flags);
        this.symbolTable.set(name, symbol);
        return symbol;
    }
    getBindingType(name) {
        return this.notLocalBindings.get(name);
    }
    setBindingType(name, bindingType) {
        return this.notLocalBindings.set(name, bindingType);
    }
    setSlotsNames(names) {
        this.slotsNames = names;
    }
    getSlotsNames() {
        return this.slotsNames;
    }
}
exports.Scope = Scope;


/***/ }),

/***/ "../pyright-internal/src/analyzer/scopeUtils.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/scopeUtils.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * scopeUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Static utility methods related to scopes and their related
 * symbol tables.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isScopeContainedWithin = exports.findTopNodeInScope = exports.getScopeHierarchy = exports.getScopeForNode = exports.getBuiltInScope = void 0;
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
function getBuiltInScope(currentScope) {
    // Starting at the current scope, find the built-in scope, which should
    // be the top-most parent.
    let builtInScope = currentScope;
    while (builtInScope.type !== 4 /* ScopeType.Builtin */) {
        builtInScope = builtInScope.parent;
    }
    return builtInScope;
}
exports.getBuiltInScope = getBuiltInScope;
// Locates the evaluation scope associated with the specified parse node.
function getScopeForNode(node) {
    const scopeNode = (0, parseTreeUtils_1.getEvaluationScopeNode)(node);
    return (0, analyzerNodeInfo_1.getScope)(scopeNode);
}
exports.getScopeForNode = getScopeForNode;
// Returns a list of scopes associated with the node and its ancestor nodes.
// If stopScope is provided, the search will stop at that scope.
// Returns undefined if stopScope is not found.
function getScopeHierarchy(node, stopScope) {
    const scopeHierarchy = [];
    let curNode = node;
    while (curNode) {
        const scopeNode = (0, parseTreeUtils_1.getEvaluationScopeNode)(curNode);
        const curScope = (0, analyzerNodeInfo_1.getScope)(scopeNode);
        if (!curScope) {
            return undefined;
        }
        if (scopeHierarchy.length === 0 || scopeHierarchy[scopeHierarchy.length - 1] !== curScope) {
            scopeHierarchy.push(curScope);
        }
        if (curScope === stopScope) {
            return scopeHierarchy;
        }
        curNode = scopeNode.parent;
    }
    return stopScope ? undefined : scopeHierarchy;
}
exports.getScopeHierarchy = getScopeHierarchy;
// Walks up the parse tree from the specified node to find the top-most node
// that is within specified scope.
function findTopNodeInScope(node, scope) {
    let curNode = node;
    let prevNode;
    let foundScope = false;
    while (curNode) {
        if ((0, analyzerNodeInfo_1.getScope)(curNode) === scope) {
            foundScope = true;
        }
        else if (foundScope) {
            return prevNode;
        }
        prevNode = curNode;
        curNode = curNode.parent;
    }
    return undefined;
}
exports.findTopNodeInScope = findTopNodeInScope;
function isScopeContainedWithin(scope, potentialParentScope) {
    let curScope = scope;
    while (curScope) {
        if (curScope.parent === potentialParentScope) {
            return true;
        }
        curScope = curScope.parent;
    }
    return false;
}
exports.isScopeContainedWithin = isScopeContainedWithin;


/***/ }),

/***/ "../pyright-internal/src/analyzer/semanticTokensWalker.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/analyzer/semanticTokensWalker.ts ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SemanticTokensWalker = void 0;
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const semanticTokensProvider_1 = __webpack_require__(/*! ../languageService/semanticTokensProvider */ "../pyright-internal/src/languageService/semanticTokensProvider.ts");
const declaration_1 = __webpack_require__(/*! ./declaration */ "../pyright-internal/src/analyzer/declaration.ts");
class SemanticTokensWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_evaluator) {
        super();
        this._evaluator = _evaluator;
        this.builtinModules = new Set(['builtins', '__builtins__']);
        this.items = [];
    }
    visitClass(node) {
        this._addItem(node.name.start, node.name.length, vscode_languageserver_1.SemanticTokenTypes.class, [vscode_languageserver_1.SemanticTokenModifiers.definition]);
        return super.visitClass(node);
    }
    visitFunction(node) {
        var _a;
        const modifiers = [vscode_languageserver_1.SemanticTokenModifiers.definition];
        if (node.isAsync) {
            modifiers.push(vscode_languageserver_1.SemanticTokenModifiers.async);
        }
        //TODO: whats the correct type here
        if ((_a = node.declaration) === null || _a === void 0 ? void 0 : _a.isMethod) {
            this._addItem(node.name.start, node.name.length, vscode_languageserver_1.SemanticTokenTypes.method, modifiers);
        }
        else {
            this._addItem(node.name.start, node.name.length, vscode_languageserver_1.SemanticTokenTypes.function, modifiers);
        }
        // parameters & return type are covered by visitName
        return super.visitFunction(node);
    }
    visitParameter(node) {
        if (node.name) {
            this._addItem(node.name.start, node.name.length, vscode_languageserver_1.SemanticTokenTypes.parameter, [
                vscode_languageserver_1.SemanticTokenModifiers.definition,
            ]);
        }
        return super.visitParameter(node);
    }
    visitDecorator(node) {
        let nameNode;
        this._addItem(node.start, 1 /* '@' symbol */, vscode_languageserver_1.SemanticTokenTypes.decorator, []);
        switch (node.expression.nodeType) {
            case 9 /* ParseNodeType.Call */:
                if (node.expression.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                    nameNode = node.expression.leftExpression.memberName;
                }
                else if (node.expression.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    nameNode = node.expression.leftExpression;
                }
                break;
            case 35 /* ParseNodeType.MemberAccess */:
                nameNode = node.expression.memberName;
                break;
            case 38 /* ParseNodeType.Name */:
                nameNode = node.expression;
                break;
        }
        if (nameNode) {
            this._addItem(nameNode.start, nameNode.length, vscode_languageserver_1.SemanticTokenTypes.decorator, []);
        }
        return super.visitDecorator(node);
    }
    visitImportAs(node) {
        for (const part of node.module.nameParts) {
            this._addItem(part.start, part.length, vscode_languageserver_1.SemanticTokenTypes.namespace, []);
        }
        if (node.alias) {
            this._addItem(node.alias.start, node.alias.length, vscode_languageserver_1.SemanticTokenTypes.namespace, []);
        }
        return super.visitImportAs(node);
    }
    visitImportFromAs(node) {
        var _a, _b;
        this._visitNameWithType(node.name, (_a = this._evaluator) === null || _a === void 0 ? void 0 : _a.getType((_b = node.alias) !== null && _b !== void 0 ? _b : node.name));
        return super.visitImportFromAs(node);
    }
    visitImportFrom(node) {
        for (const part of node.module.nameParts) {
            this._addItem(part.start, part.length, vscode_languageserver_1.SemanticTokenTypes.namespace, []);
        }
        return super.visitImportFrom(node);
    }
    visitName(node) {
        var _a;
        this._visitNameWithType(node, (_a = this._evaluator) === null || _a === void 0 ? void 0 : _a.getType(node));
        return super.visitName(node);
    }
    visitTypeAlias(node) {
        // this shouldn't be needed because keywords are part of syntax highlighting, not semantic highlighting,
        // but vscode incorrectly treats the type keyword as a type instead of a keyword so we need to fix it
        // TODO: keyword makes it purple like `if`, `for`, `import`, etc. but the `type` keyword is more like
        // `def`, `class` and `lambda` which are blue but i can't figure out what semantic token type does that.
        this._addItem(node.start, 4 /* length of the word "type" */, vscode_languageserver_1.SemanticTokenTypes.keyword, []);
        return super.visitTypeAlias(node);
    }
    _visitNameWithType(node, type) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        switch (type === null || type === void 0 ? void 0 : type.category) {
            case 4 /* TypeCategory.Function */:
                if (type.flags & 2 /* TypeFlags.Instance */) {
                    if ((_a = type.details.declaration) === null || _a === void 0 ? void 0 : _a.isMethod) {
                        this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.method, []);
                    }
                    else {
                        const modifiers = this.builtinModules.has(type.details.moduleName)
                            ? [vscode_languageserver_1.SemanticTokenModifiers.defaultLibrary, semanticTokensProvider_1.CustomSemanticTokenModifiers.builtin]
                            : [];
                        this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.function, modifiers);
                    }
                }
                else {
                    // type alias to Callable
                    this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.type, []);
                }
                return;
            case 5 /* TypeCategory.OverloadedFunction */:
                if (type.flags & 2 /* TypeFlags.Instance */) {
                    const details = types_1.OverloadedFunctionType.getOverloads(type)[0].details;
                    if ((_b = details.declaration) === null || _b === void 0 ? void 0 : _b.isMethod) {
                        this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.method, []);
                    }
                    else {
                        const modifiers = this.builtinModules.has(details.moduleName)
                            ? [vscode_languageserver_1.SemanticTokenModifiers.defaultLibrary, semanticTokensProvider_1.CustomSemanticTokenModifiers.builtin]
                            : [];
                        this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.function, modifiers);
                    }
                }
                else {
                    // dunno if this is possible but better safe than sorry!!!
                    this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.type, []);
                }
                return;
            case 7 /* TypeCategory.Module */:
                this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.namespace, []);
                return;
            // handled bellow
            case 2 /* TypeCategory.Any */:
            case 1 /* TypeCategory.Unknown */:
            case 9 /* TypeCategory.TypeVar */:
                break;
            case 0 /* TypeCategory.Unbound */:
            case undefined:
                return;
            case 8 /* TypeCategory.Union */:
                if (!(type.flags & 2 /* TypeFlags.Instance */)) {
                    this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.type, []);
                    return;
                }
                break;
            case 6 /* TypeCategory.Class */:
                //type annotations handled by visitTypeAnnotation
                if (!(type.flags & 2 /* TypeFlags.Instance */)) {
                    // Exclude type aliases:
                    // PEP 613 > Name: TypeAlias = Types
                    // PEP 695 > type Name = Types
                    const declarations = (_c = this._evaluator) === null || _c === void 0 ? void 0 : _c.getDeclarationsForNameNode(node);
                    const isPEP613TypeAlias = declarations &&
                        declarations.some((declaration) => { var _a; return (_a = this._evaluator) === null || _a === void 0 ? void 0 : _a.isExplicitTypeAliasDeclaration(declaration); });
                    const isTypeAlias = isPEP613TypeAlias || ((_d = type.typeAliasInfo) === null || _d === void 0 ? void 0 : _d.isPep695Syntax);
                    const isBuiltIn = (!isTypeAlias &&
                        this.builtinModules.has(type.details.moduleName) &&
                        type.aliasName === undefined) ||
                        (((_e = type.typeAliasInfo) === null || _e === void 0 ? void 0 : _e.moduleName) && this.builtinModules.has(type.typeAliasInfo.moduleName));
                    const modifiers = isBuiltIn
                        ? [vscode_languageserver_1.SemanticTokenModifiers.defaultLibrary, semanticTokensProvider_1.CustomSemanticTokenModifiers.builtin]
                        : [];
                    this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.class, modifiers);
                    return;
                }
        }
        const symbol = (_g = (_f = this._evaluator) === null || _f === void 0 ? void 0 : _f.lookUpSymbolRecursive(node, node.value, false)) === null || _g === void 0 ? void 0 : _g.symbol;
        if ((type === null || type === void 0 ? void 0 : type.category) === 3 /* TypeCategory.Never */ && symbol && !this._evaluator.getDeclaredTypeOfSymbol(symbol).type) {
            // for some reason Never is considered both instantiable and an instance, so we need to look up the type this way
            // to differentiate between "instances" of `Never` and type aliases/annotations of Never:
            this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.type, []);
            return;
        }
        const declarations = (_h = this._evaluator) === null || _h === void 0 ? void 0 : _h.getDeclarationsForNameNode(node);
        if (declarations === null || declarations === void 0 ? void 0 : declarations.some(declaration_1.isParameterDeclaration)) {
            const parent = declarations[0].node.parent;
            // Avoid duplicates for parameters visited by `visitParameter`
            if (!parent.parameters.some((param) => { var _a; return ((_a = param.name) === null || _a === void 0 ? void 0 : _a.id) === node.id; })) {
                this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.parameter, []);
            }
        }
        else if ((type === null || type === void 0 ? void 0 : type.category) === 9 /* TypeCategory.TypeVar */ && !(type.flags & 2 /* TypeFlags.Instance */)) {
            // `cls` method parameter is treated as a TypeVar in some special methods (methods
            // with @classmethod decorator, `__new__`, `__init_subclass__`, etc.) so we need to
            // check first if it's a parameter before checking that it's a TypeVar
            this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.typeParameter, []);
            return;
        }
        else if (((type === null || type === void 0 ? void 0 : type.category) === 1 /* TypeCategory.Unknown */ || (type === null || type === void 0 ? void 0 : type.category) === 2 /* TypeCategory.Any */) &&
            (declarations === undefined || declarations.length === 0)) {
            return;
        }
        else if ((0, symbolNameUtils_1.isConstantName)(node.value) || (symbol && this._evaluator.isFinalVariable(symbol))) {
            this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.variable, [vscode_languageserver_1.SemanticTokenModifiers.readonly]);
        }
        else {
            this._addItem(node.start, node.length, vscode_languageserver_1.SemanticTokenTypes.variable, []);
        }
    }
    _addItem(start, length, type, modifiers) {
        this.items.push({ type, modifiers, start, length });
    }
}
exports.SemanticTokensWalker = SemanticTokensWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/service.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/analyzer/service.ts ***!
  \***************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * service.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A service that is able to analyze a collection of
 * Python files.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AnalyzerService = exports.getNextServiceId = exports.pyprojectTomlName = exports.configFileNames = void 0;
const TOML = __importStar(__webpack_require__(/*! @iarna/toml */ "../pyright-internal/node_modules/@iarna/toml/toml.js"));
const JSONC = __importStar(__webpack_require__(/*! jsonc-parser */ "../pyright-internal/node_modules/jsonc-parser/lib/esm/main.js"));
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ../common/console */ "../pyright-internal/src/common/console.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const fileWatcher_1 = __webpack_require__(/*! ../common/fileWatcher */ "../pyright-internal/src/common/fileWatcher.ts");
const host_1 = __webpack_require__(/*! ../common/host */ "../pyright-internal/src/common/host.ts");
const pathConsts_1 = __webpack_require__(/*! ../common/pathConsts */ "../pyright-internal/src/common/pathConsts.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const backgroundAnalysisProgram_1 = __webpack_require__(/*! ./backgroundAnalysisProgram */ "../pyright-internal/src/analyzer/backgroundAnalysisProgram.ts");
const importResolver_1 = __webpack_require__(/*! ./importResolver */ "../pyright-internal/src/analyzer/importResolver.ts");
const pythonPathUtils_1 = __webpack_require__(/*! ./pythonPathUtils */ "../pyright-internal/src/analyzer/pythonPathUtils.ts");
const sourceFile_1 = __webpack_require__(/*! ./sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const constants_1 = __webpack_require__(/*! ../constants */ "../pyright-internal/src/constants.ts");
exports.configFileNames = ['pyrightconfig.json'];
exports.pyprojectTomlName = 'pyproject.toml';
// How long since the last user activity should we wait until running
// the analyzer on any files that have not yet been analyzed?
const _userActivityBackoffTimeInMs = 250;
const _gitDirectory = (0, pathUtils_1.normalizeSlashes)('/.git/');
// Hold uniqueId for this service. It can be used to distinguish each service later.
let _nextServiceId = 1;
function getNextServiceId(name) {
    return `${name}_${_nextServiceId++}`;
}
exports.getNextServiceId = getNextServiceId;
class AnalyzerService {
    constructor(instanceName, serviceProvider, options) {
        var _a, _b, _c, _d, _e;
        this._typeStubTargetIsSingleFile = false;
        this._requireTrackedFileUpdate = true;
        this._lastUserInteractionTime = Date.now();
        this._disposed = false;
        this._pendingLibraryChanges = { changesOnly: true };
        this._instanceName = instanceName;
        this._executionRootUri = uri_1.Uri.empty();
        this._options = options;
        this._options.serviceId = (_a = this._options.serviceId) !== null && _a !== void 0 ? _a : getNextServiceId(instanceName);
        this._options.console = options.console || new console_1.StandardConsole();
        // Create local copy of the given service provider.
        this._serviceProvider = serviceProvider.clone();
        // Override the console and the file system if they were explicitly provided.
        if (this._options.console) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.console, this._options.console);
        }
        if (this._options.fileSystem) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.fs, this._options.fileSystem);
        }
        this._options.importResolverFactory = (_b = options.importResolverFactory) !== null && _b !== void 0 ? _b : AnalyzerService.createImportResolver;
        this._options.cancellationProvider = (_c = options.cancellationProvider) !== null && _c !== void 0 ? _c : new cancellationUtils_1.DefaultCancellationProvider();
        this._options.hostFactory = (_d = options.hostFactory) !== null && _d !== void 0 ? _d : (() => new host_1.NoAccessHost());
        this._options.configOptions =
            (_e = options.configOptions) !== null && _e !== void 0 ? _e : new configOptions_1.BasedConfigOptions(uri_1.Uri.file(process.cwd(), this._serviceProvider));
        const importResolver = this._options.importResolverFactory(this._serviceProvider, this._options.configOptions, this._options.hostFactory());
        this._backgroundAnalysisProgram =
            this._options.backgroundAnalysisProgramFactory !== undefined
                ? this._options.backgroundAnalysisProgramFactory(this._options.serviceId, this._serviceProvider, this._options.configOptions, importResolver, this._options.backgroundAnalysis, this._options.maxAnalysisTime)
                : new backgroundAnalysisProgram_1.BackgroundAnalysisProgram(this._options.serviceId, this._serviceProvider, this._options.configOptions, importResolver, this._options.backgroundAnalysis, this._options.maxAnalysisTime, 
                /* disableChecker */ undefined);
    }
    get fs() {
        return this._backgroundAnalysisProgram.importResolver.fileSystem;
    }
    get serviceProvider() {
        return this._serviceProvider;
    }
    get cancellationProvider() {
        return this._options.cancellationProvider;
    }
    get librarySearchUrisToWatch() {
        return this._librarySearchUrisToWatch;
    }
    get backgroundAnalysisProgram() {
        return this._backgroundAnalysisProgram;
    }
    get test_program() {
        return this._program;
    }
    get id() {
        return this._options.serviceId;
    }
    clone(instanceName, serviceId, backgroundAnalysis, fileSystem) {
        var _a;
        const service = new AnalyzerService(instanceName, this._serviceProvider, {
            ...this._options,
            serviceId,
            backgroundAnalysis,
            skipScanningUserFiles: true,
            fileSystem,
        });
        // Cloned service will use whatever user files the service currently has.
        const userFiles = this.getUserFiles();
        service.backgroundAnalysisProgram.setTrackedFiles(userFiles);
        service.backgroundAnalysisProgram.markAllFilesDirty(true);
        // Make sure we keep editor content (open file) which could be different than one in the file system.
        for (const fileInfo of this.backgroundAnalysisProgram.program.getOpened()) {
            const version = fileInfo.sourceFile.getClientVersion();
            if (version !== undefined) {
                service.setFileOpened(fileInfo.sourceFile.getUri(), version, fileInfo.sourceFile.getOpenFileContents(), fileInfo.sourceFile.getIPythonMode(), (_a = fileInfo.chainedSourceFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getUri());
            }
        }
        return service;
    }
    runEditMode(callback, token) {
        let edits = [];
        this._backgroundAnalysisProgram.enterEditMode();
        try {
            this._program.runEditMode(callback, token);
        }
        finally {
            edits = this._backgroundAnalysisProgram.exitEditMode();
        }
        return token.isCancellationRequested ? [] : edits;
    }
    dispose() {
        if (!this._disposed) {
            // Make sure we dispose program, otherwise, entire program
            // will leak.
            this._backgroundAnalysisProgram.dispose();
        }
        this._disposed = true;
        this._removeSourceFileWatchers();
        this._removeConfigFileWatcher();
        this._removeLibraryFileWatcher();
        this._clearReloadConfigTimer();
        this._clearReanalysisTimer();
        this._clearLibraryReanalysisTimer();
    }
    static createImportResolver(serviceProvider, options, host) {
        return new importResolver_1.ImportResolver(serviceProvider, options, host);
    }
    setCompletionCallback(callback) {
        this._onCompletionCallback = callback;
        this._backgroundAnalysisProgram.setCompletionCallback(callback);
    }
    setOptions(commandLineOptions) {
        this._commandLineOptions = commandLineOptions;
        const host = this._hostFactory();
        const configOptions = this._getConfigOptions(host, commandLineOptions);
        if (configOptions.pythonPath) {
            // Make sure we have default python environment set.
            configOptions.ensureDefaultPythonVersion(host, this._console);
        }
        configOptions.ensureDefaultPythonPlatform(host, this._console);
        this._backgroundAnalysisProgram.setConfigOptions(configOptions);
        this._executionRootUri = configOptions.projectRoot;
        this._applyConfigOptions(host);
    }
    hasSourceFile(uri) {
        return this.backgroundAnalysisProgram.hasSourceFile(uri);
    }
    isTracked(uri) {
        return this._program.owns(uri);
    }
    getUserFiles() {
        return this._program.getUserFiles().map((i) => i.sourceFile.getUri());
    }
    getOpenFiles() {
        return this._program.getOpened().map((i) => i.sourceFile.getUri());
    }
    setFileOpened(uri, version, contents, ipythonMode = sourceFile_1.IPythonMode.None, chainedFileUri) {
        // Open the file. Notebook cells are always tracked as they aren't 3rd party library files.
        // This is how it's worked in the past since each notebook used to have its own
        // workspace and the workspace include setting marked all cells as tracked.
        this._backgroundAnalysisProgram.setFileOpened(uri, version, contents, {
            isTracked: this.isTracked(uri) || ipythonMode !== sourceFile_1.IPythonMode.None,
            ipythonMode,
            chainedFileUri: chainedFileUri,
        });
        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
    }
    getChainedUri(uri) {
        return this._backgroundAnalysisProgram.getChainedUri(uri);
    }
    updateChainedUri(uri, chainedFileUri) {
        this._backgroundAnalysisProgram.updateChainedUri(uri, chainedFileUri);
        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
    }
    updateOpenFileContents(uri, version, contents, ipythonMode = sourceFile_1.IPythonMode.None) {
        this._backgroundAnalysisProgram.updateOpenFileContents(uri, version, contents, {
            isTracked: this.isTracked(uri),
            ipythonMode,
            chainedFileUri: undefined,
        });
        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
    }
    setFileClosed(uri, isTracked) {
        this._backgroundAnalysisProgram.setFileClosed(uri, isTracked);
        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
    }
    addInterimFile(uri) {
        this._backgroundAnalysisProgram.addInterimFile(uri);
    }
    getParserOutput(uri) {
        return this._program.getParserOutput(uri);
    }
    getParseResults(uri) {
        return this._program.getParseResults(uri);
    }
    getSourceFile(uri) {
        return this._program.getBoundSourceFile(uri);
    }
    getTextOnRange(fileUri, range, token) {
        return this._program.getTextOnRange(fileUri, range, token);
    }
    getEvaluator() {
        return this._program.evaluator;
    }
    run(callback, token) {
        return this._program.run(callback, token);
    }
    printStats() {
        this._console.info('');
        this._console.info('Analysis stats');
        const boundFileCount = this._program.getFileCount(/* userFileOnly */ false);
        this._console.info('Total files parsed and bound: ' + boundFileCount.toString());
        const checkedFileCount = this._program.getUserFileCount();
        this._console.info('Total files checked: ' + checkedFileCount.toString());
    }
    printDetailedAnalysisTimes() {
        this._program.printDetailedAnalysisTimes();
    }
    printDependencies(verbose) {
        this._program.printDependencies(this._executionRootUri, verbose);
    }
    analyzeFile(fileUri, token) {
        return this._backgroundAnalysisProgram.analyzeFile(fileUri, token);
    }
    getDiagnosticsForRange(fileUri, range, token) {
        return this._backgroundAnalysisProgram.getDiagnosticsForRange(fileUri, range, token);
    }
    getConfigOptions() {
        return this._configOptions;
    }
    getImportResolver() {
        return this._backgroundAnalysisProgram.importResolver;
    }
    recordUserInteractionTime() {
        this._lastUserInteractionTime = Date.now();
        // If we have a pending timer for reanalysis, cancel it
        // and reschedule for some time in the future.
        if (this._analyzeTimer) {
            this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
        }
    }
    test_getConfigOptions(commandLineOptions) {
        return this._getConfigOptions(this._backgroundAnalysisProgram.host, commandLineOptions);
    }
    test_getFileNamesFromFileSpecs() {
        return this._getFileNamesFromFileSpecs();
    }
    test_shouldHandleSourceFileWatchChanges(uri, isFile) {
        return this._shouldHandleSourceFileWatchChanges(uri, isFile);
    }
    test_shouldHandleLibraryFileWatchChanges(uri, libSearchUris) {
        return this._shouldHandleLibraryFileWatchChanges(uri, libSearchUris);
    }
    writeTypeStub(token) {
        var _a;
        const typingsSubdirUri = this._getTypeStubFolder();
        this._program.writeTypeStub((_a = this._typeStubTargetUri) !== null && _a !== void 0 ? _a : uri_1.Uri.empty(), this._typeStubTargetIsSingleFile, typingsSubdirUri, token);
    }
    writeTypeStubInBackground(token) {
        var _a;
        const typingsSubdirUri = this._getTypeStubFolder();
        return this._backgroundAnalysisProgram.writeTypeStub((_a = this._typeStubTargetUri) !== null && _a !== void 0 ? _a : uri_1.Uri.empty(), this._typeStubTargetIsSingleFile, typingsSubdirUri, token);
    }
    invalidateAndForceReanalysis(reason) {
        this._backgroundAnalysisProgram.invalidateAndForceReanalysis(reason);
    }
    // Forces the service to stop all analysis, discard all its caches,
    // and research for files.
    restart() {
        this._applyConfigOptions(this._hostFactory());
        this._backgroundAnalysisProgram.restart();
    }
    get _console() {
        return this._options.console;
    }
    get _hostFactory() {
        return this._options.hostFactory;
    }
    get _importResolverFactory() {
        return this._options.importResolverFactory;
    }
    get _program() {
        return this._backgroundAnalysisProgram.program;
    }
    get _configOptions() {
        return this._backgroundAnalysisProgram.configOptions;
    }
    get _watchForSourceChanges() {
        var _a;
        return !!((_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.watchForSourceChanges);
    }
    get _watchForLibraryChanges() {
        var _a;
        return !!((_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.watchForLibraryChanges) && !!this._options.libraryReanalysisTimeProvider;
    }
    get _watchForConfigChanges() {
        var _a;
        return !!((_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.watchForConfigChanges);
    }
    get _typeCheckingMode() {
        var _a;
        return (_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.typeCheckingMode;
    }
    get _verboseOutput() {
        return !!this._configOptions.verboseOutput;
    }
    get _typeStubTargetImportName() {
        var _a;
        return (_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.typeStubTargetImportName;
    }
    // Calculates the effective options based on the command-line options,
    // an optional config file, and default values.
    _getConfigOptions(host, commandLineOptions) {
        var _a, _b, _c;
        const optionRoot = commandLineOptions.executionRoot;
        const executionRootUri = uri_1.Uri.is(optionRoot)
            ? optionRoot
            : (0, core_1.isString)(optionRoot)
                ? uri_1.Uri.file(optionRoot, this.serviceProvider, /* checkRelative */ true)
                : uri_1.Uri.empty();
        const executionRoot = this.fs.realCasePath(executionRootUri);
        let projectRoot = executionRoot;
        let configFilePath;
        let pyprojectFilePath;
        if (commandLineOptions.configFilePath) {
            // If the config file path was specified, determine whether it's
            // a directory (in which case the default config file name is assumed)
            // or a file.
            configFilePath = this.fs.realCasePath((0, pathUtils_1.isRootedDiskPath)(commandLineOptions.configFilePath)
                ? uri_1.Uri.file(commandLineOptions.configFilePath, this.serviceProvider, /* checkRelative */ true)
                : projectRoot.resolvePaths(commandLineOptions.configFilePath));
            if (!this.fs.existsSync(configFilePath)) {
                this._console.info(`Configuration file not found at ${configFilePath.toUserVisibleString()}.`);
                configFilePath = projectRoot;
            }
            else {
                if (configFilePath.lastExtension.endsWith('.json')) {
                    projectRoot = configFilePath.getDirectory();
                }
                else {
                    projectRoot = configFilePath;
                    configFilePath = this._findConfigFile(configFilePath);
                    if (!configFilePath) {
                        this._console.info(`Configuration file not found at ${projectRoot.toUserVisibleString()}.`);
                    }
                }
            }
        }
        else if (commandLineOptions.executionRoot) {
            // In a project-based IDE like VS Code, we should assume that the
            // project root directory contains the config file.
            configFilePath = this._findConfigFile(projectRoot);
            // If pyright is being executed from the command line, the working
            // directory may be deep within a project, and we need to walk up the
            // directory hierarchy to find the project root.
            if (!configFilePath && !commandLineOptions.fromVsCodeExtension) {
                configFilePath = this._findConfigFileHereOrUp(projectRoot);
            }
            if (configFilePath) {
                projectRoot = configFilePath.getDirectory();
            }
            else {
                this._console.log(`No configuration file found.`);
                configFilePath = undefined;
            }
        }
        if (!configFilePath) {
            // See if we can find a pyproject.toml file in this directory.
            pyprojectFilePath = this._findPyprojectTomlFile(projectRoot);
            if (!pyprojectFilePath && !commandLineOptions.fromVsCodeExtension) {
                pyprojectFilePath = this._findPyprojectTomlFileHereOrUp(projectRoot);
            }
            if (pyprojectFilePath) {
                projectRoot = pyprojectFilePath.getDirectory();
                this._console.log(`pyproject.toml file found at ${projectRoot.toUserVisibleString()}.`);
            }
            else {
                this._console.log(`No pyproject.toml file found.`);
            }
        }
        const configOptions = new configOptions_1.BasedConfigOptions(projectRoot, this._typeCheckingMode);
        const defaultExcludes = ['**/node_modules', '**/__pycache__', '**/.*'];
        if (commandLineOptions.pythonPath) {
            this._console.info(`Setting pythonPath for service "${this._instanceName}": ` + `"${commandLineOptions.pythonPath}"`);
            configOptions.pythonPath = this.fs.realCasePath(uri_1.Uri.file(commandLineOptions.pythonPath, this.serviceProvider, /* checkRelative */ true));
        }
        if (commandLineOptions.pythonEnvironmentName) {
            this._console.info(`Setting environmentName for service "${this._instanceName}": ` +
                `"${commandLineOptions.pythonEnvironmentName}"`);
            configOptions.pythonEnvironmentName = commandLineOptions.pythonEnvironmentName;
        }
        // The pythonPlatform and pythonVersion from the command-line can be overridden
        // by the config file, so initialize them upfront.
        configOptions.defaultPythonPlatform = commandLineOptions.pythonPlatform;
        configOptions.defaultPythonVersion = commandLineOptions.pythonVersion;
        configOptions.ensureDefaultExtraPaths(this.fs, (_a = commandLineOptions.autoSearchPaths) !== null && _a !== void 0 ? _a : false, commandLineOptions.extraPaths);
        if (commandLineOptions.includeFileSpecs.length > 0) {
            commandLineOptions.includeFileSpecs.forEach((fileSpec) => {
                configOptions.include.push((0, uriUtils_1.getFileSpec)(projectRoot, fileSpec));
            });
        }
        if (commandLineOptions.excludeFileSpecs.length > 0) {
            commandLineOptions.excludeFileSpecs.forEach((fileSpec) => {
                configOptions.exclude.push((0, uriUtils_1.getFileSpec)(projectRoot, fileSpec));
            });
        }
        if (commandLineOptions.ignoreFileSpecs.length > 0) {
            commandLineOptions.ignoreFileSpecs.forEach((fileSpec) => {
                configOptions.ignore.push((0, uriUtils_1.getFileSpec)(projectRoot, fileSpec));
            });
        }
        if (!configFilePath && commandLineOptions.executionRoot) {
            if (commandLineOptions.includeFileSpecs.length === 0) {
                // If no config file was found and there are no explicit include
                // paths specified, assume the caller wants to include all source
                // files under the execution root path.
                configOptions.include.push((0, uriUtils_1.getFileSpec)(executionRoot, '.'));
            }
            if (commandLineOptions.excludeFileSpecs.length === 0) {
                // Add a few common excludes to avoid long scan times.
                defaultExcludes.forEach((exclude) => {
                    configOptions.exclude.push((0, uriUtils_1.getFileSpec)(executionRoot, exclude));
                });
            }
        }
        this._configFileUri = configFilePath || pyprojectFilePath;
        configOptions.disableTaggedHints = !!commandLineOptions.disableTaggedHints;
        // If we found a config file, parse it to compute the effective options.
        let configJsonObj;
        if (configFilePath) {
            this._console.info(`Loading configuration file at ${configFilePath.toUserVisibleString()}`);
            configJsonObj = this._parseJsonConfigFile(configFilePath);
        }
        else if (pyprojectFilePath) {
            this._console.info(`Loading pyproject.toml file at ${pyprojectFilePath.toUserVisibleString()}`);
            configJsonObj = this._parsePyprojectTomlFile(pyprojectFilePath);
        }
        if (configJsonObj) {
            const errors = configOptions.initializeFromJson(configJsonObj, this._typeCheckingMode, this.serviceProvider, host, commandLineOptions);
            if (errors.length > 0) {
                for (const error of errors) {
                    this._console.error(error);
                }
                this._reportConfigParseError();
            }
            const configFileDir = this._configFileUri.getDirectory();
            // If no include paths were provided, assume that all files within
            // the project should be included.
            if (configOptions.include.length === 0) {
                this._console.info(`No include entries specified; assuming ${configFileDir.toUserVisibleString()}`);
                configOptions.include.push((0, uriUtils_1.getFileSpec)(configFileDir, '.'));
            }
            // If there was no explicit set of excludes, add a few common ones to avoid long scan times.
            if (configOptions.exclude.length === 0) {
                defaultExcludes.forEach((exclude) => {
                    this._console.info(`Auto-excluding ${exclude}`);
                    configOptions.exclude.push((0, uriUtils_1.getFileSpec)(configFileDir, exclude));
                });
                if (configOptions.autoExcludeVenv === undefined) {
                    configOptions.autoExcludeVenv = true;
                }
            }
        }
        else {
            configOptions.autoExcludeVenv = true;
            configOptions.applyDiagnosticOverrides(commandLineOptions.diagnosticSeverityOverrides);
        }
        // Override the analyzeUnannotatedFunctions setting based on the command-line setting.
        if (commandLineOptions.analyzeUnannotatedFunctions !== undefined) {
            configOptions.diagnosticRuleSet.analyzeUnannotatedFunctions =
                commandLineOptions.analyzeUnannotatedFunctions;
        }
        // Override the include based on command-line settings.
        if (commandLineOptions.includeFileSpecsOverride) {
            configOptions.include = [];
            commandLineOptions.includeFileSpecsOverride.forEach((include) => {
                configOptions.include.push((0, uriUtils_1.getFileSpec)(uri_1.Uri.file(include, this.serviceProvider, /* checkRelative */ true), '.'));
            });
        }
        const reportDuplicateSetting = (settingName, configValue) => {
            const settingSource = commandLineOptions.fromVsCodeExtension
                ? 'the client settings'
                : 'a command-line option';
            this._console.warn(`The ${settingName} has been specified in both the config file and ` +
                `${settingSource}. The value in the config file (${configValue}) ` +
                `will take precedence`);
        };
        // Apply the command-line options if the corresponding
        // item wasn't already set in the config file. Report any
        // duplicates.
        if (commandLineOptions.venvPath) {
            if (!configOptions.venvPath) {
                configOptions.venvPath = projectRoot.resolvePaths(commandLineOptions.venvPath);
            }
            else {
                reportDuplicateSetting('venvPath', configOptions.venvPath.toUserVisibleString());
            }
        }
        if (commandLineOptions.typeshedPath) {
            if (!configOptions.typeshedPath) {
                configOptions.typeshedPath = projectRoot.resolvePaths(commandLineOptions.typeshedPath);
            }
            else {
                reportDuplicateSetting('typeshedPath', configOptions.typeshedPath.toUserVisibleString());
            }
        }
        // If the caller specified that "typeshedPath" is the root of the project,
        // then we're presumably running in the typeshed project itself. Auto-exclude
        // stdlib packages that don't match the current Python version.
        if (configOptions.typeshedPath &&
            configOptions.typeshedPath === projectRoot &&
            configOptions.defaultPythonVersion !== undefined) {
            const excludeList = this.getImportResolver().getTypeshedStdlibExcludeList(configOptions.typeshedPath, configOptions.defaultPythonVersion, configOptions.defaultPythonPlatform);
            this._console.info(`Excluding typeshed stdlib stubs according to VERSIONS file:`);
            excludeList.forEach((exclude) => {
                this._console.info(`    ${exclude}`);
                configOptions.exclude.push((0, uriUtils_1.getFileSpec)(executionRoot, exclude.getFilePath()));
            });
        }
        configOptions.verboseOutput = (_b = commandLineOptions.verboseOutput) !== null && _b !== void 0 ? _b : configOptions.verboseOutput;
        configOptions.checkOnlyOpenFiles = !!commandLineOptions.checkOnlyOpenFiles;
        configOptions.autoImportCompletions = !!commandLineOptions.autoImportCompletions;
        configOptions.indexing = !!commandLineOptions.indexing;
        configOptions.taskListTokens = commandLineOptions.taskListTokens;
        configOptions.logTypeEvaluationTime = !!commandLineOptions.logTypeEvaluationTime;
        configOptions.typeEvaluationTimeThreshold = commandLineOptions.typeEvaluationTimeThreshold;
        // If useLibraryCodeForTypes was not specified in the config, allow the settings
        // or command line to override it.
        if (configOptions.useLibraryCodeForTypes === undefined) {
            configOptions.useLibraryCodeForTypes = commandLineOptions.useLibraryCodeForTypes;
        }
        else if (commandLineOptions.useLibraryCodeForTypes !== undefined) {
            reportDuplicateSetting('useLibraryCodeForTypes', configOptions.useLibraryCodeForTypes);
        }
        // If useLibraryCodeForTypes is unspecified, default it to true.
        if (configOptions.useLibraryCodeForTypes === undefined) {
            configOptions.useLibraryCodeForTypes = true;
        }
        if (commandLineOptions.stubPath) {
            if (!configOptions.stubPath) {
                configOptions.stubPath = this.fs.realCasePath(projectRoot.resolvePaths(commandLineOptions.stubPath));
            }
            else {
                reportDuplicateSetting('stubPath', configOptions.stubPath.toUserVisibleString());
            }
        }
        if (configOptions.stubPath) {
            // If there was a stub path specified, validate it.
            if (!this.fs.existsSync(configOptions.stubPath) || !(0, uriUtils_1.isDirectory)(this.fs, configOptions.stubPath)) {
                this._console.warn(`stubPath ${configOptions.stubPath} is not a valid directory.`);
            }
        }
        else {
            // If no stub path was specified, use a default path.
            configOptions.stubPath = configOptions.projectRoot.resolvePaths(pathConsts_1.defaultStubsDirectory);
        }
        // Do some sanity checks on the specified settings and report missing
        // or inconsistent information.
        if (configOptions.venvPath) {
            if (!this.fs.existsSync(configOptions.venvPath) || !(0, uriUtils_1.isDirectory)(this.fs, configOptions.venvPath)) {
                this._console.error(`venvPath ${configOptions.venvPath.toUserVisibleString()} is not a valid directory.`);
            }
            // venvPath without venv means it won't do anything while resolveImport.
            // so first, try to set venv from existing configOption if it is null. if both are null,
            // then, resolveImport won't consider venv
            configOptions.venv = (_c = configOptions.venv) !== null && _c !== void 0 ? _c : this._configOptions.venv;
            if (configOptions.venv && configOptions.venvPath) {
                const fullVenvPath = configOptions.venvPath.resolvePaths(configOptions.venv);
                if (!this.fs.existsSync(fullVenvPath) || !(0, uriUtils_1.isDirectory)(this.fs, fullVenvPath)) {
                    this._console.error(`venv ${configOptions.venv} subdirectory not found in venv path ${configOptions.venvPath.toUserVisibleString()}.`);
                }
                else {
                    const importFailureInfo = [];
                    if ((0, pythonPathUtils_1.findPythonSearchPaths)(this.fs, configOptions, host, importFailureInfo) === undefined) {
                        this._console.error(`site-packages directory cannot be located for venvPath ` +
                            `${configOptions.venvPath.toUserVisibleString()} and venv ${configOptions.venv}.`);
                        if (configOptions.verboseOutput) {
                            importFailureInfo.forEach((diag) => {
                                this._console.error(`  ${diag}`);
                            });
                        }
                    }
                }
            }
        }
        // Is there a reference to a venv? If so, there needs to be a valid venvPath.
        if (configOptions.venv) {
            if (!configOptions.venvPath) {
                this._console.warn(`venvPath not specified, so venv settings will be ignored.`);
            }
        }
        if (configOptions.typeshedPath) {
            if (!this.fs.existsSync(configOptions.typeshedPath) || !(0, uriUtils_1.isDirectory)(this.fs, configOptions.typeshedPath)) {
                this._console.error(`typeshedPath ${configOptions.typeshedPath.toUserVisibleString()} is not a valid directory.`);
            }
        }
        return configOptions;
    }
    _getTypeStubFolder() {
        var _a;
        const stubPath = (_a = this._configOptions.stubPath) !== null && _a !== void 0 ? _a : this.fs.realCasePath(this._configOptions.projectRoot.resolvePaths(pathConsts_1.defaultStubsDirectory));
        if (!this._typeStubTargetUri || !this._typeStubTargetImportName) {
            const errMsg = `Import '${this._typeStubTargetImportName}'` + ` could not be resolved`;
            this._console.error(errMsg);
            throw new Error(errMsg);
        }
        const typeStubInputTargetParts = this._typeStubTargetImportName.split('.');
        if (typeStubInputTargetParts[0].length === 0) {
            // We should never get here because the import resolution
            // would have failed.
            const errMsg = `Import '${this._typeStubTargetImportName}'` + ` could not be resolved`;
            this._console.error(errMsg);
            throw new Error(errMsg);
        }
        try {
            // Generate a new typings directory if necessary.
            if (!this.fs.existsSync(stubPath)) {
                this.fs.mkdirSync(stubPath);
            }
        }
        catch (e) {
            const errMsg = `Could not create typings directory '${stubPath.toUserVisibleString()}'`;
            this._console.error(errMsg);
            throw new Error(errMsg);
        }
        // Generate a typings subdirectory hierarchy.
        const typingsSubdirPath = stubPath.resolvePaths(typeStubInputTargetParts[0]);
        const typingsSubdirHierarchy = stubPath.resolvePaths(...typeStubInputTargetParts);
        try {
            // Generate a new typings subdirectory if necessary.
            if (!this.fs.existsSync(typingsSubdirHierarchy)) {
                (0, uriUtils_1.makeDirectories)(this.fs, typingsSubdirHierarchy, stubPath);
            }
        }
        catch (e) {
            const errMsg = `Could not create typings subdirectory '${typingsSubdirHierarchy.toUserVisibleString()}'`;
            this._console.error(errMsg);
            throw new Error(errMsg);
        }
        return typingsSubdirPath;
    }
    _findConfigFileHereOrUp(searchPath) {
        return (0, uriUtils_1.forEachAncestorDirectory)(searchPath, (ancestor) => this._findConfigFile(ancestor));
    }
    _findConfigFile(searchPath) {
        for (const name of exports.configFileNames) {
            const fileName = searchPath.resolvePaths(name);
            if (this.fs.existsSync(fileName)) {
                return this.fs.realCasePath(fileName);
            }
        }
        return undefined;
    }
    _findPyprojectTomlFileHereOrUp(searchPath) {
        return (0, uriUtils_1.forEachAncestorDirectory)(searchPath, (ancestor) => this._findPyprojectTomlFile(ancestor));
    }
    _findPyprojectTomlFile(searchPath) {
        const fileName = searchPath.resolvePaths(exports.pyprojectTomlName);
        if (this.fs.existsSync(fileName)) {
            return this.fs.realCasePath(fileName);
        }
        return undefined;
    }
    _parseJsonConfigFile(configPath) {
        return this._attemptParseFile(configPath, (fileContents) => {
            const errors = [];
            const result = JSONC.parse(fileContents, errors, { allowTrailingComma: true });
            if (errors.length > 0) {
                throw new Error('Errors parsing JSON file');
            }
            return result;
        });
    }
    _parsePyprojectTomlFile(pyprojectPath) {
        return this._attemptParseFile(pyprojectPath, (fileContents, attemptCount) => {
            try {
                const configObj = TOML.parse(fileContents);
                if (configObj && configObj.tool) {
                    const toml = configObj.tool;
                    if (toml.basedpyright && toml.pyright) {
                        throw new Error('Pyproject file cannot have both `pyright` and `basedpyright` sections. pick one');
                    }
                    return (toml.basedpyright || toml.pyright);
                }
            }
            catch (e) {
                this._console.error(`Pyproject file parse attempt ${attemptCount} ${e instanceof Error ? e : `error: ${JSON.stringify(e)}`}`);
                throw e;
            }
            this._console.info(`Pyproject file "${pyprojectPath.toUserVisibleString()}" has no "[tool.basedpyright]" section.`);
            return undefined;
        });
    }
    _attemptParseFile(fileUri, parseCallback) {
        let fileContents = '';
        let parseAttemptCount = 0;
        while (true) {
            // Attempt to read the file contents.
            try {
                fileContents = this.fs.readFileSync(fileUri, 'utf8');
            }
            catch {
                this._console.error(`Config file "${fileUri.toUserVisibleString()}" could not be read.`);
                this._reportConfigParseError();
                return undefined;
            }
            // Attempt to parse the file.
            let parseFailed = false;
            try {
                return parseCallback(fileContents, parseAttemptCount + 1);
            }
            catch (e) {
                parseFailed = true;
            }
            if (!parseFailed) {
                break;
            }
            // If we attempt to read the file immediately after it was saved, it
            // may have been partially written when we read it, resulting in parse
            // errors. We'll give it a little more time and try again.
            if (parseAttemptCount++ >= 5) {
                this._console.error(`Config file "${fileUri.toUserVisibleString()}" could not be parsed. Verify that format is correct.`);
                this._reportConfigParseError();
                return undefined;
            }
        }
        return undefined;
    }
    _getFileNamesFromFileSpecs() {
        // Use a map to generate a list of unique files.
        const fileMap = new Map();
        // Scan all matching files from file system.
        timing_1.timingStats.findFilesTime.timeOperation(() => {
            const matchedFiles = this._matchFiles(this._configOptions.include, this._configOptions.exclude);
            for (const file of matchedFiles) {
                fileMap.set(file.key, file);
            }
        });
        // And scan all matching open files. We need to do this since some of files are not backed by
        // files in file system but only exist in memory (ex, virtual workspace)
        this._backgroundAnalysisProgram.program
            .getOpened()
            .map((o) => o.sourceFile.getUri())
            .filter((f) => (0, configOptions_1.matchFileSpecs)(this._program.configOptions, f))
            .forEach((f) => fileMap.set(f.key, f));
        return Array.from(fileMap.values());
    }
    // If markFilesDirtyUnconditionally is true, we need to reparse
    // and reanalyze all files in the program. If false, we will
    // reparse and reanalyze only those files whose on-disk contents
    // have changed. Unconditional dirtying is needed in the case where
    // configuration options have changed.
    _updateTrackedFileList(markFilesDirtyUnconditionally) {
        // Are we in type stub generation mode? If so, we need to search
        // for a different set of files.
        if (this._typeStubTargetImportName) {
            const execEnv = this._configOptions.findExecEnvironment(this._executionRootUri);
            const moduleDescriptor = (0, importResolver_1.createImportedModuleDescriptor)(this._typeStubTargetImportName);
            const importResult = this._backgroundAnalysisProgram.importResolver.resolveImport(uri_1.Uri.empty(), execEnv, moduleDescriptor);
            if (importResult.isImportFound) {
                const filesToImport = [];
                // Determine the directory that contains the root package.
                const finalResolvedPath = importResult.resolvedUris[importResult.resolvedUris.length - 1];
                const isFinalPathFile = (0, uriUtils_1.isFile)(this.fs, finalResolvedPath);
                const isFinalPathInitFile = isFinalPathFile && finalResolvedPath.stripAllExtensions().fileName === '__init__';
                let rootPackagePath = finalResolvedPath;
                if (isFinalPathFile) {
                    // If the module is a __init__.pyi? file, use its parent directory instead.
                    rootPackagePath = rootPackagePath.getDirectory();
                }
                for (let i = importResult.resolvedUris.length - 2; i >= 0; i--) {
                    if (!importResult.resolvedUris[i].isEmpty()) {
                        rootPackagePath = importResult.resolvedUris[i];
                    }
                    else {
                        // If there was no file corresponding to this portion
                        // of the name path, assume that it's contained
                        // within its parent directory.
                        rootPackagePath = rootPackagePath.getDirectory();
                    }
                }
                if ((0, uriUtils_1.isDirectory)(this.fs, rootPackagePath)) {
                    this._typeStubTargetUri = rootPackagePath;
                }
                else if ((0, uriUtils_1.isFile)(this.fs, rootPackagePath)) {
                    // This can occur if there is a "dir/__init__.py" at the same level as a
                    // module "dir/module.py" that is specifically targeted for stub generation.
                    this._typeStubTargetUri = rootPackagePath.getDirectory();
                }
                if (!finalResolvedPath) {
                    this._typeStubTargetIsSingleFile = false;
                }
                else {
                    filesToImport.push(finalResolvedPath);
                    this._typeStubTargetIsSingleFile = importResult.resolvedUris.length === 1 && !isFinalPathInitFile;
                }
                // Add the implicit import paths.
                importResult.filteredImplicitImports.forEach((implicitImport) => {
                    if (importResolver_1.ImportResolver.isSupportedImportSourceFile(implicitImport.uri)) {
                        filesToImport.push(implicitImport.uri);
                    }
                });
                this._backgroundAnalysisProgram.setAllowedThirdPartyImports([this._typeStubTargetImportName]);
                this._backgroundAnalysisProgram.setTrackedFiles(filesToImport);
            }
            else {
                this._console.error(`Import '${this._typeStubTargetImportName}' not found`);
            }
        }
        else if (!this._options.skipScanningUserFiles) {
            let fileList = [];
            this._console.log(`Searching for source files`);
            fileList = this._getFileNamesFromFileSpecs();
            // getFileNamesFromFileSpecs might have updated configOptions, resync options.
            this._backgroundAnalysisProgram.setConfigOptions(this._configOptions);
            this._backgroundAnalysisProgram.setTrackedFiles(fileList);
            this._backgroundAnalysisProgram.markAllFilesDirty(markFilesDirtyUnconditionally);
            if (fileList.length === 0) {
                this._console.info(`No source files found.`);
            }
            else {
                this._console.info(`Found ${fileList.length} ` + `source ${fileList.length === 1 ? 'file' : 'files'}`);
            }
        }
        this._requireTrackedFileUpdate = false;
    }
    _matchFiles(include, exclude) {
        const envMarkers = [['bin', 'activate'], ['Scripts', 'activate'], ['pyvenv.cfg'], ['conda-meta']];
        const results = [];
        const startTime = Date.now();
        const longOperationLimitInSec = 10;
        let loggedLongOperationError = false;
        const visitDirectoryUnchecked = (absolutePath, includeRegExp, hasDirectoryWildcard) => {
            if (!loggedLongOperationError) {
                const secondsSinceStart = (Date.now() - startTime) * 0.001;
                // If this is taking a long time, log an error to help the user
                // diagnose and mitigate the problem.
                if (secondsSinceStart >= longOperationLimitInSec) {
                    this._console.error(`Enumeration of workspace source files is taking longer than ${longOperationLimitInSec} seconds.\n` +
                        'This may be because:\n' +
                        '* You have opened your home directory or entire hard drive as a workspace\n' +
                        '* Your workspace contains a very large number of directories and files\n' +
                        '* Your workspace contains a symlink to a directory with many files\n' +
                        '* Your workspace is remote, and file enumeration is slow\n' +
                        'To reduce this time, open a workspace directory with fewer files ' +
                        'or add a pyrightconfig.json configuration file with an "exclude" section to exclude ' +
                        'subdirectories from your workspace. For more details, refer to ' +
                        `${constants_1.githubRepo}/blob/main/docs/configuration.md.`);
                    loggedLongOperationError = true;
                }
            }
            if (this._configOptions.autoExcludeVenv) {
                if (envMarkers.some((f) => this.fs.existsSync(absolutePath.resolvePaths(...f)))) {
                    // Save auto exclude paths in the configOptions once we found them.
                    if (!uriUtils_1.FileSpec.isInPath(absolutePath, exclude)) {
                        exclude.push((0, uriUtils_1.getFileSpec)(this._configOptions.projectRoot, `${absolutePath}/**`));
                    }
                    this._console.info(`Auto-excluding ${absolutePath.toUserVisibleString()}`);
                    return;
                }
            }
            const { files, directories } = (0, uriUtils_1.getFileSystemEntries)(this.fs, absolutePath);
            for (const filePath of files) {
                if (uriUtils_1.FileSpec.matchIncludeFileSpec(includeRegExp, exclude, filePath)) {
                    results.push(filePath);
                }
            }
            for (const dirPath of directories) {
                if (dirPath.matchesRegex(includeRegExp) || hasDirectoryWildcard) {
                    if (!uriUtils_1.FileSpec.isInPath(dirPath, exclude)) {
                        visitDirectory(dirPath, includeRegExp, hasDirectoryWildcard);
                    }
                }
            }
        };
        const seenDirs = new Set();
        const visitDirectory = (absolutePath, includeRegExp, hasDirectoryWildcard) => {
            const realDirPath = (0, uriUtils_1.tryRealpath)(this.fs, absolutePath);
            if (!realDirPath) {
                this._console.warn(`Skipping broken link "${absolutePath}"`);
                return;
            }
            if (seenDirs.has(realDirPath.key)) {
                this._console.warn(`Skipping recursive symlink "${absolutePath}" -> "${realDirPath}"`);
                return;
            }
            seenDirs.add(realDirPath.key);
            try {
                visitDirectoryUnchecked(absolutePath, includeRegExp, hasDirectoryWildcard);
            }
            finally {
                seenDirs.delete(realDirPath.key);
            }
        };
        include.forEach((includeSpec) => {
            if (!uriUtils_1.FileSpec.isInPath(includeSpec.wildcardRoot, exclude)) {
                let foundFileSpec = false;
                const stat = (0, uriUtils_1.tryStat)(this.fs, includeSpec.wildcardRoot);
                if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
                    results.push(includeSpec.wildcardRoot);
                    foundFileSpec = true;
                }
                else if (stat === null || stat === void 0 ? void 0 : stat.isDirectory()) {
                    visitDirectory(includeSpec.wildcardRoot, includeSpec.regExp, includeSpec.hasDirectoryWildcard);
                    foundFileSpec = true;
                }
                if (!foundFileSpec) {
                    this._console.error(`File or directory "${includeSpec.wildcardRoot.toUserVisibleString()}" does not exist.`);
                }
            }
        });
        return results;
    }
    _removeSourceFileWatchers() {
        if (this._sourceFileWatcher) {
            this._sourceFileWatcher.close();
            this._sourceFileWatcher = undefined;
        }
    }
    _updateSourceFileWatchers() {
        this._removeSourceFileWatchers();
        if (!this._watchForSourceChanges) {
            return;
        }
        if (this._configOptions.include.length > 0) {
            const fileList = this._configOptions.include.map((spec) => {
                return spec.wildcardRoot;
            });
            try {
                if (this._verboseOutput) {
                    this._console.info(`Adding fs watcher for directories:\n ${fileList.join('\n')}`);
                }
                const isIgnored = (0, fileWatcher_1.ignoredWatchEventFunction)(fileList.map((f) => f.getFilePath()));
                this._sourceFileWatcher = this.fs.createFileSystemWatcher(fileList, (event, path) => {
                    if (!path) {
                        return;
                    }
                    if (this._verboseOutput) {
                        this._console.info(`SourceFile: Received fs event '${event}' for path '${path}'`);
                    }
                    if (isIgnored(path)) {
                        return;
                    }
                    // Wholesale ignore events that appear to be from tmp file / .git modification.
                    if (path.endsWith('.tmp') || path.endsWith('.git') || path.includes(_gitDirectory)) {
                        return;
                    }
                    let uri = uri_1.Uri.file(path, this.serviceProvider, /* checkRelative */ true);
                    // Make sure path is the true case.
                    uri = this.fs.realCasePath(uri);
                    const eventInfo = getEventInfo(this.fs, this._console, this._program, event, uri);
                    if (!eventInfo) {
                        // no-op event, return.
                        return;
                    }
                    if (!this._shouldHandleSourceFileWatchChanges(uri, eventInfo.isFile)) {
                        return;
                    }
                    // This is for performance optimization. If the change only pertains to the content of one file,
                    // then it can't affect the 'import resolution' result. All we need to do is reanalyze the related files
                    // (those that have a transitive dependency on this file).
                    if (eventInfo.isFile && eventInfo.event === 'change') {
                        this._backgroundAnalysisProgram.markFilesDirty([uri], /* evenIfContentsAreSame */ false);
                        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
                        return;
                    }
                    // When the file system structure changes, like when files are added or removed,
                    // this can affect how we resolve imports. This requires us to reset caches and reanalyze everything.
                    //
                    // However, we don't need to rebuild any indexes in this situation. Changes to workspace files don't affect library indices.
                    // As for user files, their indices don't contain import alias symbols, so adding or removing user files won't affect the existing indices.
                    // We only rebuild the indices for a user file when the symbols within the file are changed, like when a user edits the file.
                    // The index scanner will index any new files during its next background run.
                    this.invalidateAndForceReanalysis(backgroundAnalysisProgram_1.InvalidatedReason.SourceWatcherChanged);
                    this._scheduleReanalysis(/* requireTrackedFileUpdate */ true);
                });
            }
            catch {
                this._console.error(`Exception caught when installing fs watcher for:\n ${fileList
                    .map((f) => f.toUserVisibleString())
                    .join('\n')}`);
            }
        }
        function getEventInfo(fs, console, program, event, path) {
            // Due to the way we implemented file watcher, we will only get 2 events; 'add' and 'change'.
            // Here, we will convert those 2 to 3 events. 'add', 'change' and 'unlink';
            const stats = (0, uriUtils_1.tryStat)(fs, path);
            if (event === 'add') {
                if (!stats) {
                    // If we are told that the path is added, but if we can't access it, then consider it as already deleted.
                    // there is nothing we need to do.
                    return undefined;
                }
                return { event, isFile: stats.isFile() };
            }
            if (event === 'change') {
                // If we got 'change', but can't access the path, then we consider it as delete.
                if (!stats) {
                    // See whether it is a file that got deleted.
                    const isFile = !!program.getSourceFile(path);
                    // If not, check whether it is a part of the workspace at all.
                    if (!isFile && !program.containsSourceFileIn(path)) {
                        // There is no source file under the given path. There is nothing we need to do.
                        return undefined;
                    }
                    return { event: 'unlink', isFile };
                }
                return { event, isFile: stats.isFile() };
            }
            // We have unknown event.
            console.warn(`Received unknown file change event: '${event}' for '${path}'`);
            return undefined;
        }
    }
    _shouldHandleSourceFileWatchChanges(path, isFile) {
        if (isFile) {
            if (!(0, uriUtils_1.hasPythonExtension)(path) || isTemporaryFile(path)) {
                return false;
            }
            // Check whether the file change can affect semantics. If the file changed is not a user file or already a part of
            // the program (since we lazily load library files or extra path files when they are used), then the change can't
            // affect semantics. so just bail out.
            if (!this.isTracked(path) && !this._program.getSourceFileInfo(path)) {
                return false;
            }
            return true;
        }
        // The fs change is on a folder.
        if (!(0, configOptions_1.matchFileSpecs)(this._program.configOptions, path, /* isFile */ false)) {
            // First, make sure the folder is included. By default, we exclude any folder whose name starts with '.'
            return false;
        }
        const parentPath = path.getDirectory();
        const hasInit = parentPath.startsWith(this._configOptions.projectRoot) &&
            (this.fs.existsSync(parentPath.initPyUri) || this.fs.existsSync(parentPath.initPyiUri));
        // We don't have any file under the given path and its parent folder doesn't have __init__ then this folder change
        // doesn't have any meaning to us.
        if (!hasInit && !this._program.containsSourceFileIn(path)) {
            return false;
        }
        return true;
        function isTemporaryFile(path) {
            // Determine if this is an add or delete event related to a temporary
            // file. Some tools (like auto-formatters) create temporary files
            // alongside the original file and name them "x.py.<temp-id>.py" where
            // <temp-id> is a 32-character random string of hex digits. We don't
            // want these events to trigger a full reanalysis.
            const fileName = path.fileName;
            const fileNameSplit = fileName.split('.');
            if (fileNameSplit.length === 4) {
                if (fileNameSplit[3] === fileNameSplit[1] && fileNameSplit[2].length === 32) {
                    return true;
                }
            }
            return false;
        }
    }
    _removeLibraryFileWatcher() {
        if (this._libraryFileWatcher) {
            this._libraryFileWatcher.close();
            this._libraryFileWatcher = undefined;
        }
    }
    _updateLibraryFileWatcher() {
        this._removeLibraryFileWatcher();
        if (!this._watchForLibraryChanges) {
            this._librarySearchUrisToWatch = undefined;
            return;
        }
        // Watch the library paths for package install/uninstall.
        const importFailureInfo = [];
        this._librarySearchUrisToWatch = (0, pythonPathUtils_1.findPythonSearchPaths)(this.fs, this._backgroundAnalysisProgram.configOptions, this._backgroundAnalysisProgram.host, importFailureInfo, 
        /* includeWatchPathsOnly */ true, this._executionRootUri);
        const watchList = this._librarySearchUrisToWatch;
        if (watchList && watchList.length > 0) {
            try {
                if (this._verboseOutput) {
                    this._console.info(`Adding fs watcher for library directories:\n ${watchList.join('\n')}`);
                }
                const isIgnored = (0, fileWatcher_1.ignoredWatchEventFunction)(watchList.map((f) => f.getFilePath()));
                this._libraryFileWatcher = this.fs.createFileSystemWatcher(watchList, (event, path) => {
                    if (!path) {
                        return;
                    }
                    if (this._verboseOutput) {
                        this._console.info(`LibraryFile: Received fs event '${event}' for path '${path}'`);
                    }
                    if (isIgnored(path)) {
                        return;
                    }
                    const uri = uri_1.Uri.file(path, this.serviceProvider, /* checkRelative */ true);
                    if (!this._shouldHandleLibraryFileWatchChanges(uri, watchList)) {
                        return;
                    }
                    // If file doesn't exist, it is delete.
                    const isChange = event === 'change' && this.fs.existsSync(uri);
                    this._scheduleLibraryAnalysis(isChange);
                });
            }
            catch {
                this._console.error(`Exception caught when installing fs watcher for:\n ${watchList
                    .map((w) => w.toUserVisibleString())
                    .join('\n')}`);
            }
        }
    }
    _shouldHandleLibraryFileWatchChanges(path, libSearchPaths) {
        if (this._program.getSourceFileInfo(path)) {
            return true;
        }
        // find the innermost matching search path
        let matchingSearchPath;
        for (const libSearchPath of libSearchPaths) {
            if (path.isChild(libSearchPath) &&
                (!matchingSearchPath || matchingSearchPath.getPathLength() < libSearchPath.getPathLength())) {
                matchingSearchPath = libSearchPath;
            }
        }
        if (!matchingSearchPath) {
            return true;
        }
        const parentComponents = matchingSearchPath.getPathComponents();
        const childComponents = path.getPathComponents();
        for (let i = parentComponents.length; i < childComponents.length; i++) {
            if (childComponents[i].startsWith('.')) {
                return false;
            }
        }
        return true;
    }
    _clearLibraryReanalysisTimer() {
        var _a, _b, _c;
        if (this._libraryReanalysisTimer) {
            clearTimeout(this._libraryReanalysisTimer);
            this._libraryReanalysisTimer = undefined;
            const handled = (_a = this._backgroundAnalysisProgram) === null || _a === void 0 ? void 0 : _a.libraryUpdated();
            (_c = (_b = this._options.libraryReanalysisTimeProvider) === null || _b === void 0 ? void 0 : _b.libraryUpdated) === null || _c === void 0 ? void 0 : _c.call(_b, handled);
        }
    }
    _scheduleLibraryAnalysis(isChange) {
        if (this._disposed) {
            // Already disposed.
            return;
        }
        this._clearLibraryReanalysisTimer();
        const reanalysisTimeProvider = this._options.libraryReanalysisTimeProvider;
        const backOffTimeInMS = reanalysisTimeProvider === null || reanalysisTimeProvider === void 0 ? void 0 : reanalysisTimeProvider();
        if (!backOffTimeInMS) {
            // We don't support library reanalysis.
            return;
        }
        // Add pending library files/folders changes.
        this._pendingLibraryChanges.changesOnly = this._pendingLibraryChanges.changesOnly && isChange;
        // Wait for a little while, since library changes
        // tend to happen in big batches when packages
        // are installed or uninstalled.
        this._libraryReanalysisTimer = setTimeout(() => {
            var _a, _b;
            this._clearLibraryReanalysisTimer();
            // Invalidate import resolver, mark all files dirty unconditionally,
            // and reanalyze.
            this.invalidateAndForceReanalysis(this._pendingLibraryChanges.changesOnly
                ? backgroundAnalysisProgram_1.InvalidatedReason.LibraryWatcherContentOnlyChanged
                : backgroundAnalysisProgram_1.InvalidatedReason.LibraryWatcherChanged);
            this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
            // No more pending changes.
            (_b = (_a = reanalysisTimeProvider).libraryReanalysisStarted) === null || _b === void 0 ? void 0 : _b.call(_a);
            this._pendingLibraryChanges.changesOnly = true;
        }, backOffTimeInMS);
    }
    _removeConfigFileWatcher() {
        if (this._configFileWatcher) {
            this._configFileWatcher.close();
            this._configFileWatcher = undefined;
        }
    }
    _updateConfigFileWatcher() {
        this._removeConfigFileWatcher();
        if (!this._watchForConfigChanges) {
            return;
        }
        if (this._configFileUri) {
            this._configFileWatcher = this.fs.createFileSystemWatcher([this._configFileUri], (event) => {
                if (this._verboseOutput) {
                    this._console.info(`Received fs event '${event}' for config file`);
                }
                this._scheduleReloadConfigFile();
            });
        }
        else if (this._executionRootUri) {
            this._configFileWatcher = this.fs.createFileSystemWatcher([this._executionRootUri], (event, path) => {
                if (!path) {
                    return;
                }
                if (event === 'add' || event === 'change') {
                    const fileName = (0, pathUtils_1.getFileName)(path);
                    if (fileName && exports.configFileNames.some((name) => name === fileName)) {
                        if (this._verboseOutput) {
                            this._console.info(`Received fs event '${event}' for config file`);
                        }
                        if (this._commandLineOptions) {
                            this.setOptions(this._commandLineOptions);
                        }
                    }
                }
            });
        }
    }
    _clearReloadConfigTimer() {
        if (this._reloadConfigTimer) {
            clearTimeout(this._reloadConfigTimer);
            this._reloadConfigTimer = undefined;
        }
    }
    _scheduleReloadConfigFile() {
        this._clearReloadConfigTimer();
        // Wait for a little while after we receive the
        // change update event because it may take a while
        // for the file to be written out. Plus, there may
        // be multiple changes.
        this._reloadConfigTimer = setTimeout(() => {
            this._clearReloadConfigTimer();
            this._reloadConfigFile();
        }, 100);
    }
    _reloadConfigFile() {
        this._updateConfigFileWatcher();
        if (this._configFileUri) {
            this._console.info(`Reloading configuration file at ${this._configFileUri.toUserVisibleString()}`);
            const host = this._backgroundAnalysisProgram.host;
            // We can't just reload config file when it is changed; we need to consider
            // command line options as well to construct new config Options.
            const configOptions = this._getConfigOptions(host, this._commandLineOptions);
            this._backgroundAnalysisProgram.setConfigOptions(configOptions);
            this._applyConfigOptions(host);
        }
    }
    _applyConfigOptions(host) {
        var _a;
        // Allocate a new import resolver because the old one has information
        // cached based on the previous config options.
        const importResolver = this._importResolverFactory(this._serviceProvider, this._backgroundAnalysisProgram.configOptions, host);
        this._backgroundAnalysisProgram.setImportResolver(importResolver);
        if (((_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.fromVsCodeExtension) || this._configOptions.verboseOutput) {
            const logLevel = this._configOptions.verboseOutput ? console_1.LogLevel.Info : console_1.LogLevel.Log;
            for (const execEnv of this._configOptions.getExecutionEnvironments()) {
                (0, console_1.log)(this._console, logLevel, `Search paths for ${execEnv.root || '<default>'}`);
                const roots = importResolver.getImportRoots(execEnv, /* forLogging */ true);
                roots.forEach((path) => {
                    (0, console_1.log)(this._console, logLevel, `  ${path.toUserVisibleString()}`);
                });
            }
        }
        this._updateLibraryFileWatcher();
        this._updateConfigFileWatcher();
        this._updateSourceFileWatchers();
        this._updateTrackedFileList(/* markFilesDirtyUnconditionally */ true);
        this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
    }
    _clearReanalysisTimer() {
        if (this._analyzeTimer) {
            clearTimeout(this._analyzeTimer);
            this._analyzeTimer = undefined;
        }
    }
    _scheduleReanalysis(requireTrackedFileUpdate) {
        var _a, _b;
        if (this._disposed || !((_a = this._commandLineOptions) === null || _a === void 0 ? void 0 : _a.enableAmbientAnalysis)) {
            // already disposed
            return;
        }
        if (requireTrackedFileUpdate) {
            this._requireTrackedFileUpdate = true;
        }
        (_b = this._backgroundAnalysisCancellationSource) === null || _b === void 0 ? void 0 : _b.cancel();
        // Remove any existing analysis timer.
        this._clearReanalysisTimer();
        // How long has it been since the user interacted with the service?
        // If the user is actively typing, back off to let him or her finish.
        const timeSinceLastUserInteractionInMs = Date.now() - this._lastUserInteractionTime;
        const minBackoffTimeInMs = _userActivityBackoffTimeInMs;
        // We choose a small non-zero value here. If this value
        // is too small (like zero), the VS Code extension becomes
        // unresponsive during heavy analysis. If this number is too
        // large, analysis takes longer.
        const minTimeBetweenAnalysisPassesInMs = 20;
        const timeUntilNextAnalysisInMs = Math.max(minBackoffTimeInMs - timeSinceLastUserInteractionInMs, minTimeBetweenAnalysisPassesInMs);
        // Schedule a new timer.
        this._analyzeTimer = setTimeout(() => {
            this._analyzeTimer = undefined;
            if (this._requireTrackedFileUpdate) {
                this._updateTrackedFileList(/* markFilesDirtyUnconditionally */ false);
            }
            // This creates a cancellation source only if it actually gets used.
            this._backgroundAnalysisCancellationSource = this.cancellationProvider.createCancellationTokenSource();
            const moreToAnalyze = this._backgroundAnalysisProgram.startAnalysis(this._backgroundAnalysisCancellationSource.token);
            if (moreToAnalyze) {
                this._scheduleReanalysis(/* requireTrackedFileUpdate */ false);
            }
        }, timeUntilNextAnalysisInMs);
    }
    _reportConfigParseError() {
        if (this._onCompletionCallback) {
            this._onCompletionCallback({
                diagnostics: [],
                filesInProgram: 0,
                filesRequiringAnalysis: 0,
                checkingOnlyOpenFiles: true,
                fatalErrorOccurred: false,
                configParseErrorOccurred: true,
                elapsedTime: 0,
            });
        }
    }
}
exports.AnalyzerService = AnalyzerService;


/***/ }),

/***/ "../pyright-internal/src/analyzer/sourceFile.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/sourceFile.ts ***!
  \******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * sourceFile.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that represents a single Python source or stub file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SourceFile = exports.IPythonMode = void 0;
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ../common/console */ "../pyright-internal/src/common/console.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const diagnosticSink_1 = __webpack_require__(/*! ../common/diagnosticSink */ "../pyright-internal/src/common/diagnosticSink.ts");
const logTracker_1 = __webpack_require__(/*! ../common/logTracker */ "../pyright-internal/src/common/logTracker.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const StringUtils = __importStar(__webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts"));
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const textRangeCollection_1 = __webpack_require__(/*! ../common/textRangeCollection */ "../pyright-internal/src/common/textRangeCollection.ts");
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const parser_1 = __webpack_require__(/*! ../parser/parser */ "../pyright-internal/src/parser/parser.ts");
const tokenizer_1 = __webpack_require__(/*! ../parser/tokenizer */ "../pyright-internal/src/parser/tokenizer.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const binder_1 = __webpack_require__(/*! ./binder */ "../pyright-internal/src/analyzer/binder.ts");
const checker_1 = __webpack_require__(/*! ./checker */ "../pyright-internal/src/analyzer/checker.ts");
const CommentUtils = __importStar(__webpack_require__(/*! ./commentUtils */ "../pyright-internal/src/analyzer/commentUtils.ts"));
const parseTreeCleaner_1 = __webpack_require__(/*! ./parseTreeCleaner */ "../pyright-internal/src/analyzer/parseTreeCleaner.ts");
const testWalker_1 = __webpack_require__(/*! ./testWalker */ "../pyright-internal/src/analyzer/testWalker.ts");
// Limit the number of import cycles tracked per source file.
const _maxImportCyclesPerFile = 4;
// Allow files up to 50MB in length, same as VS Code.
// https://github.com/microsoft/vscode/blob/1e750a7514f365585d8dab1a7a82e0938481ea2f/src/vs/editor/common/model/textModel.ts#L194
const _maxSourceFileSize = 50 * 1024 * 1024;
// Indicates whether IPython syntax is supported and if so, what
// type of notebook support is in use.
var IPythonMode;
(function (IPythonMode) {
    // Not a notebook. This is the only falsy enum value, so you
    // can test if IPython is supported via "if (ipythonMode)"
    IPythonMode[IPythonMode["None"] = 0] = "None";
    // Each cell is its own document.
    IPythonMode[IPythonMode["CellDocs"] = 1] = "CellDocs";
})(IPythonMode || (exports.IPythonMode = IPythonMode = {}));
class WriteableData {
    constructor() {
        // Number that is incremented every time the diagnostics
        // are updated.
        this.diagnosticVersion = 0;
        // Generation count of the file contents. When the contents
        // change, this is incremented.
        this.fileContentsVersion = 0;
        // Length and hash of the file the last time it was read from disk.
        this.lastFileContentLength = undefined;
        this.lastFileContentHash = undefined;
        // Version of file contents that have been analyzed.
        this.analyzedFileContentsVersion = -1;
        // Do we need to walk the parse tree and clean
        // the binder information hanging from it?
        this.parseTreeNeedsCleaning = false;
        // Reentrancy check for binding.
        this.isBindingInProgress = false;
        // Diagnostics generated during different phases of analysis.
        this.parseDiagnostics = [];
        this.commentDiagnostics = [];
        this.bindDiagnostics = [];
        this.checkerDiagnostics = [];
        this.taskListDiagnostics = [];
        this.typeIgnoreLines = new Map();
        this.pyrightIgnoreLines = new Map();
        // Accumulated and filtered diagnostics that combines all of the
        // above information. This needs to be recomputed any time the
        // above change.
        this.accumulatedDiagnostics = [];
        // Circular dependencies that have been reported in this file.
        this.circularDependencies = [];
        this.noCircularDependencyConfirmed = false;
        // Do we need to perform a binding step?
        this.isBindingNeeded = true;
        // Do we have valid diagnostic results from a checking pass?
        this.isCheckingNeeded = true;
        // True if the file appears to have been deleted.
        this.isFileDeleted = false;
    }
    debugPrint() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
        return `WritableData: 
 diagnosticVersion=${this.diagnosticVersion}, 
 noCircularDependencyConfirmed=${this.noCircularDependencyConfirmed}, 
 isBindingNeeded=${this.isBindingNeeded},
 isBindingInProgress=${this.isBindingInProgress},
 isCheckingNeeded=${this.isCheckingNeeded},
 isFileDeleted=${this.isFileDeleted},
 hitMaxImportDepth=${this.hitMaxImportDepth},
 parseTreeNeedsCleaning=${this.parseTreeNeedsCleaning},
 fileContentsVersion=${this.fileContentsVersion},
 analyzedFileContentsVersion=${this.analyzedFileContentsVersion},
 clientDocumentVersion=${this.clientDocumentVersion},
 lastFileContentLength=${this.lastFileContentLength},
 lastFileContentHash=${this.lastFileContentHash},
 typeIgnoreAll=${this.typeIgnoreAll},
 imports=${(_a = this.imports) === null || _a === void 0 ? void 0 : _a.length},
 builtinsImport=${(_b = this.builtinsImport) === null || _b === void 0 ? void 0 : _b.importName},
 circularDependencies=${(_c = this.circularDependencies) === null || _c === void 0 ? void 0 : _c.length},
 parseDiagnostics=${(_d = this.parseDiagnostics) === null || _d === void 0 ? void 0 : _d.length},
 commentDiagnostics=${(_e = this.commentDiagnostics) === null || _e === void 0 ? void 0 : _e.length},
 bindDiagnostics=${(_f = this.bindDiagnostics) === null || _f === void 0 ? void 0 : _f.length},
 checkerDiagnostics=${(_g = this.checkerDiagnostics) === null || _g === void 0 ? void 0 : _g.length},
 taskListDiagnostics=${(_h = this.taskListDiagnostics) === null || _h === void 0 ? void 0 : _h.length},
 accumulatedDiagnostics=${(_j = this.accumulatedDiagnostics) === null || _j === void 0 ? void 0 : _j.length},
 typeIgnoreLines=${(_k = this.typeIgnoreLines) === null || _k === void 0 ? void 0 : _k.size},
 pyrightIgnoreLines=${(_l = this.pyrightIgnoreLines) === null || _l === void 0 ? void 0 : _l.size},
 checkTime=${this.checkTime},
 clientDocumentContents=${(_m = this.clientDocumentContents) === null || _m === void 0 ? void 0 : _m.length},
 parseResults=${(_o = this.parserOutput) === null || _o === void 0 ? void 0 : _o.parseTree.length}`;
    }
}
class SourceFile {
    constructor(serviceProvider, uri, moduleName, isThirdPartyImport, isThirdPartyPyTypedPresent, editMode, console, logTracker, ipythonMode) {
        this.serviceProvider = serviceProvider;
        // Data that changes when the source file changes.
        this._writableData = new WriteableData();
        // Settings that control which diagnostics should be output. The rules
        // are initialized to the basic set. They should be updated after the
        // the file is parsed.
        this._diagnosticRuleSet = (0, configOptions_1.getBasicDiagnosticRuleSet)();
        // Indicate whether this file is for ipython or not.
        this._ipythonMode = IPythonMode.None;
        this._getRangeFromIgnoreComment = (ignoreComment) => {
            const rangeStart = ignoreComment.range.start;
            const rangeEnd = rangeStart + ignoreComment.range.length;
            return (0, positionUtils_1.convertOffsetsToRange)(rangeStart, rangeEnd, this._writableData.tokenizerLines);
        };
        this.fileSystem = serviceProvider.get(serviceKeys_1.ServiceKeys.fs);
        this._console = console || new console_1.StandardConsole();
        this._editMode = editMode;
        this._uri = uri;
        this._moduleName = moduleName;
        this._isStubFile = uri.hasExtension('.pyi');
        this._isThirdPartyImport = isThirdPartyImport;
        this._isThirdPartyPyTypedPresent = isThirdPartyPyTypedPresent;
        const fileName = uri.fileName;
        this._isTypingStubFile =
            this._isStubFile && (this._uri.pathEndsWith('stdlib/typing.pyi') || fileName === 'typing_extensions.pyi');
        this._isTypingExtensionsStubFile = this._isStubFile && fileName === 'typing_extensions.pyi';
        this._isTypeshedStubFile = this._isStubFile && this._uri.pathEndsWith('stdlib/_typeshed/__init__.pyi');
        this._isBuiltInStubFile = false;
        if (this._isStubFile) {
            if (this._uri.pathEndsWith('stdlib/collections/__init__.pyi') ||
                this._uri.pathEndsWith('stdlib/asyncio/futures.pyi') ||
                this._uri.pathEndsWith('stdlib/asyncio/tasks.pyi') ||
                this._uri.pathEndsWith('stdlib/builtins.pyi') ||
                this._uri.pathEndsWith('stdlib/_importlib_modulespec.pyi') ||
                this._uri.pathEndsWith('stdlib/dataclasses.pyi') ||
                this._uri.pathEndsWith('stdlib/abc.pyi') ||
                this._uri.pathEndsWith('stdlib/enum.pyi') ||
                this._uri.pathEndsWith('stdlib/queue.pyi') ||
                this._uri.pathEndsWith('stdlib/types.pyi')) {
                this._isBuiltInStubFile = true;
            }
        }
        // 'FG' or 'BG' based on current thread.
        this._logTracker = logTracker !== null && logTracker !== void 0 ? logTracker : new logTracker_1.LogTracker(console, worker_threads_1.isMainThread ? 'FG' : 'BG');
        this._ipythonMode = ipythonMode !== null && ipythonMode !== void 0 ? ipythonMode : IPythonMode.None;
    }
    getIPythonMode() {
        return this._ipythonMode;
    }
    getUri() {
        return this._uri;
    }
    getModuleName() {
        if (this._moduleName) {
            return this._moduleName;
        }
        // Synthesize a module name using the file path.
        return (0, pathUtils_1.stripFileExtension)(this._uri.fileName);
    }
    setModuleName(name) {
        this._moduleName = name;
    }
    getDiagnosticVersion() {
        return this._writableData.diagnosticVersion;
    }
    isStubFile() {
        return this._isStubFile;
    }
    isTypingStubFile() {
        return this._isTypingStubFile;
    }
    isThirdPartyPyTypedPresent() {
        return this._isThirdPartyPyTypedPresent;
    }
    // Returns a list of cached diagnostics from the latest analysis job.
    // If the prevVersion is specified, the method returns undefined if
    // the diagnostics haven't changed.
    getDiagnostics(options, prevDiagnosticVersion) {
        if (this._writableData.diagnosticVersion === prevDiagnosticVersion) {
            return undefined;
        }
        return this._writableData.accumulatedDiagnostics;
    }
    getImports() {
        return this._writableData.imports || [];
    }
    getBuiltinsImport() {
        return this._writableData.builtinsImport;
    }
    getModuleSymbolTable() {
        return this._writableData.moduleSymbolTable;
    }
    getCheckTime() {
        return this._writableData.checkTime;
    }
    restore() {
        // If we had an edit, return our text.
        if (this._preEditData) {
            const text = this._writableData.clientDocumentContents;
            this._writableData = this._preEditData;
            this._preEditData = undefined;
            return text;
        }
        return undefined;
    }
    // Indicates whether the contents of the file have changed since
    // the last analysis was performed.
    didContentsChangeOnDisk() {
        // If this is an open file any content changes will be
        // provided through the editor. We can assume contents
        // didn't change without us knowing about them.
        if (this._writableData.clientDocumentContents) {
            return false;
        }
        // If the file was never read previously, no need to check for a change.
        if (this._writableData.lastFileContentLength === undefined) {
            return false;
        }
        // Read in the latest file contents and see if the hash matches
        // that of the previous contents.
        try {
            // Read the file's contents.
            if (this.fileSystem.existsSync(this._uri)) {
                const fileContents = this.fileSystem.readFileSync(this._uri, 'utf8');
                if (fileContents.length !== this._writableData.lastFileContentLength) {
                    return true;
                }
                if (StringUtils.hashString(fileContents) !== this._writableData.lastFileContentHash) {
                    return true;
                }
            }
            else {
                // No longer exists, so yes it has changed.
                return true;
            }
        }
        catch (error) {
            return true;
        }
        return false;
    }
    // Drop parse and binding info to save memory. It is used
    // in cases where memory is low. When info is needed, the file
    // will be re-parsed and rebound.
    dropParseAndBindInfo() {
        this._fireFileDirtyEvent();
        this._writableData.parserOutput = undefined;
        this._writableData.tokenizerLines = undefined;
        this._writableData.tokenizerOutput = undefined;
        this._writableData.parsedFileContents = undefined;
        this._writableData.moduleSymbolTable = undefined;
        this._writableData.isBindingNeeded = true;
    }
    markDirty() {
        this._writableData.fileContentsVersion++;
        this._writableData.noCircularDependencyConfirmed = false;
        this._writableData.isCheckingNeeded = true;
        this._writableData.isBindingNeeded = true;
        this._writableData.moduleSymbolTable = undefined;
        this._fireFileDirtyEvent();
    }
    markReanalysisRequired(forceRebinding) {
        // Keep the parse info, but reset the analysis to the beginning.
        this._writableData.isCheckingNeeded = true;
        this._writableData.noCircularDependencyConfirmed = false;
        // If the file contains a wildcard import or __all__ symbols,
        // we need to rebind because a dependent import may have changed.
        if (this._writableData.parserOutput) {
            if (this._writableData.parserOutput.containsWildcardImport ||
                AnalyzerNodeInfo.getDunderAllInfo(this._writableData.parserOutput.parseTree) !== undefined ||
                forceRebinding) {
                // We don't need to rebuild index data since wildcard
                // won't affect user file indices. User file indices
                // don't contain import alias info.
                this._writableData.parseTreeNeedsCleaning = true;
                this._writableData.isBindingNeeded = true;
                this._writableData.moduleSymbolTable = undefined;
            }
        }
    }
    getFileContentsVersion() {
        return this._writableData.fileContentsVersion;
    }
    getClientVersion() {
        return this._writableData.clientDocumentVersion;
    }
    getOpenFileContents() {
        return this._writableData.clientDocumentContents;
    }
    getFileContent() {
        // Get current buffer content if the file is opened.
        const openFileContent = this.getOpenFileContents();
        if (openFileContent !== undefined) {
            return openFileContent;
        }
        // Otherwise, get content from file system.
        try {
            // Check the file's length before attempting to read its full contents.
            const fileStat = this.fileSystem.statSync(this._uri);
            if (fileStat.size > _maxSourceFileSize) {
                this._console.error(`File length of "${this._uri}" is ${fileStat.size} ` +
                    `which exceeds the maximum supported file size of ${_maxSourceFileSize}`);
                throw new Error('File larger than max');
            }
            return this.fileSystem.readFileSync(this._uri, 'utf8');
        }
        catch (error) {
            return undefined;
        }
    }
    setClientVersion(version, contents) {
        // Save pre edit state if in edit mode.
        this._cachePreEditState();
        if (version === null) {
            this._writableData.clientDocumentVersion = undefined;
            this._writableData.clientDocumentContents = undefined;
            // Since the file is no longer open, dump the tokenizer output
            // so it doesn't consume memory.
            this._writableData.tokenizerOutput = undefined;
        }
        else {
            this._writableData.clientDocumentVersion = version;
            this._writableData.clientDocumentContents = contents;
            const contentsHash = StringUtils.hashString(contents);
            // Have the contents of the file changed?
            if (contents.length !== this._writableData.lastFileContentLength ||
                contentsHash !== this._writableData.lastFileContentHash) {
                this.markDirty();
            }
            this._writableData.lastFileContentLength = contents.length;
            this._writableData.lastFileContentHash = contentsHash;
            this._writableData.isFileDeleted = false;
        }
    }
    prepareForClose() {
        this._fireFileDirtyEvent();
    }
    isFileDeleted() {
        return this._writableData.isFileDeleted;
    }
    isParseRequired() {
        return (!this._writableData.parserOutput ||
            this._writableData.analyzedFileContentsVersion !== this._writableData.fileContentsVersion);
    }
    isBindingRequired() {
        if (this._writableData.isBindingInProgress) {
            return false;
        }
        if (this.isParseRequired()) {
            return true;
        }
        return this._writableData.isBindingNeeded;
    }
    isCheckingRequired() {
        return this._writableData.isCheckingNeeded;
    }
    getParseResults() {
        var _a;
        if (this.isParseRequired()) {
            return undefined;
        }
        (0, debug_1.assert)(this._writableData.parserOutput !== undefined && this._writableData.parsedFileContents !== undefined);
        // If we've cached the tokenizer output, use the cached version.
        // Otherwise re-tokenize the contents on demand.
        const tokenizerOutput = (_a = this._writableData.tokenizerOutput) !== null && _a !== void 0 ? _a : this._tokenizeContents(this._writableData.parsedFileContents);
        return {
            parserOutput: this._writableData.parserOutput,
            tokenizerOutput,
            text: this._writableData.parsedFileContents,
        };
    }
    getParserOutput() {
        if (this.isParseRequired()) {
            return undefined;
        }
        (0, debug_1.assert)(this._writableData.parserOutput !== undefined);
        return this._writableData.parserOutput;
    }
    // Adds a new circular dependency for this file but only if
    // it hasn't already been added.
    addCircularDependency(configOptions, circDependency) {
        let updatedDependencyList = false;
        // Some topologies can result in a massive number of cycles. We'll cut it off.
        if (this._writableData.circularDependencies.length < _maxImportCyclesPerFile) {
            if (!this._writableData.circularDependencies.some((dep) => dep.isEqual(circDependency))) {
                this._writableData.circularDependencies.push(circDependency);
                updatedDependencyList = true;
            }
        }
        if (updatedDependencyList) {
            this._recomputeDiagnostics(configOptions);
        }
    }
    setNoCircularDependencyConfirmed() {
        this._writableData.noCircularDependencyConfirmed = true;
    }
    isNoCircularDependencyConfirmed() {
        return !this.isParseRequired() && this._writableData.noCircularDependencyConfirmed;
    }
    setHitMaxImportDepth(maxImportDepth) {
        this._writableData.hitMaxImportDepth = maxImportDepth;
    }
    // Parse the file and update the state. Callers should wait for completion
    // (or at least cancel) prior to calling again. It returns true if a parse
    // was required and false if the parse information was up to date already.
    parse(configOptions, importResolver, content) {
        return this._logTracker.log(`parsing: ${this._getPathForLogging(this._uri)}`, (logState) => {
            // If the file is already parsed, we can skip.
            if (!this.isParseRequired()) {
                logState.suppress();
                return false;
            }
            const diagSink = this.createDiagnosticSink();
            let fileContents = this.getOpenFileContents();
            if (fileContents === undefined) {
                try {
                    const startTime = timing_1.timingStats.readFileTime.totalTime;
                    timing_1.timingStats.readFileTime.timeOperation(() => {
                        // Read the file's contents.
                        fileContents = content !== null && content !== void 0 ? content : this.getFileContent();
                        if (fileContents === undefined) {
                            throw new Error("Can't get file content");
                        }
                        // Remember the length and hash for comparison purposes.
                        this._writableData.lastFileContentLength = fileContents.length;
                        this._writableData.lastFileContentHash = StringUtils.hashString(fileContents);
                    });
                    logState.add(`fs read ${timing_1.timingStats.readFileTime.totalTime - startTime}ms`);
                }
                catch (error) {
                    diagSink.addError(`Source file could not be read`, (0, textRange_1.getEmptyRange)());
                    fileContents = '';
                    if (!this.fileSystem.existsSync(this._uri)) {
                        this._writableData.isFileDeleted = true;
                    }
                }
            }
            try {
                // Parse the token stream, building the abstract syntax tree.
                const parseFileResults = this._parseFile(configOptions, this._uri, fileContents, this._ipythonMode, diagSink);
                (0, debug_1.assert)(parseFileResults !== undefined && parseFileResults.tokenizerOutput !== undefined);
                this._writableData.parserOutput = parseFileResults.parserOutput;
                this._writableData.tokenizerLines = parseFileResults.tokenizerOutput.lines;
                this._writableData.parsedFileContents = fileContents;
                this._writableData.typeIgnoreLines = parseFileResults.tokenizerOutput.typeIgnoreLines;
                this._writableData.typeIgnoreAll = parseFileResults.tokenizerOutput.typeIgnoreAll;
                this._writableData.pyrightIgnoreLines = parseFileResults.tokenizerOutput.pyrightIgnoreLines;
                // Cache the tokenizer output only if this file is open.
                if (this._writableData.clientDocumentContents !== undefined) {
                    this._writableData.tokenizerOutput = parseFileResults.tokenizerOutput;
                }
                // Resolve imports.
                const execEnvironment = configOptions.findExecEnvironment(this._uri);
                timing_1.timingStats.resolveImportsTime.timeOperation(() => {
                    const importResult = this._resolveImports(importResolver, parseFileResults.parserOutput.importedModules, execEnvironment);
                    this._writableData.imports = importResult.imports;
                    this._writableData.builtinsImport = importResult.builtinsImportResult;
                    this._writableData.parseDiagnostics = diagSink.fetchAndClear();
                    this._writableData.taskListDiagnostics = [];
                    this._addTaskListDiagnostics(configOptions.taskListTokens, parseFileResults.tokenizerOutput, this._writableData.taskListDiagnostics);
                });
                // Is this file in a "strict" path?
                const useStrict = configOptions.strict.find((strictFileSpec) => this._uri.matchesRegex(strictFileSpec.regExp)) !==
                    undefined;
                const commentDiags = [];
                this._diagnosticRuleSet = CommentUtils.getFileLevelDirectives(parseFileResults.tokenizerOutput.tokens, parseFileResults.tokenizerOutput.lines, configOptions.diagnosticRuleSet, useStrict, commentDiags);
                this._writableData.commentDiagnostics = [];
                commentDiags.forEach((commentDiag) => {
                    this._writableData.commentDiagnostics.push(new diagnostic_1.Diagnostic(0 /* DiagnosticCategory.Error */, commentDiag.message, (0, positionUtils_1.convertTextRangeToRange)(commentDiag.range, parseFileResults.tokenizerOutput.lines)));
                });
            }
            catch (e) {
                const message = (e.stack ? e.stack.toString() : undefined) ||
                    (typeof e.message === 'string' ? e.message : undefined) ||
                    JSON.stringify(e);
                this._console.error(localize_1.LocMessage.internalParseError().format({
                    file: this.getUri().toUserVisibleString(),
                    message,
                }));
                // Create dummy parse results.
                this._writableData.parsedFileContents = '';
                this._writableData.parserOutput = {
                    parseTree: parseNodes_1.ModuleNode.create({ start: 0, length: 0 }),
                    importedModules: [],
                    futureImports: new Set(),
                    containsWildcardImport: false,
                    typingSymbolAliases: new Map(),
                };
                this._writableData.tokenizerLines = new textRangeCollection_1.TextRangeCollection([]);
                this._writableData.tokenizerOutput = {
                    tokens: new textRangeCollection_1.TextRangeCollection([]),
                    lines: this._writableData.tokenizerLines,
                    typeIgnoreAll: undefined,
                    typeIgnoreLines: new Map(),
                    pyrightIgnoreLines: new Map(),
                    predominantEndOfLineSequence: '\n',
                    hasPredominantTabSequence: false,
                    predominantTabSequence: '    ',
                    predominantSingleQuoteCharacter: "'",
                };
                this._writableData.imports = undefined;
                this._writableData.builtinsImport = undefined;
                const diagSink = this.createDiagnosticSink();
                diagSink.addError(localize_1.LocMessage.internalParseError().format({
                    file: this.getUri().toUserVisibleString(),
                    message,
                }), (0, textRange_1.getEmptyRange)());
                this._writableData.parseDiagnostics = diagSink.fetchAndClear();
                this._writableData.taskListDiagnostics = diagSink.fetchAndClear();
                // Do not rethrow the exception, swallow it here. Callers are not
                // prepared to handle an exception.
            }
            this._writableData.analyzedFileContentsVersion = this._writableData.fileContentsVersion;
            this._writableData.isBindingNeeded = true;
            this._writableData.isCheckingNeeded = true;
            this._writableData.parseTreeNeedsCleaning = false;
            this._writableData.hitMaxImportDepth = undefined;
            this._recomputeDiagnostics(configOptions);
            return true;
        });
    }
    bind(configOptions, importLookup, builtinsScope, futureImports) {
        (0, debug_1.assert)(!this.isParseRequired(), 'Bind called before parsing');
        (0, debug_1.assert)(this.isBindingRequired(), 'Bind called unnecessarily');
        (0, debug_1.assert)(!this._writableData.isBindingInProgress, 'Bind called while binding in progress');
        (0, debug_1.assert)(this._writableData.parserOutput !== undefined, 'Parse results not available');
        return this._logTracker.log(`binding: ${this._getPathForLogging(this._uri)}`, () => {
            try {
                // Perform name binding.
                timing_1.timingStats.bindTime.timeOperation(() => {
                    this._cleanParseTreeIfRequired();
                    const fileInfo = this._buildFileInfo(configOptions, this._writableData.parsedFileContents, importLookup, builtinsScope, futureImports);
                    AnalyzerNodeInfo.setFileInfo(this._writableData.parserOutput.parseTree, fileInfo);
                    const binder = new binder_1.Binder(fileInfo, configOptions.indexGenerationMode);
                    this._writableData.isBindingInProgress = true;
                    binder.bindModule(this._writableData.parserOutput.parseTree);
                    // If we're in "test mode" (used for unit testing), run an additional
                    // "test walker" over the parse tree to validate its internal consistency.
                    if (configOptions.internalTestMode) {
                        const testWalker = new testWalker_1.TestWalker();
                        testWalker.walk(this._writableData.parserOutput.parseTree);
                    }
                    this._writableData.bindDiagnostics = fileInfo.diagnosticSink.fetchAndClear();
                    const moduleScope = AnalyzerNodeInfo.getScope(this._writableData.parserOutput.parseTree);
                    (0, debug_1.assert)(moduleScope !== undefined, 'Module scope not returned by binder');
                    this._writableData.moduleSymbolTable = moduleScope.symbolTable;
                });
            }
            catch (e) {
                const message = (e.stack ? e.stack.toString() : undefined) ||
                    (typeof e.message === 'string' ? e.message : undefined) ||
                    JSON.stringify(e);
                this._console.error(localize_1.LocMessage.internalBindError().format({
                    file: this.getUri().toUserVisibleString(),
                    message,
                }));
                const diagSink = this.createDiagnosticSink();
                diagSink.addError(localize_1.LocMessage.internalBindError().format({
                    file: this.getUri().toUserVisibleString(),
                    message,
                }), (0, textRange_1.getEmptyRange)());
                this._writableData.bindDiagnostics = diagSink.fetchAndClear();
                // Do not rethrow the exception, swallow it here. Callers are not
                // prepared to handle an exception.
            }
            finally {
                this._writableData.isBindingInProgress = false;
            }
            // Prepare for the next stage of the analysis.
            this._writableData.isCheckingNeeded = true;
            this._writableData.isBindingNeeded = false;
            this._recomputeDiagnostics(configOptions);
        });
    }
    check(configOptions, importResolver, evaluator, sourceMapper, dependentFiles) {
        (0, debug_1.assert)(!this.isParseRequired(), 'Check called before parsing');
        (0, debug_1.assert)(!this.isBindingRequired(), `Check called before binding: state=${this._writableData.debugPrint()}`);
        (0, debug_1.assert)(!this._writableData.isBindingInProgress, 'Check called while binding in progress');
        (0, debug_1.assert)(this.isCheckingRequired(), 'Check called unnecessarily');
        (0, debug_1.assert)(this._writableData.parserOutput !== undefined, 'Parse results not available');
        return this._logTracker.log(`checking: ${this._getPathForLogging(this._uri)}`, () => {
            try {
                timing_1.timingStats.typeCheckerTime.timeOperation(() => {
                    const checkDuration = new timing_1.Duration();
                    const checker = new checker_1.Checker(importResolver, evaluator, this._writableData.parserOutput, sourceMapper, dependentFiles);
                    checker.check();
                    this._writableData.isCheckingNeeded = false;
                    const fileInfo = AnalyzerNodeInfo.getFileInfo(this._writableData.parserOutput.parseTree);
                    this._writableData.checkerDiagnostics = fileInfo.diagnosticSink.fetchAndClear();
                    this._writableData.checkTime = checkDuration.getDurationInMilliseconds();
                });
            }
            catch (e) {
                const isCancellation = cancellationUtils_1.OperationCanceledException.is(e);
                if (!isCancellation) {
                    const message = (e.stack ? e.stack.toString() : undefined) ||
                        (typeof e.message === 'string' ? e.message : undefined) ||
                        JSON.stringify(e);
                    this._console.error(localize_1.LocMessage.internalTypeCheckingError().format({
                        file: this.getUri().toUserVisibleString(),
                        message,
                    }));
                    const diagSink = this.createDiagnosticSink();
                    diagSink.addError(localize_1.LocMessage.internalTypeCheckingError().format({
                        file: this.getUri().toUserVisibleString(),
                        message,
                    }), (0, textRange_1.getEmptyRange)());
                    this._writableData.checkerDiagnostics = diagSink.fetchAndClear();
                    // Mark the file as complete so we don't get into an infinite loop.
                    this._writableData.isCheckingNeeded = false;
                }
                throw e;
            }
            finally {
                // Clear any circular dependencies associated with this file.
                // These will be detected by the program module and associated
                // with the source file right before it is finalized.
                this._writableData.circularDependencies = [];
                this._recomputeDiagnostics(configOptions);
            }
        });
    }
    test_enableIPythonMode(enable) {
        this._ipythonMode = enable ? IPythonMode.CellDocs : IPythonMode.None;
    }
    createDiagnosticSink() {
        return new diagnosticSink_1.DiagnosticSink();
    }
    createTextRangeDiagnosticSink(lines) {
        return new diagnosticSink_1.TextRangeDiagnosticSink(lines);
    }
    // Computes an updated set of accumulated diagnostics for the file
    // based on the partial diagnostics from various analysis stages.
    _recomputeDiagnostics(configOptions) {
        this._writableData.diagnosticVersion++;
        let includeWarningsAndErrors = true;
        // If a file was imported as a third-party file, don't report
        // any errors for it. The user can't fix them anyway.
        if (this._isThirdPartyImport) {
            includeWarningsAndErrors = false;
        }
        let diagList = [];
        (0, collectionUtils_1.appendArray)(diagList, this._writableData.parseDiagnostics);
        (0, collectionUtils_1.appendArray)(diagList, this._writableData.commentDiagnostics);
        (0, collectionUtils_1.appendArray)(diagList, this._writableData.bindDiagnostics);
        (0, collectionUtils_1.appendArray)(diagList, this._writableData.checkerDiagnostics);
        (0, collectionUtils_1.appendArray)(diagList, this._writableData.taskListDiagnostics);
        const prefilteredDiagList = diagList;
        const typeIgnoreLinesClone = new Map(this._writableData.typeIgnoreLines);
        const pyrightIgnoreLinesClone = new Map(this._writableData.pyrightIgnoreLines);
        // Filter the diagnostics based on "type: ignore" lines.
        if (this._diagnosticRuleSet.enableTypeIgnoreComments) {
            if (this._writableData.typeIgnoreLines.size > 0) {
                diagList = diagList.filter((d) => {
                    if (d.category !== 3 /* DiagnosticCategory.UnusedCode */ &&
                        d.category !== 4 /* DiagnosticCategory.UnreachableCode */ &&
                        d.category !== 5 /* DiagnosticCategory.Deprecated */) {
                        for (let line = d.range.start.line; line <= d.range.end.line; line++) {
                            if (this._writableData.typeIgnoreLines.has(line)) {
                                typeIgnoreLinesClone.delete(line);
                                return false;
                            }
                        }
                    }
                    return true;
                });
            }
        }
        // Filter the diagnostics based on "pyright: ignore" lines.
        if (this._writableData.pyrightIgnoreLines.size > 0) {
            diagList = diagList.filter((d) => {
                if (d.category !== 3 /* DiagnosticCategory.UnusedCode */ &&
                    d.category !== 4 /* DiagnosticCategory.UnreachableCode */ &&
                    d.category !== 5 /* DiagnosticCategory.Deprecated */) {
                    for (let line = d.range.start.line; line <= d.range.end.line; line++) {
                        const pyrightIgnoreComment = this._writableData.pyrightIgnoreLines.get(line);
                        if (pyrightIgnoreComment) {
                            if (!pyrightIgnoreComment.rulesList.length) {
                                pyrightIgnoreLinesClone.delete(line);
                                return false;
                            }
                            const diagRule = d.getRule();
                            if (!diagRule) {
                                // If there's no diagnostic rule, it won't match
                                // against a rules list.
                                return true;
                            }
                            // Did we find this rule in the list?
                            if (pyrightIgnoreComment.rulesList.find((rule) => rule.text === diagRule)) {
                                // Update the pyrightIgnoreLinesClone to remove this rule.
                                const oldClone = pyrightIgnoreLinesClone.get(line);
                                if (oldClone === null || oldClone === void 0 ? void 0 : oldClone.rulesList.length) {
                                    const filteredRulesList = oldClone.rulesList.filter((rule) => rule.text !== diagRule);
                                    if (filteredRulesList.length === 0) {
                                        pyrightIgnoreLinesClone.delete(line);
                                    }
                                    else {
                                        pyrightIgnoreLinesClone.set(line, {
                                            range: oldClone.range,
                                            rulesList: filteredRulesList,
                                        });
                                    }
                                }
                                return false;
                            }
                            return true;
                        }
                    }
                }
                return true;
            });
        }
        // report diagnostics for ignore comments that don't specify rules
        const ignoreCommentWithoutRule = this._diagnosticRuleSet.reportIgnoreCommentWithoutRule;
        if (ignoreCommentWithoutRule !== 'none') {
            const category = (0, diagnostic_1.convertLevelToCategory)(this._diagnosticRuleSet.reportIgnoreCommentWithoutRule);
            for (const ignoreComment of this._writableData.pyrightIgnoreLines.values()) {
                if (!ignoreComment.rulesList.length) {
                    const diagnostic = new diagnostic_1.Diagnostic(category, localize_1.LocMessage.pyrightIgnoreCommentWithoutRule(), this._getRangeFromIgnoreComment(ignoreComment));
                    diagnostic.setRule(diagnosticRules_1.DiagnosticRule.reportIgnoreCommentWithoutRule);
                    diagList.push(diagnostic);
                }
            }
            if (this._diagnosticRuleSet.enableTypeIgnoreComments) {
                for (const ignoreComment of this._writableData.typeIgnoreLines.values()) {
                    if (!ignoreComment.rulesList.length) {
                        const diagnostic = new diagnostic_1.Diagnostic(category, localize_1.LocMessage.typeIgnoreCommentWithoutRule(), this._getRangeFromIgnoreComment(ignoreComment));
                        diagnostic.setRule(diagnosticRules_1.DiagnosticRule.reportIgnoreCommentWithoutRule);
                        diagList.push(diagnostic);
                    }
                }
            }
        }
        const unnecessaryTypeIgnoreDiags = [];
        // Skip this step if type checking is needed. Otherwise we'll likely produce
        // incorrect (false positive) reportUnnecessaryTypeIgnoreComment diagnostics
        // until checking is performed on this file.
        if (this._diagnosticRuleSet.reportUnnecessaryTypeIgnoreComment !== 'none' &&
            !this._writableData.isCheckingNeeded) {
            const diagCategory = (0, diagnostic_1.convertLevelToCategory)(this._diagnosticRuleSet.reportUnnecessaryTypeIgnoreComment);
            const prefilteredErrorList = prefilteredDiagList.filter((diag) => diag.category === 0 /* DiagnosticCategory.Error */ ||
                diag.category === 1 /* DiagnosticCategory.Warning */ ||
                diag.category === 2 /* DiagnosticCategory.Information */);
            const isUnreachableCodeRange = (range) => {
                return prefilteredDiagList.find((diag) => diag.category === 4 /* DiagnosticCategory.UnreachableCode */ &&
                    diag.range.start.line <= range.start.line &&
                    diag.range.end.line >= range.end.line);
            };
            if (prefilteredErrorList.length === 0 && this._writableData.typeIgnoreAll !== undefined) {
                const range = this._getRangeFromIgnoreComment(this._writableData.typeIgnoreAll);
                if (!isUnreachableCodeRange(range) && this._diagnosticRuleSet.enableTypeIgnoreComments) {
                    unnecessaryTypeIgnoreDiags.push(new diagnostic_1.Diagnostic(diagCategory, localize_1.LocMessage.unnecessaryTypeIgnore(), range));
                }
            }
            typeIgnoreLinesClone.forEach((ignoreComment) => {
                if (this._writableData.tokenizerLines) {
                    const range = this._getRangeFromIgnoreComment(ignoreComment);
                    if (!isUnreachableCodeRange(range) && this._diagnosticRuleSet.enableTypeIgnoreComments) {
                        unnecessaryTypeIgnoreDiags.push(new diagnostic_1.Diagnostic(diagCategory, localize_1.LocMessage.unnecessaryTypeIgnore(), range));
                    }
                }
            });
            pyrightIgnoreLinesClone.forEach((ignoreComment) => {
                if (this._writableData.tokenizerLines) {
                    if (!ignoreComment.rulesList.length) {
                        const range = this._getRangeFromIgnoreComment(ignoreComment);
                        if (!isUnreachableCodeRange(range)) {
                            unnecessaryTypeIgnoreDiags.push(new diagnostic_1.Diagnostic(diagCategory, localize_1.LocMessage.unnecessaryPyrightIgnore(), range));
                        }
                    }
                    else {
                        ignoreComment.rulesList.forEach((unusedRule) => {
                            const range = this._getRangeFromIgnoreComment(unusedRule);
                            if (!isUnreachableCodeRange(range)) {
                                unnecessaryTypeIgnoreDiags.push(new diagnostic_1.Diagnostic(diagCategory, localize_1.LocMessage.unnecessaryPyrightIgnoreRule().format({
                                    name: unusedRule.text,
                                }), range));
                            }
                        });
                    }
                }
            });
        }
        if (this._diagnosticRuleSet.reportImportCycles !== 'none' &&
            this._writableData.circularDependencies.length > 0) {
            const category = (0, diagnostic_1.convertLevelToCategory)(this._diagnosticRuleSet.reportImportCycles);
            this._writableData.circularDependencies.forEach((cirDep) => {
                const diag = new diagnostic_1.Diagnostic(category, localize_1.LocMessage.importCycleDetected() +
                    '\n' +
                    cirDep
                        .getPaths()
                        .map((path) => '  ' + path.toUserVisibleString())
                        .join('\n'), (0, textRange_1.getEmptyRange)());
                diag.setRule(diagnosticRules_1.DiagnosticRule.reportImportCycles);
                diagList.push(diag);
            });
        }
        if (this._writableData.hitMaxImportDepth !== undefined) {
            diagList.push(new diagnostic_1.Diagnostic(0 /* DiagnosticCategory.Error */, localize_1.LocMessage.importDepthExceeded().format({ depth: this._writableData.hitMaxImportDepth }), (0, textRange_1.getEmptyRange)()));
        }
        // If there is a "type: ignore" comment at the top of the file, clear
        // the diagnostic list of all error, warning, and information diagnostics.
        if (this._diagnosticRuleSet.enableTypeIgnoreComments) {
            if (this._writableData.typeIgnoreAll !== undefined) {
                diagList = diagList.filter((diag) => diag.category !== 0 /* DiagnosticCategory.Error */ &&
                    diag.category !== 1 /* DiagnosticCategory.Warning */ &&
                    diag.category !== 2 /* DiagnosticCategory.Information */);
            }
        }
        // Now add in the "unnecessary type ignore" diagnostics.
        diagList = diagList.concat(unnecessaryTypeIgnoreDiags);
        // If we're not returning any diagnostics, filter out all of
        // the errors and warnings, leaving only the unreachable code
        // and deprecated diagnostics.
        if (!includeWarningsAndErrors) {
            diagList = diagList.filter((diag) => diag.category === 3 /* DiagnosticCategory.UnusedCode */ ||
                diag.category === 4 /* DiagnosticCategory.UnreachableCode */ ||
                diag.category === 5 /* DiagnosticCategory.Deprecated */);
        }
        // If the file is in the ignore list, clear the diagnostic list.
        if (configOptions.ignore.find((ignoreFileSpec) => this._uri.matchesRegex(ignoreFileSpec.regExp))) {
            diagList = [];
        }
        this._writableData.accumulatedDiagnostics = diagList;
    }
    _cachePreEditState() {
        // If this is our first write, then make a copy of the writable data.
        if (!this._editMode.isEditMode || this._preEditData) {
            return;
        }
        // Copy over the writable data.
        this._preEditData = this._writableData;
        // Recreate all the writable data from scratch.
        this._writableData = new WriteableData();
    }
    // Get all task list diagnostics for the current file and add them
    // to the specified diagnostic list.
    _addTaskListDiagnostics(taskListTokens, tokenizerOutput, diagList) {
        if (!taskListTokens || taskListTokens.length === 0 || !diagList) {
            return;
        }
        for (let i = 0; i < tokenizerOutput.tokens.count; i++) {
            const token = tokenizerOutput.tokens.getItemAt(i);
            // If there are no comments, skip this token.
            if (!token.comments || token.comments.length === 0) {
                continue;
            }
            for (const comment of token.comments) {
                for (const token of taskListTokens) {
                    // Check if the comment matches the task list token.
                    // The comment must start with zero or more whitespace characters,
                    // followed by the taskListToken (case insensitive),
                    // followed by (0+ whitespace + EOL) OR (1+ NON-alphanumeric characters)
                    const regexStr = '^[\\s]*' + token.text + '([\\s]*$|[\\W]+)';
                    const regex = RegExp(regexStr, 'i'); // case insensitive
                    // If the comment doesn't match, skip it.
                    if (!regex.test(comment.value)) {
                        continue;
                    }
                    // Calculate the range for the diagnostic. This allows navigation
                    // to the comment via double clicking the item in the task list pane.
                    let rangeStart = comment.start;
                    // The comment technically starts right after the comment identifier(#),
                    // but we want the caret right before the task list token (since there
                    // might be whitespace before it).
                    const indexOfToken = comment.value.toLowerCase().indexOf(token.text.toLowerCase());
                    rangeStart += indexOfToken;
                    const rangeEnd = textRange_1.TextRange.getEnd(comment);
                    const range = (0, positionUtils_1.convertOffsetsToRange)(rangeStart, rangeEnd, tokenizerOutput.lines);
                    // Add the diagnostic to the list and trim whitespace from the comment so
                    // it's easier to read in the task list.
                    diagList.push(new diagnostic_1.Diagnostic(6 /* DiagnosticCategory.TaskItem */, comment.value.trim(), range, token.priority));
                }
            }
        }
    }
    _buildFileInfo(configOptions, fileContents, importLookup, builtinsScope, futureImports) {
        (0, debug_1.assert)(this._writableData.parserOutput !== undefined, 'Parse results not available');
        const analysisDiagnostics = this.createTextRangeDiagnosticSink(this._writableData.tokenizerLines);
        const fileInfo = {
            importLookup,
            futureImports,
            builtinsScope,
            diagnosticSink: analysisDiagnostics,
            executionEnvironment: configOptions.findExecEnvironment(this._uri),
            diagnosticRuleSet: this._diagnosticRuleSet,
            lines: this._writableData.tokenizerLines,
            typingSymbolAliases: this._writableData.parserOutput.typingSymbolAliases,
            definedConstants: configOptions.defineConstant,
            fileUri: this._uri,
            moduleName: this.getModuleName(),
            isStubFile: this._isStubFile,
            isTypingStubFile: this._isTypingStubFile,
            isTypingExtensionsStubFile: this._isTypingExtensionsStubFile,
            isTypeshedStubFile: this._isTypeshedStubFile,
            isBuiltInStubFile: this._isBuiltInStubFile,
            isInPyTypedPackage: this._isThirdPartyPyTypedPresent,
            isThirdParty: this._isThirdPartyImport,
            ipythonMode: this._ipythonMode,
            accessedSymbolSet: new Set(),
        };
        return fileInfo;
    }
    _cleanParseTreeIfRequired() {
        if (this._writableData.parserOutput) {
            if (this._writableData.parseTreeNeedsCleaning) {
                const cleanerWalker = new parseTreeCleaner_1.ParseTreeCleanerWalker(this._writableData.parserOutput.parseTree);
                cleanerWalker.clean();
                this._writableData.parseTreeNeedsCleaning = false;
            }
        }
    }
    _resolveImports(importResolver, moduleImports, execEnv) {
        const imports = [];
        const resolveAndAddIfNotSelf = (nameParts, skipMissingImport = false) => {
            const importResult = importResolver.resolveImport(this._uri, execEnv, {
                leadingDots: 0,
                nameParts,
                importedSymbols: undefined,
            });
            if (skipMissingImport && !importResult.isImportFound) {
                return undefined;
            }
            // Avoid importing module from the module file itself.
            if (importResult.resolvedUris.length === 0 || importResult.resolvedUris[0] !== this._uri) {
                imports.push(importResult);
                return importResult;
            }
            return undefined;
        };
        // Always include an implicit import of the builtins module.
        let builtinsImportResult;
        // If this is a project source file (not a stub), try to resolve
        // the __builtins__ stub first.
        if (!this._isThirdPartyImport && !this._isStubFile) {
            builtinsImportResult = resolveAndAddIfNotSelf(['__builtins__'], /* skipMissingImport */ true);
        }
        if (!builtinsImportResult) {
            builtinsImportResult = resolveAndAddIfNotSelf(['builtins']);
        }
        for (const moduleImport of moduleImports) {
            const importResult = importResolver.resolveImport(this._uri, execEnv, {
                leadingDots: moduleImport.leadingDots,
                nameParts: moduleImport.nameParts,
                importedSymbols: moduleImport.importedSymbols,
            });
            imports.push(importResult);
            // Associate the import results with the module import
            // name node in the parse tree so we can access it later
            // (for hover and definition support).
            if (moduleImport.nameParts.length === moduleImport.nameNode.nameParts.length) {
                AnalyzerNodeInfo.setImportInfo(moduleImport.nameNode, importResult);
            }
            else {
                // For implicit imports of higher-level modules within a multi-part
                // module name, the moduleImport.nameParts will refer to the subset
                // of the multi-part name rather than the full multi-part name. In this
                // case, store the import info on the name part node.
                (0, debug_1.assert)(moduleImport.nameParts.length > 0);
                (0, debug_1.assert)(moduleImport.nameParts.length - 1 < moduleImport.nameNode.nameParts.length);
                AnalyzerNodeInfo.setImportInfo(moduleImport.nameNode.nameParts[moduleImport.nameParts.length - 1], importResult);
            }
        }
        return {
            imports,
            builtinsImportResult,
        };
    }
    _getPathForLogging(fileUri) {
        return (0, logTracker_1.getPathForLogging)(this.fileSystem, fileUri);
    }
    _parseFile(configOptions, fileUri, fileContents, ipythonMode, diagSink) {
        var _a;
        // Use the configuration options to determine the environment zin which
        // this source file will be executed.
        const execEnvironment = configOptions.findExecEnvironment(fileUri);
        const parseOptions = new parser_1.ParseOptions();
        parseOptions.ipythonMode = ipythonMode;
        if (fileUri.pathEndsWith('pyi')) {
            parseOptions.isStubFile = true;
        }
        parseOptions.pythonVersion = execEnvironment.pythonVersion;
        parseOptions.skipFunctionAndClassBody = (_a = configOptions.indexGenerationMode) !== null && _a !== void 0 ? _a : false;
        // Parse the token stream, building the abstract syntax tree.
        const parser = new parser_1.Parser();
        return parser.parseSourceFile(fileContents, parseOptions, diagSink);
    }
    _tokenizeContents(fileContents) {
        const tokenizer = new tokenizer_1.Tokenizer();
        const output = tokenizer.tokenize(fileContents);
        // If the file is currently open, cache the tokenizer results.
        if (this._writableData.clientDocumentContents !== undefined) {
            this._writableData.tokenizerOutput = output;
            // Replace the existing tokenizerLines with the newly-returned
            // version. They should have the same contents, but we want to use
            // the same object so the older object can be deallocated.
            this._writableData.tokenizerLines = output.lines;
        }
        return output;
    }
    _fireFileDirtyEvent() {
        var _a;
        (_a = this.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.stateMutationListeners)) === null || _a === void 0 ? void 0 : _a.forEach((l) => {
            var _a;
            try {
                (_a = l.onFileDirty) === null || _a === void 0 ? void 0 : _a.call(l, this._uri);
            }
            catch (ex) {
                const console = this.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.console);
                if (console) {
                    console.error(`State mutation listener exception: ${ex.message}`);
                }
            }
        });
    }
}
exports.SourceFile = SourceFile;


/***/ }),

/***/ "../pyright-internal/src/analyzer/sourceFileInfo.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/sourceFileInfo.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * sourceFileInfo.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Class that represents information around single source file.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SourceFileInfo = void 0;
// Tracks information about each source file in a program,
// including the reason it was added to the program and any
// dependencies that it has on other files in the program.
class SourceFileInfo {
    constructor(sourceFile, isTypeshedFile, isThirdPartyImport, isThirdPartyPyTypedPresent, _editModeTracker, args = {}) {
        this.sourceFile = sourceFile;
        this.isTypeshedFile = isTypeshedFile;
        this.isThirdPartyImport = isThirdPartyImport;
        this.isThirdPartyPyTypedPresent = isThirdPartyPyTypedPresent;
        this._editModeTracker = _editModeTracker;
        this.isCreatedInEditMode = this._editModeTracker.isEditMode;
        this._writableData = this._createWriteableData(args);
        this._cachePreEditState();
    }
    get diagnosticsVersion() {
        return this._writableData.diagnosticsVersion;
    }
    get builtinsImport() {
        return this._writableData.builtinsImport;
    }
    // Information about the chained source file
    // Chained source file is not supposed to exist on file system but
    // must exist in the program's source file list. Module level
    // scope of the chained source file will be inserted before
    // current file's scope.
    get chainedSourceFile() {
        return this._writableData.chainedSourceFile;
    }
    get effectiveFutureImports() {
        return this._writableData.effectiveFutureImports;
    }
    // Information about why the file is included in the program
    // and its relation to other source files in the program.
    get isTracked() {
        return this._writableData.isTracked;
    }
    get isOpenByClient() {
        return this._writableData.isOpenByClient;
    }
    get imports() {
        return this._writableData.imports;
    }
    get importedBy() {
        return this._writableData.importedBy;
    }
    get shadows() {
        return this._writableData.shadows;
    }
    get shadowedBy() {
        return this._writableData.shadowedBy;
    }
    set diagnosticsVersion(value) {
        this._cachePreEditState();
        this._writableData.diagnosticsVersion = value;
    }
    set builtinsImport(value) {
        this._cachePreEditState();
        this._writableData.builtinsImport = value;
    }
    set chainedSourceFile(value) {
        this._cachePreEditState();
        this._writableData.chainedSourceFile = value;
    }
    set effectiveFutureImports(value) {
        this._cachePreEditState();
        this._writableData.effectiveFutureImports = value;
    }
    set isTracked(value) {
        this._cachePreEditState();
        this._writableData.isTracked = value;
    }
    set isOpenByClient(value) {
        this._cachePreEditState();
        this._writableData.isOpenByClient = value;
    }
    mutate(callback) {
        this._cachePreEditState();
        callback(this._writableData);
    }
    restore() {
        if (this._preEditData) {
            this._writableData = this._preEditData;
            this._preEditData = undefined;
            // Some states have changed. Force some of info to be re-calculated.
            this.sourceFile.dropParseAndBindInfo();
        }
        return this.sourceFile.restore();
    }
    _cachePreEditState() {
        if (!this._editModeTracker.isEditMode || this._preEditData) {
            return;
        }
        this._preEditData = this._writableData;
        this._writableData = this._cloneWriteableData(this._writableData);
        this._editModeTracker.addMutatedFiles(this);
    }
    _createWriteableData(args) {
        var _a, _b;
        return {
            isTracked: (_a = args.isTracked) !== null && _a !== void 0 ? _a : false,
            isOpenByClient: (_b = args.isOpenByClient) !== null && _b !== void 0 ? _b : false,
            builtinsImport: args.builtinsImport,
            chainedSourceFile: args.chainedSourceFile,
            diagnosticsVersion: args.diagnosticsVersion,
            effectiveFutureImports: args.effectiveFutureImports,
            imports: [],
            importedBy: [],
            shadows: [],
            shadowedBy: [],
        };
    }
    _cloneWriteableData(data) {
        return {
            isTracked: data.isTracked,
            isOpenByClient: data.isOpenByClient,
            builtinsImport: data.builtinsImport,
            chainedSourceFile: data.chainedSourceFile,
            diagnosticsVersion: data.diagnosticsVersion,
            effectiveFutureImports: data.effectiveFutureImports,
            imports: data.imports.slice(),
            importedBy: data.importedBy.slice(),
            shadows: data.shadows.slice(),
            shadowedBy: data.shadowedBy.slice(),
        };
    }
}
exports.SourceFileInfo = SourceFileInfo;


/***/ }),

/***/ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/analyzer/sourceFileInfoUtils.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * sourceFileInfoUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Functions that operate on SourceFileInfo objects.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createChainedByList = exports.verifyNoCyclesInChainedFiles = exports.collectImportedByCells = exports.isUserCode = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const sourceFile_1 = __webpack_require__(/*! ./sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
function isUserCode(fileInfo) {
    return !!fileInfo && fileInfo.isTracked && !fileInfo.isThirdPartyImport && !fileInfo.isTypeshedFile;
}
exports.isUserCode = isUserCode;
function collectImportedByCells(program, fileInfo) {
    // The ImportedBy only works when files are parsed. Due to the lazy-loading nature of our system,
    // we can't ensure that all files within the program are parsed, which might lead to an incomplete dependency graph.
    // Parsing all regular files goes against our lazy-nature, but for notebook cells, which we open by default,
    // it makes sense to force complete parsing since they'll be parsed at some point anyway due to things like
    // `semantic tokens` or `checkers`.
    _parseAllOpenCells(program);
    const importedByCells = new Set();
    _collectImportedByCells(fileInfo, importedByCells);
    return importedByCells;
}
exports.collectImportedByCells = collectImportedByCells;
function verifyNoCyclesInChainedFiles(program, fileInfo) {
    var _a, _b;
    let nextChainedFile = fileInfo.chainedSourceFile;
    if (!nextChainedFile) {
        return;
    }
    const set = new Set([fileInfo.sourceFile.getUri().key]);
    while (nextChainedFile) {
        const path = nextChainedFile.sourceFile.getUri().key;
        if (set.has(path)) {
            // We found a cycle.
            (0, debug_1.fail)((_b = (_a = program.serviceProvider
                .tryGet(serviceKeys_1.ServiceKeys.debugInfoInspector)) === null || _a === void 0 ? void 0 : _a.getCycleDetail(program, nextChainedFile)) !== null && _b !== void 0 ? _b : `Found a cycle in implicit imports files for ${path}`);
        }
        set.add(path);
        nextChainedFile = nextChainedFile.chainedSourceFile;
    }
}
exports.verifyNoCyclesInChainedFiles = verifyNoCyclesInChainedFiles;
function createChainedByList(program, fileInfo) {
    var _a, _b;
    // We want to create reverse map of all chained files.
    const map = new Map();
    for (const file of program.getSourceFileInfoList()) {
        if (!file.chainedSourceFile) {
            continue;
        }
        map.set(file.chainedSourceFile, file);
    }
    const visited = new Set();
    const chainedByList = [fileInfo];
    let current = fileInfo;
    while (current) {
        if (visited.has(current)) {
            (0, debug_1.fail)((_b = (_a = program.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.debugInfoInspector)) === null || _a === void 0 ? void 0 : _a.getCycleDetail(program, current)) !== null && _b !== void 0 ? _b : 'detected a cycle in chained files');
        }
        visited.add(current);
        current = map.get(current);
        if (current) {
            chainedByList.push(current);
        }
    }
    return chainedByList;
}
exports.createChainedByList = createChainedByList;
function _parseAllOpenCells(program) {
    for (const file of program.getSourceFileInfoList()) {
        if (file.sourceFile.getIPythonMode() !== sourceFile_1.IPythonMode.CellDocs) {
            continue;
        }
        program.getParserOutput(file.sourceFile.getUri());
        program.handleMemoryHighUsage();
    }
}
function _collectImportedByCells(fileInfo, importedByCells) {
    fileInfo.importedBy.forEach((dep) => {
        if (importedByCells.has(dep)) {
            // Already visited.
            return;
        }
        importedByCells.add(dep);
        _collectImportedByCells(dep, importedByCells);
    });
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/sourceMapper.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/sourceMapper.ts ***!
  \********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * sourceMapper.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Logic that maps a ".pyi" stub to its ".py" source file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isStubFile = exports.SourceMapper = void 0;
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const declaration_1 = __webpack_require__(/*! ./declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ./sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const sourceMapperUtils_1 = __webpack_require__(/*! ./sourceMapperUtils */ "../pyright-internal/src/analyzer/sourceMapperUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
class SourceMapper {
    constructor(_importResolver, _execEnv, _evaluator, _fileBinder, _boundSourceGetter, _mapCompiled, _preferStubs, _fromFile, _cancelToken) {
        this._importResolver = _importResolver;
        this._execEnv = _execEnv;
        this._evaluator = _evaluator;
        this._fileBinder = _fileBinder;
        this._boundSourceGetter = _boundSourceGetter;
        this._mapCompiled = _mapCompiled;
        this._preferStubs = _preferStubs;
        this._fromFile = _fromFile;
        this._cancelToken = _cancelToken;
    }
    findModules(stubFileUri) {
        var _a;
        const sourceFiles = this._isStubThatShouldBeMappedToImplementation(stubFileUri)
            ? this._getBoundSourceFilesFromStubFile(stubFileUri)
            : [(_a = this._boundSourceGetter(stubFileUri)) === null || _a === void 0 ? void 0 : _a.sourceFile];
        return sourceFiles
            .filter(core_1.isDefined)
            .map((sf) => { var _a; return (_a = sf.getParserOutput()) === null || _a === void 0 ? void 0 : _a.parseTree; })
            .filter(core_1.isDefined);
    }
    getModuleNode(fileUri) {
        var _a, _b;
        return (_b = (_a = this._boundSourceGetter(fileUri)) === null || _a === void 0 ? void 0 : _a.sourceFile.getParserOutput()) === null || _b === void 0 ? void 0 : _b.parseTree;
    }
    findDeclarations(stubDecl) {
        if ((0, declaration_1.isClassDeclaration)(stubDecl)) {
            return this._findClassOrTypeAliasDeclarations(stubDecl);
        }
        else if ((0, declaration_1.isFunctionDeclaration)(stubDecl)) {
            return this._findFunctionOrTypeAliasDeclarations(stubDecl);
        }
        else if ((0, declaration_1.isVariableDeclaration)(stubDecl)) {
            return this._findVariableDeclarations(stubDecl);
        }
        else if ((0, declaration_1.isParameterDeclaration)(stubDecl)) {
            return this._findParameterDeclarations(stubDecl);
        }
        else if ((0, declaration_1.isSpecialBuiltInClassDeclaration)(stubDecl)) {
            return this._findSpecialBuiltInClassDeclarations(stubDecl);
        }
        return [];
    }
    findDeclarationsByType(originatedPath, type, useTypeAlias = false) {
        const result = [];
        this._addClassTypeDeclarations(originatedPath, type, result, new Set(), useTypeAlias);
        return result;
    }
    findClassDeclarationsByType(originatedPath, type) {
        const result = this.findDeclarationsByType(originatedPath, type);
        return result.filter((r) => (0, declaration_1.isClassDeclaration)(r)).map((r) => r);
    }
    findFunctionDeclarations(stubDecl) {
        return this._findFunctionOrTypeAliasDeclarations(stubDecl)
            .filter((d) => (0, declaration_1.isFunctionDeclaration)(d))
            .map((d) => d);
    }
    isUserCode(uri) {
        return (0, sourceFileInfoUtils_1.isUserCode)(this._boundSourceGetter(uri));
    }
    getNextFileName(uri) {
        const withoutExtension = uri.stripExtension();
        let suffix = 1;
        let result = withoutExtension.addExtension(`_${suffix}.py`);
        while (this.isUserCode(result) && suffix < 1000) {
            suffix += 1;
            result = withoutExtension.addExtension(`_${suffix}.py`);
        }
        return result;
    }
    _findSpecialBuiltInClassDeclarations(stubDecl, recursiveDeclCache = new Set()) {
        if (stubDecl.node.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
            const className = stubDecl.node.valueExpression.value;
            const sourceFiles = this._getBoundSourceFilesFromStubFile(stubDecl.uri);
            return sourceFiles.flatMap((sourceFile) => this._findClassDeclarationsByName(sourceFile, className, recursiveDeclCache));
        }
        return [];
    }
    _findClassOrTypeAliasDeclarations(stubDecl, recursiveDeclCache = new Set()) {
        const className = this._getFullClassName(stubDecl.node);
        const sourceFiles = this._getBoundSourceFilesFromStubFile(stubDecl.uri);
        return sourceFiles.flatMap((sourceFile) => this._findClassDeclarationsByName(sourceFile, className, recursiveDeclCache));
    }
    _findFunctionOrTypeAliasDeclarations(stubDecl, recursiveDeclCache = new Set()) {
        const functionName = stubDecl.node.name.value;
        const sourceFiles = this._getBoundSourceFilesFromStubFile(stubDecl.uri);
        if (stubDecl.isMethod) {
            const classNode = ParseTreeUtils.getEnclosingClass(stubDecl.node);
            if (classNode === undefined) {
                return [];
            }
            const className = this._getFullClassName(classNode);
            return sourceFiles.flatMap((sourceFile) => this._findMethodDeclarationsByName(sourceFile, className, functionName, recursiveDeclCache));
        }
        else {
            return sourceFiles.flatMap((sourceFile) => this._findFunctionDeclarationsByName(sourceFile, functionName, recursiveDeclCache));
        }
    }
    _findVariableDeclarations(stubDecl, recursiveDeclCache = new Set()) {
        if (stubDecl.node.nodeType !== 38 /* ParseNodeType.Name */) {
            return [];
        }
        const variableName = stubDecl.node.value;
        const sourceFiles = this._getBoundSourceFilesFromStubFile(stubDecl.uri);
        const classNode = ParseTreeUtils.getEnclosingClass(stubDecl.node);
        if (classNode) {
            const className = this._getFullClassName(classNode);
            return sourceFiles.flatMap((sourceFile) => this._findFieldDeclarationsByName(sourceFile, className, variableName, recursiveDeclCache));
        }
        else {
            return sourceFiles.flatMap((sourceFile) => this._findVariableDeclarationsByName(sourceFile, variableName, recursiveDeclCache));
        }
    }
    _findParameterDeclarations(stubDecl) {
        const result = [];
        if (!stubDecl.node.name) {
            return result;
        }
        const functionNode = ParseTreeUtils.getEnclosingFunction(stubDecl.node);
        if (!functionNode) {
            return result;
        }
        const functionStubDecls = this._evaluator.getDeclarationsForNameNode(functionNode.name);
        if (!functionStubDecls) {
            return result;
        }
        const recursiveDeclCache = new Set();
        for (const functionStubDecl of functionStubDecls) {
            for (const functionDecl of this._findFunctionOrTypeAliasDeclarations(functionStubDecl, recursiveDeclCache)) {
                (0, collectionUtils_1.appendArray)(result, this._lookUpSymbolDeclarations(functionDecl.node, stubDecl.node.name.value)
                    .filter((d) => (0, declaration_1.isParameterDeclaration)(d))
                    .map((d) => d));
            }
        }
        return result;
    }
    _findMemberDeclarationsByName(sourceFile, className, memberName, declAdder, recursiveDeclCache) {
        const result = [];
        const classDecls = this._findClassDeclarationsByName(sourceFile, className, recursiveDeclCache);
        for (const classDecl of classDecls.filter((d) => (0, declaration_1.isClassDeclaration)(d)).map((d) => d)) {
            const classResults = this._evaluator.getTypeOfClass(classDecl.node);
            if (!classResults) {
                continue;
            }
            const member = (0, typeUtils_1.lookUpClassMember)(classResults.classType, memberName);
            if (member) {
                for (const decl of member.symbol.getDeclarations()) {
                    declAdder(decl, recursiveDeclCache, result);
                }
            }
        }
        return result;
    }
    _findFieldDeclarationsByName(sourceFile, className, variableName, recursiveDeclCache) {
        let result = [];
        const uniqueId = `@${sourceFile.getUri()}/c/${className}/v/${variableName}`;
        if (recursiveDeclCache.has(uniqueId)) {
            return result;
        }
        recursiveDeclCache.add(uniqueId);
        result = this._findMemberDeclarationsByName(sourceFile, className, variableName, (decl, cache, result) => {
            if ((0, declaration_1.isVariableDeclaration)(decl)) {
                if (this._isStubThatShouldBeMappedToImplementation(decl.uri)) {
                    for (const implDecl of this._findVariableDeclarations(decl, cache)) {
                        if ((0, declaration_1.isVariableDeclaration)(implDecl)) {
                            result.push(implDecl);
                        }
                    }
                }
                else {
                    result.push(decl);
                }
            }
        }, recursiveDeclCache);
        recursiveDeclCache.delete(uniqueId);
        return result;
    }
    _findMethodDeclarationsByName(sourceFile, className, functionName, recursiveDeclCache) {
        let result = [];
        const uniqueId = `@${sourceFile.getUri()}/c/${className}/f/${functionName}`;
        if (recursiveDeclCache.has(uniqueId)) {
            return result;
        }
        recursiveDeclCache.add(uniqueId);
        result = this._findMemberDeclarationsByName(sourceFile, className, functionName, (decl, cache, result) => {
            if ((0, declaration_1.isFunctionDeclaration)(decl)) {
                if (this._isStubThatShouldBeMappedToImplementation(decl.uri)) {
                    (0, collectionUtils_1.appendArray)(result, this._findFunctionOrTypeAliasDeclarations(decl, cache));
                }
                else {
                    result.push(decl);
                }
            }
        }, recursiveDeclCache);
        recursiveDeclCache.delete(uniqueId);
        return result;
    }
    _findVariableDeclarationsByName(sourceFile, variableName, recursiveDeclCache) {
        var _a;
        const result = [];
        const uniqueId = `@${sourceFile.getUri()}/v/${variableName}`;
        if (recursiveDeclCache.has(uniqueId)) {
            return result;
        }
        recursiveDeclCache.add(uniqueId);
        const moduleNode = (_a = sourceFile.getParserOutput()) === null || _a === void 0 ? void 0 : _a.parseTree;
        if (!moduleNode) {
            // Don't bother deleting from the cache; we'll never get any info from this
            // file if it has no tree.
            return result;
        }
        const decls = this._lookUpSymbolDeclarations(moduleNode, variableName);
        if (decls.length === 0) {
            this._addDeclarationsFollowingWildcardImports(moduleNode, variableName, result, recursiveDeclCache);
        }
        else {
            for (const decl of decls) {
                this._addVariableDeclarations(decl, result, recursiveDeclCache);
            }
        }
        recursiveDeclCache.delete(uniqueId);
        return result;
    }
    _findFunctionDeclarationsByName(sourceFile, functionName, recursiveDeclCache) {
        var _a;
        const result = [];
        const uniqueId = `@${sourceFile.getUri()}/f/${functionName}`;
        if (recursiveDeclCache.has(uniqueId)) {
            return result;
        }
        recursiveDeclCache.add(uniqueId);
        const moduleNode = (_a = sourceFile.getParserOutput()) === null || _a === void 0 ? void 0 : _a.parseTree;
        if (!moduleNode) {
            // Don't bother deleting from the cache; we'll never get any info from this
            // file if it has no tree.
            return result;
        }
        const decls = this._lookUpSymbolDeclarations(moduleNode, functionName);
        if (decls.length === 0) {
            this._addDeclarationsFollowingWildcardImports(moduleNode, functionName, result, recursiveDeclCache);
        }
        else {
            for (const decl of decls) {
                this._addClassOrFunctionDeclarations(decl, result, recursiveDeclCache);
            }
        }
        recursiveDeclCache.delete(uniqueId);
        return result;
    }
    _findClassDeclarationsByName(sourceFile, fullClassName, recursiveDeclCache) {
        var _a;
        let classDecls = [];
        // fullClassName is period delimited, for example: 'OuterClass.InnerClass'
        const parentNode = (_a = sourceFile.getParserOutput()) === null || _a === void 0 ? void 0 : _a.parseTree;
        if (parentNode) {
            let classNameParts = fullClassName.split('.');
            if (classNameParts.length > 0) {
                classDecls = this._findClassDeclarations(sourceFile, classNameParts[0], parentNode, recursiveDeclCache);
                classNameParts = classNameParts.slice(1);
            }
            for (const classNamePart of classNameParts) {
                classDecls = classDecls.flatMap((parentDecl) => this._findClassDeclarations(sourceFile, classNamePart, parentDecl.node, recursiveDeclCache));
            }
        }
        return classDecls;
    }
    _findClassDeclarations(sourceFile, className, parentNode, recursiveDeclCache) {
        const result = [];
        const uniqueId = `@${sourceFile.getUri()}[${parentNode.start}]${className}`;
        if (recursiveDeclCache.has(uniqueId)) {
            return result;
        }
        recursiveDeclCache.add(uniqueId);
        const decls = this._lookUpSymbolDeclarations(parentNode, className);
        if (decls.length === 0 && parentNode.nodeType === 36 /* ParseNodeType.Module */) {
            this._addDeclarationsFollowingWildcardImports(parentNode, className, result, recursiveDeclCache);
        }
        else {
            for (const decl of decls) {
                this._addClassOrFunctionDeclarations(decl, result, recursiveDeclCache);
            }
        }
        recursiveDeclCache.delete(uniqueId);
        return result;
    }
    _addVariableDeclarations(decl, result, recursiveDeclCache) {
        if ((0, declaration_1.isVariableDeclaration)(decl)) {
            if (this._isStubThatShouldBeMappedToImplementation(decl.uri)) {
                (0, collectionUtils_1.appendArray)(result, this._findVariableDeclarations(decl, recursiveDeclCache));
            }
            else {
                result.push(decl);
            }
        }
        else if ((0, declaration_1.isAliasDeclaration)(decl)) {
            const resolvedDecl = this._evaluator.resolveAliasDeclaration(decl, /* resolveLocalNames */ true);
            if (resolvedDecl) {
                if ((0, declaration_1.isVariableDeclaration)(resolvedDecl)) {
                    this._addVariableDeclarations(resolvedDecl, result, recursiveDeclCache);
                }
                else if ((0, declaration_1.isClassDeclaration)(resolvedDecl) || (0, declaration_1.isFunctionDeclaration)(resolvedDecl)) {
                    this._addClassOrFunctionDeclarations(resolvedDecl, result, recursiveDeclCache);
                }
            }
        }
    }
    _addClassOrFunctionDeclarations(decl, result, recursiveDeclCache) {
        var _a;
        if ((0, declaration_1.isClassDeclaration)(decl)) {
            if (this._isStubThatShouldBeMappedToImplementation(decl.uri)) {
                (0, collectionUtils_1.appendArray)(result, this._findClassOrTypeAliasDeclarations(decl, recursiveDeclCache));
            }
            else {
                result.push(decl);
            }
        }
        else if ((0, declaration_1.isSpecialBuiltInClassDeclaration)(decl)) {
            result.push(decl);
        }
        else if ((0, declaration_1.isFunctionDeclaration)(decl)) {
            if (this._isStubThatShouldBeMappedToImplementation(decl.uri)) {
                (0, collectionUtils_1.appendArray)(result, this._findFunctionOrTypeAliasDeclarations(decl, recursiveDeclCache));
            }
            else {
                result.push(decl);
            }
        }
        else if ((0, declaration_1.isAliasDeclaration)(decl)) {
            const adjustedDecl = this._handleSpecialBuiltInModule(decl);
            const resolvedDecl = this._evaluator.resolveAliasDeclaration(adjustedDecl, /* resolveLocalNames */ true);
            if (resolvedDecl && !(0, declaration_1.isAliasDeclaration)(resolvedDecl)) {
                this._addClassOrFunctionDeclarations(resolvedDecl, result, recursiveDeclCache);
            }
        }
        else if ((0, declaration_1.isVariableDeclaration)(decl)) {
            // Always add decl. This handles a case where function is dynamically generated such as pandas.read_csv or type alias.
            this._addVariableDeclarations(decl, result, recursiveDeclCache);
            // And try to add the real decl if we can. Sometimes, we can't since import resolver can't follow up the type alias or assignment.
            // Import resolver can't resolve an import that only exists in the lib but not in the stub in certain circumstance.
            const nodeToBind = (_a = decl.typeAliasName) !== null && _a !== void 0 ? _a : decl.node;
            const type = this._evaluator.getType(nodeToBind);
            if (!type) {
                return;
            }
            if ((0, types_1.isFunction)(type) && type.details.declaration) {
                this._addClassOrFunctionDeclarations(type.details.declaration, result, recursiveDeclCache);
            }
            else if ((0, types_1.isOverloadedFunction)(type)) {
                for (const overloadDecl of type.overloads.map((o) => o.details.declaration).filter(core_1.isDefined)) {
                    this._addClassOrFunctionDeclarations(overloadDecl, result, recursiveDeclCache);
                }
            }
            else if ((0, types_1.isInstantiableClass)(type)) {
                this._addClassTypeDeclarations(decl.uri, type, result, recursiveDeclCache);
            }
        }
    }
    _handleSpecialBuiltInModule(decl) {
        // Some stdlib modules import builtin modules that don't actually exist as a file.
        // For example, io.py has an import statement such as from _io import (..., ByteIO)
        // but _io doesn't actually exist on disk so, decl.path will be empty.
        // That means for symbols that belong to _io such as ByteIO, our regular method
        // won't work. to make it work, this method does 2 things, first, it fakes path
        // to _io in stdlib path which doesn't actually exist and call getSourceFiles to
        // generate or extract builtin module info from runtime, the same way we do for builtin.pyi,
        // and second, clone the given decl and set path to the generated pyi for the
        // builtin module (ex, _io) to make resolveAliasDeclaration to work.
        // once the path is set, our regular code path will work as expected.
        if (!decl.uri.isEmpty() || !decl.node) {
            // If module actually exists, nothing we need to do.
            return decl;
        }
        // See if it is one of those special cases.
        if (decl.moduleName !== 'io' && decl.moduleName !== 'collections') {
            return decl;
        }
        const stdLibPath = this._importResolver.getTypeshedStdLibPath(this._execEnv);
        if (!stdLibPath) {
            return decl;
        }
        const fileInfo = ParseTreeUtils.getFileInfoFromNode(decl.node);
        if (!fileInfo) {
            return decl;
        }
        // ImportResolver might be able to generate or extract builtin module's info
        // from runtime if we provide right synthesized stub path.
        const fakeStubPath = stdLibPath.combinePaths(getModuleName()
            .nameParts.map((n) => n.value)
            .join('.') + '.pyi');
        const sources = this._getSourceFiles(fakeStubPath, fileInfo.fileUri);
        if (sources.length === 0) {
            return decl;
        }
        const synthesizedDecl = { ...decl };
        synthesizedDecl.uri = sources[0].getUri();
        return synthesizedDecl;
        function getModuleName() {
            switch (decl.node.nodeType) {
                case 21 /* ParseNodeType.ImportAs */:
                    return decl.node.module;
                case 23 /* ParseNodeType.ImportFromAs */:
                    return decl.node.parent.module;
                case 22 /* ParseNodeType.ImportFrom */:
                    return decl.node.module;
                default:
                    return (0, debug_1.assertNever)(decl.node);
            }
        }
    }
    _addClassTypeDeclarations(originated, type, result, recursiveDeclCache, useTypeAlias = false) {
        const fileUri = useTypeAlias && type.typeAliasInfo ? type.typeAliasInfo.fileUri : type.details.fileUri;
        const sourceFiles = this._getSourceFiles(fileUri, /* stubToShadow */ undefined, originated);
        const fullName = useTypeAlias && type.typeAliasInfo ? type.typeAliasInfo.fullName : type.details.fullName;
        const moduleName = useTypeAlias && type.typeAliasInfo ? type.typeAliasInfo.moduleName : type.details.moduleName;
        const fullClassName = fullName.substring(moduleName.length + 1 /* +1 for trailing dot */);
        for (const sourceFile of sourceFiles) {
            (0, collectionUtils_1.appendArray)(result, this._findClassDeclarationsByName(sourceFile, fullClassName, recursiveDeclCache));
        }
    }
    _getSourceFiles(fileUri, stubToShadow, originated) {
        const sourceFiles = [];
        if (this._isStubThatShouldBeMappedToImplementation(fileUri)) {
            (0, collectionUtils_1.appendArray)(sourceFiles, this._getBoundSourceFilesFromStubFile(fileUri, stubToShadow, originated));
        }
        else {
            const sourceFileInfo = this._boundSourceGetter(fileUri);
            if (sourceFileInfo) {
                sourceFiles.push(sourceFileInfo.sourceFile);
            }
        }
        return sourceFiles;
    }
    _addDeclarationsFollowingWildcardImports(moduleNode, symbolName, result, recursiveDeclCache) {
        var _a, _b;
        // Symbol exists in a stub doesn't exist in a python file. Use some heuristic
        // to find one from sources.
        const table = (_a = AnalyzerNodeInfo.getScope(moduleNode)) === null || _a === void 0 ? void 0 : _a.symbolTable;
        if (!table) {
            return;
        }
        // Dig down imports with wildcard imports.
        for (const symbol of table.values()) {
            for (const decl of symbol.getDeclarations()) {
                if (!(0, declaration_1.isAliasDeclaration)(decl) ||
                    decl.uri.isEmpty() ||
                    decl.node.nodeType !== 22 /* ParseNodeType.ImportFrom */ ||
                    !decl.node.isWildcardImport) {
                    continue;
                }
                const uniqueId = `@${decl.uri.key}/l/${symbolName}`;
                if (recursiveDeclCache.has(uniqueId)) {
                    continue;
                }
                // While traversing these tables, we may encounter the same decl
                // more than once (via different files' wildcard imports). To avoid this,
                // add an ID unique to this function to the recursiveDeclCache to deduplicate
                // them.
                //
                // The ID is not deleted to avoid needing a second Set to track all decls
                // seen in this function. This is safe because the ID here is unique to this
                // function.
                recursiveDeclCache.add(uniqueId);
                const sourceFiles = this._getSourceFiles(decl.uri);
                for (const sourceFile of sourceFiles) {
                    const moduleNode = (_b = sourceFile.getParserOutput()) === null || _b === void 0 ? void 0 : _b.parseTree;
                    if (!moduleNode) {
                        continue;
                    }
                    const decls = this._lookUpSymbolDeclarations(moduleNode, symbolName);
                    if (decls.length === 0) {
                        this._addDeclarationsFollowingWildcardImports(moduleNode, symbolName, result, recursiveDeclCache);
                    }
                    else {
                        for (const decl of decls) {
                            const resolvedDecl = this._evaluator.resolveAliasDeclaration(decl, 
                            /* resolveLocalNames */ true);
                            if (!resolvedDecl) {
                                continue;
                            }
                            if ((0, declaration_1.isFunctionDeclaration)(resolvedDecl) || (0, declaration_1.isClassDeclaration)(resolvedDecl)) {
                                this._addClassOrFunctionDeclarations(resolvedDecl, result, recursiveDeclCache);
                            }
                            else if ((0, declaration_1.isVariableDeclaration)(resolvedDecl)) {
                                this._addVariableDeclarations(resolvedDecl, result, recursiveDeclCache);
                            }
                        }
                    }
                }
            }
        }
    }
    _lookUpSymbolDeclarations(node, symbolName) {
        if (node === undefined) {
            return [];
        }
        const containingScope = AnalyzerNodeInfo.getScope(node);
        const symbol = containingScope === null || containingScope === void 0 ? void 0 : containingScope.lookUpSymbol(symbolName);
        const decls = symbol === null || symbol === void 0 ? void 0 : symbol.getDeclarations();
        return decls !== null && decls !== void 0 ? decls : [];
    }
    _getFullClassName(node) {
        const fullName = [];
        let current = node;
        while (current !== undefined) {
            fullName.push(current.name.value);
            current = ParseTreeUtils.getEnclosingClass(current);
        }
        return fullName.reverse().join('.');
    }
    _getBoundSourceFilesFromStubFile(stubFileUri, stubToShadow, originated) {
        var _a;
        const paths = this._getSourcePathsFromStub(stubFileUri, originated !== null && originated !== void 0 ? originated : (_a = this._fromFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getUri());
        return paths.map((fp) => this._fileBinder(stubToShadow !== null && stubToShadow !== void 0 ? stubToShadow : stubFileUri, fp)).filter(core_1.isDefined);
    }
    _getSourcePathsFromStub(stubFileUri, fromFile) {
        // Attempt our stubFileUri to see if we can resolve it as a source file path
        let results = this._importResolver.getSourceFilesFromStub(stubFileUri, this._execEnv, this._mapCompiled);
        if (results.length > 0) {
            return results;
        }
        // If that didn't work, try looking through the graph up to our fromFile.
        // One of them should be able to resolve to an actual file.
        const stubFileImportTree = this._getStubFileImportTree(stubFileUri, fromFile);
        // Go through the items in this tree until we find at least one path.
        for (let i = 0; i < stubFileImportTree.length; i++) {
            results = this._importResolver.getSourceFilesFromStub(stubFileImportTree[i], this._execEnv, this._mapCompiled);
            if (results.length > 0) {
                return results;
            }
        }
        return [];
    }
    _getStubFileImportTree(stubFileUri, fromFile) {
        if (!fromFile || !this._isStubThatShouldBeMappedToImplementation(stubFileUri)) {
            // No path to search, just return the starting point.
            return [stubFileUri];
        }
        else {
            // Otherwise recurse through the importedBy list up to our 'fromFile'.
            return (0, sourceMapperUtils_1.buildImportTree)(fromFile, stubFileUri, (p) => {
                const boundSourceInfo = this._boundSourceGetter(p);
                return boundSourceInfo ? boundSourceInfo.importedBy.map((info) => info.sourceFile.getUri()) : [];
            }, this._cancelToken).filter((p) => this._isStubThatShouldBeMappedToImplementation(p));
        }
    }
    _isStubThatShouldBeMappedToImplementation(fileUri) {
        if (this._preferStubs) {
            return false;
        }
        const stub = isStubFile(fileUri);
        if (!stub) {
            return false;
        }
        // If we get the same file as a source file, then we treat the file as a regular file even if it has "pyi" extension.
        return this._importResolver
            .getSourceFilesFromStub(fileUri, this._execEnv, this._mapCompiled)
            .every((f) => f !== fileUri);
    }
}
exports.SourceMapper = SourceMapper;
function isStubFile(uri) {
    return uri.lastExtension === '.pyi';
}
exports.isStubFile = isStubFile;


/***/ }),

/***/ "../pyright-internal/src/analyzer/sourceMapperUtils.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/analyzer/sourceMapperUtils.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * sourceMapperUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.buildImportTree = void 0;
const MAX_TREE_SEARCH_COUNT = 1000;
class NumberReference {
    constructor() {
        this.value = 0;
    }
}
// Builds an array of imports from the 'from' to the 'to' entry where 'from'
// is on the front of the array and the item just before 'to' is on the
// back of the array.
function buildImportTree(to, from, next, token) {
    const totalCountRef = new NumberReference();
    const results = _buildImportTreeImpl(to, from, next, [], totalCountRef, token);
    // Result should always have the 'from' node in it.
    return results.length > 0 ? results : [from];
}
exports.buildImportTree = buildImportTree;
function _buildImportTreeImpl(to, from, next, previous, totalSearched, token) {
    // Exit early if cancellation is requested or we've exceeded max count
    if (totalSearched.value > MAX_TREE_SEARCH_COUNT || token.isCancellationRequested) {
        return [];
    }
    totalSearched.value += 1;
    if (from.equals(to)) {
        // At the top, previous should have our way into this recursion.
        return previous.length ? previous : [from];
    }
    if (previous.length > 1 && previous.find((s) => s.equals(from))) {
        // Fail the search, we're stuck in a loop.
        return [];
    }
    const nextEntries = next(from);
    for (let i = 0; i < nextEntries.length && !token.isCancellationRequested; i++) {
        // Do a search through the next level to get to the 'to' entry.
        const subentries = _buildImportTreeImpl(to, nextEntries[i], next, [...previous, from], totalSearched, token);
        if (subentries.length > 0) {
            return subentries;
        }
    }
    // Search failed on this tree. Fail so we can exit recursion.
    return [];
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/staticExpressions.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/analyzer/staticExpressions.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * staticExpressions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Functions that operate on expressions (parse node trees)
 * whose values can be evaluated statically.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.evaluateStaticBoolLikeExpression = exports.evaluateStaticBoolExpression = void 0;
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
// Returns undefined if the expression cannot be evaluated
// statically as a bool value or true/false if it can.
function evaluateStaticBoolExpression(node, execEnv, definedConstants, typingImportAliases, sysImportAliases) {
    if (node.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
        return evaluateStaticBoolExpression(node.rightExpression, execEnv, definedConstants, typingImportAliases, sysImportAliases);
    }
    if (node.nodeType === 55 /* ParseNodeType.UnaryOperation */) {
        if (node.operator === 38 /* OperatorType.Not */) {
            const value = evaluateStaticBoolLikeExpression(node.expression, execEnv, definedConstants, typingImportAliases, sysImportAliases);
            if (value !== undefined) {
                return !value;
            }
        }
    }
    else if (node.nodeType === 7 /* ParseNodeType.BinaryOperation */) {
        // Is it an OR or AND expression?
        if (node.operator === 37 /* OperatorType.Or */ || node.operator === 36 /* OperatorType.And */) {
            const leftValue = evaluateStaticBoolExpression(node.leftExpression, execEnv, definedConstants, typingImportAliases, sysImportAliases);
            const rightValue = evaluateStaticBoolExpression(node.rightExpression, execEnv, definedConstants, typingImportAliases, sysImportAliases);
            if (leftValue === undefined || rightValue === undefined) {
                return undefined;
            }
            if (node.operator === 37 /* OperatorType.Or */) {
                return leftValue || rightValue;
            }
            else {
                return leftValue && rightValue;
            }
        }
        if (_isSysVersionInfoExpression(node.leftExpression, sysImportAliases) &&
            node.rightExpression.nodeType === 52 /* ParseNodeType.Tuple */) {
            // Handle the special case of "sys.version_info >= (3, x)"
            const comparisonVersion = _convertTupleToVersion(node.rightExpression);
            return _evaluateVersionBinaryOperation(node.operator, execEnv.pythonVersion, comparisonVersion);
        }
        if (node.leftExpression.nodeType === 24 /* ParseNodeType.Index */ &&
            _isSysVersionInfoExpression(node.leftExpression.baseExpression, sysImportAliases) &&
            node.leftExpression.items.length === 1 &&
            !node.leftExpression.trailingComma &&
            !node.leftExpression.items[0].name &&
            node.leftExpression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
            node.leftExpression.items[0].valueExpression.nodeType === 40 /* ParseNodeType.Number */ &&
            !node.leftExpression.items[0].valueExpression.isImaginary &&
            node.leftExpression.items[0].valueExpression.value === 0 &&
            node.rightExpression.nodeType === 40 /* ParseNodeType.Number */ &&
            node.rightExpression.isInteger &&
            typeof node.rightExpression.value === 'number') {
            // Handle the special case of "sys.version_info[0] >= X"
            return _evaluateVersionBinaryOperation(node.operator, new pythonVersion_1.PythonVersion(execEnv.pythonVersion.major, 0), new pythonVersion_1.PythonVersion(node.rightExpression.value, 0));
        }
        if (_isSysPlatformInfoExpression(node.leftExpression, sysImportAliases) &&
            node.rightExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            // Handle the special case of "sys.platform != 'X'"
            const comparisonPlatform = node.rightExpression.strings.map((s) => s.value).join('');
            const expectedPlatformName = _getExpectedPlatformNameFromPlatform(execEnv);
            return _evaluateStringBinaryOperation(node.operator, expectedPlatformName, comparisonPlatform);
        }
        if (_isOsNameInfoExpression(node.leftExpression) &&
            node.rightExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            // Handle the special case of "os.name == 'X'"
            const comparisonOsName = node.rightExpression.strings.map((s) => s.value).join('');
            const expectedOsName = _getExpectedOsNameFromPlatform(execEnv);
            if (expectedOsName !== undefined) {
                return _evaluateStringBinaryOperation(node.operator, expectedOsName, comparisonOsName);
            }
        }
        else {
            // Handle the special case of <definedConstant> == 'X' or <definedConstant> != 'X'.
            if (node.rightExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                let constantValue;
                if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    constantValue = definedConstants.get(node.leftExpression.value);
                }
                else if (node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                    constantValue = definedConstants.get(node.leftExpression.memberName.value);
                }
                if (constantValue !== undefined && typeof constantValue === 'string') {
                    const comparisonStringName = node.rightExpression.strings.map((s) => s.value).join('');
                    return _evaluateStringBinaryOperation(node.operator, constantValue, comparisonStringName);
                }
            }
        }
    }
    else if (node.nodeType === 11 /* ParseNodeType.Constant */) {
        if (node.constType === 33 /* KeywordType.True */) {
            return true;
        }
        else if (node.constType === 15 /* KeywordType.False */) {
            return false;
        }
    }
    else if (node.nodeType === 38 /* ParseNodeType.Name */) {
        if (node.value === 'TYPE_CHECKING') {
            return true;
        }
        const constant = definedConstants.get(node.value);
        if (constant !== undefined) {
            return !!constant;
        }
    }
    else if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        if (typingImportAliases &&
            node.memberName.value === 'TYPE_CHECKING' &&
            node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            typingImportAliases.some((alias) => alias === node.leftExpression.value)) {
            return true;
        }
        const constant = definedConstants.get(node.memberName.value);
        if (constant !== undefined) {
            return !!constant;
        }
    }
    return undefined;
}
exports.evaluateStaticBoolExpression = evaluateStaticBoolExpression;
// Similar to evaluateStaticBoolExpression except that it handles
// other non-bool values that are statically falsy or truthy
// (like "None").
function evaluateStaticBoolLikeExpression(node, execEnv, definedConstants, typingImportAliases, sysImportAliases) {
    if (node.nodeType === 11 /* ParseNodeType.Constant */) {
        if (node.constType === 26 /* KeywordType.None */) {
            return false;
        }
    }
    return evaluateStaticBoolExpression(node, execEnv, definedConstants, typingImportAliases, sysImportAliases);
}
exports.evaluateStaticBoolLikeExpression = evaluateStaticBoolLikeExpression;
function _convertTupleToVersion(node) {
    if (node.expressions.length >= 2) {
        if (node.expressions[0].nodeType === 40 /* ParseNodeType.Number */ &&
            !node.expressions[0].isImaginary &&
            node.expressions[1].nodeType === 40 /* ParseNodeType.Number */ &&
            !node.expressions[1].isImaginary) {
            const majorNode = node.expressions[0];
            const minorNode = node.expressions[1];
            if (typeof majorNode.value !== 'number' || typeof minorNode.value !== 'number') {
                return undefined;
            }
            const major = majorNode.value;
            const minor = minorNode.value;
            let micro;
            if (node.expressions.length >= 3 &&
                node.expressions[2].nodeType === 40 /* ParseNodeType.Number */ &&
                !node.expressions[2].isImaginary &&
                typeof node.expressions[2].value === 'number') {
                micro = node.expressions[2].value;
            }
            let releaseLevel;
            if (node.expressions.length >= 4 &&
                node.expressions[3].nodeType === 48 /* ParseNodeType.StringList */ &&
                node.expressions[3].strings.length === 1 &&
                node.expressions[3].strings[0].nodeType === 49 /* ParseNodeType.String */) {
                releaseLevel = node.expressions[3].strings[0].value;
            }
            let serial;
            if (node.expressions.length >= 5 &&
                node.expressions[4].nodeType === 40 /* ParseNodeType.Number */ &&
                !node.expressions[4].isImaginary &&
                typeof node.expressions[4].value === 'number') {
                serial = node.expressions[4].value;
            }
            return new pythonVersion_1.PythonVersion(major, minor, micro, releaseLevel, serial);
        }
    }
    else if (node.expressions.length === 1) {
        const major = node.expressions[0];
        if (typeof major.value === 'number') {
            return new pythonVersion_1.PythonVersion(major.value, 0);
        }
    }
    return undefined;
}
function _evaluateVersionBinaryOperation(operatorType, leftValue, rightValue) {
    if (leftValue !== undefined && rightValue !== undefined) {
        if (operatorType === 20 /* OperatorType.LessThan */) {
            return leftValue.isLessThan(rightValue);
        }
        if (operatorType === 21 /* OperatorType.LessThanOrEqual */) {
            return leftValue.isLessOrEqualTo(rightValue);
        }
        if (operatorType === 15 /* OperatorType.GreaterThan */) {
            return leftValue.isGreaterThan(rightValue);
        }
        if (operatorType === 16 /* OperatorType.GreaterThanOrEqual */) {
            return leftValue.isGreaterOrEqualTo(rightValue);
        }
        if (operatorType === 12 /* OperatorType.Equals */) {
            return leftValue.isEqualTo(rightValue);
        }
        if (operatorType === 28 /* OperatorType.NotEquals */) {
            return !leftValue.isEqualTo(rightValue);
        }
    }
    return undefined;
}
function _evaluateStringBinaryOperation(operatorType, leftValue, rightValue) {
    if (leftValue !== undefined && rightValue !== undefined) {
        if (operatorType === 12 /* OperatorType.Equals */) {
            return leftValue === rightValue;
        }
        else if (operatorType === 28 /* OperatorType.NotEquals */) {
            return leftValue !== rightValue;
        }
    }
    return undefined;
}
function _isSysVersionInfoExpression(node, sysImportAliases = ['sys']) {
    if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.memberName.value === 'version_info') {
            if (sysImportAliases.some((alias) => alias === node.leftExpression.value)) {
                return true;
            }
        }
    }
    return false;
}
function _isSysPlatformInfoExpression(node, sysImportAliases = ['sys']) {
    if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.memberName.value === 'platform') {
            if (sysImportAliases.some((alias) => alias === node.leftExpression.value)) {
                return true;
            }
        }
    }
    return false;
}
function _isOsNameInfoExpression(node) {
    if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            node.leftExpression.value === 'os' &&
            node.memberName.value === 'name') {
            return true;
        }
    }
    return false;
}
function _getExpectedPlatformNameFromPlatform(execEnv) {
    if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Darwin) {
        return 'darwin';
    }
    else if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Windows) {
        return 'win32';
    }
    else if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Linux) {
        return 'linux';
    }
    return undefined;
}
function _getExpectedOsNameFromPlatform(execEnv) {
    if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Darwin) {
        return 'posix';
    }
    else if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Windows) {
        return 'nt';
    }
    else if (execEnv.pythonPlatform === configOptions_1.PythonPlatform.Linux) {
        return 'posix';
    }
    return undefined;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/symbol.ts":
/*!**************************************************!*\
  !*** ../pyright-internal/src/analyzer/symbol.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * symbol.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Represents an association between a name and the type
 * (or multiple types) that the symbol is associated with
 * in the program.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Symbol = exports.indeterminateSymbolId = void 0;
const declarationUtils_1 = __webpack_require__(/*! ./declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
let nextSymbolId = 1;
function getUniqueSymbolId() {
    return nextSymbolId++;
}
// Symbol ID that indicates that there is no specific symbol.
exports.indeterminateSymbolId = 0;
class Symbol {
    constructor(flags) {
        this.id = getUniqueSymbolId();
        this._flags = flags;
    }
    static createWithType(flags, type) {
        const newSymbol = new Symbol(flags);
        newSymbol._synthesizedType = type;
        return newSymbol;
    }
    isInitiallyUnbound() {
        return !!(this._flags & 1 /* SymbolFlags.InitiallyUnbound */);
    }
    setIsExternallyHidden() {
        this._flags |= 2 /* SymbolFlags.ExternallyHidden */;
    }
    isExternallyHidden() {
        return !!(this._flags & 2 /* SymbolFlags.ExternallyHidden */);
    }
    setIsIgnoredForProtocolMatch() {
        this._flags |= 64 /* SymbolFlags.IgnoredForProtocolMatch */;
    }
    isIgnoredForProtocolMatch() {
        return !!(this._flags & 64 /* SymbolFlags.IgnoredForProtocolMatch */);
    }
    setIsClassMember() {
        this._flags |= 4 /* SymbolFlags.ClassMember */;
    }
    isClassMember() {
        return !!(this._flags & 4 /* SymbolFlags.ClassMember */);
    }
    setIsInstanceMember() {
        this._flags |= 8 /* SymbolFlags.InstanceMember */;
    }
    isInstanceMember() {
        return !!(this._flags & 8 /* SymbolFlags.InstanceMember */);
    }
    setIsClassVar() {
        this._flags |= 128 /* SymbolFlags.ClassVar */;
    }
    isClassVar() {
        return !!(this._flags & 128 /* SymbolFlags.ClassVar */);
    }
    setIsFinalVarInClassBody() {
        this._flags |= 8192 /* SymbolFlags.FinalVarInClassBody */;
    }
    isFinalVarInClassBody() {
        return !!(this._flags & 8192 /* SymbolFlags.FinalVarInClassBody */);
    }
    setIsInitVar() {
        this._flags |= 1024 /* SymbolFlags.InitVar */;
    }
    isInitVar() {
        return !!(this._flags & 1024 /* SymbolFlags.InitVar */);
    }
    setIsInDunderAll() {
        this._flags |= 256 /* SymbolFlags.InDunderAll */;
    }
    isInDunderAll() {
        return !!(this._flags & 256 /* SymbolFlags.InDunderAll */);
    }
    setIsPrivateMember() {
        this._flags |= 32 /* SymbolFlags.PrivateMember */;
    }
    isPrivateMember() {
        return !!(this._flags & 32 /* SymbolFlags.PrivateMember */);
    }
    setPrivatePyTypedImport() {
        this._flags |= 512 /* SymbolFlags.PrivatePyTypedImport */;
    }
    isPrivatePyTypedImport() {
        return !!(this._flags & 512 /* SymbolFlags.PrivatePyTypedImport */);
    }
    setPrivateLocalImport() {
        this._flags |= 16384 /* SymbolFlags.PrivateLocalImport */;
    }
    isPrivateLocalImport() {
        return !!(this._flags & 16384 /* SymbolFlags.PrivateLocalImport */);
    }
    isNamedTupleMemberMember() {
        return !!(this._flags & 2048 /* SymbolFlags.NamedTupleMember */);
    }
    isIgnoredForOverrideChecks() {
        return !!(this._flags & 4096 /* SymbolFlags.IgnoredForOverrideChecks */);
    }
    addDeclaration(declaration) {
        if (this._declarations) {
            // See if this node was already identified as a declaration. If so,
            // replace it. Otherwise, add it as a new declaration to the end of
            // the list.
            const declIndex = this._declarations.findIndex((decl) => (0, declarationUtils_1.areDeclarationsSame)(decl, declaration));
            if (declIndex < 0) {
                this._declarations.push(declaration);
                // If there is more than one declaration for a symbol, we will
                // assume it is not a type alias.
                this._declarations.forEach((decl) => {
                    if (decl.type === 1 /* DeclarationType.Variable */ && decl.typeAliasName) {
                        delete decl.typeAliasName;
                    }
                });
            }
            else {
                // If the new declaration has a defined type, it should replace
                // the existing one.
                const curDecl = this._declarations[declIndex];
                if ((0, declarationUtils_1.hasTypeForDeclaration)(declaration)) {
                    this._declarations[declIndex] = declaration;
                    if (curDecl.type === 1 /* DeclarationType.Variable */ && declaration.type === 1 /* DeclarationType.Variable */) {
                        if (!declaration.inferredTypeSource && curDecl.inferredTypeSource) {
                            declaration.inferredTypeSource = curDecl.inferredTypeSource;
                        }
                    }
                }
                else if (declaration.type === 1 /* DeclarationType.Variable */) {
                    // If it's marked "final" or "type alias", this should be reflected
                    // in the existing declaration. Likewise, if the existing declaration
                    // doesn't have a type source, add it.
                    if (curDecl.type === 1 /* DeclarationType.Variable */) {
                        if (declaration.isFinal) {
                            curDecl.isFinal = true;
                        }
                        curDecl.typeAliasName = declaration.typeAliasName;
                        if (!curDecl.inferredTypeSource && declaration.inferredTypeSource) {
                            curDecl.inferredTypeSource = declaration.inferredTypeSource;
                        }
                    }
                }
            }
        }
        else {
            this._declarations = [declaration];
        }
    }
    hasDeclarations() {
        return this._declarations ? this._declarations.length > 0 : false;
    }
    getDeclarations() {
        return this._declarations ? this._declarations : [];
    }
    hasTypedDeclarations() {
        // We'll treat an synthesized type as an implicit declaration.
        if (this._synthesizedType) {
            return true;
        }
        return this.getDeclarations().some((decl) => (0, declarationUtils_1.hasTypeForDeclaration)(decl));
    }
    getTypedDeclarations() {
        return this.getDeclarations().filter((decl) => (0, declarationUtils_1.hasTypeForDeclaration)(decl));
    }
    getSynthesizedType() {
        return this._synthesizedType;
    }
}
exports.Symbol = Symbol;


/***/ }),

/***/ "../pyright-internal/src/analyzer/symbolNameUtils.ts":
/*!***********************************************************!*\
  !*** ../pyright-internal/src/analyzer/symbolNameUtils.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * symbolNameUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Static methods that apply to symbols or symbol names.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPublicConstantOrTypeAlias = exports.isTypeAliasName = exports.isConstantName = exports.isUnderscoreOnlyName = exports.isSingleDunderName = exports.isDunderName = exports.isPrivateOrProtectedName = exports.isProtectedName = exports.isPrivateName = void 0;
const _constantRegEx = /^[A-Z0-9_]+$/;
const _underscoreOnlyRegEx = /^[_]+$/;
const _camelCaseRegEx = /^_{0,2}[A-Z][A-Za-z0-9_]+$/;
// Private symbol names start with a double underscore.
function isPrivateName(name) {
    return name.length > 2 && name.startsWith('__') && !name.endsWith('__');
}
exports.isPrivateName = isPrivateName;
// Protected symbol names start with a single underscore.
function isProtectedName(name) {
    return name.length > 1 && name.startsWith('_') && !name.startsWith('__');
}
exports.isProtectedName = isProtectedName;
function isPrivateOrProtectedName(name) {
    return isPrivateName(name) || isProtectedName(name);
}
exports.isPrivateOrProtectedName = isPrivateOrProtectedName;
// "Dunder" names start and end with two underscores.
function isDunderName(name) {
    return name.length > 4 && name.startsWith('__') && name.endsWith('__');
}
exports.isDunderName = isDunderName;
// "Single Dunder" names start and end with single underscores.
function isSingleDunderName(name) {
    return name.length > 2 && name.startsWith('_') && name.endsWith('_');
}
exports.isSingleDunderName = isSingleDunderName;
/** underscore-only names mean a value is being intentionally ignored */
const isUnderscoreOnlyName = (name) => name.match(_underscoreOnlyRegEx);
exports.isUnderscoreOnlyName = isUnderscoreOnlyName;
// Constants are all-caps with possible numbers and underscores.
function isConstantName(name) {
    return !!name.match(_constantRegEx) && !(0, exports.isUnderscoreOnlyName)(name);
}
exports.isConstantName = isConstantName;
// Type aliases are CamelCase with possible numbers and underscores.
function isTypeAliasName(name) {
    return !!name.match(_camelCaseRegEx);
}
exports.isTypeAliasName = isTypeAliasName;
function isPublicConstantOrTypeAlias(name) {
    return !isPrivateOrProtectedName(name) && (isConstantName(name) || isTypeAliasName(name));
}
exports.isPublicConstantOrTypeAlias = isPublicConstantOrTypeAlias;


/***/ }),

/***/ "../pyright-internal/src/analyzer/symbolUtils.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/analyzer/symbolUtils.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * symbolUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Functions that operate on Symbol objects.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isEffectivelyClassVar = exports.isVisibleExternally = exports.isTypedDictMemberAccessedThroughIndex = exports.getLastTypedDeclarationForSymbol = void 0;
function getLastTypedDeclarationForSymbol(symbol) {
    const typedDecls = symbol.getTypedDeclarations();
    if (typedDecls.length > 0) {
        return typedDecls[typedDecls.length - 1];
    }
    return undefined;
}
exports.getLastTypedDeclarationForSymbol = getLastTypedDeclarationForSymbol;
// Within TypedDict classes, member variables are not accessible as
// normal attributes. Instead, they are accessed through index operations.
function isTypedDictMemberAccessedThroughIndex(symbol) {
    const typedDecls = symbol.getTypedDeclarations();
    if (typedDecls.length > 0) {
        const lastDecl = typedDecls[typedDecls.length - 1];
        if (lastDecl.type === 1 /* DeclarationType.Variable */) {
            return true;
        }
    }
    return false;
}
exports.isTypedDictMemberAccessedThroughIndex = isTypedDictMemberAccessedThroughIndex;
function isVisibleExternally(symbol) {
    return !symbol.isExternallyHidden() && !symbol.isPrivatePyTypedImport();
}
exports.isVisibleExternally = isVisibleExternally;
function isEffectivelyClassVar(symbol, isInDataclass) {
    if (symbol.isClassVar()) {
        return true;
    }
    if (symbol.isFinalVarInClassBody()) {
        return !isInDataclass;
    }
    return false;
}
exports.isEffectivelyClassVar = isEffectivelyClassVar;


/***/ }),

/***/ "../pyright-internal/src/analyzer/testWalker.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/testWalker.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * testWalker.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Walks a parse tree to validate internal consistency and completeness.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NameTypeWalker = exports.TestWalker = void 0;
const parseTreeWalker_1 = __webpack_require__(/*! ../analyzer/parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
class TestWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor() {
        super();
    }
    visitNode(node) {
        const children = super.visitNode(node);
        this._verifyParentChildLinks(node, children);
        this._verifyChildRanges(node, children);
        return children;
    }
    // Make sure that all of the children point to their parent.
    _verifyParentChildLinks(node, children) {
        children.forEach((child) => {
            if (child) {
                if (child.parent !== node) {
                    (0, debug_1.fail)(`Child node ${child.nodeType} does not ` + `contain a reference to its parent ${node.nodeType}`);
                }
            }
        });
    }
    // Verify that:
    //      Children are all contained within the parent
    //      Children have non-overlapping ranges
    //      Children are listed in increasing order
    _verifyChildRanges(node, children) {
        let prevNode;
        const compliant = (0, parseTreeUtils_1.isCompliantWithNodeRangeRules)(node);
        children.forEach((child) => {
            if (child) {
                let skipCheck = false;
                if (!compliant) {
                    switch (node.nodeType) {
                        case 3 /* ParseNodeType.Assignment */:
                            // There are a few exceptions we need to deal with here. Comment
                            // annotations can occur outside of an assignment node's range.
                            if (child === node.typeAnnotationComment) {
                                skipCheck = true;
                            }
                            // Portions of chained assignments can occur outside of an
                            // assignment node's range.
                            if (child.nodeType === 3 /* ParseNodeType.Assignment */) {
                                skipCheck = true;
                            }
                            break;
                        case 48 /* ParseNodeType.StringList */:
                            if (child === node.typeAnnotation) {
                                skipCheck = true;
                            }
                            break;
                        default:
                            (0, debug_1.fail)(`node ${node.nodeType} is not marked as not following range rules.`);
                    }
                }
                if (!skipCheck) {
                    // Make sure the child is contained within the parent.
                    if (child.start < node.start || textRange_1.TextRange.getEnd(child) > textRange_1.TextRange.getEnd(node)) {
                        (0, debug_1.fail)(`Child node ${child.nodeType} is not contained within its parent ${node.nodeType}`);
                    }
                    if (prevNode) {
                        // Make sure the child is after the previous child.
                        if (child.start < textRange_1.TextRange.getEnd(prevNode)) {
                            // Special-case the function annotation which can "bleed" into the suite.
                            if (prevNode.nodeType !== 62 /* ParseNodeType.FunctionAnnotation */) {
                                (0, debug_1.fail)(`Child node is not after previous child node`);
                            }
                        }
                    }
                    prevNode = child;
                }
            }
        });
    }
}
exports.TestWalker = TestWalker;
// Custom parse node walker that evaluates the types of all
// NameNodes. This helps find bugs in evaluation ordering.
class NameTypeWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_evaluator) {
        super();
        this._evaluator = _evaluator;
    }
    visitName(node) {
        var _a, _b;
        if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 23 /* ParseNodeType.ImportFromAs */ && ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) !== 21 /* ParseNodeType.ImportAs */) {
            if (this._evaluator.isNodeReachable(node, /* sourceNode */ undefined)) {
                this._evaluator.getType(node);
            }
        }
        return true;
    }
}
exports.NameTypeWalker = NameTypeWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/tracePrinter.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/analyzer/tracePrinter.ts ***!
  \********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * tracePrinter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Converts various types into string representations.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createTracePrinter = void 0;
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
function createTracePrinter(roots) {
    function wrap(value, ch = "'") {
        return value ? `${ch}${value}${ch}` : '';
    }
    // Sort roots in desc order so that we compare longer path first
    // when getting relative path.
    // ex) d:/root/.env/lib/site-packages, d:/root/.env
    roots = roots.sort((a, b) => a.key.localeCompare(b.key)).reverse();
    const separatorRegExp = /[\\/]/g;
    function printFileOrModuleName(fileUriOrModule) {
        if (fileUriOrModule) {
            if (uri_1.Uri.is(fileUriOrModule)) {
                for (const root of roots) {
                    if (fileUriOrModule.isChild(root)) {
                        const subFile = root.getRelativePath(fileUriOrModule);
                        return (0, pathUtils_1.stripFileExtension)(subFile).replace(separatorRegExp, '.');
                    }
                }
                return fileUriOrModule.toUserVisibleString();
            }
            else if (fileUriOrModule.nameParts) {
                return fileUriOrModule.nameParts.join('.');
            }
        }
        return '';
    }
    function printType(type) {
        var _a, _b, _c, _d, _e;
        if (type) {
            switch (type.category) {
                case 2 /* TypeCategory.Any */:
                    return `Any ${wrap((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.fullName)}`;
                case 6 /* TypeCategory.Class */:
                    if (types_1.TypeBase.isInstantiable(type)) {
                        return `Class '${type.details.name}' (${type.details.moduleName})`;
                    }
                    else {
                        return `Object '${type.details.name}' (${type.details.moduleName})`;
                    }
                case 4 /* TypeCategory.Function */:
                    return `Function '${type.details.name}' (${type.details.moduleName})`;
                case 7 /* TypeCategory.Module */:
                    return `Module '${type.moduleName}' (${type.moduleName})`;
                case 3 /* TypeCategory.Never */:
                    return `Never ${wrap((_b = type.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.fullName)}`;
                case 5 /* TypeCategory.OverloadedFunction */:
                    return `OverloadedFunction [${type.overloads.map((o) => wrap(printType(o), '"')).join(',')}]`;
                case 9 /* TypeCategory.TypeVar */:
                    return `TypeVar '${type.details.name}' ${wrap((_c = type.typeAliasInfo) === null || _c === void 0 ? void 0 : _c.fullName)}`;
                case 0 /* TypeCategory.Unbound */:
                    return `Unbound ${wrap((_d = type.typeAliasInfo) === null || _d === void 0 ? void 0 : _d.fullName)}`;
                case 8 /* TypeCategory.Union */:
                    return `Union [${type.subtypes.map((o) => wrap(printType(o), '"')).join(',')}]`;
                case 1 /* TypeCategory.Unknown */:
                    return `Unknown ${wrap((_e = type.typeAliasInfo) === null || _e === void 0 ? void 0 : _e.fullName)}`;
                default:
                    (0, debug_1.assertNever)(type);
            }
        }
        return '';
    }
    function printSymbol(symbol) {
        if (symbol) {
            if (symbol.hasDeclarations()) {
                return `symbol ${printDeclaration(symbol.getDeclarations()[0])}`;
            }
            return `<symbol>`;
        }
        return '';
    }
    function printDeclaration(decl) {
        if (decl) {
            switch (decl.type) {
                case 8 /* DeclarationType.Alias */:
                    return `Alias, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 6 /* DeclarationType.Class */:
                    return `Class, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 5 /* DeclarationType.Function */:
                    return `Function, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 0 /* DeclarationType.Intrinsic */:
                    return `Intrinsic, ${printNode(decl.node)} ${decl.intrinsicType} (${printFileOrModuleName(decl.uri)})`;
                case 2 /* DeclarationType.Parameter */:
                    return `Parameter, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 3 /* DeclarationType.TypeParameter */:
                    return `TypeParameter, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 7 /* DeclarationType.SpecialBuiltInClass */:
                    return `SpecialBuiltInClass, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 1 /* DeclarationType.Variable */:
                    return `Variable, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                case 4 /* DeclarationType.TypeAlias */:
                    return `TypeAlias, ${printNode(decl.node)} (${printFileOrModuleName(decl.uri)})`;
                default:
                    (0, debug_1.assertNever)(decl);
            }
        }
        return '';
    }
    function getFileInfo(node) {
        while (node.nodeType !== 36 /* ParseNodeType.Module */ && node.parent) {
            node = node.parent;
        }
        return node.nodeType === 36 /* ParseNodeType.Module */ ? AnalyzerNodeInfo.getFileInfo(node) : undefined;
    }
    function getText(value, max = 30) {
        if (value.length < max) {
            return value;
        }
        return value.substring(0, max) + ' <shortened> ';
    }
    function printNode(node, printPath = false) {
        var _a;
        if (!node) {
            return '';
        }
        let path = printPath ? `(${printFileOrModuleName((_a = getFileInfo(node)) === null || _a === void 0 ? void 0 : _a.fileUri)})` : '';
        const fileInfo = getFileInfo(node);
        if (fileInfo === null || fileInfo === void 0 ? void 0 : fileInfo.lines) {
            const position = (0, positionUtils_1.convertOffsetToPosition)(node.start, fileInfo.lines);
            path += ` [${position.line + 1}:${position.character + 1}]`;
        }
        if ((0, parseNodes_1.isExpressionNode)(node)) {
            return wrap(getText(ParseTreeUtils.printExpression(node)), '"') + ` ${path}`;
        }
        switch (node.nodeType) {
            case 21 /* ParseNodeType.ImportAs */:
                return `importAs '${printNode(node.module)}' ${wrap(node.alias ? printNode(node.alias) : '')} ${path}`;
            case 22 /* ParseNodeType.ImportFrom */:
                return `importFrom [${node.imports.map((i) => wrap(printNode(i), '"')).join(',')}]`;
            case 23 /* ParseNodeType.ImportFromAs */:
                return `ImportFromAs '${printNode(node.name)}' ${wrap(node.alias ? printNode(node.alias) : '')} ${path}`;
            case 36 /* ParseNodeType.Module */:
                return `module ${path}`;
            case 10 /* ParseNodeType.Class */:
                return `class '${printNode(node.name)}' ${path}`;
            case 28 /* ParseNodeType.Function */:
                return `function '${printNode(node.name)}' ${path}`;
            case 37 /* ParseNodeType.ModuleName */:
                return `moduleName '${node.nameParts.map((n) => printNode(n)).join('.')}' ${path}`;
            case 1 /* ParseNodeType.Argument */:
                return `argument '${node.name ? printNode(node.name) : 'N/A'}' ${path}`;
            case 41 /* ParseNodeType.Parameter */:
                return `parameter '${node.name ? printNode(node.name) : 'N/A'}' ${path}`;
            default:
                return `${ParseTreeUtils.printParseNodeType(node.nodeType)} ${path}`;
        }
    }
    function isNode(o) {
        const n = o;
        return n && (0, core_1.isNumber)(n.nodeType);
    }
    function isDeclaration(o) {
        const d = o;
        return d && (0, core_1.isNumber)(d.type) && uri_1.Uri.is(d.uri) && (0, core_1.isString)(d.moduleName);
    }
    function isType(o) {
        const t = o;
        return t && (0, core_1.isNumber)(t.category) && (0, core_1.isNumber)(t.flags);
    }
    function print(o) {
        if (!o) {
            return '';
        }
        if (isNode(o)) {
            return printNode(o, /* printPath */ true);
        }
        if (isDeclaration(o)) {
            return printDeclaration(o);
        }
        if (o instanceof symbol_1.Symbol) {
            return printSymbol(o);
        }
        if (isType(o)) {
            return printType(o);
        }
        // Do nothing, we can't print it.
        return '';
    }
    return {
        print: print,
        printFileOrModuleName: printFileOrModuleName,
    };
}
exports.createTracePrinter = createTracePrinter;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeCacheUtils.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeCacheUtils.ts ***!
  \**********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typeCacheUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utilities for managing type caches.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SpeculativeTypeTracker = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// This class maintains a stack of "speculative type contexts". When
// a context is popped off the stack, all of the speculative type cache
// entries that were created within that context are removed from the
// corresponding type caches because they are no longer valid.
// Each type context also contains a map of "speculative types" that are
// contextually evaluated based on an "expected type" and potentially
// one or more "dependent types". The "expected type" applies in cases
// where the speculative root node is being evaluated with bidirectional
// type inference. Dependent types apply in cases where the type of
// many subnodes depends on the expected type of a parent node, as in the
// case of lambda type inference.
class SpeculativeTypeTracker {
    constructor() {
        this._speculativeContextStack = [];
        this._speculativeTypeCache = new Map();
        this._activeDependentTypes = [];
    }
    enterSpeculativeContext(speculativeRootNode, options) {
        this._speculativeContextStack.push({
            speculativeRootNode,
            entriesToUndo: [],
            dependentType: options === null || options === void 0 ? void 0 : options.dependentType,
            allowDiagnostics: options === null || options === void 0 ? void 0 : options.allowDiagnostics,
        });
        // Retain a list of active dependent types. This information is already
        // contained within the speculative context stack, but we retain a copy
        // in this alternate form for performance reasons.
        if (options === null || options === void 0 ? void 0 : options.dependentType) {
            this._activeDependentTypes.push({
                speculativeRootNode,
                dependentType: options.dependentType,
            });
        }
    }
    leaveSpeculativeContext() {
        (0, debug_1.assert)(this._speculativeContextStack.length > 0);
        const context = this._speculativeContextStack.pop();
        if (context === null || context === void 0 ? void 0 : context.dependentType) {
            (0, debug_1.assert)(this._activeDependentTypes.length > 0);
            this._activeDependentTypes.pop();
        }
        // Delete all of the speculative type cache entries
        // that were tracked in this context.
        context.entriesToUndo.forEach((entry) => {
            entry.cache.delete(entry.id);
        });
    }
    isSpeculative(node, ignoreIfDiagnosticsAllowed = false) {
        if (this._speculativeContextStack.length === 0) {
            return false;
        }
        if (!node) {
            return true;
        }
        for (let i = this._speculativeContextStack.length - 1; i >= 0; i--) {
            const stackEntry = this._speculativeContextStack[i];
            if (ParseTreeUtils.isNodeContainedWithin(node, stackEntry.speculativeRootNode)) {
                if (!ignoreIfDiagnosticsAllowed || !stackEntry.allowDiagnostics) {
                    return true;
                }
            }
        }
        return false;
    }
    trackEntry(cache, id) {
        const stackSize = this._speculativeContextStack.length;
        if (stackSize > 0) {
            this._speculativeContextStack[stackSize - 1].entriesToUndo.push({
                cache,
                id,
            });
        }
    }
    // Temporarily disables speculative mode, clearing the stack
    // of speculative contexts. It returns the stack so the caller
    // can later restore it by calling enableSpeculativeMode.
    disableSpeculativeMode() {
        const stack = this._speculativeContextStack;
        this._speculativeContextStack = [];
        return stack;
    }
    enableSpeculativeMode(stack) {
        (0, debug_1.assert)(this._speculativeContextStack.length === 0);
        this._speculativeContextStack = stack;
    }
    addSpeculativeType(node, typeResult, incompleteGenerationCount, expectedType) {
        (0, debug_1.assert)(this._speculativeContextStack.length > 0);
        const maxCacheEntriesPerNode = 8;
        let cacheEntries = this._speculativeTypeCache.get(node.id);
        if (!cacheEntries) {
            cacheEntries = [];
        }
        else {
            cacheEntries = cacheEntries.filter((entry) => {
                // Filter out any incomplete entries that no longer match the generation count.
                // These are obsolete and cannot be used.
                if (entry.typeResult.isIncomplete && entry.incompleteGenerationCount !== incompleteGenerationCount) {
                    return false;
                }
                // Filter out any entries that match the expected type of the
                // new entry. The new entry replaces the old in this case.
                if (expectedType) {
                    if (!entry.expectedType) {
                        return true;
                    }
                    return !(0, types_1.isTypeSame)(entry.expectedType, expectedType);
                }
                return !!entry.expectedType;
            });
            // Don't allow the cache to grow too large.
            if (cacheEntries.length >= maxCacheEntriesPerNode) {
                cacheEntries.slice(1);
            }
        }
        // Add the new entry.
        const newEntry = {
            typeResult,
            expectedType,
            incompleteGenerationCount,
        };
        if (this._activeDependentTypes.length > 0) {
            newEntry.dependentTypes = Array.from(this._activeDependentTypes);
        }
        cacheEntries.push(newEntry);
        this._speculativeTypeCache.set(node.id, cacheEntries);
    }
    getSpeculativeType(node, expectedType) {
        if (this._speculativeContextStack.some((context) => ParseTreeUtils.isNodeContainedWithin(node, context.speculativeRootNode))) {
            const entries = this._speculativeTypeCache.get(node.id);
            if (entries) {
                for (const entry of entries) {
                    if (!expectedType) {
                        if (!entry.expectedType && this._dependentTypesMatch(entry)) {
                            return entry;
                        }
                    }
                    else if (entry.expectedType &&
                        (0, types_1.isTypeSame)(expectedType, entry.expectedType) &&
                        this._dependentTypesMatch(entry)) {
                        return entry;
                    }
                }
            }
        }
        return undefined;
    }
    // Determines whether a cache entry matches the current set of
    // active dependent types. If not, the cache entry can't be used
    // in the current context.
    _dependentTypesMatch(entry) {
        var _a;
        const cachedDependentTypes = (_a = entry.dependentTypes) !== null && _a !== void 0 ? _a : [];
        if (cachedDependentTypes.length !== this._activeDependentTypes.length) {
            return false;
        }
        return cachedDependentTypes.every((cachedDepType, index) => {
            const activeDepType = this._activeDependentTypes[index];
            if (cachedDepType.speculativeRootNode !== activeDepType.speculativeRootNode) {
                return false;
            }
            return (0, types_1.isTypeSame)(cachedDepType.dependentType, activeDepType.dependentType);
        });
    }
}
exports.SpeculativeTypeTracker = SpeculativeTypeTracker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeDocStringUtils.ts":
/*!**************************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeDocStringUtils.ts ***!
  \**************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typeDocStringUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Logic that obtains the doc string for types by looking
 * at the declaration in the type stub, and if needed, in
 * the source file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getVariableDocString = exports.getFunctionOrClassDeclDocString = exports.getClassDocString = exports.getModuleDocString = exports.getModuleDocStringFromUris = exports.getModuleDocStringFromModuleNodes = exports.getVariableInStubFileDocStrings = exports.getPropertyDocStringInherited = exports.getOverloadedFunctionDocStringsInherited = exports.getFunctionDocStringInherited = void 0;
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const sourceMapper_1 = __webpack_require__(/*! ../analyzer/sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const DefaultClassIteratorFlagsForFunctions = 4 /* MemberAccessFlags.SkipObjectBaseClass */ |
    16 /* MemberAccessFlags.SkipInstanceMembers */ |
    1 /* MemberAccessFlags.SkipOriginalClass */ |
    64 /* MemberAccessFlags.DeclaredTypesOnly */;
function isInheritedFromBuiltin(type, classType) {
    if (type.category === 5 /* TypeCategory.OverloadedFunction */) {
        if (type.overloads.length === 0) {
            return false;
        }
        type = type.overloads[0];
    }
    // Functions that are bound to a different type than where they
    // were declared are inherited.
    return (!!type.details.methodClass &&
        types_1.ClassType.isBuiltIn(type.details.methodClass) &&
        !!type.boundToType &&
        !types_1.ClassType.isBuiltIn(type.boundToType));
}
function getFunctionDocStringInherited(type, resolvedDecl, sourceMapper, classType) {
    let docString;
    // Don't allow docs to be inherited from the builtins to other classes;
    // they typically not helpful (and object's __init__ doc causes issues
    // with our current docstring traversal).
    if (!isInheritedFromBuiltin(type, classType) && resolvedDecl && (0, declaration_1.isFunctionDeclaration)(resolvedDecl)) {
        docString = _getFunctionDocString(type, resolvedDecl, sourceMapper);
    }
    // Search mro
    if (!docString && classType) {
        const funcName = type.details.name;
        const memberIterator = (0, typeUtils_1.getClassMemberIterator)(classType, funcName, DefaultClassIteratorFlagsForFunctions);
        for (const classMember of memberIterator) {
            const decls = classMember.symbol.getDeclarations();
            if (decls.length > 0) {
                const inheritedDecl = classMember.symbol.getDeclarations().slice(-1)[0];
                if ((0, declaration_1.isFunctionDeclaration)(inheritedDecl)) {
                    docString = _getFunctionDocStringFromDeclaration(inheritedDecl, sourceMapper);
                    if (docString) {
                        break;
                    }
                }
            }
        }
    }
    return docString || type.details.docString;
}
exports.getFunctionDocStringInherited = getFunctionDocStringInherited;
function getOverloadedFunctionDocStringsInherited(type, resolvedDecls, sourceMapper, evaluator, classType) {
    var _a;
    let docStrings;
    // Don't allow docs to be inherited from the builtins to other classes;
    // they typically not helpful (and object's __init__ doc causes issues
    // with our current docstring traversal).
    if (!isInheritedFromBuiltin(type, classType)) {
        for (const resolvedDecl of resolvedDecls) {
            docStrings = _getOverloadedFunctionDocStrings(type, resolvedDecl, sourceMapper);
            if (docStrings && docStrings.length > 0) {
                return docStrings;
            }
        }
    }
    // Search mro
    if (classType && type.overloads.length > 0) {
        const funcName = type.overloads[0].details.name;
        const memberIterator = (0, typeUtils_1.getClassMemberIterator)(classType, funcName, DefaultClassIteratorFlagsForFunctions);
        for (const classMember of memberIterator) {
            const inheritedDecl = classMember.symbol.getDeclarations().slice(-1)[0];
            const declType = (_a = evaluator.getTypeForDeclaration(inheritedDecl)) === null || _a === void 0 ? void 0 : _a.type;
            if (declType) {
                docStrings = _getOverloadedFunctionDocStrings(declType, inheritedDecl, sourceMapper);
                if (docStrings && docStrings.length > 0) {
                    break;
                }
            }
        }
    }
    return docStrings !== null && docStrings !== void 0 ? docStrings : [];
}
exports.getOverloadedFunctionDocStringsInherited = getOverloadedFunctionDocStringsInherited;
function getPropertyDocStringInherited(decl, sourceMapper, evaluator) {
    const enclosingClass = ParseTreeUtils.getEnclosingClass(decl.node.name, /* stopAtFunction */ false);
    const classResults = enclosingClass ? evaluator.getTypeOfClass(enclosingClass) : undefined;
    if (classResults) {
        return _getPropertyDocStringInherited(decl, sourceMapper, evaluator, classResults.classType);
    }
    return undefined;
}
exports.getPropertyDocStringInherited = getPropertyDocStringInherited;
function getVariableInStubFileDocStrings(decl, sourceMapper) {
    const docStrings = [];
    if (!(0, sourceMapper_1.isStubFile)(decl.uri)) {
        return docStrings;
    }
    for (const implDecl of sourceMapper.findDeclarations(decl)) {
        if ((0, declaration_1.isVariableDeclaration)(implDecl) && !!implDecl.docString) {
            docStrings.push(implDecl.docString);
        }
        else if ((0, declaration_1.isClassDeclaration)(implDecl) || (0, declaration_1.isFunctionDeclaration)(implDecl)) {
            // It is possible that the variable on the stub is not actually a variable on the corresponding py file.
            // in that case, get the doc string from original symbol if possible.
            const docString = getFunctionOrClassDeclDocString(implDecl);
            if (docString) {
                docStrings.push(docString);
            }
        }
    }
    return docStrings;
}
exports.getVariableInStubFileDocStrings = getVariableInStubFileDocStrings;
function getModuleDocStringFromModuleNodes(modules) {
    for (const module of modules) {
        if (module.statements) {
            const docString = ParseTreeUtils.getDocString(module.statements);
            if (docString) {
                return docString;
            }
        }
    }
    return undefined;
}
exports.getModuleDocStringFromModuleNodes = getModuleDocStringFromModuleNodes;
function getModuleDocStringFromUris(uris, sourceMapper) {
    const modules = [];
    for (const uri of uris) {
        if ((0, sourceMapper_1.isStubFile)(uri)) {
            (0, collectionUtils_1.addIfNotNull)(modules, sourceMapper.getModuleNode(uri));
        }
        (0, collectionUtils_1.appendArray)(modules, sourceMapper.findModules(uri));
    }
    return getModuleDocStringFromModuleNodes(modules);
}
exports.getModuleDocStringFromUris = getModuleDocStringFromUris;
function getModuleDocString(type, resolvedDecl, sourceMapper) {
    var _a;
    let docString = type.docString;
    if (!docString) {
        const uri = (_a = resolvedDecl === null || resolvedDecl === void 0 ? void 0 : resolvedDecl.uri) !== null && _a !== void 0 ? _a : type.fileUri;
        docString = getModuleDocStringFromUris([uri], sourceMapper);
    }
    return docString;
}
exports.getModuleDocString = getModuleDocString;
function getClassDocString(classType, resolvedDecl, sourceMapper) {
    let docString = classType.details.docString;
    if (!docString && resolvedDecl && (0, declaration_1.isClassDeclaration)(resolvedDecl)) {
        docString = _getFunctionOrClassDeclsDocString([resolvedDecl]);
        if (!docString && resolvedDecl && (0, sourceMapper_1.isStubFile)(resolvedDecl.uri) && resolvedDecl.type === 6 /* DeclarationType.Class */) {
            for (const implDecl of sourceMapper.findDeclarations(resolvedDecl)) {
                if ((0, declaration_1.isVariableDeclaration)(implDecl) && !!implDecl.docString) {
                    docString = implDecl.docString;
                    break;
                }
                if ((0, declaration_1.isClassDeclaration)(implDecl) || (0, declaration_1.isFunctionDeclaration)(implDecl)) {
                    docString = getFunctionOrClassDeclDocString(implDecl);
                    break;
                }
            }
        }
    }
    if (!docString && resolvedDecl) {
        const implDecls = sourceMapper.findClassDeclarationsByType(resolvedDecl.uri, classType);
        if (implDecls) {
            const classDecls = implDecls.filter((d) => (0, declaration_1.isClassDeclaration)(d)).map((d) => d);
            docString = _getFunctionOrClassDeclsDocString(classDecls);
        }
    }
    return docString;
}
exports.getClassDocString = getClassDocString;
function getFunctionOrClassDeclDocString(decl) {
    var _a, _b, _c;
    return ParseTreeUtils.getDocString((_c = (_b = (_a = decl.node) === null || _a === void 0 ? void 0 : _a.suite) === null || _b === void 0 ? void 0 : _b.statements) !== null && _c !== void 0 ? _c : []);
}
exports.getFunctionOrClassDeclDocString = getFunctionOrClassDeclDocString;
function getVariableDocString(decl, sourceMapper) {
    if (!decl) {
        return undefined;
    }
    if (decl.docString !== undefined) {
        return decl.docString;
    }
    else {
        return getVariableInStubFileDocStrings(decl, sourceMapper).find((doc) => doc);
    }
}
exports.getVariableDocString = getVariableDocString;
function _getOverloadedFunctionDocStrings(type, resolvedDecl, sourceMapper) {
    if (!(0, types_1.isOverloadedFunction)(type)) {
        return undefined;
    }
    const docStrings = [];
    if (type.overloads.some((o) => o.details.docString)) {
        type.overloads.forEach((overload) => {
            if (overload.details.docString) {
                docStrings.push(overload.details.docString);
            }
        });
    }
    else if (resolvedDecl && (0, sourceMapper_1.isStubFile)(resolvedDecl.uri) && (0, declaration_1.isFunctionDeclaration)(resolvedDecl)) {
        const implDecls = sourceMapper.findFunctionDeclarations(resolvedDecl);
        const docString = _getFunctionOrClassDeclsDocString(implDecls);
        if (docString) {
            docStrings.push(docString);
        }
    }
    return docStrings;
}
function _getPropertyDocStringInherited(decl, sourceMapper, evaluator, classType) {
    var _a, _b;
    if (!decl || !(0, declaration_1.isFunctionDeclaration)(decl)) {
        return;
    }
    const declaredType = (_a = evaluator.getTypeForDeclaration(decl)) === null || _a === void 0 ? void 0 : _a.type;
    if (!declaredType || !(0, typeUtils_1.isMaybeDescriptorInstance)(declaredType)) {
        return;
    }
    const fieldName = decl.node.nodeType === 28 /* ParseNodeType.Function */ ? decl.node.name.value : undefined;
    if (!fieldName) {
        return;
    }
    const classItr = (0, typeUtils_1.getClassIterator)(classType, 0 /* ClassIteratorFlags.Default */);
    // Walk the inheritance list starting with the current class searching for docStrings
    for (const [mroClass] of classItr) {
        if (!(0, types_1.isInstantiableClass)(mroClass)) {
            continue;
        }
        const symbol = types_1.ClassType.getSymbolTable(mroClass).get(fieldName);
        // Get both the setter and getter declarations
        const decls = symbol === null || symbol === void 0 ? void 0 : symbol.getDeclarations();
        if (decls) {
            for (const decl of decls) {
                if ((0, declaration_1.isFunctionDeclaration)(decl)) {
                    const declaredType = (_b = evaluator.getTypeForDeclaration(decl)) === null || _b === void 0 ? void 0 : _b.type;
                    if (declaredType && (0, typeUtils_1.isMaybeDescriptorInstance)(declaredType)) {
                        const docString = _getFunctionDocStringFromDeclaration(decl, sourceMapper);
                        if (docString) {
                            return docString;
                        }
                    }
                }
            }
        }
    }
    return;
}
function _getFunctionDocString(type, resolvedDecl, sourceMapper) {
    if (!(0, types_1.isFunction)(type)) {
        return undefined;
    }
    let docString = type.details.docString;
    if (!docString && resolvedDecl) {
        docString = _getFunctionDocStringFromDeclaration(resolvedDecl, sourceMapper);
    }
    if (!docString && type.details.declaration) {
        docString = _getFunctionDocStringFromDeclaration(type.details.declaration, sourceMapper);
    }
    return docString;
}
function _getFunctionDocStringFromDeclaration(resolvedDecl, sourceMapper) {
    let docString = _getFunctionOrClassDeclsDocString([resolvedDecl]);
    if (!docString && (0, sourceMapper_1.isStubFile)(resolvedDecl.uri)) {
        const implDecls = sourceMapper.findFunctionDeclarations(resolvedDecl);
        docString = _getFunctionOrClassDeclsDocString(implDecls);
    }
    return docString;
}
function _getFunctionOrClassDeclsDocString(decls) {
    for (const decl of decls) {
        const docString = getFunctionOrClassDeclDocString(decl);
        if (docString) {
            return docString;
        }
    }
    return undefined;
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeEvaluator.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeEvaluator.ts ***!
  \*********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typeEvaluator.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Module that evaluates types of parse tree nodes within
 * a program.
 *
 * Note: This is a gargantuan module - much larger than I would
 * normally create. It is written this way primarily for performance,
 * with the internal methods having access to the full closure of
 * the createTypeEvaluator function. This is the same approach
 * taken by the TypeScript compiler.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createTypeEvaluator = exports.maxCodeComplexity = void 0;
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const parser_1 = __webpack_require__(/*! ../parser/parser */ "../pyright-internal/src/parser/parser.ts");
const analyzerFileInfo_1 = __webpack_require__(/*! ./analyzerFileInfo */ "../pyright-internal/src/analyzer/analyzerFileInfo.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const codeFlowEngine_1 = __webpack_require__(/*! ./codeFlowEngine */ "../pyright-internal/src/analyzer/codeFlowEngine.ts");
const codeFlowTypes_1 = __webpack_require__(/*! ./codeFlowTypes */ "../pyright-internal/src/analyzer/codeFlowTypes.ts");
const constraintSolver_1 = __webpack_require__(/*! ./constraintSolver */ "../pyright-internal/src/analyzer/constraintSolver.ts");
const constructors_1 = __webpack_require__(/*! ./constructors */ "../pyright-internal/src/analyzer/constructors.ts");
const dataClasses_1 = __webpack_require__(/*! ./dataClasses */ "../pyright-internal/src/analyzer/dataClasses.ts");
const declarationUtils_1 = __webpack_require__(/*! ./declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
const decorators_1 = __webpack_require__(/*! ./decorators */ "../pyright-internal/src/analyzer/decorators.ts");
const enums_1 = __webpack_require__(/*! ./enums */ "../pyright-internal/src/analyzer/enums.ts");
const functionTransform_1 = __webpack_require__(/*! ./functionTransform */ "../pyright-internal/src/analyzer/functionTransform.ts");
const namedTuples_1 = __webpack_require__(/*! ./namedTuples */ "../pyright-internal/src/analyzer/namedTuples.ts");
const operations_1 = __webpack_require__(/*! ./operations */ "../pyright-internal/src/analyzer/operations.ts");
const parameterUtils_1 = __webpack_require__(/*! ./parameterUtils */ "../pyright-internal/src/analyzer/parameterUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const patternMatching_1 = __webpack_require__(/*! ./patternMatching */ "../pyright-internal/src/analyzer/patternMatching.ts");
const properties_1 = __webpack_require__(/*! ./properties */ "../pyright-internal/src/analyzer/properties.ts");
const protocols_1 = __webpack_require__(/*! ./protocols */ "../pyright-internal/src/analyzer/protocols.ts");
const ScopeUtils = __importStar(__webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts"));
const staticExpressions_1 = __webpack_require__(/*! ./staticExpressions */ "../pyright-internal/src/analyzer/staticExpressions.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolNameUtils_1 = __webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const symbolUtils_1 = __webpack_require__(/*! ./symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const typeCacheUtils_1 = __webpack_require__(/*! ./typeCacheUtils */ "../pyright-internal/src/analyzer/typeCacheUtils.ts");
const typeEvaluatorTypes_1 = __webpack_require__(/*! ./typeEvaluatorTypes */ "../pyright-internal/src/analyzer/typeEvaluatorTypes.ts");
const TypePrinter = __importStar(__webpack_require__(/*! ./typePrinter */ "../pyright-internal/src/analyzer/typePrinter.ts"));
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
const typedDicts_1 = __webpack_require__(/*! ./typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// This table contains the names of several types that
// are not subscriptable at runtime on older versions of Python.
// It lists the first version of Python where subscripting is
// allowed.
const nonSubscriptableTypes = new Map([
    ['asyncio.futures.Future', pythonVersion_1.pythonVersion3_9],
    ['asyncio.tasks.Task', pythonVersion_1.pythonVersion3_9],
    ['builtins.dict', pythonVersion_1.pythonVersion3_9],
    ['builtins.frozenset', pythonVersion_1.pythonVersion3_9],
    ['builtins.list', pythonVersion_1.pythonVersion3_9],
    ['builtins._PathLike', pythonVersion_1.pythonVersion3_9],
    ['builtins.set', pythonVersion_1.pythonVersion3_9],
    ['builtins.tuple', pythonVersion_1.pythonVersion3_9],
    ['collections.ChainMap', pythonVersion_1.pythonVersion3_9],
    ['collections.Counter', pythonVersion_1.pythonVersion3_9],
    ['collections.defaultdict', pythonVersion_1.pythonVersion3_9],
    ['collections.DefaultDict', pythonVersion_1.pythonVersion3_9],
    ['collections.deque', pythonVersion_1.pythonVersion3_9],
    ['collections.OrderedDict', pythonVersion_1.pythonVersion3_9],
    ['contextlib.AbstractContextManager', pythonVersion_1.pythonVersion3_9],
    ['contextlib.AbstractAsyncContextManager', pythonVersion_1.pythonVersion3_9],
    ['queue.Queue', pythonVersion_1.pythonVersion3_9],
]);
// Some types that do not inherit from others are still considered
// "compatible" based on the Python spec. These are sometimes referred
// to as "type promotions".
const typePromotions = new Map([
    ['builtins.float', ['builtins.int']],
    ['builtins.complex', ['builtins.float', 'builtins.int']],
    ['builtins.bytes', ['builtins.bytearray', 'builtins.memoryview']],
]);
// How many levels deep should we attempt to infer return
// types based on call-site argument types? The deeper we go,
// the more types we may be able to infer, but the worse the
// performance.
const maxReturnTypeInferenceStackSize = 2;
// What is the max number of input arguments we should allow
// for call-site return type inference? We've found that large,
// complex functions with many arguments can take too long to
// analyze.
const maxReturnTypeInferenceArgumentCount = 6;
// What is the max complexity of the code flow graph that
// we will analyze to determine the return type of a function
// when its parameters are unannotated? We want to keep this
// pretty low because this can be very costly.
const maxReturnTypeInferenceCodeFlowComplexity = 32;
// What is the max complexity of the code flow graph for
// call-site type inference? This is very expensive, so we
// want to keep this very low.
const maxReturnCallSiteTypeInferenceCodeFlowComplexity = 8;
// What is the max number of return types cached per function
// when using call-site inference?
const maxCallSiteReturnTypeCacheSize = 8;
// How many entries in a list, set, or dict should we examine
// when inferring the type? We need to cut it off at some point
// to avoid excessive computation.
const maxEntriesToUseForInference = 64;
// How many assignments to an unannotated variable should be used
// when inferring its type? We need to cut it off at some point
// to avoid excessive computation.
const maxDeclarationsToUseForInference = 64;
// Maximum number of times to attempt effective type evaluation
// of a variable that has no type declaration.
const maxEffectiveTypeEvaluationAttempts = 16;
// Maximum number of combinatoric union type expansions allowed
// when resolving an overload.
const maxOverloadUnionExpansionCount = 64;
// Maximum number of recursive function return type inference attempts
// that can be concurrently pending before we give up.
const maxInferFunctionReturnRecursionCount = 12;
// In certain loops, it's possible to construct arbitrarily-deep containers
// (tuples, lists, sets, or dicts) which can lead to infinite type analysis.
// This limits the depth.
const maxInferredContainerDepth = 8;
// Maximum recursion amount when comparing two recursive type aliases.
// Increasing this can greatly increase the time required to evaluate
// two recursive type aliases that have the same definition. Decreasing
// it can increase the chance of false negatives for such recursive
// type aliases.
const maxRecursiveTypeAliasRecursionCount = 10;
// This switch enables a special debug mode that attempts to catch
// bugs due to inconsistent evaluation flags used when reading types
// from the type cache.
const verifyTypeCacheEvaluatorFlags = false;
// This debugging option prints each expression and its evaluated type.
const printExpressionTypes = false;
// The following number is chosen somewhat arbitrarily. We need to cut
// off code flow analysis at some point for code flow graphs that are too
// complex. Otherwise we risk overflowing the stack or incurring extremely
// long analysis times. This number has been tuned empirically.
exports.maxCodeComplexity = 768;
function createTypeEvaluator(importLookup, evaluatorOptions) {
    const symbolResolutionStack = [];
    const asymmetricAccessorAssignmentCache = new Set();
    const speculativeTypeTracker = new typeCacheUtils_1.SpeculativeTypeTracker();
    const suppressedNodeStack = [];
    const assignClassToSelfStack = [];
    let functionRecursionMap = new Set();
    let codeFlowAnalyzerCache = new Map();
    let typeCache = new Map();
    let effectiveTypeCache = new Map();
    let expectedTypeCache = new Map();
    let deferredClassCompletions = [];
    let cancellationToken;
    let isBasicTypesInitialized = false;
    let noneClassType;
    let noneType;
    let objectType;
    let typeClassType;
    let unionClassType;
    let awaitableProtocolType;
    let functionObj;
    let tupleClassType;
    let boolClassType;
    let intClassType;
    let strClassType;
    let dictClassType;
    let typedDictClassType;
    let typedDictPrivateClassType;
    let supportsKeysAndGetItemProtocolType;
    let mappingType;
    let printExpressionSpaceCount = 0;
    let incompleteGenerationCount = 0;
    const returnTypeInferenceContextStack = [];
    let returnTypeInferenceTypeCache;
    function runWithCancellationToken(token, callback) {
        try {
            cancellationToken = token;
            return callback();
        }
        finally {
            cancellationToken = undefined;
        }
    }
    function checkForCancellation() {
        if (cancellationToken) {
            (0, cancellationUtils_1.throwIfCancellationRequested)(cancellationToken);
        }
    }
    function getTypeCacheEntryCount() {
        return typeCache.size;
    }
    // This function should be called immediately prior to discarding
    // the type evaluator. It forcibly replaces existing cache maps
    // with empty equivalents. This shouldn't be necessary, but there
    // is apparently a bug in the v8 GC where it is unable to detect
    // circular references in complex data structures, so it fails
    // to clean up the objects if we don't help it out.
    function disposeEvaluator() {
        functionRecursionMap = new Set();
        codeFlowAnalyzerCache = new Map();
        typeCache = new Map();
        effectiveTypeCache = new Map();
        expectedTypeCache = new Map();
    }
    function readTypeCacheEntry(node) {
        // Should we use a temporary cache associated with a contextual
        // analysis of a function, contextualized based on call-site argument types?
        if (returnTypeInferenceTypeCache && isNodeInReturnTypeInferenceContext(node)) {
            return returnTypeInferenceTypeCache.get(node.id);
        }
        else {
            return typeCache.get(node.id);
        }
    }
    function isTypeCached(node) {
        const cacheEntry = readTypeCacheEntry(node);
        if (!cacheEntry) {
            return false;
        }
        return (!cacheEntry.typeResult.isIncomplete || cacheEntry.incompleteGenerationCount === incompleteGenerationCount);
    }
    function readTypeCache(node, flags) {
        var _a, _b;
        const cacheEntry = readTypeCacheEntry(node);
        if (!cacheEntry || cacheEntry.typeResult.isIncomplete) {
            return undefined;
        }
        if (evaluatorOptions.verifyTypeCacheEvaluatorFlags || verifyTypeCacheEvaluatorFlags) {
            if (flags !== undefined) {
                const expectedFlags = cacheEntry.flags;
                if (expectedFlags !== undefined && flags !== expectedFlags) {
                    const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
                    const position = (0, positionUtils_1.convertOffsetToPosition)(node.start, fileInfo.lines);
                    const message = `Type cache flag mismatch for node type ${node.nodeType} ` +
                        `(parent ${(_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== null && _b !== void 0 ? _b : 'none'}): ` +
                        `cached flags = ${expectedFlags}, access flags = ${flags}, ` +
                        `file = {${fileInfo.fileUri} [${position.line + 1}:${position.character + 1}]}`;
                    if (evaluatorOptions.verifyTypeCacheEvaluatorFlags) {
                        (0, debug_1.fail)(message);
                    }
                    else {
                        console.log(message);
                    }
                }
            }
        }
        return cacheEntry.typeResult.type;
    }
    function writeTypeCache(node, typeResult, flags, inferenceContext, allowSpeculativeCaching = false) {
        // Should we use a temporary cache associated with a contextual
        // analysis of a function, contextualized based on call-site argument types?
        const typeCacheToUse = returnTypeInferenceTypeCache && isNodeInReturnTypeInferenceContext(node)
            ? returnTypeInferenceTypeCache
            : typeCache;
        if (!typeResult.isIncomplete) {
            incompleteGenerationCount++;
        }
        else {
            const oldValue = typeCacheToUse.get(node.id);
            if (oldValue !== undefined && !(0, types_1.isTypeSame)(typeResult.type, oldValue.typeResult.type)) {
                incompleteGenerationCount++;
            }
        }
        typeCacheToUse.set(node.id, { typeResult, flags, incompleteGenerationCount: incompleteGenerationCount });
        // If the entry is located within a part of the parse tree that is currently being
        // "speculatively" evaluated, track it so we delete the cached entry when we leave
        // this speculative context.
        if (isSpeculativeModeInUse(node)) {
            speculativeTypeTracker.trackEntry(typeCacheToUse, node.id);
            if (allowSpeculativeCaching) {
                speculativeTypeTracker.addSpeculativeType(node, typeResult, incompleteGenerationCount, inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType);
            }
        }
    }
    function setTypeResultForNode(node, typeResult, flags = 0 /* EvaluatorFlags.None */) {
        writeTypeCache(node, typeResult, flags);
    }
    function setAsymmetricDescriptorAssignment(node) {
        if (isSpeculativeModeInUse(/* node */ undefined)) {
            return;
        }
        asymmetricAccessorAssignmentCache.add(node.id);
    }
    function isAsymmetricAccessorAssignment(node) {
        return asymmetricAccessorAssignmentCache.has(node.id);
    }
    // Determines whether the specified node is contained within
    // the function node corresponding to the function that we
    // are currently analyzing in the context of parameter types
    // defined by a call site.
    function isNodeInReturnTypeInferenceContext(node) {
        const stackSize = returnTypeInferenceContextStack.length;
        if (stackSize === 0) {
            return false;
        }
        const contextNode = returnTypeInferenceContextStack[stackSize - 1];
        let curNode = node;
        while (curNode) {
            if (curNode === contextNode.functionNode) {
                return true;
            }
            curNode = curNode.parent;
        }
        return false;
    }
    function getCodeFlowAnalyzerForReturnTypeInferenceContext() {
        const stackSize = returnTypeInferenceContextStack.length;
        (0, debug_1.assert)(stackSize > 0);
        const contextNode = returnTypeInferenceContextStack[stackSize - 1];
        return contextNode.codeFlowAnalyzer;
    }
    function getIndexOfSymbolResolution(symbol, declaration) {
        return symbolResolutionStack.findIndex((entry) => entry.symbolId === symbol.id && entry.declaration === declaration);
    }
    function pushSymbolResolution(symbol, declaration) {
        const index = getIndexOfSymbolResolution(symbol, declaration);
        if (index >= 0) {
            // Mark all of the entries between these two as invalid.
            for (let i = index + 1; i < symbolResolutionStack.length; i++) {
                symbolResolutionStack[i].isResultValid = false;
            }
            return false;
        }
        symbolResolutionStack.push({
            symbolId: symbol.id,
            declaration,
            isResultValid: true,
        });
        return true;
    }
    function popSymbolResolution(symbol) {
        const poppedEntry = symbolResolutionStack.pop();
        (0, debug_1.assert)(poppedEntry.symbolId === symbol.id);
        return poppedEntry.isResultValid;
    }
    function setSymbolResolutionPartialType(symbol, declaration, type) {
        const index = getIndexOfSymbolResolution(symbol, declaration);
        if (index >= 0) {
            symbolResolutionStack[index].partialType = type;
        }
    }
    function getSymbolResolutionPartialType(symbol, declaration) {
        const index = getIndexOfSymbolResolution(symbol, declaration);
        if (index >= 0) {
            return symbolResolutionStack[index].partialType;
        }
        return undefined;
    }
    // Determines the type of the specified node by evaluating it in
    // context, logging any errors in the process. This may require the
    // type of surrounding statements to be evaluated.
    function getType(node) {
        var _a, _b;
        initializedBasicTypes(node);
        let type = (_a = evaluateTypeForSubnode(node, () => {
            evaluateTypesForExpressionInContext(node);
        })) === null || _a === void 0 ? void 0 : _a.type;
        // If this is a type parameter with a calculated variance, see if we
        // can swap it out for a version that has a computed variance.
        if (type && (0, types_1.isTypeVar)(type) && type.details.declaredVariance === 0 /* Variance.Auto */) {
            const typeVarType = type;
            const typeParamListNode = ParseTreeUtils.getParentNodeOfType(node, 76 /* ParseNodeType.TypeParameterList */);
            if (((_b = typeParamListNode === null || typeParamListNode === void 0 ? void 0 : typeParamListNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 10 /* ParseNodeType.Class */) {
                const classTypeResult = getTypeOfClass(typeParamListNode.parent);
                if (classTypeResult) {
                    inferTypeParameterVarianceForClass(classTypeResult.classType);
                    const typeParam = classTypeResult.classType.details.typeParameters.find((param) => (0, types_1.isTypeSame)(param, typeVarType, { ignoreTypeFlags: true }));
                    if (typeParam) {
                        type = types_1.TypeBase.isInstance(type) ? types_1.TypeVarType.cloneAsInstance(typeParam) : typeParam;
                    }
                }
            }
        }
        if (type) {
            type = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(type);
        }
        return type;
    }
    function getTypeResult(node) {
        return evaluateTypeForSubnode(node, () => {
            evaluateTypesForExpressionInContext(node);
        });
    }
    function getTypeResultForDecorator(node) {
        return evaluateTypeForSubnode(node, () => {
            evaluateTypesForExpressionInContext(node.expression);
        });
    }
    // Reads the type of the node from the cache.
    function getCachedType(node) {
        return readTypeCache(node, 0 /* EvaluatorFlags.None */);
    }
    // Determines the expected type of a specified node based on surrounding
    // context. For example, if it's a subexpression of an argument expression,
    // the associated parameter type might inform the expected type.
    function getExpectedType(node) {
        // Scan up the parse tree to find the top-most expression node
        // so we can evaluate the entire expression.
        let topExpression = node;
        let curNode = node;
        while (curNode) {
            if ((0, parseNodes_1.isExpressionNode)(curNode)) {
                topExpression = curNode;
            }
            curNode = curNode.parent;
        }
        // Evaluate the expression. This will have the side effect of
        // storing an expected type in the expected type cache.
        evaluateTypesForExpressionInContext(topExpression);
        // Look for the resulting expected type by scanning up the parse tree.
        curNode = node;
        while (curNode) {
            const expectedType = expectedTypeCache.get(curNode.id);
            if (expectedType) {
                return {
                    type: expectedType,
                    node: curNode,
                };
            }
            if (curNode === topExpression) {
                break;
            }
            curNode = curNode.parent;
        }
        return undefined;
    }
    function initializedBasicTypes(node) {
        var _a;
        if (!isBasicTypesInitialized) {
            // Some of these types have cyclical dependencies on each other,
            // so don't re-enter this block once we start executing it.
            isBasicTypesInitialized = true;
            objectType = getBuiltInObject(node, 'object');
            typeClassType = getBuiltInType(node, 'type');
            functionObj = getBuiltInObject(node, 'function');
            unionClassType = getTypesType(node, 'UnionType');
            if (unionClassType && (0, types_1.isClass)(unionClassType)) {
                unionClassType.details.flags |= -2147483648 /* ClassTypeFlags.SpecialFormClass */;
            }
            // Initialize and cache "Collection" to break a cyclical dependency
            // that occurs when resolving tuple below.
            getTypingType(node, 'Collection');
            noneClassType = (_a = getTypeshedType(node, 'NoneType')) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
            noneType = (0, types_1.isInstantiableClass)(noneClassType)
                ? types_1.ClassType.cloneAsInstance(noneClassType)
                : types_1.UnknownType.create();
            tupleClassType = getBuiltInType(node, 'tuple');
            boolClassType = getBuiltInType(node, 'bool');
            intClassType = getBuiltInType(node, 'int');
            strClassType = getBuiltInType(node, 'str');
            dictClassType = getBuiltInType(node, 'dict');
            typedDictClassType = getTypingType(node, 'TypedDict');
            typedDictPrivateClassType = getTypingType(node, '_TypedDict');
            awaitableProtocolType = getTypingType(node, 'Awaitable');
            mappingType = getTypingType(node, 'Mapping');
            supportsKeysAndGetItemProtocolType = getTypeshedType(node, 'SupportsKeysAndGetItem');
            if (!supportsKeysAndGetItemProtocolType) {
                // Fall back on 'Mapping' if 'SupportsKeysAndGetItem' is not available.
                supportsKeysAndGetItemProtocolType = mappingType;
            }
            // Wire up the `Any` class to the special-form version of our internal AnyType.
            const objectClass = getBuiltInType(node, 'object');
            if (objectClass &&
                (0, types_1.isInstantiableClass)(objectClass) &&
                typeClassType &&
                (0, types_1.isInstantiableClass)(typeClassType)) {
                const anyClass = types_1.ClassType.createInstantiable('Any', 'typing.Any', 'typing', uri_1.Uri.empty(), 1 /* ClassTypeFlags.BuiltInClass */ | -2147483648 /* ClassTypeFlags.SpecialFormClass */, 
                /* typeSourceId */ -1, 
                /* declaredMetaclass */ undefined, 
                /* effectiveMetaclass */ typeClassType);
                anyClass.details.baseClasses.push(objectClass);
                (0, typeUtils_1.computeMroLinearization)(anyClass);
                const anySpecialForm = types_1.AnyType.createSpecialForm();
                if ((0, types_1.isAny)(anySpecialForm)) {
                    anySpecialForm.specialForm = anyClass;
                }
            }
        }
    }
    function getTypeOfExpression(node, flags = 0 /* EvaluatorFlags.None */, inferenceContext) {
        // Is this type already cached?
        const cacheEntry = readTypeCacheEntry(node);
        if (cacheEntry &&
            (!cacheEntry.typeResult.isIncomplete || cacheEntry.incompleteGenerationCount === incompleteGenerationCount)) {
            if (printExpressionTypes) {
                console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Cached ${printType(cacheEntry.typeResult.type)} ${cacheEntry.typeResult.typeErrors ? ' Errors' : ''}`);
            }
            return cacheEntry.typeResult;
        }
        else {
            // Is it cached in the speculative type cache?
            const cacheEntry = speculativeTypeTracker.getSpeculativeType(node, inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType);
            if (cacheEntry &&
                (!cacheEntry.typeResult.isIncomplete ||
                    cacheEntry.incompleteGenerationCount === incompleteGenerationCount)) {
                if (printExpressionTypes) {
                    console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Speculative ${printType(cacheEntry.typeResult.type)}`);
                }
                return cacheEntry.typeResult;
            }
        }
        if (printExpressionTypes) {
            console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Pre`);
            printExpressionSpaceCount++;
        }
        // This is a frequently-called routine, so it's a good place to call
        // the cancellation check. If the operation is canceled, an exception
        // will be thrown at this point.
        checkForCancellation();
        if (inferenceContext) {
            inferenceContext.expectedType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(inferenceContext.expectedType);
        }
        // If we haven't already fetched some core type definitions from the
        // typeshed stubs, do so here. It would be better to fetch this when it's
        // needed in assignType, but we don't have access to the parse tree
        // at that point.
        initializedBasicTypes(node);
        let typeResult;
        let expectingInstantiable = (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0;
        let allowSpeculativeCaching = true;
        switch (node.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                typeResult = getTypeOfName(node, flags);
                break;
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                typeResult = getTypeOfMemberAccess(node, flags);
                break;
            }
            case 24 /* ParseNodeType.Index */: {
                typeResult = getTypeOfIndex(node, flags);
                break;
            }
            case 9 /* ParseNodeType.Call */: {
                typeResult = getTypeOfCall(node, flags, inferenceContext);
                break;
            }
            case 52 /* ParseNodeType.Tuple */: {
                typeResult = getTypeOfTuple(node, flags, inferenceContext);
                break;
            }
            case 11 /* ParseNodeType.Constant */: {
                typeResult = getTypeOfConstant(node, flags);
                break;
            }
            case 48 /* ParseNodeType.StringList */: {
                const isExpectingType = (flags & 8 /* EvaluatorFlags.EvaluateStringLiteralAsType */) !== 0 && !isAnnotationLiteralValue(node);
                if (isExpectingType) {
                    // Don't report expecting type errors again. We will have already
                    // reported them when analyzing the contents of the string.
                    expectingInstantiable = false;
                }
                typeResult = getTypeOfStringList(node, flags, isExpectingType);
                break;
            }
            case 40 /* ParseNodeType.Number */: {
                typeResult = getTypeOfNumber(node, typeResult);
                break;
            }
            case 18 /* ParseNodeType.Ellipsis */: {
                typeResult = getTypeOfEllipsis(flags, typeResult, node);
                break;
            }
            case 55 /* ParseNodeType.UnaryOperation */: {
                typeResult = (0, operations_1.getTypeOfUnaryOperation)(evaluatorInterface, node, flags, inferenceContext);
                break;
            }
            case 7 /* ParseNodeType.BinaryOperation */: {
                let effectiveFlags = flags;
                // If we're expecting an instantiable type and this isn't a union operator,
                // don't require that the two operands are also instantiable types.
                if (expectingInstantiable && node.operator !== 6 /* OperatorType.BitwiseOr */) {
                    effectiveFlags &= ~128 /* EvaluatorFlags.ExpectingInstantiableType */;
                }
                typeResult = (0, operations_1.getTypeOfBinaryOperation)(evaluatorInterface, node, effectiveFlags, inferenceContext);
                break;
            }
            case 5 /* ParseNodeType.AugmentedAssignment */: {
                typeResult = (0, operations_1.getTypeOfAugmentedAssignment)(evaluatorInterface, node, inferenceContext);
                break;
            }
            case 31 /* ParseNodeType.List */:
            case 45 /* ParseNodeType.Set */: {
                typeResult = getTypeOfListOrSet(node, flags, inferenceContext);
                break;
            }
            case 46 /* ParseNodeType.Slice */: {
                typeResult = getTypeOfSlice(node);
                break;
            }
            case 6 /* ParseNodeType.Await */: {
                typeResult = getTypeOfAwaitOperator(node, flags, inferenceContext);
                break;
            }
            case 51 /* ParseNodeType.Ternary */: {
                typeResult = (0, operations_1.getTypeOfTernaryOperation)(evaluatorInterface, node, flags, inferenceContext);
                break;
            }
            case 32 /* ParseNodeType.ListComprehension */: {
                typeResult = getTypeOfListComprehension(node, inferenceContext);
                break;
            }
            case 15 /* ParseNodeType.Dictionary */: {
                typeResult = getTypeOfDictionary(node, flags, inferenceContext);
                break;
            }
            case 30 /* ParseNodeType.Lambda */: {
                typeResult = getTypeOfLambda(node, inferenceContext);
                break;
            }
            case 3 /* ParseNodeType.Assignment */: {
                typeResult = getTypeOfExpression(node.rightExpression, flags, inferenceContext);
                assignTypeToExpression(node.leftExpression, typeResult.type, !!typeResult.isIncomplete, node.rightExpression, 
                /* ignoreEmptyContainers */ true, 
                /* allowAssignmentToFinalVar */ true);
                break;
            }
            case 4 /* ParseNodeType.AssignmentExpression */: {
                if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                    addError(localize_1.LocMessage.walrusNotAllowed(), node);
                }
                typeResult = getTypeOfExpression(node.rightExpression, flags, inferenceContext);
                assignTypeToExpression(node.name, typeResult.type, !!typeResult.isIncomplete, node.rightExpression, 
                /* ignoreEmptyContainers */ true);
                // Don't allow speculative caching for assignment expressions because
                // the target name node won't have a corresponding type cached speculatively.
                allowSpeculativeCaching = false;
                break;
            }
            case 60 /* ParseNodeType.Yield */: {
                typeResult = getTypeOfYield(node);
                break;
            }
            case 61 /* ParseNodeType.YieldFrom */: {
                typeResult = getTypeOfYieldFrom(node);
                break;
            }
            case 56 /* ParseNodeType.Unpack */: {
                typeResult = getTypeOfUnpackOperator(node, flags, inferenceContext);
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                typeResult = getTypeOfExpression(node.typeAnnotation, 128 /* EvaluatorFlags.ExpectingInstantiableType */ |
                    256 /* EvaluatorFlags.ExpectingTypeAnnotation */ |
                    8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
                    32 /* EvaluatorFlags.DisallowParamSpec */ |
                    64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                    32768 /* EvaluatorFlags.VariableTypeAnnotation */);
                break;
            }
            case 49 /* ParseNodeType.String */:
            case 27 /* ParseNodeType.FormatString */: {
                typeResult = getTypeOfString(node);
                break;
            }
            case 0 /* ParseNodeType.Error */: {
                // Evaluate the child expression as best we can so the
                // type information is cached for the completion handler.
                suppressDiagnostics(node, () => {
                    if (node.child) {
                        getTypeOfExpression(node.child);
                    }
                });
                typeResult = { type: types_1.UnknownType.create() };
                break;
            }
            default:
                (0, debug_1.assertNever)(node, `Illegal node type: ${node.nodeType}`);
        }
        if (!typeResult) {
            // We shouldn't get here. If we do, report an error.
            (0, debug_1.fail)(`Unhandled expression type '${ParseTreeUtils.printExpression(node)}'`);
        }
        // Do we need to validate that the type is instantiable?
        if (expectingInstantiable) {
            validateTypeIsInstantiable(typeResult, flags, node);
        }
        // Should we disable type promotions for bytes?
        if ((0, types_1.isInstantiableClass)(typeResult.type) &&
            typeResult.type.includePromotions &&
            !typeResult.type.includeSubclasses &&
            types_1.ClassType.isBuiltIn(typeResult.type, 'bytes')) {
            if (AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.disableBytesTypePromotions) {
                typeResult = {
                    ...typeResult,
                    type: types_1.ClassType.cloneRemoveTypePromotions(typeResult.type),
                };
            }
        }
        writeTypeCache(node, typeResult, flags, inferenceContext, allowSpeculativeCaching);
        // If there was an expected type, make sure that the result type is compatible.
        if (inferenceContext &&
            !(0, types_1.isAnyOrUnknown)(inferenceContext.expectedType) &&
            !(0, types_1.isNever)(inferenceContext.expectedType)) {
            expectedTypeCache.set(node.id, inferenceContext.expectedType);
            // If this is a generic function and there is a signature tracker,
            // make sure the signature is unique.
            if (inferenceContext.signatureTracker && (0, types_1.isFunction)(typeResult.type)) {
                typeResult.type = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(typeResult.type, inferenceContext.signatureTracker, node.start);
            }
            if (!typeResult.isIncomplete && !typeResult.expectedTypeDiagAddendum) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                // Make sure the resulting type is assignable to the expected type.
                if (!assignType(inferenceContext.expectedType, typeResult.type, diag, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 1024 /* AssignTypeFlags.IgnoreTypeVarScope */)) {
                    typeResult.typeErrors = true;
                    typeResult.expectedTypeDiagAddendum = diag;
                    diag.addTextRange(node);
                }
            }
        }
        if (printExpressionTypes) {
            printExpressionSpaceCount--;
            console.log(`${getPrintExpressionTypesSpaces()}${ParseTreeUtils.printExpression(node)} (${getLineNum(node)}): Post ${printType(typeResult.type)}${typeResult.isIncomplete ? ' Incomplete' : ''}`);
        }
        return typeResult;
    }
    // Reports the case where a function or class has been decorated with
    // @type_check_only and is used in a value expression.
    function reportUseOfTypeCheckOnly(type, node) {
        let isTypeCheckingOnly = false;
        let name = '';
        if ((0, types_1.isInstantiableClass)(type) && !type.includeSubclasses) {
            isTypeCheckingOnly = types_1.ClassType.isTypeCheckOnly(type);
            name = type.details.name;
        }
        else if ((0, types_1.isFunction)(type)) {
            isTypeCheckingOnly = types_1.FunctionType.isTypeCheckOnly(type);
            name = type.details.name;
        }
        if (isTypeCheckingOnly) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            if (!fileInfo.isStubFile) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeCheckOnly().format({ name }), node);
            }
        }
    }
    function validateTypeIsInstantiable(typeResult, flags, node) {
        var _a;
        // If the type is incomplete, don't log any diagnostics yet.
        if (typeResult.isIncomplete) {
            return;
        }
        if (flags & 64 /* EvaluatorFlags.DisallowTypeVarTuple */) {
            if ((0, types_1.isVariadicTypeVar)(typeResult.type) && !typeResult.type.isVariadicInUnion) {
                addError(localize_1.LocMessage.typeVarTupleContext(), node);
                typeResult.type = types_1.UnknownType.create();
            }
        }
        if (!(0, typeUtils_1.isEffectivelyInstantiable)(typeResult.type)) {
            const isEmptyVariadic = (0, types_1.isClassInstance)(typeResult.type) &&
                types_1.ClassType.isTupleClass(typeResult.type) &&
                ((_a = typeResult.type.tupleTypeArguments) === null || _a === void 0 ? void 0 : _a.length) === 0;
            const isEllipsis = (0, types_1.isClassInstance)(typeResult.type) && types_1.ClassType.isBuiltIn(typeResult.type, ['EllipsisType', 'ellipsis']);
            if (!isEmptyVariadic && !isEllipsis) {
                addExpectedClassDiagnostic(typeResult.type, node);
                typeResult.type = types_1.UnknownType.create();
                typeResult.typeErrors = true;
            }
        }
    }
    function getTypeOfAwaitOperator(node, flags, inferenceContext) {
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
            addError(localize_1.LocMessage.awaitNotAllowed(), node);
            return { type: types_1.UnknownType.create() };
        }
        const effectiveExpectedType = inferenceContext
            ? createAwaitableReturnType(node, inferenceContext.expectedType, 
            /* isGenerator */ false, 
            /* useCoroutine */ false)
            : undefined;
        const exprTypeResult = getTypeOfExpression(node.expression, flags, (0, typeUtils_1.makeInferenceContext)(effectiveExpectedType));
        const typeResult = {
            type: getTypeOfAwaitable(exprTypeResult.type, node.expression),
            isIncomplete: exprTypeResult.isIncomplete,
            typeErrors: exprTypeResult.typeErrors,
        };
        if (exprTypeResult.isIncomplete) {
            typeResult.isIncomplete = true;
        }
        return typeResult;
    }
    function getTypeOfEllipsis(flags, typeResult, node) {
        var _a, _b;
        if ((flags & 1 /* EvaluatorFlags.ConvertEllipsisToAny */) !== 0) {
            typeResult = { type: types_1.AnyType.create(/* isEllipsis */ true) };
        }
        else {
            const ellipsisType = (_b = (_a = getBuiltInObject(node, 'EllipsisType')) !== null && _a !== void 0 ? _a : getBuiltInObject(node, 'ellipsis')) !== null && _b !== void 0 ? _b : types_1.AnyType.create();
            typeResult = { type: ellipsisType };
        }
        return typeResult;
    }
    function getTypeOfNumber(node, typeResult) {
        if (node.isImaginary) {
            typeResult = { type: getBuiltInObject(node, 'complex') };
        }
        else if (node.isInteger) {
            typeResult = { type: cloneBuiltinObjectWithLiteral(node, 'int', node.value) };
        }
        else {
            typeResult = { type: getBuiltInObject(node, 'float') };
        }
        return typeResult;
    }
    function getTypeOfUnpackOperator(node, flags, inferenceContext) {
        var _a;
        let typeResult;
        let iterExpectedType;
        if (inferenceContext) {
            const iterableType = getBuiltInType(node, 'Iterable');
            if (iterableType && (0, types_1.isInstantiableClass)(iterableType)) {
                iterExpectedType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(iterableType, [inferenceContext.expectedType], 
                /* isTypeArgumentExplicit */ true));
            }
        }
        const iterTypeResult = getTypeOfExpression(node.expression, flags, (0, typeUtils_1.makeInferenceContext)(iterExpectedType));
        const iterType = iterTypeResult.type;
        if ((flags & 64 /* EvaluatorFlags.DisallowTypeVarTuple */) === 0 &&
            (0, types_1.isVariadicTypeVar)(iterType) &&
            !iterType.isVariadicUnpacked) {
            typeResult = { type: types_1.TypeVarType.cloneForUnpacked(iterType) };
        }
        else if ((flags & 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */) !== 0 &&
            (0, types_1.isInstantiableClass)(iterType) &&
            types_1.ClassType.isBuiltIn(iterType, 'tuple')) {
            typeResult = { type: types_1.ClassType.cloneForUnpacked(iterType) };
        }
        else if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
            addError(localize_1.LocMessage.unpackInAnnotation(), node, node.starToken);
            typeResult = { type: types_1.UnknownType.create() };
        }
        else {
            const iteratorTypeResult = (_a = getTypeOfIterator(iterTypeResult, /* isAsync */ false, node)) !== null && _a !== void 0 ? _a : {
                type: types_1.UnknownType.create(!!iterTypeResult.isIncomplete),
                isIncomplete: iterTypeResult.isIncomplete,
            };
            typeResult = {
                type: iteratorTypeResult.type,
                typeErrors: iterTypeResult.typeErrors,
                unpackedType: iterType,
                isIncomplete: iteratorTypeResult.isIncomplete,
            };
        }
        return typeResult;
    }
    function getTypeOfStringList(node, flags, isExpectingType) {
        let typeResult;
        if (isExpectingType) {
            let updatedFlags = flags | 4 /* EvaluatorFlags.AllowForwardReferences */ | 128 /* EvaluatorFlags.ExpectingInstantiableType */;
            // In most cases, annotations within a string are not parsed by the interpreter.
            // There are a few exceptions (e.g. the "bound" value for a TypeVar constructor).
            if ((flags & 4194304 /* EvaluatorFlags.InterpreterParsesStringLiteral */) === 0) {
                updatedFlags |= 524288 /* EvaluatorFlags.NotParsedByInterpreter */;
            }
            if (node.typeAnnotation) {
                typeResult = getTypeOfExpression(node.typeAnnotation, updatedFlags);
            }
            else if (!node.typeAnnotation && node.strings.length === 1) {
                const tokenFlags = node.strings[0].token.flags;
                if (tokenFlags & 32 /* StringTokenFlags.Bytes */) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.annotationBytesString(), node);
                    typeResult = { type: types_1.UnknownType.create() };
                }
                else if (tokenFlags & 8 /* StringTokenFlags.Raw */) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.annotationRawString(), node);
                    typeResult = { type: types_1.UnknownType.create() };
                }
                else if (tokenFlags & 64 /* StringTokenFlags.Format */) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.annotationFormatString(), node);
                    typeResult = { type: types_1.UnknownType.create() };
                }
                else {
                    // We didn't know at parse time that this string node was going
                    // to be evaluated as a forward-referenced type. We need
                    // to re-invoke the parser at this stage.
                    const expr = parseStringAsTypeAnnotation(node);
                    if (expr) {
                        typeResult = getTypeOfExpression(expr, updatedFlags);
                    }
                }
            }
            if (!typeResult) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.expectedTypeNotString(), node);
                typeResult = { type: types_1.UnknownType.create() };
            }
        }
        else {
            // Evaluate the format string expressions in this context.
            let isLiteralString = true;
            let isIncomplete = false;
            node.strings.forEach((expr) => {
                const typeResult = getTypeOfString(expr);
                if (typeResult.isIncomplete) {
                    isIncomplete = true;
                }
                let isExprLiteralString = false;
                if ((0, types_1.isClassInstance)(typeResult.type)) {
                    if (types_1.ClassType.isBuiltIn(typeResult.type, 'str') && typeResult.type.literalValue !== undefined) {
                        isExprLiteralString = true;
                    }
                    else if (types_1.ClassType.isBuiltIn(typeResult === null || typeResult === void 0 ? void 0 : typeResult.type, 'LiteralString')) {
                        isExprLiteralString = true;
                    }
                }
                if (!isExprLiteralString) {
                    isLiteralString = false;
                }
            });
            const isBytes = (node.strings[0].token.flags & 32 /* StringTokenFlags.Bytes */) !== 0;
            // Don't create a literal type if it's an f-string.
            if (node.strings.some((str) => str.nodeType === 27 /* ParseNodeType.FormatString */)) {
                if (isLiteralString) {
                    const literalStringType = getTypingType(node, 'LiteralString');
                    if (literalStringType && (0, types_1.isInstantiableClass)(literalStringType)) {
                        typeResult = { type: types_1.ClassType.cloneAsInstance(literalStringType) };
                    }
                }
                if (!typeResult) {
                    typeResult = {
                        type: getBuiltInObject(node, isBytes ? 'bytes' : 'str'),
                        isIncomplete,
                    };
                }
            }
            else {
                typeResult = {
                    type: cloneBuiltinObjectWithLiteral(node, isBytes ? 'bytes' : 'str', node.strings.map((s) => s.value).join('')),
                    isIncomplete,
                };
            }
        }
        return typeResult;
    }
    function getTypeOfString(node) {
        const isBytes = (node.token.flags & 32 /* StringTokenFlags.Bytes */) !== 0;
        let typeResult;
        let isIncomplete = false;
        // Don't create a literal type if it's an f-string.
        if (node.nodeType === 27 /* ParseNodeType.FormatString */) {
            let isLiteralString = true;
            // If all of the format expressions are of type LiteralString, then
            // the resulting formatted string is also LiteralString.
            node.fieldExpressions.forEach((expr) => {
                const exprTypeResult = getTypeOfExpression(expr);
                const exprType = exprTypeResult.type;
                if (exprTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                (0, typeUtils_1.doForEachSubtype)(exprType, (exprSubtype) => {
                    if (!(0, types_1.isClassInstance)(exprSubtype)) {
                        isLiteralString = false;
                        return;
                    }
                    if (types_1.ClassType.isBuiltIn(exprSubtype, 'LiteralString')) {
                        return;
                    }
                    if (types_1.ClassType.isBuiltIn(exprSubtype, 'str') && exprSubtype.literalValue !== undefined) {
                        return;
                    }
                    isLiteralString = false;
                });
            });
            if (!isBytes && isLiteralString) {
                const literalStringType = getTypingType(node, 'LiteralString');
                if (literalStringType && (0, types_1.isInstantiableClass)(literalStringType)) {
                    typeResult = { type: types_1.ClassType.cloneAsInstance(literalStringType), isIncomplete };
                }
            }
            if (!typeResult) {
                typeResult = {
                    type: getBuiltInObject(node, isBytes ? 'bytes' : 'str'),
                    isIncomplete,
                };
                if ((0, types_1.isClass)(typeResult.type) && typeResult.type.includePromotions) {
                    typeResult.type = types_1.ClassType.cloneRemoveTypePromotions(typeResult.type);
                }
            }
        }
        else {
            typeResult = {
                type: cloneBuiltinObjectWithLiteral(node, isBytes ? 'bytes' : 'str', node.value),
                isIncomplete,
            };
        }
        return typeResult;
    }
    function stripLiteralValue(type) {
        var _a, _b, _c;
        // Handle the not-uncommon case where the type is a union that consists
        // only of literal values.
        if ((0, types_1.isUnion)(type) && type.subtypes.length > 0) {
            if (((_a = type.literalInstances.literalStrMap) === null || _a === void 0 ? void 0 : _a.size) === type.subtypes.length ||
                ((_b = type.literalInstances.literalIntMap) === null || _b === void 0 ? void 0 : _b.size) === type.subtypes.length ||
                ((_c = type.literalInstances.literalEnumMap) === null || _c === void 0 ? void 0 : _c.size) === type.subtypes.length) {
                return stripLiteralValue(type.subtypes[0]);
            }
        }
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            if ((0, types_1.isClass)(subtype)) {
                if (subtype.literalValue !== undefined) {
                    return types_1.ClassType.cloneWithLiteral(subtype, /* value */ undefined);
                }
                if (types_1.ClassType.isBuiltIn(subtype, 'LiteralString')) {
                    // Handle "LiteralString" specially.
                    if (strClassType && (0, types_1.isInstantiableClass)(strClassType)) {
                        let strInstance = types_1.ClassType.cloneAsInstance(strClassType);
                        if (subtype.condition) {
                            strInstance = types_1.TypeBase.cloneForCondition(strInstance, (0, typeUtils_1.getTypeCondition)(subtype));
                        }
                        return strInstance;
                    }
                }
            }
            return subtype;
        });
    }
    function getTypeOfParameterAnnotation(paramTypeNode, paramCategory) {
        return getTypeOfAnnotation(paramTypeNode, {
            associateTypeVarsWithScope: true,
            allowTypeVarTuple: paramCategory === 1 /* ParameterCategory.ArgsList */,
            allowUnpackedTypedDict: paramCategory === 2 /* ParameterCategory.KwargsDict */,
            allowUnpackedTuple: paramCategory === 1 /* ParameterCategory.ArgsList */,
        });
    }
    function getTypeOfAnnotation(node, options) {
        var _a, _b, _c;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        // Special-case the typing.pyi file, which contains some special
        // types that the type analyzer needs to interpret differently.
        if (fileInfo.isTypingStubFile || fileInfo.isTypingExtensionsStubFile) {
            const specialType = handleTypingStubTypeAnnotation(node);
            if (specialType) {
                return specialType;
            }
        }
        let evaluatorFlags = 128 /* EvaluatorFlags.ExpectingInstantiableType */ |
            256 /* EvaluatorFlags.ExpectingTypeAnnotation */ |
            1 /* EvaluatorFlags.ConvertEllipsisToAny */ |
            8 /* EvaluatorFlags.EvaluateStringLiteralAsType */;
        if (options === null || options === void 0 ? void 0 : options.isVariableAnnotation) {
            evaluatorFlags |= 32768 /* EvaluatorFlags.VariableTypeAnnotation */;
        }
        if (!(options === null || options === void 0 ? void 0 : options.allowFinal)) {
            evaluatorFlags |= 16 /* EvaluatorFlags.DisallowFinal */;
        }
        if (!(options === null || options === void 0 ? void 0 : options.allowClassVar)) {
            evaluatorFlags |= 131072 /* EvaluatorFlags.DisallowClassVar */;
        }
        if (!(options === null || options === void 0 ? void 0 : options.allowTypeVarTuple)) {
            evaluatorFlags |= 64 /* EvaluatorFlags.DisallowTypeVarTuple */;
        }
        else {
            evaluatorFlags |= 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */;
        }
        if (!(options === null || options === void 0 ? void 0 : options.allowParamSpec)) {
            evaluatorFlags |= 32 /* EvaluatorFlags.DisallowParamSpec */;
        }
        if (options === null || options === void 0 ? void 0 : options.associateTypeVarsWithScope) {
            evaluatorFlags |= 8192 /* EvaluatorFlags.AssociateTypeVarsWithCurrentScope */;
        }
        if (options === null || options === void 0 ? void 0 : options.allowUnpackedTypedDict) {
            evaluatorFlags |= 8388608 /* EvaluatorFlags.AllowUnpackedTypedDict */;
        }
        if (options === null || options === void 0 ? void 0 : options.allowUnpackedTuple) {
            evaluatorFlags |= 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */;
        }
        if (options === null || options === void 0 ? void 0 : options.notParsedByInterpreter) {
            evaluatorFlags |= 524288 /* EvaluatorFlags.NotParsedByInterpreter */;
        }
        if (options === null || options === void 0 ? void 0 : options.allowRequired) {
            evaluatorFlags |= 1048576 /* EvaluatorFlags.AllowRequired */;
        }
        if ((0, analyzerFileInfo_1.isAnnotationEvaluationPostponed)(fileInfo)) {
            evaluatorFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */;
        }
        // If the annotation is part of a comment, allow forward references
        // even if it's not enclosed in quotes.
        if (((_a = node === null || node === void 0 ? void 0 : node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */ && node.parent.typeAnnotationComment === node) {
            evaluatorFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */ | 524288 /* EvaluatorFlags.NotParsedByInterpreter */;
        }
        else if (((_b = node === null || node === void 0 ? void 0 : node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 62 /* ParseNodeType.FunctionAnnotation */) {
            if (node.parent.returnTypeAnnotation === node || node.parent.paramTypeAnnotations.some((n) => n === node)) {
                evaluatorFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */ | 524288 /* EvaluatorFlags.NotParsedByInterpreter */;
            }
        }
        else if (((_c = node === null || node === void 0 ? void 0 : node.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 41 /* ParseNodeType.Parameter */) {
            if (node.parent.typeAnnotationComment === node) {
                evaluatorFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */ | 524288 /* EvaluatorFlags.NotParsedByInterpreter */;
            }
        }
        const annotationType = getTypeOfExpression(node, evaluatorFlags).type;
        if ((0, types_1.isModule)(annotationType)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.moduleAsType(), node);
        }
        return (0, typeUtils_1.convertToInstance)(annotationType);
    }
    function canBeFalsy(type, recursionCount = 0) {
        type = makeTopLevelTypeVarsConcrete(type);
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return true;
        }
        recursionCount++;
        switch (type.category) {
            case 0 /* TypeCategory.Unbound */:
            case 1 /* TypeCategory.Unknown */:
            case 2 /* TypeCategory.Any */:
            case 3 /* TypeCategory.Never */: {
                return true;
            }
            case 8 /* TypeCategory.Union */: {
                return (0, types_1.findSubtype)(type, (subtype) => canBeFalsy(subtype, recursionCount)) !== undefined;
            }
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */:
            case 7 /* TypeCategory.Module */:
            case 9 /* TypeCategory.TypeVar */: {
                return false;
            }
            case 6 /* TypeCategory.Class */: {
                if (types_1.TypeBase.isInstantiable(type)) {
                    return false;
                }
                // Handle tuples specially.
                if ((0, typeUtils_1.isTupleClass)(type) && type.tupleTypeArguments) {
                    return (0, typeUtils_1.isUnboundedTupleClass)(type) || type.tupleTypeArguments.length === 0;
                }
                // Handle subclasses of tuple, such as NamedTuple.
                const tupleBaseClass = type.details.mro.find((mroClass) => !(0, types_1.isClass)(mroClass) || (0, typeUtils_1.isTupleClass)(mroClass));
                if (tupleBaseClass && (0, types_1.isClass)(tupleBaseClass) && tupleBaseClass.tupleTypeArguments) {
                    return (0, typeUtils_1.isUnboundedTupleClass)(tupleBaseClass) || tupleBaseClass.tupleTypeArguments.length === 0;
                }
                // Check for Literal[False] and Literal[True].
                if (types_1.ClassType.isBuiltIn(type, 'bool') && type.literalValue !== undefined) {
                    return type.literalValue === false;
                }
                // If this is a protocol class, don't make any assumptions about the absence
                // of specific methods. These could be provided by a class that conforms
                // to the protocol.
                if (types_1.ClassType.isProtocolClass(type)) {
                    return true;
                }
                const lenMethod = (0, typeUtils_1.lookUpObjectMember)(type, '__len__');
                if (lenMethod) {
                    return true;
                }
                const boolMethod = (0, typeUtils_1.lookUpObjectMember)(type, '__bool__');
                if (boolMethod) {
                    const boolMethodType = getTypeOfMember(boolMethod);
                    // If the __bool__ function unconditionally returns True, it can never be falsy.
                    if ((0, types_1.isFunction)(boolMethodType) && boolMethodType.details.declaredReturnType) {
                        const returnType = boolMethodType.details.declaredReturnType;
                        if ((0, types_1.isClassInstance)(returnType) &&
                            types_1.ClassType.isBuiltIn(returnType, 'bool') &&
                            returnType.literalValue === true) {
                            return false;
                        }
                    }
                    return true;
                }
                // If the class is not final, it's possible that it could be overridden
                // such that it is falsy. To be fully correct, we'd need to do the
                // following:
                // return !ClassType.isFinal(type);
                // However, pragmatically if the class is not an `object`, it's typically
                // OK to assume that it will not be overridden in this manner.
                return types_1.ClassType.isBuiltIn(type, 'object');
            }
        }
    }
    function canBeTruthy(type, recursionCount = 0) {
        type = makeTopLevelTypeVarsConcrete(type);
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return true;
        }
        recursionCount++;
        switch (type.category) {
            case 1 /* TypeCategory.Unknown */:
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */:
            case 7 /* TypeCategory.Module */:
            case 9 /* TypeCategory.TypeVar */:
            case 3 /* TypeCategory.Never */:
            case 2 /* TypeCategory.Any */: {
                return true;
            }
            case 8 /* TypeCategory.Union */: {
                return (0, types_1.findSubtype)(type, (subtype) => canBeTruthy(subtype, recursionCount)) !== undefined;
            }
            case 0 /* TypeCategory.Unbound */: {
                return false;
            }
            case 6 /* TypeCategory.Class */: {
                if (types_1.TypeBase.isInstantiable(type)) {
                    return true;
                }
                if ((0, typeUtils_1.isNoneInstance)(type)) {
                    return false;
                }
                // Check for Tuple[()] (an empty tuple).
                if ((0, typeUtils_1.isTupleClass)(type)) {
                    if (type.tupleTypeArguments && type.tupleTypeArguments.length === 0) {
                        return false;
                    }
                }
                // Check for Literal[False], Literal[0], Literal[""].
                if (type.literalValue === false ||
                    type.literalValue === 0 ||
                    type.literalValue === BigInt(0) ||
                    type.literalValue === '') {
                    return false;
                }
                // If this is a protocol class, don't make any assumptions about the absence
                // of specific methods. These could be provided by a class that conforms
                // to the protocol.
                if (types_1.ClassType.isProtocolClass(type)) {
                    return true;
                }
                const boolMethod = (0, typeUtils_1.lookUpObjectMember)(type, '__bool__');
                if (boolMethod) {
                    const boolMethodType = getTypeOfMember(boolMethod);
                    // If the __bool__ function unconditionally returns False, it can never be truthy.
                    if ((0, types_1.isFunction)(boolMethodType) && boolMethodType.details.declaredReturnType) {
                        const returnType = boolMethodType.details.declaredReturnType;
                        if ((0, types_1.isClassInstance)(returnType) &&
                            types_1.ClassType.isBuiltIn(returnType, 'bool') &&
                            returnType.literalValue === false) {
                            return false;
                        }
                    }
                }
                return true;
            }
        }
    }
    // Filters a type such that that no part of it is definitely
    // truthy. For example, if a type is a union of None
    // and a custom class "Foo" that has no __len__ or __nonzero__
    // method, this method would strip off the "Foo"
    // and return only the "None".
    function removeTruthinessFromType(type) {
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            const concreteSubtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isClassInstance)(concreteSubtype)) {
                if (concreteSubtype.literalValue !== undefined) {
                    // If the object is already definitely falsy, it's fine to
                    // include, otherwise it should be removed.
                    return !concreteSubtype.literalValue ? subtype : undefined;
                }
                // If the object is a bool, make it "false", since
                // "true" is a truthy value.
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'bool')) {
                    return types_1.ClassType.cloneWithLiteral(concreteSubtype, /* value */ false);
                }
                // If the object is an int, str or bytes, narrow to a literal type.
                // This is slightly unsafe in that someone could subclass `int`, `str`
                // or `bytes` and override the `__bool__` method to change its behavior,
                // but this is extremely unlikely (and ill advised).
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'int')) {
                    return types_1.ClassType.cloneWithLiteral(concreteSubtype, /* value */ 0);
                }
                else if (types_1.ClassType.isBuiltIn(concreteSubtype, ['str', 'bytes'])) {
                    return types_1.ClassType.cloneWithLiteral(concreteSubtype, /* value */ '');
                }
            }
            // If it's possible for the type to be falsy, include it.
            if (canBeFalsy(subtype)) {
                return subtype;
            }
            return undefined;
        });
    }
    // Filters a type such that that no part of it is definitely
    // falsy. For example, if a type is a union of None
    // and an "int", this method would strip off the "None"
    // and return only the "int".
    function removeFalsinessFromType(type) {
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            const concreteSubtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isClassInstance)(concreteSubtype)) {
                if (concreteSubtype.literalValue !== undefined) {
                    // If the object is already definitely truthy, it's fine to
                    // include, otherwise it should be removed.
                    return concreteSubtype.literalValue ? subtype : undefined;
                }
                // If the object is a bool, make it "true", since
                // "false" is a falsy value.
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'bool')) {
                    return types_1.ClassType.cloneWithLiteral(concreteSubtype, /* value */ true);
                }
                // If the object is a "None" instance, we can eliminate it.
                if ((0, typeUtils_1.isNoneInstance)(concreteSubtype)) {
                    return undefined;
                }
                // If this is an instance of a class that cannot be subclassed,
                // we cannot say definitively that it's not falsy because a subclass
                // could override `__bool__`. For this reason, the code should not
                // remove any classes that are not final.
                // if (!ClassType.isFinal(concreteSubtype)) {
                //     return subtype;
                // }
                // However, we're going to pragmatically assume that any classes
                // other than `object` will not be overridden in this manner.
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'object')) {
                    return subtype;
                }
            }
            // If it's possible for the type to be truthy, include it.
            if (canBeTruthy(subtype)) {
                return subtype;
            }
            return undefined;
        });
    }
    // Gets a member type from an object or class. If it's a function, binds
    // it to the object or class. If selfType is undefined, the binding is done
    // using the objectType parameter. Callers can specify these separately
    // to handle the case where we're fetching the object member from a
    // metaclass but binding to the class.
    function getTypeOfBoundMember(errorNode, objectType, memberName, usage = { method: 'get' }, diag = undefined, flags = 0 /* MemberAccessFlags.Default */, selfType, recursionCount = 0) {
        if (types_1.ClassType.isPartiallyEvaluated(objectType)) {
            if (errorNode) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.classDefinitionCycle().format({ name: objectType.details.name }), errorNode);
            }
            return { type: types_1.UnknownType.create() };
        }
        // If this is an unspecialized generic class, specialize it using the default
        // values for its type parameters.
        if ((0, types_1.isInstantiableClass)(objectType) &&
            !objectType.includeSubclasses &&
            objectType.details.typeParameters.length > 0) {
            // Skip this if we're suppressing the use of attribute access override,
            // such as with dundered methods (like __call__).
            if ((flags & 512 /* MemberAccessFlags.SkipAttributeAccessOverride */) === 0) {
                objectType = (0, typeUtils_1.specializeWithDefaultTypeArgs)(objectType);
            }
        }
        // Determine the class that was used to instantiate the objectType.
        // If the objectType is a class itself, then the class used to instantiate
        // it is the metaclass.
        const objectTypeIsInstantiable = types_1.TypeBase.isInstantiable(objectType);
        const metaclass = objectType.details.effectiveMetaclass;
        let memberInfo;
        // If the object type is an instantiable (i.e. it derives from "type") and
        // we've been asked not to consider instance members, don't look in the class.
        // Consider only the metaclass class variables in this case.
        let skipObjectTypeLookup = objectTypeIsInstantiable && (flags & 16 /* MemberAccessFlags.SkipInstanceMembers */) !== 0;
        // Look up the attribute in the metaclass first. If the member is a descriptor
        // (an object with a __get__ and __set__ method) and the access is a 'get',
        // the Python runtime uses this descriptor to satisfy the lookup. Skip this
        // costly lookup in the common case where the metaclass is 'type' since we know
        // that `type` doesn't have any attributes that are descriptors.
        if (usage.method === 'get' &&
            objectTypeIsInstantiable &&
            metaclass &&
            (0, types_1.isInstantiableClass)(metaclass) &&
            !types_1.ClassType.isBuiltIn(metaclass, 'type') &&
            !types_1.ClassType.isSameGenericClass(metaclass, objectType)) {
            const descMemberInfo = getTypeOfClassMemberName(errorNode, metaclass, memberName, usage, 
            /* diag */ undefined, flags | 512 /* MemberAccessFlags.SkipAttributeAccessOverride */, objectType, recursionCount);
            if (descMemberInfo) {
                const isProperty = (0, types_1.isClassInstance)(descMemberInfo.type) && types_1.ClassType.isPropertyClass(descMemberInfo.type);
                if ((0, typeUtils_1.isDescriptorInstance)(descMemberInfo.type, /* requireSetter */ true) || isProperty) {
                    skipObjectTypeLookup = true;
                }
            }
        }
        let subDiag;
        if (!skipObjectTypeLookup) {
            let effectiveFlags = flags;
            if (objectTypeIsInstantiable) {
                effectiveFlags |=
                    16 /* MemberAccessFlags.SkipInstanceMembers */ |
                        512 /* MemberAccessFlags.SkipAttributeAccessOverride */ |
                        1024 /* MemberAccessFlags.DisallowGenericInstanceVariableAccess */;
                effectiveFlags &= ~32 /* MemberAccessFlags.SkipClassMembers */;
            }
            else {
                effectiveFlags |= 128 /* MemberAccessFlags.DisallowClassVarWrites */;
            }
            subDiag = diag ? new diagnostic_1.DiagnosticAddendum() : undefined;
            // See if the member is present in the object itself.
            memberInfo = getTypeOfClassMemberName(errorNode, objectType, memberName, usage, subDiag, effectiveFlags, selfType, recursionCount);
        }
        // If it wasn't found on the object, see if it's part of the metaclass.
        if (!memberInfo && metaclass && (0, types_1.isInstantiableClass)(metaclass)) {
            let effectiveFlags = flags;
            // Class members cannot be accessed on a class's metaclass through
            // an instance of a class. Limit access to metaclass instance members
            // in this case.
            if (!objectTypeIsInstantiable) {
                effectiveFlags |=
                    32 /* MemberAccessFlags.SkipClassMembers */ |
                        512 /* MemberAccessFlags.SkipAttributeAccessOverride */ |
                        8 /* MemberAccessFlags.SkipTypeBaseClass */;
                effectiveFlags &= ~16 /* MemberAccessFlags.SkipInstanceMembers */;
            }
            const metaclassDiag = diag ? new diagnostic_1.DiagnosticAddendum() : undefined;
            memberInfo = getTypeOfClassMemberName(errorNode, types_1.ClassType.cloneAsInstance(metaclass), memberName, usage, metaclassDiag, effectiveFlags, objectTypeIsInstantiable ? objectType : types_1.ClassType.cloneAsInstantiable(objectType), recursionCount);
            // If there was a descriptor error (as opposed to an error where the members
            // was simply not found), use this diagnostic message.
            if (memberInfo === null || memberInfo === void 0 ? void 0 : memberInfo.isDescriptorError) {
                subDiag = metaclassDiag;
            }
        }
        if (memberInfo) {
            if (memberInfo.isDescriptorError && diag && subDiag) {
                diag.addAddendum(subDiag);
            }
            return {
                type: memberInfo.type,
                classType: memberInfo.classType,
                isIncomplete: !!memberInfo.isTypeIncomplete,
                isAsymmetricAccessor: memberInfo.isAsymmetricAccessor,
                narrowedTypeForSet: memberInfo.narrowedTypeForSet,
                memberAccessDeprecationInfo: memberInfo.memberAccessDeprecationInfo,
                typeErrors: memberInfo.isDescriptorError,
            };
        }
        // If this is a type[Any] or type[Unknown], allow any other members.
        if ((0, types_1.isClassInstance)(objectType) && types_1.ClassType.isBuiltIn(objectType, 'type') && objectType.includeSubclasses) {
            if ((flags & 8 /* MemberAccessFlags.SkipTypeBaseClass */) === 0) {
                const typeArg = objectType.typeArguments && objectType.typeArguments.length >= 1
                    ? objectType.typeArguments[0]
                    : types_1.UnknownType.create();
                if ((0, types_1.isAnyOrUnknown)(typeArg)) {
                    return { type: typeArg, classType: types_1.UnknownType.create() };
                }
            }
        }
        if (diag && subDiag) {
            diag.addAddendum(subDiag);
        }
        return undefined;
    }
    function getBoundMagicMethod(classType, memberName, selfType, diag, recursionCount = 0) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return undefined;
        }
        recursionCount++;
        const boundMethodResult = getTypeOfBoundMember(
        /* errorNode */ undefined, classType, memberName, 
        /* usage */ undefined, diag, 16 /* MemberAccessFlags.SkipInstanceMembers */ | 512 /* MemberAccessFlags.SkipAttributeAccessOverride */, selfType, recursionCount);
        if (!boundMethodResult || boundMethodResult.typeErrors) {
            return undefined;
        }
        if ((0, types_1.isFunction)(boundMethodResult.type) || (0, types_1.isOverloadedFunction)(boundMethodResult.type)) {
            return boundMethodResult.type;
        }
        if ((0, types_1.isClassInstance)(boundMethodResult.type)) {
            return getBoundMagicMethod(boundMethodResult.type, '__call__', selfType !== null && selfType !== void 0 ? selfType : types_1.ClassType.cloneAsInstance(classType), diag, recursionCount);
        }
        if ((0, types_1.isAnyOrUnknown)(boundMethodResult.type)) {
            return (0, typeUtils_1.getUnknownTypeForCallable)();
        }
        return undefined;
    }
    //TODO: refactor this. it's mostly copied from getCallSignatureInfo, and duplicated code is bad esspecially when merging upstream changes
    function matchCallArgsToParams(callNode, callType = getType(callNode.leftExpression)) {
        const exprNode = callNode.leftExpression;
        if (callType === undefined) {
            return undefined;
        }
        const argList = [];
        callNode.arguments.forEach((arg) => {
            argList.push({
                valueExpression: arg.valueExpression,
                argumentCategory: arg.argumentCategory,
                name: arg.name,
            });
        });
        const calls = [];
        function addOneFunctionToSignature(type) {
            useSpeculativeMode(callNode, () => {
                const match = matchFunctionArgumentsToParameters(exprNode, argList, { type }, 0);
                calls.push({
                    match: match,
                    type: type,
                });
            });
        }
        function addFunctionToSignature(type) {
            if ((0, types_1.isFunction)(type)) {
                addOneFunctionToSignature(type);
            }
            else {
                types_1.OverloadedFunctionType.getOverloads(type).forEach((func) => {
                    addOneFunctionToSignature(func);
                });
            }
        }
        (0, typeUtils_1.doForEachSubtype)(callType, (subtype) => {
            switch (subtype.category) {
                case 4 /* TypeCategory.Function */:
                case 5 /* TypeCategory.OverloadedFunction */: {
                    addFunctionToSignature(subtype);
                    break;
                }
                case 6 /* TypeCategory.Class */: {
                    if (types_1.TypeBase.isInstantiable(subtype)) {
                        let constructorType;
                        // Try to get the `__init__` method first because it typically has more
                        // type information than `__new__`.
                        const initMethodResult = (0, constructors_1.getBoundInitMethod)(evaluatorInterface, callNode, types_1.ClassType.cloneAsInstance(subtype), 
                        /* diag */ undefined, 0 /* MemberAccessFlags.Default */);
                        if (initMethodResult && !initMethodResult.typeErrors) {
                            if ((0, types_1.isFunction)(initMethodResult.type) || (0, types_1.isOverloadedFunction)(initMethodResult.type)) {
                                constructorType = initMethodResult.type;
                            }
                        }
                        const isObjectInit = constructorType &&
                            (0, types_1.isFunction)(constructorType) &&
                            constructorType.details.fullName === 'builtins.object.__init__';
                        const isDefaultParams = constructorType &&
                            (0, types_1.isFunction)(constructorType) &&
                            types_1.FunctionType.hasDefaultParameters(constructorType);
                        // If there was no `__init__` or the only `__init__` that was found was from
                        // the `object` class or accepts only default parameters(* args, ** kwargs),
                        // see if we can find a better signature from the `__new__` method.
                        if (!constructorType || isObjectInit || isDefaultParams) {
                            const newMethodResult = (0, constructors_1.getBoundNewMethod)(evaluatorInterface, callNode, subtype);
                            if (newMethodResult && !newMethodResult.typeErrors && (0, types_1.isFunction)(newMethodResult.type)) {
                                if ((0, types_1.isFunction)(newMethodResult.type) &&
                                    newMethodResult.type.details.fullName !== 'builtins.object.__new__') {
                                    constructorType = newMethodResult.type;
                                }
                                else if ((0, types_1.isOverloadedFunction)(newMethodResult.type)) {
                                    constructorType = newMethodResult.type;
                                }
                            }
                        }
                        if (constructorType) {
                            addFunctionToSignature(constructorType);
                        }
                    }
                    else {
                        const methodType = getBoundMagicMethod(subtype, '__call__');
                        if (methodType) {
                            addFunctionToSignature(methodType);
                        }
                    }
                    break;
                }
            }
        });
        if (calls.length === 0) {
            return undefined;
        }
        return calls;
    }
    // Returns the signature(s) associated with a call node that contains
    // the specified node. It also returns the index of the argument
    // that contains the node.
    function getCallSignatureInfo(callNode, activeIndex, activeOrFake) {
        const exprNode = callNode.leftExpression;
        const callType = getType(exprNode);
        if (!callType) {
            return undefined;
        }
        const argList = [];
        let previousCategory = 0 /* ArgumentCategory.Simple */;
        // Empty arguments do not enter the AST as nodes, but instead are left blank.
        // Instead, we detect when we appear to be between two known arguments or at the
        // end of the argument list and insert a fake argument of an unknown type to have
        // something to match later.
        function addFakeArg() {
            argList.push({
                argumentCategory: previousCategory,
                typeResult: { type: types_1.UnknownType.create() },
                active: true,
            });
        }
        callNode.arguments.forEach((arg, index) => {
            let active = false;
            if (index === activeIndex) {
                if (activeOrFake) {
                    active = true;
                }
                else {
                    addFakeArg();
                }
            }
            previousCategory = arg.argumentCategory;
            argList.push({
                valueExpression: arg.valueExpression,
                argumentCategory: arg.argumentCategory,
                name: arg.name,
                active: active,
            });
        });
        if (callNode.arguments.length < activeIndex) {
            addFakeArg();
        }
        const signatures = [];
        function addOneFunctionToSignature(type) {
            let callResult;
            useSpeculativeMode(callNode, () => {
                callResult = validateFunctionArguments(exprNode, argList, { type }, new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(type)), 
                /* skipUnknownArgCheck */ true);
            });
            signatures.push({
                type: expandTypedKwargs(type),
                activeParam: callResult === null || callResult === void 0 ? void 0 : callResult.activeParam,
            });
        }
        function addFunctionToSignature(type) {
            if ((0, types_1.isFunction)(type)) {
                addOneFunctionToSignature(type);
            }
            else {
                types_1.OverloadedFunctionType.getOverloads(type).forEach((func) => {
                    addOneFunctionToSignature(func);
                });
            }
        }
        (0, typeUtils_1.doForEachSubtype)(callType, (subtype) => {
            switch (subtype.category) {
                case 4 /* TypeCategory.Function */:
                case 5 /* TypeCategory.OverloadedFunction */: {
                    addFunctionToSignature(subtype);
                    break;
                }
                case 6 /* TypeCategory.Class */: {
                    if (types_1.TypeBase.isInstantiable(subtype)) {
                        let constructorType;
                        // Try to get the `__init__` method first because it typically has more
                        // type information than `__new__`.
                        const initMethodResult = (0, constructors_1.getBoundInitMethod)(evaluatorInterface, callNode, types_1.ClassType.cloneAsInstance(subtype), 
                        /* diag */ undefined, 0 /* MemberAccessFlags.Default */);
                        if (initMethodResult && !initMethodResult.typeErrors) {
                            if ((0, types_1.isFunction)(initMethodResult.type) || (0, types_1.isOverloadedFunction)(initMethodResult.type)) {
                                constructorType = initMethodResult.type;
                            }
                        }
                        const isObjectInit = constructorType &&
                            (0, types_1.isFunction)(constructorType) &&
                            constructorType.details.fullName === 'builtins.object.__init__';
                        const isDefaultParams = constructorType &&
                            (0, types_1.isFunction)(constructorType) &&
                            types_1.FunctionType.hasDefaultParameters(constructorType);
                        // If there was no `__init__` or the only `__init__` that was found was from
                        // the `object` class or accepts only default parameters(* args, ** kwargs),
                        // see if we can find a better signature from the `__new__` method.
                        if (!constructorType || isObjectInit || isDefaultParams) {
                            const newMethodResult = (0, constructors_1.getBoundNewMethod)(evaluatorInterface, callNode, subtype);
                            if (newMethodResult && !newMethodResult.typeErrors) {
                                if ((0, types_1.isFunction)(newMethodResult.type) &&
                                    newMethodResult.type.details.fullName !== 'builtins.object.__new__') {
                                    constructorType = newMethodResult.type;
                                }
                                else if ((0, types_1.isOverloadedFunction)(newMethodResult.type)) {
                                    constructorType = newMethodResult.type;
                                }
                            }
                        }
                        if (constructorType) {
                            addFunctionToSignature(constructorType);
                        }
                    }
                    else {
                        const methodType = getBoundMagicMethod(subtype, '__call__');
                        if (methodType) {
                            addFunctionToSignature(methodType);
                        }
                    }
                    break;
                }
            }
        });
        if (signatures.length === 0) {
            return undefined;
        }
        return {
            callNode,
            signatures,
        };
    }
    // If the function includes a `**kwargs: Unpack[TypedDict]` parameter, the
    // parameter is expanded to include individual keyword args.
    function expandTypedKwargs(functionType) {
        var _a, _b;
        const kwargsIndex = functionType.details.parameters.findIndex((param) => param.category === 2 /* ParameterCategory.KwargsDict */);
        if (kwargsIndex < 0) {
            return functionType;
        }
        (0, debug_1.assert)(kwargsIndex === functionType.details.parameters.length - 1);
        const kwargsType = types_1.FunctionType.getEffectiveParameterType(functionType, kwargsIndex);
        if (!(0, types_1.isClassInstance)(kwargsType) || !types_1.ClassType.isTypedDictClass(kwargsType) || !kwargsType.isUnpacked) {
            return functionType;
        }
        const tdEntries = (_a = kwargsType.typedDictNarrowedEntries) !== null && _a !== void 0 ? _a : (_b = kwargsType.details.typedDictEntries) === null || _b === void 0 ? void 0 : _b.knownItems;
        if (!tdEntries) {
            return functionType;
        }
        const newFunction = types_1.FunctionType.clone(functionType);
        newFunction.details.parameters.splice(kwargsIndex);
        if (newFunction.specializedTypes) {
            newFunction.specializedTypes.parameterTypes.splice(kwargsIndex);
        }
        const kwSeparatorIndex = functionType.details.parameters.findIndex((param) => param.category === 1 /* ParameterCategory.ArgsList */);
        // Add a keyword separator if necessary.
        if (kwSeparatorIndex < 0) {
            types_1.FunctionType.addKeywordOnlyParameterSeparator(newFunction);
        }
        tdEntries.forEach((tdEntry, name) => {
            types_1.FunctionType.addParameter(newFunction, {
                category: 0 /* ParameterCategory.Simple */,
                name,
                hasDeclaredType: true,
                type: tdEntry.valueType,
                hasDefault: !tdEntry.isRequired,
                defaultType: tdEntry.valueType,
            });
        });
        return newFunction;
    }
    // Determines whether the specified expression is an explicit TypeAlias declaration.
    function isDeclaredTypeAlias(expression) {
        if (expression.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            if (expression.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
                const symbolWithScope = lookUpSymbolRecursive(expression, expression.valueExpression.value, 
                /* honorCodeFlow */ false);
                if (symbolWithScope) {
                    const symbol = symbolWithScope.symbol;
                    return symbol.getDeclarations().find((decl) => isExplicitTypeAliasDeclaration(decl)) !== undefined;
                }
            }
        }
        return false;
    }
    // Determines whether the specified expression is a symbol with a declared type.
    function getDeclaredTypeForExpression(expression, usage) {
        var _a, _b;
        let symbol;
        let classOrObjectBase;
        let memberAccessClass;
        let bindFunction = true;
        let useDescriptorSetterType = false;
        switch (expression.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                const symbolWithScope = lookUpSymbolRecursive(expression, expression.value, /* honorCodeFlow */ true);
                if (symbolWithScope) {
                    symbol = symbolWithScope.symbol;
                    // Handle the case where the symbol is a class-level variable
                    // where the type isn't declared in this class but is in
                    // a parent class.
                    if (!((_a = getDeclaredTypeOfSymbol(symbol, expression)) === null || _a === void 0 ? void 0 : _a.type) &&
                        symbolWithScope.scope.type === 2 /* ScopeType.Class */) {
                        const enclosingClass = ParseTreeUtils.getEnclosingClassOrFunction(expression);
                        if (enclosingClass && enclosingClass.nodeType === 10 /* ParseNodeType.Class */) {
                            const classTypeInfo = getTypeOfClass(enclosingClass);
                            if (classTypeInfo) {
                                const classMemberInfo = (0, typeUtils_1.lookUpClassMember)(classTypeInfo.classType, expression.value, 16 /* MemberAccessFlags.SkipInstanceMembers */ | 64 /* MemberAccessFlags.DeclaredTypesOnly */);
                                if (classMemberInfo) {
                                    symbol = classMemberInfo.symbol;
                                }
                            }
                        }
                    }
                }
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                return getDeclaredTypeForExpression(expression.valueExpression, usage);
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                const baseType = makeTopLevelTypeVarsConcrete(getTypeOfExpression(expression.leftExpression, 2 /* EvaluatorFlags.MemberAccessBaseDefaults */).type);
                let classMemberInfo;
                if ((0, types_1.isClassInstance)(baseType)) {
                    classMemberInfo = (0, typeUtils_1.lookUpObjectMember)(baseType, expression.memberName.value, 64 /* MemberAccessFlags.DeclaredTypesOnly */);
                    classOrObjectBase = baseType;
                    memberAccessClass = classMemberInfo === null || classMemberInfo === void 0 ? void 0 : classMemberInfo.classType;
                    // If this is an instance member (e.g. a dataclass field), don't
                    // bind it to the object if it's a function.
                    if (classMemberInfo === null || classMemberInfo === void 0 ? void 0 : classMemberInfo.isInstanceMember) {
                        bindFunction = false;
                    }
                    useDescriptorSetterType = true;
                }
                else if ((0, types_1.isInstantiableClass)(baseType)) {
                    classMemberInfo = (0, typeUtils_1.lookUpClassMember)(baseType, expression.memberName.value, 16 /* MemberAccessFlags.SkipInstanceMembers */ | 64 /* MemberAccessFlags.DeclaredTypesOnly */);
                    classOrObjectBase = baseType;
                    memberAccessClass = classMemberInfo === null || classMemberInfo === void 0 ? void 0 : classMemberInfo.classType;
                }
                if (classMemberInfo) {
                    symbol = classMemberInfo.symbol;
                }
                break;
            }
            case 24 /* ParseNodeType.Index */: {
                const baseType = makeTopLevelTypeVarsConcrete(getTypeOfExpression(expression.baseExpression, 2 /* EvaluatorFlags.IndexBaseDefaults */).type);
                if (baseType && (0, types_1.isClassInstance)(baseType)) {
                    const setItemType = getBoundMagicMethod(baseType, '__setitem__');
                    if (setItemType && (0, types_1.isFunction)(setItemType) && setItemType.details.parameters.length >= 2) {
                        const paramType = types_1.FunctionType.getEffectiveParameterType(setItemType, 1);
                        if (!(0, types_1.isAnyOrUnknown)(paramType)) {
                            return paramType;
                        }
                    }
                    else if (types_1.ClassType.isTypedDictClass(baseType)) {
                        const typeFromTypedDict = (0, typedDicts_1.getTypeOfIndexedTypedDict)(evaluatorInterface, expression, baseType, usage || { method: 'get' });
                        if (typeFromTypedDict) {
                            return typeFromTypedDict.type;
                        }
                    }
                }
                break;
            }
        }
        if (symbol) {
            let declaredType = (_b = getDeclaredTypeOfSymbol(symbol)) === null || _b === void 0 ? void 0 : _b.type;
            if (declaredType) {
                // If it's a descriptor, we need to get the setter type.
                if (useDescriptorSetterType && (0, types_1.isClassInstance)(declaredType)) {
                    const setter = getBoundMagicMethod(declaredType, '__set__');
                    if (setter && (0, types_1.isFunction)(setter) && setter.details.parameters.length >= 2) {
                        declaredType = setter.details.parameters[1].type;
                        if ((0, types_1.isAnyOrUnknown)(declaredType)) {
                            return undefined;
                        }
                    }
                }
                if (classOrObjectBase) {
                    if (memberAccessClass && (0, types_1.isInstantiableClass)(memberAccessClass)) {
                        declaredType = (0, typeUtils_1.partiallySpecializeType)(declaredType, memberAccessClass);
                    }
                    if ((0, types_1.isFunction)(declaredType) || (0, types_1.isOverloadedFunction)(declaredType)) {
                        if (bindFunction) {
                            declaredType = bindFunctionToClassOrObject(classOrObjectBase, declaredType);
                        }
                    }
                }
                return declaredType;
            }
        }
        return undefined;
    }
    // Applies an "await" operation to the specified type and returns
    // the result. According to PEP 492, await operates on an Awaitable
    // (object that provides an __await__ that returns a generator object).
    // If errorNode is undefined, no errors are reported.
    function getTypeOfAwaitable(type, errorNode) {
        if (!awaitableProtocolType ||
            !(0, types_1.isInstantiableClass)(awaitableProtocolType) ||
            awaitableProtocolType.details.typeParameters.length !== 1) {
            return types_1.UnknownType.create();
        }
        const awaitableProtocolObj = types_1.ClassType.cloneAsInstance(awaitableProtocolType);
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            subtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return subtype;
            }
            const diag = errorNode ? new diagnostic_1.DiagnosticAddendum() : undefined;
            if ((0, types_1.isClassInstance)(subtype)) {
                const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(awaitableProtocolObj));
                if (assignType(awaitableProtocolObj, subtype, diag, typeVarContext)) {
                    const specializedType = (0, typeUtils_1.applySolvedTypeVars)(awaitableProtocolObj, typeVarContext);
                    if ((0, types_1.isClass)(specializedType) &&
                        specializedType.typeArguments &&
                        specializedType.typeArguments.length > 0) {
                        return specializedType.typeArguments[0];
                    }
                    return types_1.UnknownType.create();
                }
            }
            if (errorNode) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeNotAwaitable().format({ type: printType(subtype) }) + (diag === null || diag === void 0 ? void 0 : diag.getString()), errorNode);
            }
            return types_1.UnknownType.create();
        });
    }
    // Validates that the type is an iterator and returns the iterated type
    // (i.e. the type returned from the '__next__' or '__anext__' method).
    function getTypeOfIterator(typeResult, isAsync, errorNode, emitNotIterableError = true) {
        const iterMethodName = isAsync ? '__aiter__' : '__iter__';
        const nextMethodName = isAsync ? '__anext__' : '__next__';
        let isValidIterator = true;
        let type = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(typeResult.type);
        type = makeTopLevelTypeVarsConcrete(type);
        type = (0, types_1.removeUnbound)(type);
        if ((0, typeUtils_1.isOptionalType)(type) && emitNotIterableError) {
            if (!typeResult.isIncomplete) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalIterable, localize_1.LocMessage.noneNotIterable(), errorNode);
            }
            type = (0, typeUtils_1.removeNoneFromUnion)(type);
        }
        const iterableType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            subtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return subtype;
            }
            const diag = new diagnostic_1.DiagnosticAddendum();
            if ((0, types_1.isClass)(subtype)) {
                // Handle an empty tuple specially.
                if (types_1.TypeBase.isInstance(subtype) &&
                    (0, typeUtils_1.isTupleClass)(subtype) &&
                    subtype.tupleTypeArguments &&
                    subtype.tupleTypeArguments.length === 0) {
                    return types_1.NeverType.createNever();
                }
                const iterReturnType = getTypeOfMagicMethodCall(subtype, iterMethodName, [], errorNode);
                if (!iterReturnType) {
                    // There was no __iter__. See if we can fall back to
                    // the __getitem__ method instead.
                    if (!isAsync && (0, types_1.isClassInstance)(subtype)) {
                        const getItemReturnType = getTypeOfMagicMethodCall(subtype, '__getitem__', [
                            {
                                type: intClassType && (0, types_1.isInstantiableClass)(intClassType)
                                    ? types_1.ClassType.cloneAsInstance(intClassType)
                                    : types_1.UnknownType.create(),
                            },
                        ], errorNode);
                        if (getItemReturnType) {
                            return getItemReturnType;
                        }
                    }
                    diag.addMessage(localize_1.LocMessage.methodNotDefined().format({ name: iterMethodName }));
                }
                else {
                    const iterReturnTypeDiag = new diagnostic_1.DiagnosticAddendum();
                    const returnType = mapSubtypesExpandTypeVars(iterReturnType, /* options */ undefined, (subtype) => {
                        if ((0, types_1.isAnyOrUnknown)(subtype)) {
                            return subtype;
                        }
                        if ((0, types_1.isClassInstance)(subtype)) {
                            let nextReturnType = getTypeOfMagicMethodCall(subtype, nextMethodName, [], errorNode);
                            if (!nextReturnType) {
                                iterReturnTypeDiag.addMessage(localize_1.LocMessage.methodNotDefinedOnType().format({
                                    name: nextMethodName,
                                    type: printType(subtype),
                                }));
                            }
                            else {
                                // Convert any unpacked TypeVarTuples into object instances. We don't
                                // know anything more about them.
                                nextReturnType = (0, typeUtils_1.mapSubtypes)(nextReturnType, (returnSubtype) => {
                                    if ((0, types_1.isTypeVar)(returnSubtype) && (0, types_1.isUnpackedVariadicTypeVar)(returnSubtype)) {
                                        return objectType !== null && objectType !== void 0 ? objectType : types_1.UnknownType.create();
                                    }
                                    return returnSubtype;
                                });
                                if (!isAsync) {
                                    return nextReturnType;
                                }
                                // If it's an async iteration, there's an implicit
                                // 'await' operator applied.
                                return getTypeOfAwaitable(nextReturnType, errorNode);
                            }
                        }
                        else {
                            iterReturnTypeDiag.addMessage(localize_1.LocMessage.methodReturnsNonObject().format({ name: iterMethodName }));
                        }
                        return undefined;
                    });
                    if (iterReturnTypeDiag.isEmpty()) {
                        return returnType;
                    }
                    diag.addAddendum(iterReturnTypeDiag);
                }
            }
            if (!typeResult.isIncomplete && emitNotIterableError) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeNotIterable().format({ type: printType(subtype) }) + diag.getString(), errorNode);
            }
            isValidIterator = false;
            return undefined;
        });
        return isValidIterator ? { type: iterableType, isIncomplete: typeResult.isIncomplete } : undefined;
    }
    // Validates that the type is an iterable and returns the iterable type argument.
    function getTypeOfIterable(typeResult, isAsync, errorNode, emitNotIterableError = true) {
        const iterMethodName = isAsync ? '__aiter__' : '__iter__';
        let isValidIterable = true;
        let type = makeTopLevelTypeVarsConcrete(typeResult.type);
        if ((0, typeUtils_1.isOptionalType)(type)) {
            if (!typeResult.isIncomplete && emitNotIterableError) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalIterable, localize_1.LocMessage.noneNotIterable(), errorNode);
            }
            type = (0, typeUtils_1.removeNoneFromUnion)(type);
        }
        const iterableType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return subtype;
            }
            if ((0, types_1.isClass)(subtype)) {
                const iterReturnType = getTypeOfMagicMethodCall(subtype, iterMethodName, [], errorNode);
                if (iterReturnType) {
                    return makeTopLevelTypeVarsConcrete(iterReturnType);
                }
            }
            if (emitNotIterableError) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeNotIterable().format({ type: printType(subtype) }), errorNode);
            }
            isValidIterable = false;
            return undefined;
        });
        return isValidIterable ? { type: iterableType, isIncomplete: typeResult.isIncomplete } : undefined;
    }
    function isTypeHashable(type) {
        let isTypeHashable = true;
        (0, typeUtils_1.doForEachSubtype)(makeTopLevelTypeVarsConcrete(type), (subtype) => {
            if ((0, types_1.isClassInstance)(subtype)) {
                // Assume the class is hashable.
                let isObjectHashable = true;
                // Have we already computed and cached the hashability?
                if (subtype.details.isInstanceHashable !== undefined) {
                    isObjectHashable = subtype.details.isInstanceHashable;
                }
                else {
                    const hashMember = (0, typeUtils_1.lookUpObjectMember)(subtype, '__hash__', 4 /* MemberAccessFlags.SkipObjectBaseClass */);
                    if (hashMember && hashMember.isTypeDeclared) {
                        const decls = hashMember.symbol.getTypedDeclarations();
                        const synthesizedType = hashMember.symbol.getSynthesizedType();
                        // Handle the case where the type is synthesized (used for
                        // dataclasses).
                        if (synthesizedType) {
                            isObjectHashable = !(0, typeUtils_1.isNoneInstance)(synthesizedType);
                        }
                        else {
                            // Assume that if '__hash__' is declared as a variable, it is
                            // not hashable. If it's declared as a function, it is. We'll
                            // skip evaluating its full type because that's not needed in
                            // this case.
                            if (decls.every((decl) => decl.type === 1 /* DeclarationType.Variable */)) {
                                isObjectHashable = false;
                            }
                        }
                    }
                    // Cache the hashability for next time.
                    subtype.details.isInstanceHashable = isObjectHashable;
                }
                if (!isObjectHashable) {
                    isTypeHashable = false;
                }
            }
        });
        return isTypeHashable;
    }
    function getTypedDictClassType() {
        return typedDictPrivateClassType && (0, types_1.isInstantiableClass)(typedDictPrivateClassType)
            ? typedDictPrivateClassType
            : undefined;
    }
    function getTupleClassType() {
        return tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType) ? tupleClassType : undefined;
    }
    function getObjectType() {
        return objectType !== null && objectType !== void 0 ? objectType : types_1.UnknownType.create();
    }
    function getNoneType() {
        return noneType !== null && noneType !== void 0 ? noneType : types_1.UnknownType.create();
    }
    function getUnionClassType() {
        return unionClassType !== null && unionClassType !== void 0 ? unionClassType : types_1.UnknownType.create();
    }
    function getTypingType(node, symbolName) {
        var _a;
        return ((_a = getTypeOfModule(node, symbolName, ['typing'])) !== null && _a !== void 0 ? _a : getTypeOfModule(node, symbolName, ['typing_extensions']));
    }
    function getTypesType(node, symbolName) {
        return getTypeOfModule(node, symbolName, ['types']);
    }
    function getTypeshedType(node, symbolName) {
        return getTypeOfModule(node, symbolName, ['_typeshed']);
    }
    function getTypeOfModule(node, symbolName, nameParts) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const lookupResult = importLookup({ nameParts, importingFileUri: fileInfo.fileUri });
        if (!lookupResult) {
            return undefined;
        }
        const symbol = lookupResult.symbolTable.get(symbolName);
        if (!symbol) {
            return undefined;
        }
        return getEffectiveTypeOfSymbol(symbol);
    }
    function checkCodeFlowTooComplex(node) {
        const scopeNode = node.nodeType === 28 /* ParseNodeType.Function */ ? node : ParseTreeUtils.getExecutionScopeNode(node);
        const codeComplexity = AnalyzerNodeInfo.getCodeFlowComplexity(scopeNode);
        if (codeComplexity > exports.maxCodeComplexity) {
            let errorRange = scopeNode;
            if (scopeNode.nodeType === 28 /* ParseNodeType.Function */) {
                errorRange = scopeNode.name;
            }
            else if (scopeNode.nodeType === 36 /* ParseNodeType.Module */) {
                errorRange = { start: 0, length: 0 };
            }
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            addDiagnosticForTextRange(fileInfo, fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.codeTooComplexToAnalyze(), errorRange);
            return true;
        }
        return false;
    }
    function isNodeReachable(node, sourceNode) {
        if (checkCodeFlowTooComplex(node)) {
            return true;
        }
        const flowNode = AnalyzerNodeInfo.getFlowNode(node);
        if (!flowNode) {
            if (node.parent) {
                return isNodeReachable(node.parent, sourceNode);
            }
            return false;
        }
        const sourceFlowNode = sourceNode ? AnalyzerNodeInfo.getFlowNode(sourceNode) : undefined;
        return codeFlowEngine.isFlowNodeReachable(flowNode, sourceFlowNode);
    }
    function isNotTypeCheckingBlock(node) {
        //TODO: abstract this logic, its used in isNodeReachable as well
        const flowNode = AnalyzerNodeInfo.getFlowNode(node);
        if (!flowNode) {
            if (node.parent) {
                return isNotTypeCheckingBlock(node.parent);
            }
            return false;
        }
        return !!(flowNode.flags & codeFlowTypes_1.FlowFlags.NotTypeChecking);
    }
    function isAfterNodeReachable(node) {
        const returnFlowNode = AnalyzerNodeInfo.getAfterFlowNode(node);
        if (!returnFlowNode) {
            return false;
        }
        if (checkCodeFlowTooComplex(node)) {
            return true;
        }
        if (!codeFlowEngine.isFlowNodeReachable(returnFlowNode)) {
            return false;
        }
        if (!isFlowNodeReachableUsingNeverNarrowing(node, returnFlowNode)) {
            return false;
        }
        return true;
    }
    // Although isFlowNodeReachable indicates that the node is reachable, it
    // may not be reachable if we apply "never narrowing".
    function isFlowNodeReachableUsingNeverNarrowing(node, flowNode) {
        const analyzer = getCodeFlowAnalyzerForNode(node.id, /* typeAtStart */ undefined);
        if (checkCodeFlowTooComplex(node)) {
            return true;
        }
        const codeFlowResult = analyzer.getTypeFromCodeFlow(flowNode, /* reference */ undefined, {
            typeAtStart: { type: types_1.UnboundType.create() },
        });
        return codeFlowResult.type !== undefined && !(0, types_1.isNever)(codeFlowResult.type);
    }
    // Determines whether there is a code flow path from sourceNode to sinkNode.
    function isFlowPathBetweenNodes(sourceNode, sinkNode, allowSelf = true) {
        if (checkCodeFlowTooComplex(sourceNode)) {
            return true;
        }
        const sourceFlowNode = AnalyzerNodeInfo.getFlowNode(sourceNode);
        const sinkFlowNode = AnalyzerNodeInfo.getFlowNode(sinkNode);
        if (!sourceFlowNode || !sinkFlowNode) {
            return false;
        }
        if (sourceFlowNode === sinkFlowNode) {
            return allowSelf;
        }
        return codeFlowEngine.isFlowNodeReachable(sinkFlowNode, sourceFlowNode, /* ignoreNoReturn */ true);
    }
    // Determines whether the specified string literal is part
    // of a Literal['xxx'] statement. If so, we will not treat
    // the string as a normal forward-declared type annotation.
    function isAnnotationLiteralValue(node) {
        if (node.parent && node.parent.nodeType === 24 /* ParseNodeType.Index */) {
            const baseType = getTypeOfExpression(node.parent.baseExpression).type;
            if (baseType && (0, types_1.isInstantiableClass)(baseType)) {
                if (types_1.ClassType.isSpecialBuiltIn(baseType, 'Literal')) {
                    return true;
                }
            }
        }
        return false;
    }
    function addInformation(message, node, range) {
        return addDiagnosticWithSuppressionCheck('information', message, node, range);
    }
    /** @deprecated use {@link addDiagnostic} with a specific diagnostic rule instead */
    function addError(message, node, range) {
        //TODO: the errors about ignore comments do not call this function and therefore do not
        // have a code. but suppressing an unused ignore comment is an edge case sooooo
        return addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, message, node, range);
    }
    function addUnusedCode(node, textRange) {
        if (!isDiagnosticSuppressedForNode(node)) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            fileInfo.diagnosticSink.addUnusedCodeWithTextRange(localize_1.LocMessage.unreachableCode(), textRange);
        }
    }
    function addUnreachableCode(node, textRange) {
        if (!isDiagnosticSuppressedForNode(node)) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            const message = localize_1.LocMessage.unreachableCode();
            if (fileInfo.diagnosticRuleSet.reportUnreachable === 'none' || isNotTypeCheckingBlock(node)) {
                fileInfo.diagnosticSink.addUnreachableCodeWithTextRange(message, textRange);
            }
            else {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnreachable, message, node, textRange);
            }
        }
    }
    function addDeprecated(message, node) {
        if (!isDiagnosticSuppressedForNode(node)) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            fileInfo.diagnosticSink.addDeprecatedWithTextRange(message, node);
        }
    }
    function addDiagnosticWithSuppressionCheck(diagLevel, message, node, range) {
        if (!isDiagnosticSuppressedForNode(node)) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            return fileInfo.diagnosticSink.addDiagnosticWithTextRange(diagLevel, message, range || node);
        }
        return undefined;
    }
    function isDiagnosticSuppressedForNode(node) {
        return (suppressedNodeStack.some((suppressedNode) => ParseTreeUtils.isNodeContainedWithin(node, suppressedNode)) ||
            speculativeTypeTracker.isSpeculative(node, /* ignoreIfDiagnosticsAllowed */ true));
    }
    function addDiagnostic(rule, message, node, range) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const diagLevel = fileInfo.diagnosticRuleSet[rule];
        if (diagLevel === 'none') {
            return undefined;
        }
        const containingFunction = ParseTreeUtils.getEnclosingFunction(node);
        if (containingFunction) {
            // Should we suppress this diagnostic because it's within an unannotated function?
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            if (!fileInfo.diagnosticRuleSet.analyzeUnannotatedFunctions) {
                // Is the target node within the body of the function? If so, suppress the diagnostic.
                if (ParseTreeUtils.isUnannotatedFunction(containingFunction) &&
                    ParseTreeUtils.isNodeContainedWithin(node, containingFunction.suite)) {
                    return undefined;
                }
            }
            // Should we suppress this diagnostic because it's within a no_type_check function?
            const containingClassNode = ParseTreeUtils.getEnclosingClass(containingFunction, /* stopAtFunction */ true);
            const functionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, containingFunction, !!containingClassNode);
            if ((functionInfo.flags & 524288 /* FunctionTypeFlags.NoTypeCheck */) !== 0) {
                return undefined;
            }
        }
        const diagnostic = addDiagnosticWithSuppressionCheck(diagLevel, message, node, range);
        if (diagnostic) {
            diagnostic.setRule(rule);
        }
        return diagnostic;
    }
    function addDiagnosticForTextRange(fileInfo, diagLevel, rule, message, range) {
        if (diagLevel === 'none') {
            return undefined;
        }
        const diagnostic = fileInfo.diagnosticSink.addDiagnosticWithTextRange(diagLevel, message, range);
        if (rule) {
            diagnostic.setRule(rule);
        }
        return diagnostic;
    }
    function addExpectedClassDiagnostic(type, node) {
        const diag = new diagnostic_1.DiagnosticAddendum();
        if ((0, types_1.isUnion)(type)) {
            (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                if (!(0, typeUtils_1.isEffectivelyInstantiable)(subtype)) {
                    diag.addMessage(localize_1.LocAddendum.typeNotClass().format({ type: printType(subtype) }));
                }
            });
        }
        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeExpectedClass().format({ type: printType(type) }) + diag.getString(), node);
    }
    function assignTypeToNameNode(nameNode, type, isTypeIncomplete, ignoreEmptyContainers, srcExpression, allowAssignmentToFinalVar = false, expectedTypeDiagAddendum) {
        var _a, _b, _c;
        const nameValue = nameNode.value;
        const symbolWithScope = lookUpSymbolRecursive(nameNode, nameValue, /* honorCodeFlow */ false);
        if (!symbolWithScope) {
            // This can happen when we are evaluating a piece of code that was
            // determined to be unreachable by the binder.
            return;
        }
        const declarations = symbolWithScope.symbol.getDeclarations();
        let declaredType = (_a = getDeclaredTypeOfSymbol(symbolWithScope.symbol)) === null || _a === void 0 ? void 0 : _a.type;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(nameNode);
        // If this is a class scope and there is no type declared for this class variable,
        // see if a parent class has a type declared.
        if (declaredType === undefined && symbolWithScope.scope.type === 2 /* ScopeType.Class */) {
            const containingClass = ParseTreeUtils.getEnclosingClass(nameNode);
            if (containingClass) {
                const classType = getTypeOfClass(containingClass);
                if (classType) {
                    const memberInfo = (0, typeUtils_1.lookUpClassMember)(classType.classType, nameNode.value, 1 /* MemberAccessFlags.SkipOriginalClass */);
                    if (memberInfo === null || memberInfo === void 0 ? void 0 : memberInfo.isTypeDeclared) {
                        declaredType = getTypeOfMember(memberInfo);
                    }
                }
            }
        }
        // We found an existing declared type. Make sure the type is assignable.
        let destType = type;
        const isTypeAlias = !!declaredType && (0, types_1.isClassInstance)(declaredType) && types_1.ClassType.isBuiltIn(declaredType, 'TypeAlias');
        if (declaredType && !isTypeAlias) {
            let diagAddendum = new diagnostic_1.DiagnosticAddendum();
            if (!assignType(declaredType, type, diagAddendum)) {
                // If there was an expected type mismatch, use that diagnostic
                // addendum because it will be more informative.
                if (expectedTypeDiagAddendum) {
                    diagAddendum = expectedTypeDiagAddendum;
                }
                if (!isTypeIncomplete) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAssignmentType, localize_1.LocMessage.typeAssignmentMismatch().format(printSrcDestTypes(type, declaredType)) +
                        diagAddendum.getString(), srcExpression !== null && srcExpression !== void 0 ? srcExpression : nameNode, (_c = (_b = diagAddendum.getEffectiveTextRange()) !== null && _b !== void 0 ? _b : srcExpression) !== null && _c !== void 0 ? _c : nameNode);
                }
                // Replace the assigned type with the (unnarrowed) declared type.
                destType = declaredType;
            }
            else {
                // Constrain the resulting type to match the declared type.
                destType = narrowTypeBasedOnAssignment(nameNode, declaredType, type);
            }
        }
        else {
            // If this is a member name (within a class scope) and the member name
            // appears to be a constant, use the strict source type. If it's a member
            // variable that can be overridden by a child class, use the more general
            // version by stripping off the literal.
            const scope = ScopeUtils.getScopeForNode(nameNode);
            if ((scope === null || scope === void 0 ? void 0 : scope.type) === 2 /* ScopeType.Class */) {
                if (types_1.TypeBase.isInstance(destType) &&
                    !(0, symbolNameUtils_1.isConstantName)(nameValue) &&
                    !isFinalVariable(symbolWithScope.symbol)) {
                    destType = stripLiteralValue(destType);
                }
            }
        }
        const varDeclIndex = declarations.findIndex((decl) => decl.type === 1 /* DeclarationType.Variable */);
        const varDecl = varDeclIndex >= 0 ? declarations[varDeclIndex] : undefined;
        // Are there any non-var decls before the var decl?
        const nonVarDecl = declarations.find((decl, index) => varDeclIndex < index && decl.type !== 1 /* DeclarationType.Variable */);
        if (varDecl && varDecl.type === 1 /* DeclarationType.Variable */) {
            if (varDecl.isConstant) {
                // A constant variable can be assigned only once. If this
                // isn't the first assignment, generate an error.
                if (nameNode !== (0, declarationUtils_1.getNameNodeForDeclaration)(declarations[0]) || !!nonVarDecl) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportConstantRedefinition, localize_1.LocMessage.constantRedefinition().format({ name: nameValue }), nameNode);
                }
            }
            else if (isFinalVariableDeclaration(varDecl) && !allowAssignmentToFinalVar) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.finalReassigned().format({ name: nameValue }), nameNode);
            }
        }
        if (!isTypeIncomplete) {
            reportPossibleUnknownAssignment(fileInfo.diagnosticRuleSet, diagnosticRules_1.DiagnosticRule.reportUnknownVariableType, nameNode, destType, nameNode, ignoreEmptyContainers);
        }
        writeTypeCache(nameNode, { type: destType, isIncomplete: isTypeIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function assignTypeToMemberAccessNode(target, type, isTypeIncomplete, srcExpr, expectedTypeDiagAddendum) {
        var _a;
        const baseTypeResult = getTypeOfExpression(target.leftExpression, 2 /* EvaluatorFlags.MemberAccessBaseDefaults */);
        const baseType = makeTopLevelTypeVarsConcrete(baseTypeResult.type);
        // Handle member accesses (e.g. self.x or cls.y).
        if (target.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
            // Determine whether we're writing to a class or instance member.
            const enclosingClassNode = ParseTreeUtils.getEnclosingClass(target);
            if (enclosingClassNode) {
                const classTypeResults = getTypeOfClass(enclosingClassNode);
                if (classTypeResults && (0, types_1.isInstantiableClass)(classTypeResults.classType)) {
                    if ((0, types_1.isClassInstance)(baseType)) {
                        if (types_1.ClassType.isSameGenericClass(baseType, classTypeResults.classType)) {
                            assignTypeToMemberVariable(target, type, isTypeIncomplete, 
                            /* isInstanceMember */ true, srcExpr);
                        }
                    }
                    else if ((0, types_1.isInstantiableClass)(baseType)) {
                        if (types_1.ClassType.isSameGenericClass(baseType, classTypeResults.classType)) {
                            assignTypeToMemberVariable(target, type, isTypeIncomplete, 
                            /* isInstanceMember */ false, srcExpr);
                        }
                    }
                    // Assignments to instance or class variables through "self" or "cls" is not
                    // allowed for protocol classes unless it is also declared within the class.
                    if (types_1.ClassType.isProtocolClass(classTypeResults.classType)) {
                        const memberSymbol = types_1.ClassType.getSymbolTable(classTypeResults.classType).get(target.memberName.value);
                        if (memberSymbol) {
                            const classLevelDecls = memberSymbol.getDeclarations().filter((decl) => {
                                return !ParseTreeUtils.getEnclosingFunction(decl.node);
                            });
                            if (classLevelDecls.length === 0) {
                                addError(localize_1.LocMessage.assignmentInProtocol(), target.memberName);
                            }
                        }
                    }
                }
            }
        }
        const setTypeResult = getTypeOfMemberAccessWithBaseType(target, baseTypeResult, {
            method: 'set',
            setType: { type, isIncomplete: isTypeIncomplete },
            setErrorNode: srcExpr,
            setExpectedTypeDiag: expectedTypeDiagAddendum,
        }, 0 /* EvaluatorFlags.None */);
        if (setTypeResult.isAsymmetricAccessor) {
            setAsymmetricDescriptorAssignment(target);
        }
        const resultToCache = {
            type: (_a = setTypeResult.narrowedTypeForSet) !== null && _a !== void 0 ? _a : type,
            isIncomplete: isTypeIncomplete,
            memberAccessDeprecationInfo: setTypeResult.memberAccessDeprecationInfo,
        };
        writeTypeCache(target.memberName, resultToCache, 0 /* EvaluatorFlags.None */);
        writeTypeCache(target, resultToCache, 0 /* EvaluatorFlags.None */);
    }
    function assignTypeToMemberVariable(node, srcType, isTypeIncomplete, isInstanceMember, srcExprNode) {
        var _a;
        const memberName = node.memberName.value;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const classDef = ParseTreeUtils.getEnclosingClass(node);
        if (!classDef) {
            return;
        }
        const classTypeInfo = getTypeOfClass(classDef);
        if (classTypeInfo && (0, types_1.isInstantiableClass)(classTypeInfo.classType)) {
            let memberInfo = (0, typeUtils_1.lookUpClassMember)(classTypeInfo.classType, memberName, isInstanceMember ? 0 /* MemberAccessFlags.Default */ : 16 /* MemberAccessFlags.SkipInstanceMembers */);
            const memberFields = types_1.ClassType.getSymbolTable(classTypeInfo.classType);
            if (memberInfo) {
                // Are we accessing an existing member on this class, or is
                // it a member on a parent class?
                const memberClass = (0, types_1.isInstantiableClass)(memberInfo.classType) ? memberInfo.classType : undefined;
                const isThisClass = memberClass && types_1.ClassType.isSameGenericClass(classTypeInfo.classType, memberClass);
                // Check for an attempt to write to an instance variable that is
                // not defined by __slots__.
                if (isThisClass && isInstanceMember && memberClass) {
                    const inheritedSlotsNames = types_1.ClassType.getInheritedSlotsNames(memberClass);
                    if (inheritedSlotsNames && memberClass.details.localSlotsNames) {
                        // Skip this check if the local slots is specified but empty because this pattern
                        // is used in a legitimate manner for mix-in classes.
                        if (memberClass.details.localSlotsNames.length > 0 &&
                            !inheritedSlotsNames.some((name) => name === memberName)) {
                            // Determine whether the assignment corresponds to a descriptor
                            // that was assigned as a class variable. If so, then slots will not
                            // apply in this case.
                            const classMemberDetails = (0, typeUtils_1.lookUpClassMember)(memberClass, memberName, 16 /* MemberAccessFlags.SkipInstanceMembers */);
                            let isPotentiallyDescriptor = false;
                            if (classMemberDetails) {
                                const classMemberSymbolType = getEffectiveTypeOfSymbol(classMemberDetails.symbol);
                                if ((0, types_1.isAnyOrUnknown)(classMemberSymbolType) ||
                                    (0, types_1.isUnbound)(classMemberSymbolType) ||
                                    (0, typeUtils_1.isMaybeDescriptorInstance)(classMemberSymbolType)) {
                                    isPotentiallyDescriptor = true;
                                }
                            }
                            if (!isPotentiallyDescriptor) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.slotsAttributeError().format({ name: memberName }), node.memberName);
                            }
                        }
                    }
                }
                if (isThisClass && memberInfo.isInstanceMember === isInstanceMember) {
                    const symbol = memberFields.get(memberName);
                    (0, debug_1.assert)(symbol !== undefined);
                    const typedDecls = symbol.getDeclarations();
                    // Check for an attempt to overwrite a constant member variable.
                    if (typedDecls.length > 0 &&
                        typedDecls[0].type === 1 /* DeclarationType.Variable */ &&
                        srcExprNode &&
                        node.memberName !== typedDecls[0].node) {
                        if (typedDecls[0].isConstant) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportConstantRedefinition, localize_1.LocMessage.constantRedefinition().format({ name: node.memberName.value }), node.memberName);
                        }
                    }
                }
                else {
                    // Is the target a property?
                    const declaredType = (_a = getDeclaredTypeOfSymbol(memberInfo.symbol)) === null || _a === void 0 ? void 0 : _a.type;
                    if (declaredType && !(0, typeUtils_1.isProperty)(declaredType)) {
                        // Handle the case where there is a class variable defined with the same
                        // name, but there's also now an instance variable introduced. Combine the
                        // type of the class variable with that of the new instance variable.
                        if (!memberInfo.isInstanceMember && isInstanceMember) {
                            // The class variable is accessed in this case.
                            setSymbolAccessed(fileInfo, memberInfo.symbol, node.memberName);
                            const memberType = getTypeOfMember(memberInfo);
                            srcType = (0, types_1.combineTypes)([srcType, memberType]);
                        }
                    }
                }
            }
            // Look up the member info again, now that we've potentially updated it.
            memberInfo = (0, typeUtils_1.lookUpClassMember)(classTypeInfo.classType, memberName, 64 /* MemberAccessFlags.DeclaredTypesOnly */);
            if (!memberInfo && srcExprNode && !isTypeIncomplete) {
                reportPossibleUnknownAssignment(fileInfo.diagnosticRuleSet, diagnosticRules_1.DiagnosticRule.reportUnknownMemberType, node.memberName, srcType, node, 
                /* ignoreEmptyContainers */ true);
            }
        }
    }
    function assignTypeToTupleOrListNode(target, type, isTypeIncomplete, srcExpr) {
        const targetExpressions = target.nodeType === 31 /* ParseNodeType.List */ ? target.entries : target.expressions;
        // Initialize the array of target types, one for each target.
        const targetTypes = new Array(targetExpressions.length);
        for (let i = 0; i < targetExpressions.length; i++) {
            targetTypes[i] = [];
        }
        const targetUnpackIndex = targetExpressions.findIndex((expr) => expr.nodeType === 56 /* ParseNodeType.Unpack */);
        // Do any of the targets use an unpack operator? If so, it will consume all of the
        // entries at that location.
        const unpackIndex = targetExpressions.findIndex((expr) => expr.nodeType === 56 /* ParseNodeType.Unpack */);
        type = makeTopLevelTypeVarsConcrete(type);
        const diagAddendum = new diagnostic_1.DiagnosticAddendum();
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            var _a, _b;
            // Is this subtype a tuple?
            const tupleType = (0, typeUtils_1.getSpecializedTupleType)(subtype);
            if (tupleType && tupleType.tupleTypeArguments) {
                const sourceEntryTypes = tupleType.tupleTypeArguments.map((t) => (0, typeUtils_1.addConditionToType)(t.type, (0, typeUtils_1.getTypeCondition)(subtype), /* skipSelfCondition */ true));
                const unboundedIndex = tupleType.tupleTypeArguments.findIndex((t) => t.isUnbounded);
                if (unboundedIndex >= 0) {
                    if (sourceEntryTypes.length < targetTypes.length) {
                        const typeToReplicate = sourceEntryTypes.length > 0 ? sourceEntryTypes[unboundedIndex] : types_1.AnyType.create();
                        // Add elements to make the count match the target count.
                        while (sourceEntryTypes.length < targetTypes.length) {
                            sourceEntryTypes.splice(unboundedIndex, 0, typeToReplicate);
                        }
                    }
                }
                // If there's an unpack operator in the target and we have too many source elements,
                // combine them to assign to the unpacked target.
                if (targetUnpackIndex >= 0) {
                    if (sourceEntryTypes.length > targetTypes.length) {
                        const removedEntries = sourceEntryTypes.splice(targetUnpackIndex, sourceEntryTypes.length - targetTypes.length + 1);
                        let combinedTypes = (0, types_1.combineTypes)(removedEntries);
                        if (target.nodeType === 31 /* ParseNodeType.List */) {
                            combinedTypes = stripLiteralValue(combinedTypes);
                        }
                        sourceEntryTypes.splice(targetUnpackIndex, 0, combinedTypes);
                    }
                    else if (sourceEntryTypes.length === targetTypes.length - 1) {
                        sourceEntryTypes.splice(targetUnpackIndex, 0, types_1.NeverType.createNever());
                    }
                }
                sourceEntryTypes.forEach((type, targetIndex) => {
                    if (targetIndex < targetTypes.length) {
                        targetTypes[targetIndex].push(type);
                    }
                });
                // Have we accounted for all of the targets and sources? If not, we have a size mismatch.
                if (sourceEntryTypes.length !== targetExpressions.length) {
                    const subDiag = diagAddendum.createAddendum();
                    subDiag.addMessage((target.nodeType === 31 /* ParseNodeType.List */
                        ? localize_1.LocAddendum.listAssignmentMismatch()
                        : localize_1.LocAddendum.tupleAssignmentMismatch()).format({
                        type: printType(subtype),
                    }));
                    subDiag.createAddendum().addMessage((unpackIndex >= 0
                        ? localize_1.LocAddendum.tupleSizeMismatchIndeterminateDest()
                        : localize_1.LocAddendum.tupleSizeMismatch()).format({
                        expected: unpackIndex >= 0 ? targetExpressions.length - 1 : targetExpressions.length,
                        received: sourceEntryTypes.length,
                    }));
                }
            }
            else {
                // The assigned expression isn't a tuple, so it had better
                // be some iterable type.
                const iterableType = (_b = (_a = getTypeOfIterator({ type: subtype, isIncomplete: isTypeIncomplete }, /* isAsync */ false, srcExpr)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
                for (let index = 0; index < targetExpressions.length; index++) {
                    targetTypes[index].push((0, typeUtils_1.addConditionToType)(iterableType, (0, typeUtils_1.getTypeCondition)(subtype)));
                }
            }
        });
        if (!diagAddendum.isEmpty()) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAssignmentType, (target.nodeType === 31 /* ParseNodeType.List */
                ? localize_1.LocMessage.listAssignmentMismatch()
                : localize_1.LocMessage.tupleAssignmentMismatch()).format({
                type: printType(type),
            }) + diagAddendum.getString(), target);
        }
        // Assign the resulting types to the individual names in the tuple
        // or list target expression.
        targetExpressions.forEach((expr, index) => {
            const typeList = targetTypes[index];
            const targetType = typeList.length === 0 ? types_1.UnknownType.create() : (0, types_1.combineTypes)(typeList);
            assignTypeToExpression(expr, targetType, isTypeIncomplete, srcExpr, /* ignoreEmptyContainers */ true);
        });
        writeTypeCache(target, { type, isIncomplete: isTypeIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    // If the type includes promotion types, expand these to their constituent types.
    function expandPromotionTypes(node, type, excludeBytes = false) {
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            if (!(0, types_1.isClass)(subtype) || !subtype.includePromotions) {
                return subtype;
            }
            if (excludeBytes && types_1.ClassType.isBuiltIn(subtype, 'bytes')) {
                return subtype;
            }
            const typesToCombine = [types_1.ClassType.cloneRemoveTypePromotions(subtype)];
            const promotionTypeNames = typePromotions.get(subtype.details.fullName);
            if (promotionTypeNames) {
                for (const promotionTypeName of promotionTypeNames) {
                    const nameSplit = promotionTypeName.split('.');
                    let promotionSubtype = getBuiltInType(node, nameSplit[nameSplit.length - 1]);
                    if (promotionSubtype && (0, types_1.isInstantiableClass)(promotionSubtype)) {
                        promotionSubtype = types_1.ClassType.cloneRemoveTypePromotions(promotionSubtype);
                        if ((0, types_1.isClassInstance)(subtype)) {
                            promotionSubtype = types_1.ClassType.cloneAsInstance(promotionSubtype);
                        }
                        promotionSubtype = (0, typeUtils_1.addConditionToType)(promotionSubtype, subtype.condition);
                        typesToCombine.push(promotionSubtype);
                    }
                }
            }
            return (0, types_1.combineTypes)(typesToCombine);
        });
    }
    // Replaces all of the top-level TypeVars (as opposed to TypeVars
    // used as type arguments in other types) with their concrete form.
    // If conditionFilter is specified and the TypeVar is a constrained
    // TypeVar, only the conditions that match the filter will be included.
    function makeTopLevelTypeVarsConcrete(type, makeParamSpecsConcrete = false, conditionFilter) {
        return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            var _a, _b;
            if ((0, types_1.isParamSpec)(subtype)) {
                if (subtype.paramSpecAccess === 'args') {
                    if (objectType && (0, types_1.isClassInstance)(objectType)) {
                        return makeTupleObject([{ type: objectType, isUnbounded: true }]);
                    }
                    return types_1.UnknownType.create();
                }
                else if (subtype.paramSpecAccess === 'kwargs') {
                    if (dictClassType &&
                        (0, types_1.isInstantiableClass)(dictClassType) &&
                        strClassType &&
                        (0, types_1.isInstantiableClass)(strClassType) &&
                        objectType &&
                        (0, types_1.isClassInstance)(objectType)) {
                        return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictClassType, [(0, typeUtils_1.convertToInstance)(strClassType), objectType], 
                        /* isTypeArgumentExplicit */ true));
                    }
                    return types_1.UnknownType.create();
                }
            }
            // If this is a function that contains only a ParamSpec (no additional
            // parameters), convert it to a concrete type of (*args: Any, **kwargs: Any).
            if (makeParamSpecsConcrete &&
                (0, types_1.isFunction)(subtype) &&
                subtype.details.parameters.length === 0 &&
                subtype.details.paramSpec) {
                return types_1.FunctionType.cloneForParamSpec(subtype, (0, typeUtils_1.getUnknownTypeForCallable)());
            }
            if ((0, types_1.isTypeVar)(subtype) && subtype.details.isVariadic) {
                // If it's in a union, convert to type or object.
                if (subtype.isVariadicInUnion) {
                    if (types_1.TypeBase.isInstantiable(subtype)) {
                        if (typeClassType && (0, types_1.isInstantiableClass)(typeClassType)) {
                            return typeClassType;
                        }
                    }
                    else if (objectType) {
                        return objectType;
                    }
                    return types_1.AnyType.create();
                }
                // Fall back to "*tuple[object, ...]".
                return makeTupleObject([{ type: objectType !== null && objectType !== void 0 ? objectType : types_1.UnknownType.create(), isUnbounded: true }], 
                /* isUnpacked */ true);
            }
            if ((0, types_1.isTypeVar)(subtype)) {
                // If this is a recursive type alias placeholder
                // that hasn't yet been resolved, return it as is.
                if (subtype.details.recursiveTypeAliasName) {
                    return subtype;
                }
                if (subtype.details.constraints.length > 0) {
                    const typesToCombine = [];
                    // Expand the list of constrained subtypes, filtering out any that are
                    // disallowed by the conditionFilter.
                    subtype.details.constraints.forEach((constraintType, constraintIndex) => {
                        if (conditionFilter) {
                            const typeVarName = types_1.TypeVarType.getNameWithScope(subtype);
                            const applicableConstraint = conditionFilter.find((filter) => filter.typeVar.nameWithScope === typeVarName);
                            // If this type variable is being constrained to a single index,
                            // don't include the other indices.
                            if (applicableConstraint && applicableConstraint.constraintIndex !== constraintIndex) {
                                return;
                            }
                        }
                        if (types_1.TypeBase.isInstantiable(subtype)) {
                            constraintType = (0, typeUtils_1.convertToInstantiable)(constraintType);
                        }
                        typesToCombine.push((0, typeUtils_1.addConditionToType)(constraintType, [{ typeVar: subtype, constraintIndex }]));
                    });
                    return (0, types_1.combineTypes)(typesToCombine);
                }
                if (subtype.details.isExemptFromBoundCheck) {
                    return types_1.AnyType.create();
                }
                // Fall back to a bound of "object" if no bound is provided.
                let boundType = (_b = (_a = subtype.details.boundType) !== null && _a !== void 0 ? _a : objectType) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
                boundType = types_1.TypeBase.isInstantiable(subtype) ? (0, typeUtils_1.convertToInstantiable)(boundType) : boundType;
                return (0, typeUtils_1.addConditionToType)(boundType, [{ typeVar: subtype, constraintIndex: 0 }]);
            }
            return subtype;
        });
    }
    // Creates a new type by mapping an existing type (which could be a union)
    // to another type or types. The callback is called for each subtype.
    // Top-level TypeVars are expanded (e.g. a bound TypeVar is expanded to
    // its bound type and a constrained TypeVar is expanded to its individual
    // constrained types). If conditionFilter is specified, conditions that
    // do not match will be ignored.
    function mapSubtypesExpandTypeVars(type, options, callback, recursionCount = 0) {
        const newSubtypes = [];
        let typeChanged = false;
        function expandSubtype(unexpandedType, isLastSubtype) {
            let expandedType = (0, types_1.isUnion)(unexpandedType) ? unexpandedType : makeTopLevelTypeVarsConcrete(unexpandedType);
            expandedType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(expandedType);
            if (options === null || options === void 0 ? void 0 : options.expandCallback) {
                expandedType = options.expandCallback(expandedType);
            }
            (0, typeUtils_1.doForEachSubtype)(expandedType, (subtype, index, allSubtypes) => {
                var _a;
                if (options === null || options === void 0 ? void 0 : options.conditionFilter) {
                    const filteredType = applyConditionFilterToType(subtype, options.conditionFilter, recursionCount);
                    if (!filteredType) {
                        return undefined;
                    }
                    subtype = filteredType;
                }
                let transformedType = callback(subtype, unexpandedType, isLastSubtype && index === allSubtypes.length - 1);
                if (transformedType !== unexpandedType) {
                    typeChanged = true;
                }
                if (transformedType) {
                    // Apply the type condition if it's associated with a constrained TypeVar.
                    const typeCondition = (_a = (0, typeUtils_1.getTypeCondition)(subtype)) === null || _a === void 0 ? void 0 : _a.filter((condition) => condition.typeVar.details.constraints.length > 0);
                    if (typeCondition && typeCondition.length > 0) {
                        transformedType = (0, typeUtils_1.addConditionToType)(transformedType, typeCondition);
                    }
                    // This code path can often produce many duplicate subtypes. We can
                    // reduce the cost of the combineTypes call below by filtering out these
                    // duplicates proactively.
                    if (newSubtypes.length === 0 ||
                        !(0, types_1.isTypeSame)(transformedType, newSubtypes[newSubtypes.length - 1])) {
                        newSubtypes.push(transformedType);
                    }
                }
                return undefined;
            }, options === null || options === void 0 ? void 0 : options.sortSubtypes);
        }
        if ((0, types_1.isUnion)(type)) {
            const subtypes = (options === null || options === void 0 ? void 0 : options.sortSubtypes) ? (0, typeUtils_1.sortTypes)(type.subtypes) : type.subtypes;
            subtypes.forEach((subtype, index) => {
                expandSubtype(subtype, index === type.subtypes.length - 1);
            });
        }
        else {
            expandSubtype(type, /* isLastSubtype */ true);
        }
        if (!typeChanged) {
            return type;
        }
        const newType = (0, types_1.combineTypes)(newSubtypes);
        // Do our best to retain type aliases.
        if (newType.category === 8 /* TypeCategory.Union */) {
            types_1.UnionType.addTypeAliasSource(newType, type);
        }
        return newType;
    }
    function applyConditionFilterToType(type, conditionFilter, recursionCount) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return type;
        }
        recursionCount++;
        // If the type has a condition associated with it, make sure it's compatible.
        if (!types_1.TypeCondition.isCompatible((0, typeUtils_1.getTypeCondition)(type), conditionFilter)) {
            return undefined;
        }
        // If the type is generic, see if any of its type arguments should be filtered.
        // This is possible only in cases where the type parameter is covariant.
        // TODO - handle functions and tuples
        if ((0, types_1.isClass)(type) && type.typeArguments && !type.tupleTypeArguments) {
            inferTypeParameterVarianceForClass(type);
            let typeWasTransformed = false;
            const filteredTypeArgs = type.typeArguments.map((typeArg, index) => {
                if (index >= type.details.typeParameters.length) {
                    return typeArg;
                }
                const variance = types_1.TypeVarType.getVariance(type.details.typeParameters[index]);
                if (variance !== 3 /* Variance.Covariant */) {
                    return typeArg;
                }
                const filteredTypeArg = mapSubtypesExpandTypeVars(typeArg, { conditionFilter }, (expandedSubtype) => {
                    return expandedSubtype;
                }, recursionCount);
                if (filteredTypeArg !== typeArg) {
                    typeWasTransformed = true;
                }
                return filteredTypeArg;
            });
            if (typeWasTransformed) {
                return types_1.ClassType.cloneForSpecialization(type, filteredTypeArgs, /* isTypeArgumentExplicit */ true);
            }
        }
        return type;
    }
    function markNamesAccessed(node, names) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const scope = ScopeUtils.getScopeForNode(node);
        if (scope) {
            names.forEach((symbolName) => {
                const symbolInScope = scope.lookUpSymbolRecursive(symbolName);
                if (symbolInScope) {
                    setSymbolAccessed(fileInfo, symbolInScope.symbol, node);
                }
            });
        }
    }
    function assignTypeToExpression(target, type, isTypeIncomplete, srcExpr, ignoreEmptyContainers = false, allowAssignmentToFinalVar = false, expectedTypeDiagAddendum) {
        // Is the source expression a TypeVar() call?
        if ((0, types_1.isTypeVar)(type)) {
            if (srcExpr && srcExpr.nodeType === 9 /* ParseNodeType.Call */) {
                const callType = getTypeOfExpression(srcExpr.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                if ((0, types_1.isInstantiableClass)(callType) &&
                    (types_1.ClassType.isBuiltIn(callType, 'TypeVar') ||
                        types_1.ClassType.isBuiltIn(callType, 'TypeVarTuple') ||
                        types_1.ClassType.isBuiltIn(callType, 'ParamSpec'))) {
                    const typeVarTarget = target.nodeType === 54 /* ParseNodeType.TypeAnnotation */ ? target.valueExpression : target;
                    if (typeVarTarget.nodeType !== 38 /* ParseNodeType.Name */ || typeVarTarget.value !== type.details.name) {
                        addError(type.details.isParamSpec
                            ? localize_1.LocMessage.paramSpecAssignedName().format({
                                name: types_1.TypeVarType.getReadableName(type),
                            })
                            : localize_1.LocMessage.typeVarAssignedName().format({
                                name: types_1.TypeVarType.getReadableName(type),
                            }), typeVarTarget);
                    }
                }
            }
        }
        // If the type was partially unbound, an error will have already been logged.
        // Remove the unbound before assigning to the target expression so the unbound
        // error doesn't propagate.
        type = (0, types_1.removeUnbound)(type);
        switch (target.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                assignTypeToNameNode(target, type, isTypeIncomplete, ignoreEmptyContainers, srcExpr, allowAssignmentToFinalVar, expectedTypeDiagAddendum);
                break;
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                assignTypeToMemberAccessNode(target, type, isTypeIncomplete, srcExpr, expectedTypeDiagAddendum);
                break;
            }
            case 24 /* ParseNodeType.Index */: {
                const baseTypeResult = getTypeOfExpression(target.baseExpression, 2 /* EvaluatorFlags.IndexBaseDefaults */);
                getTypeOfIndexWithBaseType(target, baseTypeResult, {
                    method: 'set',
                    setType: { type, isIncomplete: isTypeIncomplete },
                    setErrorNode: srcExpr,
                    setExpectedTypeDiag: expectedTypeDiagAddendum,
                }, 0 /* EvaluatorFlags.None */);
                writeTypeCache(target, { type, isIncomplete: isTypeIncomplete }, 0 /* EvaluatorFlags.None */);
                break;
            }
            case 31 /* ParseNodeType.List */:
            case 52 /* ParseNodeType.Tuple */: {
                assignTypeToTupleOrListNode(target, type, isTypeIncomplete, srcExpr);
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                const annotationType = getTypeOfAnnotation(target.typeAnnotation, {
                    isVariableAnnotation: true,
                    allowFinal: ParseTreeUtils.isFinalAllowedForAssignmentTarget(target.valueExpression),
                    allowClassVar: ParseTreeUtils.isClassVarAllowedForAssignmentTarget(target.valueExpression),
                });
                // Handle a bare "Final" or "ClassVar" in a special manner.
                const isBareFinalOrClassVar = (0, types_1.isClassInstance)(annotationType) &&
                    (types_1.ClassType.isBuiltIn(annotationType, 'Final') || types_1.ClassType.isBuiltIn(annotationType, 'ClassVar'));
                if (!isBareFinalOrClassVar) {
                    const isTypeAliasAnnotation = (0, types_1.isClassInstance)(annotationType) && types_1.ClassType.isBuiltIn(annotationType, 'TypeAlias');
                    if (!isTypeAliasAnnotation) {
                        if (assignType(annotationType, type)) {
                            // Don't attempt to narrow based on the annotated type if the type
                            // is a enum because the annotated type in an enum doesn't reflect
                            // the type of the symbol.
                            if (!(0, types_1.isClassInstance)(type) || !types_1.ClassType.isEnumClass(type)) {
                                type = narrowTypeBasedOnAssignment(target, annotationType, type);
                            }
                        }
                    }
                }
                assignTypeToExpression(target.valueExpression, type, isTypeIncomplete, srcExpr, ignoreEmptyContainers, allowAssignmentToFinalVar, expectedTypeDiagAddendum);
                break;
            }
            case 56 /* ParseNodeType.Unpack */: {
                if (target.expression.nodeType === 38 /* ParseNodeType.Name */) {
                    assignTypeToNameNode(target.expression, getBuiltInObject(target.expression, 'list', [type]), 
                    /* isIncomplete */ false, ignoreEmptyContainers, srcExpr);
                }
                break;
            }
            case 0 /* ParseNodeType.Error */: {
                // Evaluate the child expression as best we can so the
                // type information is cached for the completion handler.
                if (target.child) {
                    suppressDiagnostics(target.child, () => {
                        getTypeOfExpression(target.child);
                    });
                }
                break;
            }
            default: {
                addError(localize_1.LocMessage.assignmentTargetExpr(), target);
                break;
            }
        }
    }
    function verifyRaiseExceptionType(node) {
        const baseExceptionType = getBuiltInType(node, 'BaseException');
        if (node.typeExpression) {
            const exceptionType = getTypeOfExpression(node.typeExpression).type;
            // Validate that the argument of "raise" is an exception object or class.
            // If it is a class, validate that the class's constructor accepts zero
            // arguments.
            if (exceptionType && baseExceptionType && (0, types_1.isInstantiableClass)(baseExceptionType)) {
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                (0, typeUtils_1.doForEachSubtype)(exceptionType, (subtype) => {
                    const concreteSubtype = makeTopLevelTypeVarsConcrete(subtype);
                    if (!(0, types_1.isAnyOrUnknown)(concreteSubtype)) {
                        if ((0, types_1.isInstantiableClass)(concreteSubtype) && concreteSubtype.literalValue === undefined) {
                            if (!(0, typeUtils_1.derivesFromClassRecursive)(concreteSubtype, baseExceptionType, 
                            /* ignoreUnknown */ false)) {
                                diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                                    type: printType(subtype),
                                }));
                            }
                            else {
                                let callResult;
                                suppressDiagnostics(node.typeExpression, () => {
                                    callResult = (0, constructors_1.validateConstructorArguments)(evaluatorInterface, node.typeExpression, [], concreteSubtype, 
                                    /* skipUnknownArgCheck */ false, 
                                    /* inferenceContext */ undefined);
                                });
                                if (callResult && callResult.argumentErrors) {
                                    diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeNotInstantiable().format({
                                        type: printType(subtype),
                                    }));
                                }
                            }
                        }
                        else if ((0, types_1.isClassInstance)(concreteSubtype)) {
                            if (!(0, typeUtils_1.derivesFromClassRecursive)(types_1.ClassType.cloneAsInstantiable(concreteSubtype), baseExceptionType, 
                            /* ignoreUnknown */ false)) {
                                diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                                    type: printType(subtype),
                                }));
                            }
                        }
                        else {
                            diagAddendum.addMessage(localize_1.LocMessage.exceptionTypeIncorrect().format({
                                type: printType(subtype),
                            }));
                        }
                    }
                });
                if (!diagAddendum.isEmpty()) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.expectedExceptionClass() + diagAddendum.getString(), node.typeExpression);
                }
            }
        }
    }
    function verifyDeleteExpression(node) {
        switch (node.nodeType) {
            case 38 /* ParseNodeType.Name */: {
                // Get the type to evaluate whether it's bound
                // and to mark it accessed.
                getTypeOfExpression(node);
                break;
            }
            case 35 /* ParseNodeType.MemberAccess */: {
                const baseTypeResult = getTypeOfExpression(node.leftExpression, 2 /* EvaluatorFlags.MemberAccessBaseDefaults */);
                const delAccessResult = getTypeOfMemberAccessWithBaseType(node, baseTypeResult, { method: 'del' }, 0 /* EvaluatorFlags.None */);
                const resultToCache = {
                    type: delAccessResult.type,
                    memberAccessDeprecationInfo: delAccessResult.memberAccessDeprecationInfo,
                };
                writeTypeCache(node.memberName, resultToCache, 0 /* EvaluatorFlags.None */);
                writeTypeCache(node, resultToCache, 0 /* EvaluatorFlags.None */);
                break;
            }
            case 24 /* ParseNodeType.Index */: {
                const baseTypeResult = getTypeOfExpression(node.baseExpression, 2 /* EvaluatorFlags.IndexBaseDefaults */);
                getTypeOfIndexWithBaseType(node, baseTypeResult, { method: 'del' }, 0 /* EvaluatorFlags.None */);
                writeTypeCache(node, { type: types_1.UnboundType.create() }, 0 /* EvaluatorFlags.None */);
                break;
            }
            case 52 /* ParseNodeType.Tuple */: {
                node.expressions.forEach((expr) => {
                    verifyDeleteExpression(expr);
                });
                break;
            }
            case 0 /* ParseNodeType.Error */: {
                // Evaluate the child expression as best we can so the
                // type information is cached for the completion handler.
                if (node.child) {
                    suppressDiagnostics(node.child, () => {
                        getTypeOfExpression(node.child);
                    });
                }
                break;
            }
            default: {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.delTargetExpr(), node);
                break;
            }
        }
    }
    function setSymbolAccessed(fileInfo, symbol, node) {
        if (!isSpeculativeModeInUse(node)) {
            fileInfo.accessedSymbolSet.add(symbol.id);
        }
    }
    function getTypeOfName(node, flags) {
        var _a;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const name = node.value;
        let symbol;
        let type;
        let isIncomplete = false;
        const allowForwardReferences = (flags & 4 /* EvaluatorFlags.AllowForwardReferences */) !== 0 || fileInfo.isStubFile;
        // Does this name refer to a PEP 695-style type parameter?
        const typeParamSymbol = AnalyzerNodeInfo.getTypeParameterSymbol(node);
        if (typeParamSymbol) {
            symbol = typeParamSymbol;
            (0, debug_1.assert)(symbol.getDeclarations().length === 1);
            const decl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
            (0, debug_1.assert)((decl === null || decl === void 0 ? void 0 : decl.type) === 3 /* DeclarationType.TypeParameter */);
            type = getTypeOfTypeParameter(decl.node);
            setSymbolAccessed(fileInfo, symbol, node);
        }
        else {
            // Look for the scope that contains the value definition and
            // see if it has a declared type.
            let symbolWithScope = lookUpSymbolRecursive(node, name, !allowForwardReferences, allowForwardReferences && (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0);
            if (!symbolWithScope) {
                // If the node is part of a "from X import Y as Z" statement and the node
                // is the "Y" (non-aliased) name, we need to look up the alias symbol
                // since the non-aliased name is not in the symbol table.
                const alias = getAliasFromImport(node);
                if (alias) {
                    symbolWithScope = lookUpSymbolRecursive(alias, alias.value, !allowForwardReferences, allowForwardReferences && (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0);
                }
            }
            if (symbolWithScope) {
                let useCodeFlowAnalysis = !allowForwardReferences;
                // If the symbol is implicitly imported from the builtin
                // scope, there's no need to use code flow analysis.
                if (symbolWithScope.scope.type === 4 /* ScopeType.Builtin */) {
                    useCodeFlowAnalysis = false;
                }
                symbol = symbolWithScope.symbol;
                setSymbolAccessed(fileInfo, symbol, node);
                // If we're not supposed to be analyzing this function, skip the remaining work
                // to determine the name's type. Simply evaluate its type as Any.
                if (!fileInfo.diagnosticRuleSet.analyzeUnannotatedFunctions) {
                    const containingFunction = ParseTreeUtils.getEnclosingFunction(node);
                    if (containingFunction && ParseTreeUtils.isUnannotatedFunction(containingFunction)) {
                        return {
                            type: types_1.AnyType.create(),
                            isIncomplete: false,
                        };
                    }
                }
                // Get the effective type (either the declared type or the inferred type).
                // If we're using code flow analysis, pass the usage node so we consider
                // only the assignment nodes that are reachable from this usage.
                const effectiveTypeInfo = getEffectiveTypeOfSymbolForUsage(symbol, useCodeFlowAnalysis ? node : undefined);
                let effectiveType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(effectiveTypeInfo.type);
                if (effectiveTypeInfo.isIncomplete) {
                    if ((0, types_1.isUnbound)(effectiveType)) {
                        effectiveType = types_1.UnknownType.create(/* isIncomplete */ true);
                    }
                    isIncomplete = true;
                }
                if (effectiveTypeInfo.isRecursiveDefinition && isNodeReachable(node)) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.recursiveDefinition().format({ name }), node);
                }
                const isSpecialBuiltIn = !!effectiveType && (0, types_1.isInstantiableClass)(effectiveType) && types_1.ClassType.isSpecialBuiltIn(effectiveType);
                type = effectiveType;
                if (useCodeFlowAnalysis && !isSpecialBuiltIn) {
                    // See if code flow analysis can tell us anything more about the type.
                    // If the symbol is declared outside of our execution scope, use its effective
                    // type. If it's declared inside our execution scope, it generally starts
                    // as unbound at the start of the code flow.
                    let typeAtStart = effectiveType;
                    let isTypeAtStartIncomplete = false;
                    if (!symbolWithScope.isBeyondExecutionScope && symbol.isInitiallyUnbound()) {
                        typeAtStart = types_1.UnboundType.create();
                        // Is this a module-level scope? If so, see if it's an alias of a builtin.
                        if (symbolWithScope.scope.type === 3 /* ScopeType.Module */) {
                            (0, debug_1.assert)(symbolWithScope.scope.parent);
                            const builtInSymbol = symbolWithScope.scope.parent.lookUpSymbol(name);
                            if (builtInSymbol) {
                                const builtInEffectiveType = getEffectiveTypeOfSymbolForUsage(builtInSymbol);
                                typeAtStart = builtInEffectiveType.type;
                            }
                        }
                    }
                    if (symbolWithScope.isBeyondExecutionScope) {
                        const outerScopeTypeResult = getCodeFlowTypeForCapturedVariable(node, symbolWithScope, effectiveType);
                        if (outerScopeTypeResult === null || outerScopeTypeResult === void 0 ? void 0 : outerScopeTypeResult.type) {
                            type = outerScopeTypeResult.type;
                            typeAtStart = type;
                            isTypeAtStartIncomplete = !!outerScopeTypeResult.isIncomplete;
                        }
                    }
                    const codeFlowTypeResult = getFlowTypeOfReference(node, /* startNode */ undefined, {
                        targetSymbolId: symbol.id,
                        typeAtStart: { type: typeAtStart, isIncomplete: isTypeAtStartIncomplete },
                        skipConditionalNarrowing: (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0,
                    });
                    if (codeFlowTypeResult.type) {
                        type = codeFlowTypeResult.type;
                    }
                    if (codeFlowTypeResult.isIncomplete) {
                        isIncomplete = true;
                    }
                }
                // Detect, report, and fill in missing type arguments if appropriate.
                type = reportMissingTypeArguments(node, type, flags);
                if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                    // Verify that the name does not refer to a (non type alias) variable.
                    if (effectiveTypeInfo.includesVariableDecl && !type.typeAliasInfo) {
                        let isAllowedTypeForVariable = (0, types_1.isTypeVar)(type) || (0, typeUtils_1.isTypeAliasPlaceholder)(type);
                        if ((0, types_1.isClass)(type) &&
                            !type.includeSubclasses &&
                            !symbol.hasTypedDeclarations() &&
                            types_1.ClassType.isValidTypeAliasClass(type)) {
                            // This check exempts class types that are created by calling
                            // NewType, NamedTuple, etc.
                            isAllowedTypeForVariable = true;
                        }
                        // Disable for assignments in the typings.pyi file, since it defines special forms.
                        if (!isAllowedTypeForVariable && !fileInfo.isTypingStubFile) {
                            // This might be a union that was previously a type alias
                            // but was reconstituted in such a way that we lost the
                            // typeAliasInfo. Avoid the false positive error by suppressing
                            // the error when it looks like a plausible type alias type.
                            if (effectiveTypeInfo.includesIllegalTypeAliasDecl ||
                                !types_1.TypeBase.isInstantiable(type) ||
                                (flags & 2 /* EvaluatorFlags.DoNotSpecialize */) !== 0) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.typeAnnotationVariable(), node);
                                type = types_1.UnknownType.create();
                            }
                        }
                    }
                }
            }
            else {
                // Handle the special case of "reveal_type" and "reveal_locals".
                if (name === 'reveal_type' || name === 'reveal_locals') {
                    type = types_1.AnyType.create();
                }
                else {
                    (_a = addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUndefinedVariable, localize_1.LocMessage.symbolIsUndefined().format({ name }), node)) === null || _a === void 0 ? void 0 : _a.addAction({ action: "basedpyright.import" /* Commands.import */ });
                    type = types_1.UnknownType.create();
                }
            }
        }
        if ((0, types_1.isParamSpec)(type)) {
            if (flags & 32 /* EvaluatorFlags.DisallowParamSpec */) {
                addError(localize_1.LocMessage.paramSpecContext(), node);
                type = types_1.UnknownType.create();
            }
        }
        type = convertTypeVarToRuntimeInstance(node, type, flags);
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) === 0) {
            reportUseOfTypeCheckOnly(type, node);
        }
        if ((flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0) {
            if ((flags & 1024 /* EvaluatorFlags.AllowGenericClassType */) === 0) {
                if ((0, types_1.isInstantiableClass)(type) && types_1.ClassType.isBuiltIn(type, 'Generic')) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.genericNotAllowed(), node);
                }
            }
        }
        if ((0, types_1.isTypeVar)(type) && !type.details.isSynthesized) {
            type = validateTypeVarUsage(node, type, flags);
        }
        return { type, isIncomplete };
    }
    // If the type is a TypeVar and we're not expecting a type, convert
    // a TypeVar, TypeVarTuple or ParamSpec into a runtime type.
    function convertTypeVarToRuntimeInstance(node, type, flags) {
        var _a;
        if (!type.specialForm || type.typeAliasInfo) {
            return type;
        }
        if (!(0, types_1.isTypeVar)(type) || type.isVariadicInUnion || (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0) {
            return type;
        }
        if ((flags & 33554432 /* EvaluatorFlags.SkipConvertParamSpecToRuntimeObject */) !== 0 && type.details.isParamSpec) {
            return types_1.TypeBase.cloneAsSpecialForm(type, undefined);
        }
        // Handle the special case of a PEP 604 union. These can appear within
        // an implied type alias where we are not expecting a type.
        const isPep604Union = ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 7 /* ParseNodeType.BinaryOperation */ && node.parent.operator === 6 /* OperatorType.BitwiseOr */;
        if (isPep604Union) {
            return types_1.TypeBase.cloneAsSpecialForm(type, undefined);
        }
        return types_1.ClassType.cloneAsInstance(type.specialForm);
    }
    // Handles the case where a variable or parameter is defined in an outer
    // scope and captured by an inner scope (a function, lambda, or comprehension).
    function getCodeFlowTypeForCapturedVariable(node, symbolWithScope, effectiveType) {
        // This function applies only to variables, parameters, and imports, not to other
        // types of symbols.
        const decls = symbolWithScope.symbol.getDeclarations();
        if (!decls.every((decl) => decl.type === 1 /* DeclarationType.Variable */ ||
            decl.type === 2 /* DeclarationType.Parameter */ ||
            decl.type === 8 /* DeclarationType.Alias */)) {
            return undefined;
        }
        // If the symbol is modified in scopes other than the one in which it is
        // declared (e.g. through a nonlocal or global binding), it is not eligible
        // for code flow analysis.
        if (!decls.every((decl) => decl.type === 2 /* DeclarationType.Parameter */ ||
            ScopeUtils.getScopeForNode(decl.node) === symbolWithScope.scope)) {
            return undefined;
        }
        // If the symbol is a variable captured by an inner function
        // or lambda, see if we can infer the type from the outer scope.
        const scopeHierarchy = ScopeUtils.getScopeHierarchy(node, symbolWithScope.scope);
        if (scopeHierarchy && scopeHierarchy.length >= 2) {
            // Find the parse node associated with the scope that is just inside of the
            // scope that declares the captured variable.
            const innerScopeNode = ScopeUtils.findTopNodeInScope(node, scopeHierarchy[scopeHierarchy.length - 2]);
            if ((innerScopeNode === null || innerScopeNode === void 0 ? void 0 : innerScopeNode.nodeType) === 28 /* ParseNodeType.Function */ ||
                (innerScopeNode === null || innerScopeNode === void 0 ? void 0 : innerScopeNode.nodeType) === 30 /* ParseNodeType.Lambda */ ||
                (innerScopeNode === null || innerScopeNode === void 0 ? void 0 : innerScopeNode.nodeType) === 10 /* ParseNodeType.Class */) {
                const innerScopeCodeFlowNode = AnalyzerNodeInfo.getFlowNode(innerScopeNode);
                if (innerScopeCodeFlowNode) {
                    // See if any of the assignments of the symbol are reachable
                    // from this node. If so, we cannot apply any narrowing because
                    // the type could change after the capture.
                    if (symbolWithScope.symbol.getDeclarations().every((decl) => {
                        // Parameter declarations always start life at the beginning
                        // of the execution scope, so they are always safe to narrow.
                        if (decl.type === 2 /* DeclarationType.Parameter */) {
                            return true;
                        }
                        const declCodeFlowNode = AnalyzerNodeInfo.getFlowNode(decl.node);
                        if (!declCodeFlowNode) {
                            return false;
                        }
                        return !codeFlowEngine.isFlowNodeReachable(declCodeFlowNode, innerScopeCodeFlowNode, 
                        /* ignoreNoReturn */ true);
                    })) {
                        let typeAtStart = effectiveType;
                        if (symbolWithScope.symbol.isInitiallyUnbound()) {
                            typeAtStart = types_1.UnboundType.create();
                        }
                        return getFlowTypeOfReference(node, innerScopeNode, {
                            targetSymbolId: symbolWithScope.symbol.id,
                            typeAtStart: { type: typeAtStart },
                        });
                    }
                }
            }
        }
        return undefined;
    }
    // Validates that a TypeVar is valid in this context. If so, it clones it
    // and provides a scope ID defined by its containing scope (class, function
    // or type alias). If not, it emits errors indicating why the TypeVar
    // cannot be used in this location.
    function validateTypeVarUsage(node, type, flags) {
        var _a;
        if (types_1.TypeBase.isInstantiable(type) && !type.scopeId && !(0, typeUtils_1.isTypeAliasPlaceholder)(type)) {
            const scopedTypeVarInfo = findScopedTypeVar(node, type);
            type = scopedTypeVarInfo.type;
            if ((flags & 2048 /* EvaluatorFlags.DisallowTypeVarsWithScopeId */) !== 0 && type.scopeId !== undefined) {
                if (!type.details.isSynthesized && !type.details.isParamSpec) {
                    // This TypeVar already has a scope ID assigned to it. See if it
                    // originates from type parameter syntax. If so, allow it.
                    if (type.details.isTypeParamSyntax) {
                        return type;
                    }
                    // If this type variable expression is used within a generic class,
                    // function, or type alias that uses type parameter syntax, there is
                    // no need to report an error here.
                    const typeVarScopeNode = ParseTreeUtils.getTypeVarScopeNode(node);
                    if (typeVarScopeNode &&
                        typeVarScopeNode.typeParameters &&
                        !typeVarScopeNode.typeParameters.parameters.some((t) => t.name === node)) {
                        return type;
                    }
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarUsedByOuterScope().format({ name: type.details.name }), node);
                }
            }
            else if ((flags & 8192 /* EvaluatorFlags.AssociateTypeVarsWithCurrentScope */) !== 0) {
                if (type.scopeId === undefined) {
                    if (!scopedTypeVarInfo.foundInterveningClass) {
                        let enclosingScope = ParseTreeUtils.getEnclosingClassOrFunction(node);
                        // Handle P.args and P.kwargs as a special case for inner functions.
                        if (enclosingScope &&
                            ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 35 /* ParseNodeType.MemberAccess */ &&
                            node.parent.leftExpression === node) {
                            const memberName = node.parent.memberName.value;
                            if (memberName === 'args' || memberName === 'kwargs') {
                                const outerFunctionScope = ParseTreeUtils.getEnclosingClassOrFunction(enclosingScope);
                                if ((outerFunctionScope === null || outerFunctionScope === void 0 ? void 0 : outerFunctionScope.nodeType) === 28 /* ParseNodeType.Function */) {
                                    if (scopedTypeVarInfo.isRescoped) {
                                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramSpecScopedToReturnType().format({
                                            name: type.details.name,
                                        }), node);
                                    }
                                    else {
                                        enclosingScope = outerFunctionScope;
                                    }
                                }
                                else if (!scopedTypeVarInfo.type.scopeId) {
                                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramSpecNotUsedByOuterScope().format({
                                        name: type.details.name,
                                    }), node);
                                }
                            }
                        }
                        if (enclosingScope) {
                            // If the enclosing scope is using type parameter syntax, traditional
                            // type variables can't be used in this context.
                            if (enclosingScope.typeParameters &&
                                !enclosingScope.typeParameters.parameters.some((param) => param.name.value === type.details.name)) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeParameterNotDeclared().format({
                                    name: type.details.name,
                                    container: enclosingScope.name.value,
                                }), node);
                            }
                            type = types_1.TypeVarType.cloneForScopeId(type, ParseTreeUtils.getScopeIdForNode(enclosingScope), enclosingScope.name.value, enclosingScope.nodeType === 28 /* ParseNodeType.Function */
                                ? 1 /* TypeVarScopeType.Function */
                                : 0 /* TypeVarScopeType.Class */);
                        }
                        else {
                            (0, debug_1.fail)('AssociateTypeVarsWithCurrentScope flag was set but enclosing scope not found');
                        }
                    }
                    else {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarUsedByOuterScope().format({ name: type.details.name }), node);
                    }
                }
            }
            else if ((flags & 4096 /* EvaluatorFlags.AllowTypeVarsWithoutScopeId */) === 0) {
                if ((type.scopeId === undefined || scopedTypeVarInfo.foundInterveningClass) &&
                    !type.details.isSynthesized) {
                    let message;
                    if (scopedTypeVarInfo.isRescoped) {
                        message = (0, types_1.isParamSpec)(type)
                            ? localize_1.LocMessage.paramSpecScopedToReturnType()
                            : localize_1.LocMessage.typeVarScopedToReturnType();
                    }
                    else {
                        message = (0, types_1.isParamSpec)(type)
                            ? localize_1.LocMessage.paramSpecNotUsedByOuterScope()
                            : localize_1.LocMessage.typeVarNotUsedByOuterScope();
                    }
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, message.format({ name: type.details.name }), node);
                }
            }
        }
        // If this type var is variadic, the name refers to the packed form. It
        // must be unpacked in most contexts.
        if ((0, types_1.isUnpackedVariadicTypeVar)(type)) {
            type = types_1.TypeVarType.cloneForPacked(type);
        }
        return type;
    }
    // Determines if the type is a generic class or type alias with missing
    // type arguments. If so, it fills in these type arguments with Unknown
    // and optionally reports an error.
    function reportMissingTypeArguments(node, type, flags) {
        var _a;
        if ((flags & 2 /* EvaluatorFlags.DoNotSpecialize */) !== 0) {
            return type;
        }
        // Is this a generic class that needs to be specialized?
        if ((0, types_1.isInstantiableClass)(type)) {
            if ((flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0 &&
                (flags & 512 /* EvaluatorFlags.AllowMissingTypeArgs */) === 0) {
                if (!type.typeAliasInfo && (0, typeUtils_1.requiresTypeArguments)(type)) {
                    if (!type.typeArguments || !type.isTypeArgumentExplicit) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.LocMessage.typeArgsMissingForClass().format({
                            name: type.aliasName || type.details.name,
                        }), node);
                    }
                }
            }
            if (!type.typeArguments) {
                type = (_a = createSpecializedClassType(type, /* typeArgs */ undefined, flags, node)) === null || _a === void 0 ? void 0 : _a.type;
            }
        }
        // Is this a generic type alias that needs to be specialized?
        if ((flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0 &&
            type.typeAliasInfo &&
            type.typeAliasInfo.typeParameters &&
            type.typeAliasInfo.typeParameters.length > 0 &&
            !type.typeAliasInfo.typeArguments) {
            let reportMissingTypeArguments = false;
            const defaultTypeArgs = [];
            const typeVarContext = new typeVarContext_1.TypeVarContext(type.typeAliasInfo.typeVarScopeId);
            type.typeAliasInfo.typeParameters.forEach((param) => {
                if (!param.details.isDefaultExplicit) {
                    reportMissingTypeArguments = true;
                }
                let defaultType;
                if (param.details.isDefaultExplicit || param.details.isParamSpec) {
                    defaultType = (0, typeUtils_1.applySolvedTypeVars)(param, typeVarContext, { unknownIfNotFound: true });
                }
                else if (param.details.isVariadic && tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                    defaultType = makeTupleObject([{ type: types_1.UnknownType.create(), isUnbounded: true }], 
                    /* isUnpackedTuple */ true);
                }
                else {
                    defaultType = types_1.UnknownType.create();
                }
                defaultTypeArgs.push(defaultType);
                typeVarContext.setTypeVarType(param, defaultType);
            });
            if (reportMissingTypeArguments) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.LocMessage.typeArgsMissingForAlias().format({
                    name: type.typeAliasInfo.name,
                }), node);
            }
            type = types_1.TypeBase.cloneForTypeAlias((0, typeUtils_1.applySolvedTypeVars)(type, typeVarContext, { unknownIfNotFound: true }), type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, defaultTypeArgs);
        }
        return type;
    }
    // Walks up the parse tree to find a function, class, or type alias
    // declaration that provides the context for a type variable.
    function findScopedTypeVar(node, type) {
        var _a;
        let curNode = node;
        let nestedClassCount = 0;
        (0, debug_1.assert)(types_1.TypeBase.isInstantiable(type));
        while (curNode) {
            curNode = ParseTreeUtils.getTypeVarScopeNode(curNode);
            if (!curNode) {
                break;
            }
            let typeParametersForScope;
            let scopeUsesTypeParameterSyntax = false;
            if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
                const classTypeInfo = getTypeOfClass(curNode);
                if (classTypeInfo && !types_1.ClassType.isPartiallyEvaluated(classTypeInfo.classType)) {
                    typeParametersForScope = classTypeInfo.classType.details.typeParameters;
                }
                scopeUsesTypeParameterSyntax = !!curNode.typeParameters;
                nestedClassCount++;
            }
            else if (curNode.nodeType === 28 /* ParseNodeType.Function */) {
                const functionType = getTypeOfFunctionPredecorated(curNode);
                if (functionType) {
                    const functionDetails = functionType.details;
                    typeParametersForScope = functionDetails.typeParameters;
                    // Was this type parameter "rescoped" to a callable found within the
                    // return type annotation? If so, it is not available for use within
                    // the function body.
                    if ((_a = functionDetails.rescopedTypeParameters) === null || _a === void 0 ? void 0 : _a.some((tp) => tp.details.name === type.details.name)) {
                        return { type, isRescoped: true, foundInterveningClass: false };
                    }
                }
                scopeUsesTypeParameterSyntax = !!curNode.typeParameters;
            }
            else if (curNode.nodeType === 77 /* ParseNodeType.TypeAlias */) {
                scopeUsesTypeParameterSyntax = !!curNode.typeParameters;
            }
            if (typeParametersForScope) {
                const match = typeParametersForScope.find((typeVar) => typeVar.details.name === type.details.name);
                if ((match === null || match === void 0 ? void 0 : match.scopeId) !== undefined && match.scopeName !== undefined && match.scopeType !== undefined) {
                    // Use the scoped version of the TypeVar rather than the (unscoped) original type.
                    type = types_1.TypeVarType.cloneForScopeId(type, match.scopeId, match.scopeName, match.scopeType);
                    return {
                        type,
                        isRescoped: false,
                        foundInterveningClass: nestedClassCount > 1 && !scopeUsesTypeParameterSyntax,
                    };
                }
            }
            curNode = curNode.parent;
        }
        // See if this is part of an assignment statement that is defining a type alias.
        curNode = node;
        while (curNode) {
            let leftType;
            let typeAliasNode = undefined;
            if (curNode.nodeType === 77 /* ParseNodeType.TypeAlias */) {
                leftType = readTypeCache(curNode.name, 0 /* EvaluatorFlags.None */);
                typeAliasNode = curNode;
            }
            else if (curNode.nodeType === 3 /* ParseNodeType.Assignment */) {
                leftType = readTypeCache(curNode.leftExpression, 0 /* EvaluatorFlags.None */);
            }
            if (leftType) {
                // Is this a placeholder that was temporarily written to the cache for
                // purposes of resolving type aliases?
                if (leftType &&
                    (0, types_1.isTypeVar)(leftType) &&
                    leftType.details.recursiveTypeAliasScopeId &&
                    leftType.details.recursiveTypeAliasName) {
                    // Type alias statements cannot be used with old-style type variables.
                    if (typeAliasNode && !type.details.isTypeParamSyntax) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeParameterNotDeclared().format({
                            name: type.details.name,
                            container: typeAliasNode.name.value,
                        }), node);
                    }
                    else {
                        // If this is a TypeAliasType call, the recursiveTypeParameters will already
                        // be populated, and we need to verify that the type parameter is in the
                        // list of allowed type parameters.
                        const allowedTypeParams = leftType.details.recursiveTypeParameters;
                        if (allowedTypeParams) {
                            if (!allowedTypeParams.some((param) => param.details.name === type.details.name)) {
                                // Return the original type.
                                return { type, isRescoped: false, foundInterveningClass: false };
                            }
                        }
                    }
                    return {
                        type: types_1.TypeVarType.cloneForScopeId(type, leftType.details.recursiveTypeAliasScopeId, leftType.details.recursiveTypeAliasName, 2 /* TypeVarScopeType.TypeAlias */),
                        isRescoped: false,
                        foundInterveningClass: false,
                    };
                }
            }
            curNode = curNode.parent;
        }
        // Return the original type.
        return { type, isRescoped: false, foundInterveningClass: false };
    }
    function getTypeOfMemberAccess(node, flags) {
        var _a;
        // Compute flags specifically for evaluating the left expression.
        let leftExprFlags = 2 /* EvaluatorFlags.MemberAccessBaseDefaults */;
        leftExprFlags |=
            flags &
                (256 /* EvaluatorFlags.ExpectingTypeAnnotation */ |
                    32768 /* EvaluatorFlags.VariableTypeAnnotation */ |
                    4 /* EvaluatorFlags.AllowForwardReferences */ |
                    524288 /* EvaluatorFlags.NotParsedByInterpreter */ |
                    2048 /* EvaluatorFlags.DisallowTypeVarsWithScopeId */ |
                    8192 /* EvaluatorFlags.AssociateTypeVarsWithCurrentScope */);
        // Handle special casing for ParamSpec "args" and "kwargs" accesses.
        if ((flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0) {
            const memberName = node.memberName.value;
            if (memberName === 'args' || memberName === 'kwargs') {
                leftExprFlags |= 33554432 /* EvaluatorFlags.SkipConvertParamSpecToRuntimeObject */;
            }
        }
        const baseTypeResult = getTypeOfExpression(node.leftExpression, leftExprFlags);
        if ((0, typeUtils_1.isTypeAliasPlaceholder)(baseTypeResult.type)) {
            return {
                type: types_1.UnknownType.create(/* isIncomplete */ true),
                isIncomplete: true,
            };
        }
        const typeResult = getTypeOfMemberAccessWithBaseType(node, baseTypeResult, { method: 'get' }, flags | 2 /* EvaluatorFlags.DoNotSpecialize */);
        if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(node)) {
            // Before performing code flow analysis, update the cache to prevent recursion.
            writeTypeCache(node, { ...typeResult, isIncomplete: true }, flags);
            writeTypeCache(node.memberName, { ...typeResult, isIncomplete: true }, flags);
            // If the type is initially unbound, see if there's a parent class that
            // potentially initialized the value.
            let typeAtStart = typeResult.type;
            let isTypeAtStartIncomplete = !!typeResult.isIncomplete;
            if ((0, types_1.isUnbound)(typeAtStart)) {
                const baseType = makeTopLevelTypeVarsConcrete(baseTypeResult.type);
                let classMemberInfo;
                if ((0, types_1.isInstantiableClass)(baseType)) {
                    classMemberInfo = (0, typeUtils_1.lookUpClassMember)(baseType, node.memberName.value, 1 /* MemberAccessFlags.SkipOriginalClass */);
                }
                else if ((0, types_1.isClassInstance)(baseType)) {
                    classMemberInfo = (0, typeUtils_1.lookUpObjectMember)(baseType, node.memberName.value, 1 /* MemberAccessFlags.SkipOriginalClass */);
                }
                if (classMemberInfo) {
                    typeAtStart = getTypeOfMember(classMemberInfo);
                    isTypeAtStartIncomplete = false;
                }
            }
            // See if we can refine the type based on code flow analysis.
            const codeFlowTypeResult = getFlowTypeOfReference(node, /* startNode */ undefined, {
                targetSymbolId: symbol_1.indeterminateSymbolId,
                typeAtStart: { type: typeAtStart, isIncomplete: isTypeAtStartIncomplete },
                skipConditionalNarrowing: (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0,
            });
            if (codeFlowTypeResult.type) {
                typeResult.type = codeFlowTypeResult.type;
            }
            if (codeFlowTypeResult.isIncomplete) {
                typeResult.isIncomplete = true;
            }
            // Detect, report, and fill in missing type arguments if appropriate.
            typeResult.type = reportMissingTypeArguments(node, typeResult.type, flags);
        }
        if (baseTypeResult.isIncomplete) {
            typeResult.isIncomplete = true;
        }
        // See if we need to log an "unknown member access" diagnostic.
        let skipPartialUnknownCheck = typeResult.isIncomplete;
        // Don't report an error if the type is a partially-specialized
        // class being passed as an argument. This comes up frequently in
        // cases where a type is passed as an argument (e.g. "defaultdict(list)").
        // It can also come up in cases like "isinstance(x, (list, dict))".
        // We need to check for functions as well to handle Callable.
        if (((0, types_1.isInstantiableClass)(typeResult.type) && !typeResult.type.includeSubclasses) ||
            typeResult.type.specialForm) {
            const argNode = ParseTreeUtils.getParentNodeOfType(node, 1 /* ParseNodeType.Argument */);
            if (argNode && ((_a = argNode === null || argNode === void 0 ? void 0 : argNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 9 /* ParseNodeType.Call */) {
                skipPartialUnknownCheck = true;
            }
        }
        if (!skipPartialUnknownCheck) {
            reportPossibleUnknownAssignment(AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet, diagnosticRules_1.DiagnosticRule.reportUnknownMemberType, node.memberName, typeResult.type, node, 
            /* ignoreEmptyContainers */ false);
        }
        // Cache the type information in the member name node.
        writeTypeCache(node.memberName, typeResult, flags);
        return typeResult;
    }
    function getTypeOfMemberAccessWithBaseType(node, baseTypeResult, usage, flags) {
        var _a;
        let baseType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(baseTypeResult.type);
        const memberName = node.memberName.value;
        let diag = new diagnostic_1.DiagnosticAddendum();
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        let type;
        let narrowedTypeForSet;
        let typeErrors = false;
        let isIncomplete = !!baseTypeResult.isIncomplete;
        let isAsymmetricAccessor;
        const isRequired = false;
        const isNotRequired = false;
        let memberAccessDeprecationInfo;
        // If the base type was incomplete and unbound, don't proceed
        // because false positive errors will be generated.
        if (baseTypeResult.isIncomplete && (0, types_1.isUnbound)(baseType)) {
            return { type: types_1.UnknownType.create(/* isIncomplete */ true), isIncomplete: true };
        }
        if (baseType.specialForm) {
            baseType = baseType.specialForm;
        }
        if ((0, types_1.isParamSpec)(baseType) && baseType.paramSpecAccess) {
            baseType = makeTopLevelTypeVarsConcrete(baseType);
        }
        switch (baseType.category) {
            case 2 /* TypeCategory.Any */:
            case 1 /* TypeCategory.Unknown */:
            case 3 /* TypeCategory.Never */: {
                type = baseType;
                break;
            }
            case 0 /* TypeCategory.Unbound */: {
                break;
            }
            case 9 /* TypeCategory.TypeVar */: {
                if (baseType.details.isParamSpec) {
                    // Handle special cases for "P.args" and "P.kwargs".
                    if (memberName === 'args' || memberName === 'kwargs') {
                        const isArgs = memberName === 'args';
                        const paramNode = ParseTreeUtils.getEnclosingParameter(node);
                        const expectedCategory = isArgs ? 1 /* ParameterCategory.ArgsList */ : 2 /* ParameterCategory.KwargsDict */;
                        if (!paramNode || paramNode.category !== expectedCategory) {
                            const errorMessage = isArgs
                                ? localize_1.LocMessage.paramSpecArgsUsage()
                                : localize_1.LocMessage.paramSpecKwargsUsage();
                            addError(errorMessage, node);
                            type = types_1.UnknownType.create(isIncomplete);
                            break;
                        }
                        type = types_1.TypeVarType.cloneForParamSpecAccess(baseType, memberName);
                        break;
                    }
                    if (!isIncomplete) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramSpecUnknownMember().format({ name: memberName }), node);
                    }
                    type = types_1.UnknownType.create(isIncomplete);
                    break;
                }
                // It's illegal to reference a member from a type variable.
                if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                    if (!isIncomplete) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarNoMember().format({
                            type: printType(baseType),
                            name: memberName,
                        }), node.leftExpression);
                    }
                    type = types_1.UnknownType.create(isIncomplete);
                    break;
                }
                if (baseType.details.recursiveTypeAliasName) {
                    type = types_1.UnknownType.create(/* isIncomplete */ true);
                    isIncomplete = true;
                    break;
                }
                if (baseType.details.isVariadic) {
                    break;
                }
                return getTypeOfMemberAccessWithBaseType(node, {
                    type: makeTopLevelTypeVarsConcrete(baseType),
                    bindToSelfType: types_1.TypeBase.isInstantiable(baseType) ? (0, typeUtils_1.convertToInstance)(baseType) : baseType,
                    isIncomplete,
                }, usage, 0 /* EvaluatorFlags.None */);
            }
            case 6 /* TypeCategory.Class */: {
                let typeResult;
                if (usage.method === 'get') {
                    typeResult = (0, enums_1.getTypeOfEnumMember)(evaluatorInterface, node, baseType, memberName, isIncomplete);
                }
                if (!typeResult) {
                    typeResult = getTypeOfBoundMember(node.memberName, baseType, memberName, usage, diag, 
                    /* memberAccessFlags */ undefined, baseTypeResult.bindToSelfType);
                }
                if (typeResult) {
                    if (!typeResult.typeErrors) {
                        type = (0, typeUtils_1.addConditionToType)(typeResult.type, (0, typeUtils_1.getTypeCondition)(baseType), 
                        /* skipSelfCondition */ true);
                    }
                    else {
                        typeErrors = true;
                    }
                    if (typeResult.isAsymmetricAccessor) {
                        isAsymmetricAccessor = true;
                    }
                    if (typeResult.isIncomplete) {
                        isIncomplete = true;
                    }
                    if (typeResult.narrowedTypeForSet) {
                        narrowedTypeForSet = (0, typeUtils_1.addConditionToType)(typeResult.narrowedTypeForSet, (0, typeUtils_1.getTypeCondition)(baseType), 
                        /* skipSelfCondition */ true);
                    }
                    if (typeResult.memberAccessDeprecationInfo) {
                        memberAccessDeprecationInfo = typeResult.memberAccessDeprecationInfo;
                    }
                }
                break;
            }
            case 7 /* TypeCategory.Module */: {
                const symbol = types_1.ModuleType.getField(baseType, memberName);
                if (symbol && !symbol.isExternallyHidden()) {
                    if (usage.method === 'get') {
                        setSymbolAccessed(fileInfo, symbol, node.memberName);
                    }
                    type = getEffectiveTypeOfSymbolForUsage(symbol, 
                    /* usageNode */ undefined, 
                    /* useLastDecl */ true).type;
                    if ((0, types_1.isTypeVar)(type)) {
                        type = validateTypeVarUsage(node, type, flags);
                    }
                    // If the type resolved to "unbound", treat it as "unknown" in
                    // the case of a module reference because if it's truly unbound,
                    // that error will be reported within the module and should not
                    // leak into other modules that import it.
                    if ((0, types_1.isUnbound)(type)) {
                        type = types_1.UnknownType.create(/* isIncomplete */ true);
                    }
                    if (symbol.isPrivateMember()) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateUsage, localize_1.LocMessage.privateUsedOutsideOfModule().format({
                            name: memberName,
                        }), node.memberName);
                    }
                    if (symbol.isPrivatePyTypedImport()) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateImportUsage, localize_1.LocMessage.privateImportFromPyTypedModule().format({
                            name: memberName,
                            module: baseType.moduleName,
                        }), node.memberName);
                    }
                    else if (symbol.isPrivateLocalImport()) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateLocalImportUsage, localize_1.LocMessage.privateImportFromPyTypedModule().format({
                            name: memberName,
                            module: baseType.moduleName,
                        }), node.memberName);
                    }
                }
                else {
                    // Does the module export a top-level __getattr__ function?
                    if (usage.method === 'get') {
                        const getAttrSymbol = types_1.ModuleType.getField(baseType, '__getattr__');
                        if (getAttrSymbol) {
                            const isModuleGetAttrSupported = fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_7) ||
                                getAttrSymbol.getDeclarations().some((decl) => decl.uri.hasExtension('.pyi'));
                            if (isModuleGetAttrSupported) {
                                const getAttrTypeResult = getEffectiveTypeOfSymbolForUsage(getAttrSymbol);
                                if ((0, types_1.isFunction)(getAttrTypeResult.type)) {
                                    type = getFunctionEffectiveReturnType(getAttrTypeResult.type);
                                    if (getAttrTypeResult.isIncomplete) {
                                        isIncomplete = true;
                                    }
                                }
                            }
                        }
                    }
                    // If the field was not found and the module type is marked
                    // such that all fields should be Any/Unknown, return that type.
                    if (!type && baseType.notPresentFieldType) {
                        type = baseType.notPresentFieldType;
                    }
                    if (!type) {
                        if (!isIncomplete) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAttributeAccessIssue, localize_1.LocMessage.moduleUnknownMember().format({
                                memberName,
                                moduleName: baseType.moduleName,
                            }), node.memberName);
                        }
                        type = evaluatorOptions.evaluateUnknownImportsAsAny ? types_1.AnyType.create() : types_1.UnknownType.create();
                    }
                }
                break;
            }
            case 8 /* TypeCategory.Union */: {
                type = (0, typeUtils_1.mapSubtypes)(baseType, (subtype) => {
                    if ((0, types_1.isUnbound)(subtype)) {
                        // Don't do anything if it's unbound. The error will already
                        // be reported elsewhere.
                        return undefined;
                    }
                    if ((0, typeUtils_1.isNoneInstance)(subtype) && noneType && (0, types_1.isClassInstance)(noneType)) {
                        const typeResult = getTypeOfBoundMember(node.memberName, noneType, memberName, usage, diag);
                        if (typeResult && !typeResult.typeErrors) {
                            type = (0, typeUtils_1.addConditionToType)(typeResult.type, (0, typeUtils_1.getTypeCondition)(baseType));
                            if (typeResult.isIncomplete) {
                                isIncomplete = true;
                            }
                            return type;
                        }
                        if (!isIncomplete) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalMemberAccess, localize_1.LocMessage.noneUnknownMember().format({ name: memberName }), node.memberName);
                        }
                        return undefined;
                    }
                    const typeResult = getTypeOfMemberAccessWithBaseType(node, {
                        type: subtype,
                        isIncomplete: baseTypeResult.isIncomplete,
                    }, usage, 0 /* EvaluatorFlags.None */);
                    if (typeResult.isIncomplete) {
                        isIncomplete = true;
                    }
                    if (typeResult.memberAccessDeprecationInfo) {
                        memberAccessDeprecationInfo = typeResult.memberAccessDeprecationInfo;
                    }
                    if (typeResult.typeErrors) {
                        typeErrors = true;
                    }
                    return typeResult.type;
                });
                break;
            }
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */: {
                if (memberName === '__self__') {
                    // The "__self__" member is not currently defined in the "function"
                    // class, so we'll special-case it here.
                    const functionType = (0, types_1.isFunction)(baseType) ? baseType : baseType.overloads[0];
                    if (functionType.preBoundFlags !== undefined &&
                        (functionType.preBoundFlags & 4 /* FunctionTypeFlags.StaticMethod */) === 0) {
                        type = functionType.boundToType;
                    }
                }
                else {
                    type = getTypeOfMemberAccessWithBaseType(node, { type: functionObj !== null && functionObj !== void 0 ? functionObj : types_1.AnyType.create() }, usage, flags).type;
                }
                break;
            }
            default:
                (0, debug_1.assertNever)(baseType);
        }
        // If type is undefined, emit a general error message indicating that the
        // member could not be accessed.
        if (!type) {
            const isFunctionRule = (0, types_1.isFunction)(baseType) ||
                (0, types_1.isOverloadedFunction)(baseType) ||
                ((0, types_1.isClassInstance)(baseType) && types_1.ClassType.isBuiltIn(baseType, 'function'));
            if (!baseTypeResult.isIncomplete) {
                let diagMessage = localize_1.LocMessage.memberAccess();
                if (usage.method === 'set') {
                    diagMessage = localize_1.LocMessage.memberSet();
                }
                else if (usage.method === 'del') {
                    diagMessage = localize_1.LocMessage.memberDelete();
                }
                // If there is an expected type diagnostic addendum (used for assignments),
                // use that rather than the local diagnostic addendum because it will be
                // more informative.
                if (usage.setExpectedTypeDiag) {
                    diag = usage.setExpectedTypeDiag;
                }
                // If the class is a TypedDict, and there's a key with the same name,
                // suggest that they user want to use ["key"] name instead.
                if ((0, types_1.isClass)(baseType) && baseType.details.typedDictEntries) {
                    const tdKey = baseType.details.typedDictEntries.knownItems.get(memberName);
                    if (tdKey) {
                        const subDiag = new diagnostic_1.DiagnosticAddendum();
                        subDiag.addMessage(localize_1.LocAddendum.typedDictKeyAccess().format({ name: memberName }));
                        diag.addAddendum(subDiag);
                    }
                }
                const rule = isFunctionRule
                    ? diagnosticRules_1.DiagnosticRule.reportFunctionMemberAccess
                    : diagnosticRules_1.DiagnosticRule.reportAttributeAccessIssue;
                addDiagnostic(rule, diagMessage.format({ name: memberName, type: printType(baseType) }) + diag.getString(), node.memberName, (_a = diag.getEffectiveTextRange()) !== null && _a !== void 0 ? _a : node.memberName);
            }
            // If this is member access on a function, use "Any" so if the
            // reportFunctionMemberAccess rule is disabled, we don't trigger
            // additional reportUnknownMemberType diagnostics.
            type = isFunctionRule ? types_1.AnyType.create() : types_1.UnknownType.create();
        }
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) === 0) {
            reportUseOfTypeCheckOnly(type, node.memberName);
        }
        return {
            type,
            isIncomplete,
            isAsymmetricAccessor,
            narrowedTypeForSet,
            isRequired,
            isNotRequired,
            memberAccessDeprecationInfo,
            typeErrors,
        };
    }
    function getTypeOfClassMemberName(errorNode, classType, memberName, usage, diag, flags, selfType, recursionCount = 0) {
        var _a, _b, _c;
        const isAccessedThroughObject = types_1.TypeBase.isInstance(classType);
        // Always look for a member with a declared type first.
        let memberInfo = (0, typeUtils_1.lookUpClassMember)(classType, memberName, flags | 64 /* MemberAccessFlags.DeclaredTypesOnly */);
        // If we couldn't find a symbol with a declared type, use
        // a symbol with an inferred type.
        if (!memberInfo) {
            memberInfo = (0, typeUtils_1.lookUpClassMember)(classType, memberName, flags);
        }
        if (!memberInfo) {
            // No attribute of that name was found. If this is a member access
            // through an object, see if there's an attribute access override
            // method ("__getattr__", etc.).
            if ((flags & 512 /* MemberAccessFlags.SkipAttributeAccessOverride */) === 0 && errorNode) {
                const generalAttrType = applyAttributeAccessOverride(errorNode, classType, usage, memberName, selfType);
                if (generalAttrType) {
                    return {
                        symbol: undefined,
                        type: generalAttrType.type,
                        isTypeIncomplete: false,
                        isDescriptorError: false,
                        isClassMember: false,
                        isClassVar: false,
                        isAsymmetricAccessor: !!generalAttrType.isAsymmetricAccessor,
                    };
                }
            }
            // Report that the member could not be accessed.
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.memberUnknown().format({ name: memberName }));
            return undefined;
        }
        let type;
        let isTypeIncomplete = false;
        let narrowedTypeForSet;
        if (memberInfo.symbol.isInitVar()) {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.memberIsInitVar().format({ name: memberName }));
            return undefined;
        }
        if (usage.method !== 'get' && errorNode) {
            // If the usage indicates a 'set' or 'delete' and the access is within the
            // class definition itself, use only the declared type to avoid circular
            // type evaluation.
            const containingClass = ParseTreeUtils.getEnclosingClass(errorNode);
            if (containingClass) {
                const containingClassType = (_a = getTypeOfClass(containingClass)) === null || _a === void 0 ? void 0 : _a.classType;
                if (containingClassType &&
                    (0, types_1.isInstantiableClass)(containingClassType) &&
                    types_1.ClassType.isSameGenericClass(containingClassType, classType)) {
                    type = (_b = getDeclaredTypeOfSymbol(memberInfo.symbol)) === null || _b === void 0 ? void 0 : _b.type;
                    if (type && (0, types_1.isInstantiableClass)(memberInfo.classType)) {
                        type = (0, typeUtils_1.partiallySpecializeType)(type, memberInfo.classType);
                    }
                    // If we're setting a class variable via a write through an object,
                    // this is normally considered a type violation. But it is allowed
                    // if the class variable is a descriptor object. In this case, we will
                    // clear the flag that causes an error to be generated.
                    if (usage.method === 'set' &&
                        (0, symbolUtils_1.isEffectivelyClassVar)(memberInfo.symbol, types_1.ClassType.isDataClass(containingClassType)) &&
                        isAccessedThroughObject) {
                        const selfClass = (selfType !== null && selfType !== void 0 ? selfType : memberName === '__new__') ? undefined : classType;
                        const typeResult = getTypeOfMemberInternal(errorNode, memberInfo, selfClass, flags);
                        if (typeResult) {
                            if ((0, typeUtils_1.isDescriptorInstance)(typeResult.type, /* requireSetter */ true)) {
                                type = typeResult.type;
                                flags &= 128 /* MemberAccessFlags.DisallowClassVarWrites */;
                            }
                        }
                    }
                    if (!type) {
                        type = types_1.UnknownType.create();
                    }
                }
            }
        }
        if (!type) {
            let selfClass;
            if (selfType) {
                selfClass = (0, typeUtils_1.convertToInstantiable)(selfType);
            }
            else {
                // Skip this for __new__ methods because they are not bound
                // to the class but rather assume the type of the cls argument.
                if (memberName !== '__new__') {
                    selfClass = classType;
                }
            }
            const typeResult = getTypeOfMemberInternal(errorNode, memberInfo, selfClass, flags);
            type = (_c = typeResult === null || typeResult === void 0 ? void 0 : typeResult.type) !== null && _c !== void 0 ? _c : types_1.UnknownType.create();
            if (typeResult === null || typeResult === void 0 ? void 0 : typeResult.isIncomplete) {
                isTypeIncomplete = true;
            }
        }
        // Don't include variables within typed dict classes.
        if ((0, types_1.isClass)(memberInfo.classType) && types_1.ClassType.isTypedDictClass(memberInfo.classType)) {
            const typedDecls = memberInfo.symbol.getTypedDeclarations();
            if (typedDecls.length > 0 && typedDecls[0].type === 1 /* DeclarationType.Variable */) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.memberUnknown().format({ name: memberName }));
                return undefined;
            }
        }
        if (usage.method === 'get') {
            // Mark the member accessed if it's not coming from a parent class.
            if (errorNode &&
                (0, types_1.isInstantiableClass)(memberInfo.classType) &&
                types_1.ClassType.isSameGenericClass(memberInfo.classType, classType)) {
                setSymbolAccessed(AnalyzerNodeInfo.getFileInfo(errorNode), memberInfo.symbol, errorNode);
            }
            // Special-case `__init_subclass` and `__class_getitem__` because
            // these are always treated as class methods even if they're not
            // decorated as such.
            if (memberName === '__init_subclass__' || memberName === '__class_getitem__') {
                if ((0, types_1.isFunction)(type) && !types_1.FunctionType.isClassMethod(type)) {
                    type = types_1.FunctionType.cloneWithNewFlags(type, type.details.flags | 2 /* FunctionTypeFlags.ClassMethod */);
                }
            }
        }
        // If the member is a descriptor object, apply the descriptor protocol
        // now. If the member is an instance or class method, bind the method.
        let isDescriptorError = false;
        let isAsymmetricAccessor = false;
        let isDescriptorApplied = false;
        let memberAccessDeprecationInfo;
        type = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
            const concreteSubtype = makeTopLevelTypeVarsConcrete(subtype);
            const isClassMember = !memberInfo || memberInfo.isClassMember;
            let resultType;
            if ((0, types_1.isClass)(concreteSubtype) && isClassMember && errorNode) {
                const descResult = applyDescriptorAccessMethod(subtype, concreteSubtype, memberInfo, classType, selfType, flags, errorNode, memberName, usage, diag);
                if (descResult.isAsymmetricAccessor) {
                    isAsymmetricAccessor = true;
                }
                if (descResult.memberAccessDeprecationInfo) {
                    memberAccessDeprecationInfo = descResult.memberAccessDeprecationInfo;
                }
                if (descResult.typeErrors) {
                    isDescriptorError = true;
                }
                if (descResult.isDescriptorApplied) {
                    isDescriptorApplied = true;
                }
                resultType = descResult.type;
            }
            else if ((0, types_1.isFunction)(concreteSubtype) || (0, types_1.isOverloadedFunction)(concreteSubtype)) {
                const typeResult = bindMethodForMemberAccess(subtype, concreteSubtype, memberInfo, classType, selfType, flags, memberName, usage, diag, recursionCount);
                resultType = typeResult.type;
                if (typeResult.typeErrors) {
                    isDescriptorError = true;
                }
            }
            else {
                resultType = subtype;
            }
            // If this is a "set" or "delete" operation, we have a bit more work to do.
            if (usage.method === 'get') {
                return resultType;
            }
            // Check for an attempt to overwrite or delete a ClassVar member from an instance.
            if (!isDescriptorApplied &&
                memberInfo &&
                (0, symbolUtils_1.isEffectivelyClassVar)(memberInfo.symbol, types_1.ClassType.isDataClass(classType)) &&
                (flags & 128 /* MemberAccessFlags.DisallowClassVarWrites */) !== 0) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.memberSetClassVar().format({ name: memberName }));
                isDescriptorError = true;
            }
            // Check for an attempt to overwrite or delete a final member variable.
            const finalVarTypeDecl = memberInfo === null || memberInfo === void 0 ? void 0 : memberInfo.symbol.getDeclarations().find((decl) => isFinalVariableDeclaration(decl));
            if (finalVarTypeDecl &&
                errorNode &&
                !ParseTreeUtils.isNodeContainedWithin(errorNode, finalVarTypeDecl.node)) {
                // If a Final instance variable is declared in the class body but is
                // being assigned within an __init__ method, it's allowed.
                const enclosingFunctionNode = ParseTreeUtils.getEnclosingFunction(errorNode);
                if (!enclosingFunctionNode || enclosingFunctionNode.name.value !== '__init__') {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocMessage.finalReassigned().format({ name: memberName }));
                    isDescriptorError = true;
                }
            }
            // Check for an attempt to overwrite or delete an instance variable that is
            // read-only (e.g. in a named tuple).
            if ((memberInfo === null || memberInfo === void 0 ? void 0 : memberInfo.isInstanceMember) &&
                (0, types_1.isClass)(memberInfo.classType) &&
                types_1.ClassType.isReadOnlyInstanceVariables(memberInfo.classType)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.readOnlyAttribute().format({ name: memberName }));
                isDescriptorError = true;
            }
            return resultType;
        });
        if (!isDescriptorError && usage.method === 'set' && usage.setType) {
            if (errorNode && memberInfo.symbol.hasTypedDeclarations()) {
                // This is an assignment to a member with a declared type. Apply
                // narrowing logic based on the assigned type. Skip this for
                // descriptor-based accesses.
                narrowedTypeForSet = isDescriptorApplied
                    ? usage.setType.type
                    : narrowTypeBasedOnAssignment(errorNode, type, usage.setType.type);
            }
            // Verify that the assigned type is compatible.
            if (!assignType(type, usage.setType.type, diag === null || diag === void 0 ? void 0 : diag.createAddendum())) {
                if (!usage.setType.isIncomplete) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.memberAssignment().format({
                        type: printType(usage.setType.type),
                        name: memberName,
                        classType: printObjectTypeForClass(classType),
                    }));
                }
                // Do not narrow the type in this case. Assume the declared type.
                narrowedTypeForSet = type;
                isDescriptorError = true;
            }
            if ((0, types_1.isInstantiableClass)(memberInfo.classType) &&
                types_1.ClassType.isFrozenDataClass(memberInfo.classType) &&
                isAccessedThroughObject) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.dataClassFrozen().format({
                    name: printType(types_1.ClassType.cloneAsInstance(memberInfo.classType)),
                }));
                isDescriptorError = true;
            }
        }
        return {
            symbol: memberInfo.symbol,
            type,
            isTypeIncomplete,
            isDescriptorError,
            isClassMember: !memberInfo.isInstanceMember,
            isClassVar: memberInfo.isClassVar,
            classType: memberInfo.classType,
            isAsymmetricAccessor,
            narrowedTypeForSet,
            memberAccessDeprecationInfo,
        };
    }
    // Applies descriptor access methods "__get__", "__set__", or "__delete__"
    // if they apply.
    function applyDescriptorAccessMethod(memberType, concreteMemberType, memberInfo, classType, selfType, flags, errorNode, memberName, usage, diag) {
        var _a, _b, _c, _d, _e, _f, _g;
        const isAccessedThroughObject = types_1.TypeBase.isInstance(classType);
        let accessMethodName;
        if (usage.method === 'get') {
            accessMethodName = '__get__';
        }
        else if (usage.method === 'set') {
            accessMethodName = '__set__';
        }
        else {
            accessMethodName = '__delete__';
        }
        const methodTypeResult = getTypeOfBoundMember(errorNode, concreteMemberType, accessMethodName, 
        /* usage */ undefined, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), 16 /* MemberAccessFlags.SkipInstanceMembers */ | 512 /* MemberAccessFlags.SkipAttributeAccessOverride */);
        if (!methodTypeResult || methodTypeResult.typeErrors) {
            // Provide special error messages for properties.
            if (types_1.ClassType.isPropertyClass(concreteMemberType)) {
                if (usage.method !== 'get') {
                    const message = usage.method === 'set'
                        ? localize_1.LocAddendum.propertyMissingSetter()
                        : localize_1.LocAddendum.propertyMissingDeleter();
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(message.format({ name: memberName }));
                    return { type: types_1.AnyType.create(), typeErrors: true };
                }
            }
            return { type: memberType };
        }
        const methodClassType = methodTypeResult.classType;
        let methodType = methodTypeResult.type;
        if (methodTypeResult.typeErrors || !methodClassType) {
            return { type: types_1.UnknownType.create(), typeErrors: true };
        }
        if (!(0, types_1.isFunction)(methodType) && !(0, types_1.isOverloadedFunction)(methodType)) {
            if ((0, types_1.isAnyOrUnknown)(methodType)) {
                return { type: methodType };
            }
            // TODO - emit an error for this condition.
            return { type: memberType, typeErrors: true };
        }
        // Special-case logic for properties.
        if (types_1.ClassType.isPropertyClass(concreteMemberType) &&
            memberInfo &&
            (0, types_1.isInstantiableClass)(memberInfo.classType) &&
            methodType) {
            // If the property is being accessed from a protocol class (not an instance),
            // flag this as an error because a property within a protocol is meant to be
            // interpreted as a read-only attribute rather than a protocol, so accessing
            // it directly from the class has an ambiguous meaning.
            if ((flags & 16 /* MemberAccessFlags.SkipInstanceMembers */) !== 0 && types_1.ClassType.isProtocolClass(classType)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.propertyAccessFromProtocolClass());
                return { type: memberType, typeErrors: true };
            }
            // Infer return types before specializing. Otherwise a generic inferred
            // return type won't be properly specialized.
            inferReturnTypeIfNecessary(methodType);
            // This specialization is required specifically for properties, which should be
            // generic but are not defined that way. Because of this, we use type variables
            // in the synthesized methods (e.g. __get__) for the property class that are
            // defined in the class that declares the fget method.
            let accessMethodClass;
            if (usage.method === 'get') {
                accessMethodClass = (_a = concreteMemberType.fgetInfo) === null || _a === void 0 ? void 0 : _a.classType;
            }
            else if (usage.method === 'set') {
                accessMethodClass = (_b = concreteMemberType.fsetInfo) === null || _b === void 0 ? void 0 : _b.classType;
            }
            else {
                accessMethodClass = (_c = concreteMemberType.fdelInfo) === null || _c === void 0 ? void 0 : _c.classType;
            }
            if (accessMethodClass) {
                const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(accessMethodClass));
                accessMethodClass = (0, typeUtils_1.selfSpecializeClass)(accessMethodClass);
                assignType(types_1.ClassType.cloneAsInstance(accessMethodClass), types_1.ClassType.cloneAsInstance(memberInfo.classType), 
                /* diag */ undefined, typeVarContext);
                accessMethodClass = (0, typeUtils_1.applySolvedTypeVars)(accessMethodClass, typeVarContext);
                const specializedType = (0, typeUtils_1.partiallySpecializeType)(methodType, accessMethodClass, selfType ? (0, typeUtils_1.convertToInstantiable)(selfType) : classType);
                if ((0, types_1.isFunction)(specializedType) || (0, types_1.isOverloadedFunction)(specializedType)) {
                    methodType = specializedType;
                }
            }
        }
        // Determine if we're calling __set__ on an asymmetric descriptor or property.
        let isAsymmetricAccessor = false;
        if (usage.method === 'set' && (0, types_1.isClass)(methodClassType)) {
            if (isAsymmetricDescriptorClass(methodClassType)) {
                isAsymmetricAccessor = true;
            }
        }
        if (!methodType) {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.descriptorAccessBindingFailed().format({
                name: accessMethodName,
                className: printType((0, typeUtils_1.convertToInstance)(methodClassType)),
            }));
            return {
                type: types_1.UnknownType.create(),
                typeErrors: true,
                isDescriptorApplied: true,
                isAsymmetricAccessor,
            };
        }
        // Simulate a call to the access method.
        const argList = [];
        // Provide "obj" argument.
        let objArgType;
        if (types_1.ClassType.isClassProperty(concreteMemberType)) {
            // Handle "class properties" as a special case. We need to pass
            // the class rather than the object instance in this case.
            objArgType = isAccessedThroughObject ? types_1.ClassType.cloneAsInstantiable(classType) : classType;
        }
        else if (isAccessedThroughObject) {
            objArgType = selfType !== null && selfType !== void 0 ? selfType : types_1.ClassType.cloneAsInstance(classType);
        }
        else {
            objArgType = getNoneType();
        }
        argList.push({
            argumentCategory: 0 /* ArgumentCategory.Simple */,
            typeResult: { type: objArgType },
        });
        if (usage.method === 'get') {
            let classArgType;
            if (selfType) {
                classArgType = (0, typeUtils_1.convertToInstantiable)(selfType);
            }
            else {
                classArgType = isAccessedThroughObject ? types_1.ClassType.cloneAsInstantiable(classType) : classType;
            }
            // Provide "owner" argument.
            argList.push({
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                typeResult: { type: classArgType },
            });
        }
        else if (usage.method === 'set') {
            // Provide "value" argument.
            argList.push({
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                typeResult: {
                    type: (_e = (_d = usage.setType) === null || _d === void 0 ? void 0 : _d.type) !== null && _e !== void 0 ? _e : types_1.UnknownType.create(),
                    isIncomplete: !!((_f = usage.setType) === null || _f === void 0 ? void 0 : _f.isIncomplete),
                },
            });
        }
        // Suppress diagnostics for these method calls because they would be redundant.
        const callResult = suppressDiagnostics(errorNode, () => {
            return validateCallArguments(errorNode, argList, { type: methodType }, 
            /* typeVarContext */ undefined, 
            /* skipUnknownArgCheck */ true);
        });
        // Collect deprecation information associated with the member access method.
        let deprecationInfo;
        if (callResult.overloadsUsedForCall && callResult.overloadsUsedForCall.length >= 1) {
            const overloadUsed = callResult.overloadsUsedForCall[0];
            if (overloadUsed.details.deprecatedMessage) {
                deprecationInfo = {
                    deprecationMessage: overloadUsed.details.deprecatedMessage,
                    accessType: types_1.ClassType.isPropertyClass(concreteMemberType) ? 'property' : 'descriptor',
                    accessMethod: usage.method,
                };
            }
        }
        if (!callResult.argumentErrors) {
            return {
                // For set or delete, always return Any.
                type: usage.method === 'get' ? (_g = callResult.returnType) !== null && _g !== void 0 ? _g : types_1.UnknownType.create() : types_1.AnyType.create(),
                isDescriptorApplied: true,
                isAsymmetricAccessor,
                memberAccessDeprecationInfo: deprecationInfo,
            };
        }
        // Errors were detected when evaluating the access method call.
        if (usage.method === 'set') {
            if (usage.setType &&
                (0, types_1.isFunction)(methodType) &&
                methodType.details.parameters.length >= 2 &&
                !usage.setType.isIncomplete) {
                const setterType = types_1.FunctionType.getEffectiveParameterType(methodType, 1);
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeIncompatible().format({
                    destType: printType(setterType),
                    sourceType: printType(usage.setType.type),
                }));
            }
            else if ((0, types_1.isOverloadedFunction)(methodType)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocMessage.noOverload().format({ name: accessMethodName }));
            }
        }
        else {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.descriptorAccessCallFailed().format({
                name: accessMethodName,
                className: printType((0, typeUtils_1.convertToInstance)(methodClassType)),
            }));
        }
        return {
            type: types_1.UnknownType.create(),
            typeErrors: true,
            isDescriptorApplied: true,
            isAsymmetricAccessor,
            memberAccessDeprecationInfo: deprecationInfo,
        };
    }
    function bindMethodForMemberAccess(type, concreteType, memberInfo, classType, selfType, flags, memberName, usage, diag, recursionCount = 0) {
        // Check for an attempt to overwrite a final method.
        if (usage.method === 'set') {
            const impl = (0, types_1.isFunction)(concreteType)
                ? concreteType
                : types_1.OverloadedFunctionType.getImplementation(concreteType);
            if (impl && types_1.FunctionType.isFinal(impl) && memberInfo && (0, types_1.isClass)(memberInfo.classType)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocMessage.finalMethodOverride().format({
                    name: memberName,
                    className: memberInfo.classType.details.name,
                }));
                return { type: types_1.UnknownType.create(), typeErrors: true };
            }
        }
        // If this function is an instance member (e.g. a lambda that was
        // assigned to an instance variable), don't perform any binding.
        if (types_1.TypeBase.isInstance(classType)) {
            if (!memberInfo || memberInfo.isInstanceMember) {
                return { type: type };
            }
        }
        const boundType = bindFunctionToClassOrObject(classType, concreteType, memberInfo && (0, types_1.isInstantiableClass)(memberInfo.classType) ? memberInfo.classType : undefined, (flags & 256 /* MemberAccessFlags.TreatConstructorAsClassMethod */) !== 0, selfType && (0, types_1.isClass)(selfType) ? types_1.ClassType.cloneIncludeSubclasses(selfType) : selfType, diag, recursionCount);
        return { type: boundType !== null && boundType !== void 0 ? boundType : types_1.UnknownType.create(), typeErrors: !boundType };
    }
    function isAsymmetricDescriptorClass(classType) {
        var _a;
        // If the value has already been cached in this type, return the cached value.
        if (classType.isAsymmetricDescriptor !== undefined) {
            return classType.isAsymmetricDescriptor;
        }
        let isAsymmetric = false;
        const getterSymbolResult = (0, typeUtils_1.lookUpClassMember)(classType, '__get__', 2 /* MemberAccessFlags.SkipBaseClasses */);
        const setterSymbolResult = (0, typeUtils_1.lookUpClassMember)(classType, '__set__', 2 /* MemberAccessFlags.SkipBaseClasses */);
        if (!getterSymbolResult || !setterSymbolResult) {
            isAsymmetric = false;
        }
        else {
            const getterType = getEffectiveTypeOfSymbol(getterSymbolResult.symbol);
            const setterType = getEffectiveTypeOfSymbol(setterSymbolResult.symbol);
            // If either the setter or getter is an overload (or some other non-function type),
            // conservatively assume that it's not asymmetric.
            if ((0, types_1.isFunction)(getterType) && (0, types_1.isFunction)(setterType)) {
                // If there's no declared return type on the getter, assume it's symmetric.
                if (setterType.details.parameters.length >= 3 && getterType.details.declaredReturnType) {
                    const setterValueType = types_1.FunctionType.getEffectiveParameterType(setterType, 2);
                    const getterReturnType = (_a = types_1.FunctionType.getSpecializedReturnType(getterType)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
                    if (!(0, types_1.isTypeSame)(setterValueType, getterReturnType)) {
                        isAsymmetric = true;
                    }
                }
            }
        }
        // Cache the value for next time.
        classType.isAsymmetricDescriptor = isAsymmetric;
        return isAsymmetric;
    }
    function isClassWithAsymmetricAttributeAccessor(classType) {
        var _a;
        // If the value has already been cached in this type, return the cached value.
        if (classType.isAsymmetricAttributeAccessor !== undefined) {
            return classType.isAsymmetricAttributeAccessor;
        }
        let isAsymmetric = false;
        const getterSymbolResult = (0, typeUtils_1.lookUpClassMember)(classType, '__getattr__', 2 /* MemberAccessFlags.SkipBaseClasses */);
        const setterSymbolResult = (0, typeUtils_1.lookUpClassMember)(classType, '__setattr__', 2 /* MemberAccessFlags.SkipBaseClasses */);
        if (!getterSymbolResult || !setterSymbolResult) {
            isAsymmetric = false;
        }
        else {
            const getterType = getEffectiveTypeOfSymbol(getterSymbolResult.symbol);
            const setterType = getEffectiveTypeOfSymbol(setterSymbolResult.symbol);
            // If either the setter or getter is an overload (or some other non-function type),
            // conservatively assume that it's not asymmetric.
            if ((0, types_1.isFunction)(getterType) && (0, types_1.isFunction)(setterType)) {
                // If there's no declared return type on the getter, assume it's symmetric.
                if (setterType.details.parameters.length >= 3 && getterType.details.declaredReturnType) {
                    const setterValueType = types_1.FunctionType.getEffectiveParameterType(setterType, 2);
                    const getterReturnType = (_a = types_1.FunctionType.getSpecializedReturnType(getterType)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
                    if (!(0, types_1.isTypeSame)(setterValueType, getterReturnType)) {
                        isAsymmetric = true;
                    }
                }
            }
        }
        // Cache the value for next time.
        classType.isAsymmetricAttributeAccessor = isAsymmetric;
        return isAsymmetric;
    }
    // Applies the __getattr__, __setattr__ or __delattr__ method if present.
    // If it's not applicable, returns undefined.
    function applyAttributeAccessOverride(errorNode, classType, usage, memberName, selfType) {
        var _a, _b, _c, _d, _e;
        const getAttributeAccessMember = (name) => {
            var _a;
            return (_a = getTypeOfBoundMember(errorNode, classType, name, 
            /* usage */ undefined, 
            /* diag */ undefined, 16 /* MemberAccessFlags.SkipInstanceMembers */ |
                4 /* MemberAccessFlags.SkipObjectBaseClass */ |
                8 /* MemberAccessFlags.SkipTypeBaseClass */ |
                512 /* MemberAccessFlags.SkipAttributeAccessOverride */, selfType)) === null || _a === void 0 ? void 0 : _a.type;
        };
        let accessMemberType;
        if (usage.method === 'get') {
            accessMemberType = (_a = getAttributeAccessMember('__getattribute__')) !== null && _a !== void 0 ? _a : getAttributeAccessMember('__getattr__');
        }
        else if (usage.method === 'set') {
            accessMemberType = getAttributeAccessMember('__setattr__');
        }
        else {
            (0, debug_1.assert)(usage.method === 'del');
            accessMemberType = getAttributeAccessMember('__delattr__');
        }
        if (!accessMemberType) {
            return undefined;
        }
        const argList = [];
        // Provide "name" argument.
        argList.push({
            argumentCategory: 0 /* ArgumentCategory.Simple */,
            typeResult: {
                type: strClassType && (0, types_1.isInstantiableClass)(strClassType)
                    ? types_1.ClassType.cloneWithLiteral(types_1.ClassType.cloneAsInstance(strClassType), memberName)
                    : types_1.AnyType.create(),
            },
        });
        if (usage.method === 'set') {
            // Provide "value" argument.
            argList.push({
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                typeResult: {
                    type: (_c = (_b = usage.setType) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : types_1.UnknownType.create(),
                    isIncomplete: !!((_d = usage.setType) === null || _d === void 0 ? void 0 : _d.isIncomplete),
                },
            });
        }
        if (!(0, types_1.isFunction)(accessMemberType) && !(0, types_1.isOverloadedFunction)(accessMemberType)) {
            if ((0, types_1.isAnyOrUnknown)(accessMemberType)) {
                return { type: accessMemberType };
            }
            // TODO - emit an error for this condition.
            return undefined;
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(accessMemberType));
        const callResult = validateCallArguments(errorNode, argList, { type: accessMemberType }, typeVarContext, 
        /* skipUnknownArgCheck */ true);
        let isAsymmetricAccessor = false;
        if (usage.method === 'set') {
            isAsymmetricAccessor = isClassWithAsymmetricAttributeAccessor(classType);
        }
        return {
            type: (_e = callResult.returnType) !== null && _e !== void 0 ? _e : types_1.UnknownType.create(),
            typeErrors: callResult.argumentErrors,
            isAsymmetricAccessor,
        };
    }
    function getTypeOfIndex(node, flags = 0 /* EvaluatorFlags.None */) {
        const baseTypeResult = getTypeOfExpression(node.baseExpression, flags | 2 /* EvaluatorFlags.IndexBaseDefaults */);
        // If this is meant to be a type and the base expression is a string expression,
        // emit an error because this is an illegal annotation form and will generate a
        // runtime exception.
        if (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) {
            if (node.baseExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                addError(localize_1.LocMessage.stringNotSubscriptable(), node.baseExpression);
            }
        }
        // Check for builtin classes that will generate runtime exceptions if subscripted.
        if ((flags & 4 /* EvaluatorFlags.AllowForwardReferences */) === 0) {
            // We can skip this check if the class is used within a PEP 526 variable
            // type annotation within a class or function. For some undocumented reason,
            // they don't result in runtime exceptions when used in this manner.
            let skipSubscriptCheck = (flags & 32768 /* EvaluatorFlags.VariableTypeAnnotation */) !== 0;
            if (skipSubscriptCheck) {
                const scopeNode = ParseTreeUtils.getExecutionScopeNode(node);
                if ((scopeNode === null || scopeNode === void 0 ? void 0 : scopeNode.nodeType) === 36 /* ParseNodeType.Module */) {
                    skipSubscriptCheck = false;
                }
            }
            if (!skipSubscriptCheck) {
                const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
                if ((0, types_1.isInstantiableClass)(baseTypeResult.type) && !baseTypeResult.type.aliasName) {
                    const minPythonVersion = nonSubscriptableTypes.get(baseTypeResult.type.details.fullName);
                    if (minPythonVersion !== undefined &&
                        fileInfo.executionEnvironment.pythonVersion.isLessThan(minPythonVersion) &&
                        !fileInfo.isStubFile) {
                        addError(localize_1.LocMessage.classNotRuntimeSubscriptable().format({
                            name: baseTypeResult.type.aliasName || baseTypeResult.type.details.name,
                        }), node.baseExpression);
                    }
                }
            }
        }
        const indexTypeResult = getTypeOfIndexWithBaseType(node, baseTypeResult, { method: 'get' }, flags);
        if ((0, codeFlowTypes_1.isCodeFlowSupportedForReference)(node)) {
            // We limit type narrowing for index expressions to built-in types that are
            // known to have symmetric __getitem__ and __setitem__ methods (i.e. the value
            // passed to __setitem__ is the same type as the value returned by __getitem__).
            let baseTypeSupportsIndexNarrowing = !(0, types_1.isAny)(baseTypeResult.type);
            mapSubtypesExpandTypeVars(baseTypeResult.type, /* options */ undefined, (subtype) => {
                if (!(0, types_1.isClassInstance)(subtype) ||
                    !(types_1.ClassType.isBuiltIn(subtype) || types_1.ClassType.isTypedDictClass(subtype))) {
                    baseTypeSupportsIndexNarrowing = false;
                }
                return undefined;
            });
            if (baseTypeSupportsIndexNarrowing) {
                // Before performing code flow analysis, update the cache to prevent recursion.
                writeTypeCache(node, { ...indexTypeResult, isIncomplete: true }, flags);
                // See if we can refine the type based on code flow analysis.
                const codeFlowTypeResult = getFlowTypeOfReference(node, /* startNode */ undefined, {
                    targetSymbolId: symbol_1.indeterminateSymbolId,
                    typeAtStart: {
                        type: indexTypeResult.type,
                        isIncomplete: !!baseTypeResult.isIncomplete || !!indexTypeResult.isIncomplete,
                    },
                    skipConditionalNarrowing: (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0,
                });
                if (codeFlowTypeResult.type) {
                    indexTypeResult.type = codeFlowTypeResult.type;
                }
                if (codeFlowTypeResult.isIncomplete) {
                    indexTypeResult.isIncomplete = true;
                }
            }
        }
        if (baseTypeResult.isIncomplete) {
            indexTypeResult.isIncomplete = true;
        }
        return indexTypeResult;
    }
    // If the list of type parameters includes a TypeVarTuple, we may need to adjust
    // the supplied type arguments to map to the type parameter list.
    function adjustTypeArgumentsForVariadicTypeVar(typeArgs, typeParameters, errorNode) {
        const variadicIndex = typeParameters.findIndex((param) => (0, types_1.isVariadicTypeVar)(param));
        // Is there a *tuple[T, ...] somewhere in the type arguments that we can expand if needed?
        let srcUnboundedTupleType;
        let srcUnboundedTupleIndex = typeArgs.findIndex((arg) => {
            if ((0, types_1.isUnpackedClass)(arg.type) &&
                arg.type.tupleTypeArguments &&
                arg.type.tupleTypeArguments.length === 1 &&
                arg.type.tupleTypeArguments[0].isUnbounded) {
                srcUnboundedTupleType = arg.type.tupleTypeArguments[0].type;
                return true;
            }
            return false;
        });
        if (srcUnboundedTupleType &&
            srcUnboundedTupleIndex >= 0 &&
            variadicIndex >= 0 &&
            typeArgs.length < typeParameters.length) {
            // "Smear" the tuple type across type argument slots prior to the variadic type var.
            while (variadicIndex > srcUnboundedTupleIndex) {
                typeArgs = [
                    ...typeArgs.slice(0, srcUnboundedTupleIndex),
                    { node: typeArgs[srcUnboundedTupleIndex].node, type: srcUnboundedTupleType },
                    ...typeArgs.slice(srcUnboundedTupleIndex),
                ];
                srcUnboundedTupleIndex++;
            }
            // "Smear" the tuple type across type argument slots following the variadic type var.
            while (typeArgs.length < typeParameters.length) {
                typeArgs = [
                    ...typeArgs.slice(0, srcUnboundedTupleIndex + 1),
                    { node: typeArgs[srcUnboundedTupleIndex].node, type: srcUnboundedTupleType },
                    ...typeArgs.slice(srcUnboundedTupleIndex + 1),
                ];
            }
        }
        // Do we need to adjust the type arguments to map to a variadic type
        // param somewhere in the list?
        if (variadicIndex >= 0) {
            const variadicTypeVar = typeParameters[variadicIndex];
            // If the type param list ends with a ParamSpec with a default value,
            // we can ignore it for purposes of finding type args that map to the
            // TypeVarTuple.
            let typeParamCount = typeParameters.length;
            while (typeParamCount > 0) {
                const lastTypeParam = typeParameters[typeParamCount - 1];
                if (!lastTypeParam.details.isParamSpec || !lastTypeParam.details.isDefaultExplicit) {
                    break;
                }
                typeParamCount--;
            }
            if (variadicIndex < typeArgs.length) {
                // If there are typeArg lists at the end, these should map to ParamSpecs rather
                // than the TypeVarTuple, so exclude them.
                let variadicEndIndex = variadicIndex + 1 + typeArgs.length - typeParamCount;
                while (variadicEndIndex > variadicIndex) {
                    if (!typeArgs[variadicEndIndex - 1].typeList) {
                        break;
                    }
                    variadicEndIndex--;
                }
                const variadicTypeResults = typeArgs.slice(variadicIndex, variadicEndIndex);
                // If the type args consist of a lone variadic type variable, don't wrap it in a tuple.
                if (variadicTypeResults.length === 1 && (0, types_1.isVariadicTypeVar)(variadicTypeResults[0].type)) {
                    validateVariadicTypeVarIsUnpacked(variadicTypeResults[0].type, variadicTypeResults[0].node);
                }
                else {
                    variadicTypeResults.forEach((arg, index) => {
                        validateTypeArg(arg, {
                            allowEmptyTuple: index === 0,
                            allowVariadicTypeVar: true,
                            allowUnpackedTuples: true,
                        });
                    });
                    const variadicTypes = [];
                    if (variadicTypeResults.length !== 1 || !variadicTypeResults[0].isEmptyTupleShorthand) {
                        variadicTypeResults.forEach((typeResult) => {
                            if ((0, types_1.isUnpackedClass)(typeResult.type) && typeResult.type.tupleTypeArguments) {
                                (0, collectionUtils_1.appendArray)(variadicTypes, typeResult.type.tupleTypeArguments);
                            }
                            else {
                                variadicTypes.push({
                                    type: (0, typeUtils_1.convertToInstance)(typeResult.type),
                                    isUnbounded: false,
                                });
                            }
                        });
                    }
                    const tupleObject = makeTupleObject(variadicTypes, /* isUnpackedTuple */ true);
                    typeArgs = [
                        ...typeArgs.slice(0, variadicIndex),
                        { node: typeArgs[variadicIndex].node, type: tupleObject },
                        ...typeArgs.slice(variadicEndIndex, typeArgs.length),
                    ];
                }
            }
            else if (!variadicTypeVar.details.isDefaultExplicit) {
                // Add an empty tuple that maps to the TypeVarTuple type parameter.
                typeArgs.push({
                    node: errorNode,
                    type: makeTupleObject([], /* isUnpackedTuple */ true),
                });
            }
        }
        return typeArgs;
    }
    // If the variadic type variable is not unpacked, report an error.
    function validateVariadicTypeVarIsUnpacked(type, node) {
        if (!type.isVariadicUnpacked) {
            addError(localize_1.LocMessage.unpackedTypeVarTupleExpected().format({
                name1: type.details.name,
                name2: type.details.name,
            }), node);
            return false;
        }
        return true;
    }
    // Handles index expressions that are providing type arguments for a
    // generic type alias.
    function createSpecializedTypeAlias(node, baseType, flags) {
        var _a, _b, _c;
        if (!((_a = baseType.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeParameters) ||
            (baseType.typeAliasInfo.typeParameters.length === 0 && baseType.typeAliasInfo.typeArguments)) {
            return undefined;
        }
        // If this is not instantiable, then the index expression isn't a specialization.
        if (!types_1.TypeBase.isInstantiable(baseType)) {
            return undefined;
        }
        // If this is already specialized, the index expression isn't a specialization.
        if (baseType.typeAliasInfo.typeArguments) {
            return undefined;
        }
        const typeParameters = baseType.typeAliasInfo.typeParameters;
        let typeArgs = adjustTypeArgumentsForVariadicTypeVar(getTypeArgs(node, flags), typeParameters, node);
        // PEP 612 says that if the class has only one type parameter consisting
        // of a ParamSpec, the list of arguments does not need to be enclosed in
        // a list. We'll handle that case specially here. Presumably this applies to
        // type aliases as well.
        if (typeParameters.length === 1 && typeParameters[0].details.isParamSpec && typeArgs) {
            if (typeArgs.every((typeArg) => !(0, typeUtils_1.isEllipsisType)(typeArg.type) && !typeArg.typeList && !(0, types_1.isParamSpec)(typeArg.type))) {
                typeArgs = [
                    {
                        type: types_1.UnknownType.create(),
                        node: typeArgs[0].node,
                        typeList: typeArgs,
                    },
                ];
            }
        }
        let minTypeArgCount = typeParameters.length;
        const firstDefaultParamIndex = typeParameters.findIndex((param) => !!param.details.isDefaultExplicit);
        if (firstDefaultParamIndex >= 0) {
            minTypeArgCount = firstDefaultParamIndex;
        }
        if (typeArgs.length > typeParameters.length) {
            addError(localize_1.LocMessage.typeArgsTooMany().format({
                name: printType(baseType),
                expected: typeParameters.length,
                received: typeArgs.length,
            }), typeArgs[typeParameters.length].node);
        }
        else if (typeArgs.length < minTypeArgCount) {
            addError(localize_1.LocMessage.typeArgsTooFew().format({
                name: printType(baseType),
                expected: typeParameters.length,
                received: typeArgs.length,
            }), node.items[node.items.length - 1]);
        }
        // Handle the mypy_extensions.FlexibleAlias type specially.
        if ((0, types_1.isInstantiableClass)(baseType) &&
            baseType.details.fullName === 'mypy_extensions.FlexibleAlias' &&
            typeArgs.length >= 1) {
            return { node, type: typeArgs[0].type };
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext(baseType.typeAliasInfo.typeVarScopeId);
        const diag = new diagnostic_1.DiagnosticAddendum();
        typeParameters.forEach((param, index) => {
            if (param.details.isParamSpec && index < typeArgs.length) {
                const typeArgType = typeArgs[index].type;
                const typeList = typeArgs[index].typeList;
                if (typeList) {
                    const functionType = types_1.FunctionType.createSynthesizedInstance('', 65536 /* FunctionTypeFlags.ParamSpecValue */);
                    typeList.forEach((paramType, paramIndex) => {
                        types_1.FunctionType.addParameter(functionType, {
                            category: 0 /* ParameterCategory.Simple */,
                            name: `__p${paramIndex}`,
                            isNameSynthesized: true,
                            type: (0, typeUtils_1.convertToInstance)(paramType.type),
                            hasDeclaredType: true,
                        });
                    });
                    if (typeList.length > 0) {
                        types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                    }
                    (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, functionType, diag, typeVarContext, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */);
                }
                else if ((0, types_1.isParamSpec)(typeArgType)) {
                    (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, (0, typeUtils_1.convertToInstance)(typeArgType), diag, typeVarContext, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */);
                }
                else if ((0, types_1.isInstantiableClass)(typeArgType) && types_1.ClassType.isBuiltIn(typeArgType, 'Concatenate')) {
                    const concatTypeArgs = typeArgType.typeArguments;
                    const functionType = types_1.FunctionType.createInstance('', '', '', 0 /* FunctionTypeFlags.None */);
                    if (concatTypeArgs && concatTypeArgs.length > 0) {
                        concatTypeArgs.forEach((typeArg, index) => {
                            if (index === concatTypeArgs.length - 1) {
                                types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                                if ((0, types_1.isParamSpec)(typeArg)) {
                                    functionType.details.paramSpec = typeArg;
                                }
                                else if ((0, typeUtils_1.isEllipsisType)(typeArg)) {
                                    types_1.FunctionType.addDefaultParameters(functionType);
                                    functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
                                }
                            }
                            else {
                                types_1.FunctionType.addParameter(functionType, {
                                    category: 0 /* ParameterCategory.Simple */,
                                    name: `__p${index}`,
                                    isNameSynthesized: true,
                                    hasDeclaredType: true,
                                    type: typeArg,
                                });
                            }
                        });
                    }
                    (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, functionType, diag, typeVarContext, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */);
                }
                else if ((0, typeUtils_1.isEllipsisType)(typeArgType)) {
                    const functionType = types_1.FunctionType.createSynthesizedInstance('', 65536 /* FunctionTypeFlags.ParamSpecValue */ | 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */);
                    types_1.FunctionType.addDefaultParameters(functionType);
                    (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, functionType, diag, typeVarContext);
                }
                else {
                    addError(localize_1.LocMessage.typeArgListExpected(), typeArgs[index].node);
                }
            }
            else {
                if (index < typeArgs.length && typeArgs[index].typeList) {
                    addError(localize_1.LocMessage.typeArgListNotAllowed(), typeArgs[index].node);
                }
                let typeArgType;
                if (index < typeArgs.length) {
                    typeArgType = (0, typeUtils_1.convertToInstance)(typeArgs[index].type);
                }
                else if (param.details.isDefaultExplicit) {
                    typeArgType = (0, typeUtils_1.applySolvedTypeVars)(param, typeVarContext, { unknownIfNotFound: true });
                }
                else {
                    typeArgType = types_1.UnknownType.create();
                }
                if ((flags & 16384 /* EvaluatorFlags.EnforceTypeVarVarianceConsistency */) !== 0) {
                    const usageVariances = inferTypeParameterVarianceForTypeAlias(baseType);
                    if (usageVariances && index < usageVariances.length) {
                        const usageVariance = usageVariances[index];
                        if (!(0, typeUtils_1.isVarianceOfTypeArgumentCompatible)(typeArgType, usageVariance)) {
                            const messageDiag = diag.createAddendum();
                            messageDiag.addMessage(localize_1.LocAddendum.varianceMismatchForTypeAlias().format({
                                typeVarName: printType(typeArgType),
                                typeAliasParam: printType(typeParameters[index]),
                            }));
                            messageDiag.addTextRange(typeArgs[index].node);
                        }
                    }
                }
                if ((0, types_1.isUnpacked)(typeArgType) && !(0, types_1.isVariadicTypeVar)(param)) {
                    const messageDiag = diag.createAddendum();
                    messageDiag.addMessage(localize_1.LocMessage.unpackedArgInTypeArgument());
                    messageDiag.addTextRange(typeArgs[index].node);
                    typeArgType = types_1.UnknownType.create();
                }
                (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, param, typeArgType, diag, typeVarContext, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */);
            }
        });
        if (!diag.isEmpty()) {
            addError(localize_1.LocMessage.typeNotSpecializable().format({ type: printType(baseType) }) + diag.getString(), node, (_b = diag.getEffectiveTextRange()) !== null && _b !== void 0 ? _b : node);
        }
        const primarySignatureContext = typeVarContext.getPrimarySignature();
        const aliasTypeArgs = [];
        (_c = baseType.typeAliasInfo.typeParameters) === null || _c === void 0 ? void 0 : _c.forEach((typeParam) => {
            let typeVarType;
            if ((0, types_1.isParamSpec)(typeParam)) {
                const paramSpecType = primarySignatureContext.getParamSpecType(typeParam);
                typeVarType = paramSpecType ? (0, typeUtils_1.convertParamSpecValueToType)(paramSpecType) : types_1.UnknownType.create();
                if (!typeVarType) {
                    typeVarType = (0, typeUtils_1.getUnknownTypeForParamSpec)();
                    primarySignatureContext.setTypeVarType(typeParam, typeVarType);
                }
            }
            else {
                typeVarType = primarySignatureContext.getTypeVarType(typeParam);
                if (!typeVarType) {
                    typeVarType = types_1.UnknownType.create();
                    primarySignatureContext.setTypeVarType(typeParam, typeVarType);
                }
            }
            aliasTypeArgs.push(typeVarType);
        });
        const type = types_1.TypeBase.cloneForTypeAlias((0, typeUtils_1.applySolvedTypeVars)(baseType, typeVarContext), baseType.typeAliasInfo.name, baseType.typeAliasInfo.fullName, baseType.typeAliasInfo.moduleName, baseType.typeAliasInfo.fileUri, baseType.typeAliasInfo.typeVarScopeId, baseType.typeAliasInfo.isPep695Syntax, baseType.typeAliasInfo.typeParameters, aliasTypeArgs);
        return { type, node };
    }
    function getTypeOfIndexWithBaseType(node, baseTypeResult, usage, flags) {
        // Handle the case where we're specializing a generic type alias.
        const typeAliasResult = createSpecializedTypeAlias(node, baseTypeResult.type, flags);
        if (typeAliasResult) {
            return typeAliasResult;
        }
        if ((0, types_1.isTypeVar)(baseTypeResult.type) && (0, typeUtils_1.isTypeAliasPlaceholder)(baseTypeResult.type)) {
            const typeArgTypes = getTypeArgs(node, flags).map((t) => (0, typeUtils_1.convertToInstance)(t.type));
            const type = types_1.TypeBase.cloneForTypeAlias(baseTypeResult.type, baseTypeResult.type.details.recursiveTypeAliasName, '', '', uri_1.Uri.empty(), baseTypeResult.type.details.recursiveTypeAliasScopeId, !!baseTypeResult.type.details.recursiveTypeAliasIsPep695Syntax, baseTypeResult.type.details.recursiveTypeParameters, typeArgTypes);
            return { type };
        }
        let isIncomplete = baseTypeResult.isIncomplete;
        let isRequired = false;
        let isNotRequired = false;
        let isReadOnly = false;
        const type = mapSubtypesExpandTypeVars(baseTypeResult.type, 
        /* options */ undefined, (concreteSubtype, unexpandedSubtype) => {
            var _a;
            const selfType = (0, types_1.isTypeVar)(unexpandedSubtype) ? unexpandedSubtype : undefined;
            if ((0, types_1.isAnyOrUnknown)(concreteSubtype)) {
                return concreteSubtype;
            }
            if (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) {
                if ((0, types_1.isTypeVar)(unexpandedSubtype)) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarNotSubscriptable().format({
                        type: printType(unexpandedSubtype),
                    }), node.baseExpression);
                    // Evaluate the index expressions as though they are type arguments for error-reporting.
                    getTypeArgs(node, flags);
                    return types_1.UnknownType.create();
                }
            }
            if ((0, types_1.isInstantiableClass)(concreteSubtype)) {
                // See if the class has a custom metaclass that supports __getitem__, etc.
                if (concreteSubtype.details.effectiveMetaclass &&
                    (0, types_1.isInstantiableClass)(concreteSubtype.details.effectiveMetaclass) &&
                    !types_1.ClassType.isBuiltIn(concreteSubtype.details.effectiveMetaclass, ['type', '_InitVarMeta']) &&
                    (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) === 0) {
                    const itemMethodType = getBoundMagicMethod(concreteSubtype, getIndexAccessMagicMethodName(usage));
                    if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                        // If the class doesn't derive from Generic, a type argument should not be allowed.
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsExpectingNone().format({
                            name: printType(types_1.ClassType.cloneAsInstance(concreteSubtype)),
                        }), node);
                    }
                    if (itemMethodType) {
                        return getTypeOfIndexedObjectOrClass(node, concreteSubtype, selfType, usage).type;
                    }
                }
                // Setting the value of an indexed class will always result
                // in an exception.
                if (usage.method === 'set') {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.genericClassAssigned(), node.baseExpression);
                }
                else if (usage.method === 'del') {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.genericClassDeleted(), node.baseExpression);
                }
                if (types_1.ClassType.isSpecialBuiltIn(concreteSubtype, 'Literal')) {
                    // Special-case Literal types.
                    return createLiteralType(concreteSubtype, node, flags);
                }
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'InitVar')) {
                    // Special-case InitVar, used in dataclasses.
                    const typeArgs = getTypeArgs(node, flags);
                    if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                        if ((flags & 32768 /* EvaluatorFlags.VariableTypeAnnotation */) === 0) {
                            addError(localize_1.LocMessage.initVarNotAllowed(), node.baseExpression);
                        }
                    }
                    if (typeArgs.length === 1) {
                        return typeArgs[0].type;
                    }
                    else {
                        addError(localize_1.LocMessage.typeArgsMismatchOne().format({ received: typeArgs.length }), node.baseExpression);
                        return types_1.UnknownType.create();
                    }
                }
                if (types_1.ClassType.isEnumClass(concreteSubtype)) {
                    // Special-case Enum types.
                    // TODO - validate that there's only one index entry
                    // that is a str type.
                    // TODO - validate that literal strings are referencing
                    // a known enum member.
                    return types_1.ClassType.cloneAsInstance(concreteSubtype);
                }
                const isAnnotatedClass = (0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.isBuiltIn(concreteSubtype, 'Annotated');
                const hasCustomClassGetItem = (0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.hasCustomClassGetItem(concreteSubtype);
                const isGenericClass = ((_a = concreteSubtype.details.typeParameters) === null || _a === void 0 ? void 0 : _a.length) > 0 ||
                    types_1.ClassType.isSpecialBuiltIn(concreteSubtype) ||
                    types_1.ClassType.isBuiltIn(concreteSubtype, 'type') ||
                    types_1.ClassType.isPartiallyEvaluated(concreteSubtype);
                const isFinalAnnotation = (0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.isBuiltIn(concreteSubtype, 'Final');
                const isClassVarAnnotation = (0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.isBuiltIn(concreteSubtype, 'ClassVar');
                // Inlined TypedDicts are supported only for 'dict' (and not for 'Dict').
                // This feature is currently experimental.
                const supportsTypedDictTypeArg = AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.enableExperimentalFeatures &&
                    types_1.ClassType.isBuiltIn(concreteSubtype, 'dict') &&
                    !types_1.ClassType.isBuiltIn(concreteSubtype, 'Dict');
                let typeArgs = getTypeArgs(node, flags, {
                    isAnnotatedClass,
                    hasCustomClassGetItem: hasCustomClassGetItem || !isGenericClass,
                    isFinalAnnotation,
                    isClassVarAnnotation,
                    supportsTypedDictTypeArg,
                });
                if (!isAnnotatedClass) {
                    typeArgs = adjustTypeArgumentsForVariadicTypeVar(typeArgs, concreteSubtype.details.typeParameters, node);
                }
                // If this is a custom __class_getitem__, there's no need to specialize the class.
                // Just return it as is.
                if (hasCustomClassGetItem) {
                    return concreteSubtype;
                }
                if (concreteSubtype.typeArguments) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.classAlreadySpecialized().format({
                        type: printType((0, typeUtils_1.convertToInstance)(concreteSubtype), { expandTypeAlias: true }),
                    }), node.baseExpression);
                    return concreteSubtype;
                }
                const result = createSpecializedClassType(concreteSubtype, typeArgs, flags, node);
                if (result.isRequired) {
                    isRequired = true;
                }
                else if (result.isNotRequired) {
                    isNotRequired = true;
                }
                if (result.isReadOnly) {
                    isReadOnly = true;
                }
                return result.type;
            }
            if ((0, typeUtils_1.isNoneInstance)(concreteSubtype)) {
                if (!isIncomplete) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalSubscript, localize_1.LocMessage.noneNotSubscriptable(), node.baseExpression);
                }
                return types_1.UnknownType.create();
            }
            if ((0, types_1.isClassInstance)(concreteSubtype)) {
                const typeResult = getTypeOfIndexedObjectOrClass(node, concreteSubtype, selfType, usage);
                if (typeResult.isIncomplete) {
                    isIncomplete = true;
                }
                return typeResult.type;
            }
            if ((0, types_1.isNever)(concreteSubtype)) {
                return types_1.NeverType.createNever();
            }
            if ((0, types_1.isUnbound)(concreteSubtype)) {
                return types_1.UnknownType.create();
            }
            if (!isIncomplete) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIndexIssue, localize_1.LocMessage.typeNotSubscriptable().format({ type: printType(concreteSubtype) }), node.baseExpression);
            }
            return types_1.UnknownType.create();
        });
        // In case we didn't walk the list items above, do so now.
        // If we have, this information will be cached.
        if (!baseTypeResult.isIncomplete) {
            node.items.forEach((item) => {
                if (!isTypeCached(item.valueExpression)) {
                    getTypeOfExpression(item.valueExpression, flags & 4 /* EvaluatorFlags.AllowForwardReferences */);
                }
            });
        }
        return { type, isIncomplete, isReadOnly, isRequired, isNotRequired };
    }
    // Determines the effective variance of the type parameters for a generic
    // type alias. Normally, variance is not important for type aliases, but
    // it can be important in cases where the type alias is used to specify
    // a base class in a class definition.
    function inferTypeParameterVarianceForTypeAlias(type) {
        // If this isn't a generic type alias, there's nothing to do.
        if (!type.typeAliasInfo || !type.typeAliasInfo.typeParameters) {
            return undefined;
        }
        // Is the usage variance info already cached?
        if (type.typeAliasInfo.usageVariance) {
            return type.typeAliasInfo.usageVariance;
        }
        const typeParams = type.typeAliasInfo.typeParameters;
        // Start with all of the usage variances unknown.
        const usageVariances = typeParams.map(() => 1 /* Variance.Unknown */);
        // Prepopulate the cached value for the type alias to handle
        // recursive type aliases.
        type.typeAliasInfo.usageVariance = usageVariances;
        // Traverse the type alias type definition and adjust the usage
        // variances accordingly.
        updateUsageVariancesRecursive(type, typeParams, usageVariances);
        return usageVariances;
    }
    // Looks at uses of the type parameters within the type and adjusts the
    // variances accordingly. For example, if the type is `Mapping[T1, T2]`,
    // then T1 will be set to invariant and T2 will be set to covariant.
    function updateUsageVariancesRecursive(type, typeAliasTypeParams, usageVariances, recursionCount = 0) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return;
        }
        recursionCount++;
        // Define a helper function that performs the actual usage variant update.
        function updateUsageVarianceForType(type, variance) {
            (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                const typeParamIndex = typeAliasTypeParams.findIndex((param) => (0, types_1.isTypeSame)(param, subtype));
                if (typeParamIndex >= 0) {
                    usageVariances[typeParamIndex] = (0, typeUtils_1.combineVariances)(usageVariances[typeParamIndex], variance);
                }
                else {
                    updateUsageVariancesRecursive(subtype, typeAliasTypeParams, usageVariances, recursionCount);
                }
            });
        }
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if (subtype.category === 4 /* TypeCategory.Function */) {
                if (subtype.specializedTypes) {
                    subtype.specializedTypes.parameterTypes.forEach((paramType) => {
                        updateUsageVarianceForType(paramType, 4 /* Variance.Contravariant */);
                    });
                    const returnType = subtype.specializedTypes.returnType;
                    if (returnType) {
                        updateUsageVarianceForType(returnType, 3 /* Variance.Covariant */);
                    }
                }
            }
            else if (subtype.category === 6 /* TypeCategory.Class */) {
                if (subtype.typeArguments) {
                    // If the class includes type parameters that uses auto variance,
                    // compute the calculated variance.
                    inferTypeParameterVarianceForClass(subtype);
                    // Is the class specialized using any type arguments that correspond to
                    // the type alias' type parameters?
                    subtype.typeArguments.forEach((typeArg, classParamIndex) => {
                        var _a;
                        if ((0, typeUtils_1.isTupleClass)(subtype)) {
                            updateUsageVarianceForType(typeArg, 3 /* Variance.Covariant */);
                        }
                        else if (classParamIndex < subtype.details.typeParameters.length) {
                            const classTypeParam = subtype.details.typeParameters[classParamIndex];
                            if ((0, types_1.isUnpackedClass)(typeArg) && typeArg.tupleTypeArguments) {
                                typeArg.tupleTypeArguments.forEach((tupleTypeArg) => {
                                    updateUsageVarianceForType(tupleTypeArg.type, 2 /* Variance.Invariant */);
                                });
                            }
                            else {
                                updateUsageVarianceForType(typeArg, (_a = classTypeParam.computedVariance) !== null && _a !== void 0 ? _a : classTypeParam.details.declaredVariance);
                            }
                        }
                    });
                }
            }
        });
    }
    function makeTupleObject(typeArgs, isUnpackedTuple = false) {
        if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
            return (0, typeUtils_1.convertToInstance)((0, typeUtils_1.specializeTupleClass)(tupleClassType, typeArgs, /* isTypeArgumentExplicit */ true, isUnpackedTuple));
        }
        return types_1.UnknownType.create();
    }
    function getIndexAccessMagicMethodName(usage) {
        if (usage.method === 'get') {
            return '__getitem__';
        }
        else if (usage.method === 'set') {
            return '__setitem__';
        }
        else {
            (0, debug_1.assert)(usage.method === 'del');
            return '__delitem__';
        }
    }
    function getTypeOfIndexedObjectOrClass(node, baseType, selfType, usage) {
        var _a, _b, _c, _d;
        // Handle index operations for TypedDict classes specially.
        if ((0, types_1.isClassInstance)(baseType) && types_1.ClassType.isTypedDictClass(baseType)) {
            const typeFromTypedDict = (0, typedDicts_1.getTypeOfIndexedTypedDict)(evaluatorInterface, node, baseType, usage);
            if (typeFromTypedDict) {
                return typeFromTypedDict;
            }
        }
        const magicMethodName = getIndexAccessMagicMethodName(usage);
        const itemMethodType = getBoundMagicMethod(baseType, magicMethodName, selfType);
        if (!itemMethodType) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportIndexIssue, localize_1.LocMessage.methodNotDefinedOnType().format({
                name: magicMethodName,
                type: printType(baseType),
            }), node.baseExpression);
            return { type: types_1.UnknownType.create() };
        }
        // Handle the special case where the object is a tuple and
        // the index is a constant number (integer) or a slice with integer
        // start and end values. In these cases, we can determine
        // the exact type by indexing into the tuple type array.
        if (node.items.length === 1 &&
            !node.trailingComma &&
            !node.items[0].name &&
            node.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
            (0, types_1.isClassInstance)(baseType)) {
            const index0Expr = node.items[0].valueExpression;
            const valueType = getTypeOfExpression(index0Expr).type;
            if ((0, types_1.isClassInstance)(valueType) &&
                types_1.ClassType.isBuiltIn(valueType, 'int') &&
                (0, typeUtils_1.isLiteralType)(valueType) &&
                typeof valueType.literalValue === 'number') {
                const indexValue = valueType.literalValue;
                const tupleType = (0, typeUtils_1.getSpecializedTupleType)(baseType);
                if (tupleType && tupleType.tupleTypeArguments) {
                    if ((0, typeUtils_1.isTupleIndexUnambiguous)(tupleType, indexValue)) {
                        if (indexValue >= 0 && indexValue < tupleType.tupleTypeArguments.length) {
                            return { type: tupleType.tupleTypeArguments[indexValue].type };
                        }
                        else if (indexValue < 0 && tupleType.tupleTypeArguments.length + indexValue >= 0) {
                            return {
                                type: tupleType.tupleTypeArguments[tupleType.tupleTypeArguments.length + indexValue]
                                    .type,
                            };
                        }
                    }
                }
            }
            else if ((0, types_1.isClassInstance)(valueType) && types_1.ClassType.isBuiltIn(valueType, 'slice')) {
                const tupleType = (0, typeUtils_1.getSpecializedTupleType)(baseType);
                if (tupleType && index0Expr.nodeType === 46 /* ParseNodeType.Slice */) {
                    const slicedTupleType = getSlicedTupleType(tupleType, index0Expr);
                    if (slicedTupleType) {
                        return { type: slicedTupleType };
                    }
                }
            }
        }
        // Follow PEP 637 rules for positional and keyword arguments.
        const positionalArgs = node.items.filter((item) => item.argumentCategory === 0 /* ArgumentCategory.Simple */ && !item.name);
        const unpackedListArgs = node.items.filter((item) => item.argumentCategory === 1 /* ArgumentCategory.UnpackedList */);
        const keywordArgs = node.items.filter((item) => item.argumentCategory === 0 /* ArgumentCategory.Simple */ && !!item.name);
        const unpackedDictArgs = node.items.filter((item) => item.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */);
        let positionalIndexType;
        let isPositionalIndexTypeIncomplete = false;
        if (positionalArgs.length === 1 && unpackedListArgs.length === 0 && !node.trailingComma) {
            // Handle the common case where there is a single positional argument.
            const typeResult = getTypeOfExpression(positionalArgs[0].valueExpression);
            positionalIndexType = typeResult.type;
            if (typeResult.isIncomplete) {
                isPositionalIndexTypeIncomplete = true;
            }
        }
        else if (positionalArgs.length === 0 && unpackedListArgs.length === 0) {
            // Handle the case where there are no positionals provided but there are keywords.
            positionalIndexType = makeTupleObject([]);
        }
        else {
            // Package up all of the positionals into a tuple.
            const tupleTypeArgs = [];
            positionalArgs.forEach((arg) => {
                const typeResult = getTypeOfExpression(arg.valueExpression);
                tupleTypeArgs.push({ type: typeResult.type, isUnbounded: false });
                if (typeResult.isIncomplete) {
                    isPositionalIndexTypeIncomplete = true;
                }
            });
            unpackedListArgs.forEach((arg) => {
                var _a, _b;
                const typeResult = getTypeOfExpression(arg.valueExpression);
                if (typeResult.isIncomplete) {
                    isPositionalIndexTypeIncomplete = true;
                }
                const iterableType = (_b = (_a = getTypeOfIterator(typeResult, /* isAsync */ false, arg.valueExpression)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
                tupleTypeArgs.push({ type: iterableType, isUnbounded: true });
            });
            positionalIndexType = makeTupleObject(tupleTypeArgs);
        }
        let argList = [
            {
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                typeResult: { type: positionalIndexType, isIncomplete: isPositionalIndexTypeIncomplete },
            },
        ];
        if (usage.method === 'set') {
            let setType = (_b = (_a = usage.setType) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.AnyType.create();
            // Expand constrained type variables.
            if ((0, types_1.isTypeVar)(setType) && setType.details.constraints.length > 0) {
                const conditionFilter = (0, types_1.isClassInstance)(baseType) ? baseType.condition : undefined;
                setType = makeTopLevelTypeVarsConcrete(setType, 
                /* makeParamSpecsConcrete */ undefined, conditionFilter);
            }
            argList.push({
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                typeResult: {
                    type: setType,
                    isIncomplete: !!((_c = usage.setType) === null || _c === void 0 ? void 0 : _c.isIncomplete),
                },
            });
        }
        keywordArgs.forEach((arg) => {
            argList.push({
                argumentCategory: 0 /* ArgumentCategory.Simple */,
                valueExpression: arg.valueExpression,
                node: arg,
                name: arg.name,
            });
        });
        unpackedDictArgs.forEach((arg) => {
            argList.push({
                argumentCategory: 2 /* ArgumentCategory.UnpackedDictionary */,
                valueExpression: arg.valueExpression,
                node: arg,
            });
        });
        let callResult;
        // Speculatively attempt the call. We may need to replace the index
        // type with 'int', and we don't want to emit errors before we know
        // which type to use.
        if (keywordArgs.length === 0 && unpackedDictArgs.length === 0 && positionalArgs.length === 1) {
            useSpeculativeMode(node, () => {
                callResult = validateCallArguments(node, argList, { type: itemMethodType }, 
                /* typeVarContext */ undefined, 
                /* skipUnknownArgCheck */ true);
                if (callResult.argumentErrors) {
                    // If the object supports "__index__" magic method, convert
                    // the index to an int and try again.
                    if ((0, types_1.isClassInstance)(positionalIndexType)) {
                        const altArgList = [...argList];
                        altArgList[0] = { ...altArgList[0] };
                        const indexMethod = getBoundMagicMethod(positionalIndexType, '__index__');
                        if (indexMethod) {
                            const intType = getBuiltInObject(node, 'int');
                            if ((0, types_1.isClassInstance)(intType)) {
                                altArgList[0].typeResult = { type: intType };
                            }
                        }
                        callResult = validateCallArguments(node, altArgList, { type: itemMethodType });
                        // We were successful, so replace the arg list.
                        if (!callResult.argumentErrors) {
                            argList = altArgList;
                        }
                    }
                }
            });
        }
        callResult = validateCallArguments(node, argList, { type: itemMethodType }, 
        /* typeVarContext */ undefined, 
        /* skipUnknownArgCheck */ true);
        return {
            type: (_d = callResult.returnType) !== null && _d !== void 0 ? _d : types_1.UnknownType.create(),
            isIncomplete: !!callResult.isTypeIncomplete,
        };
    }
    // Given a tuple type and a slice expression, determines the resulting
    // type if it can be determined. If not, it returns undefined.
    function getSlicedTupleType(tupleType, sliceNode) {
        // We don't handle step values.
        if (sliceNode.stepValue || !tupleType.tupleTypeArguments) {
            return undefined;
        }
        const tupleTypeArgs = tupleType.tupleTypeArguments;
        const startValue = getTupleSliceParameter(sliceNode.startValue, 0, tupleTypeArgs);
        const endValue = getTupleSliceParameter(sliceNode.endValue, tupleTypeArgs.length, tupleTypeArgs);
        if (startValue === undefined || endValue === undefined || endValue < startValue) {
            return undefined;
        }
        const slicedTypeArgs = tupleTypeArgs.slice(startValue, endValue);
        return makeTupleObject(slicedTypeArgs);
    }
    function getTupleSliceParameter(expression, defaultValue, tupleTypeArgs) {
        let value = defaultValue;
        if (expression) {
            const valType = getTypeOfExpression(expression).type;
            if (!(0, types_1.isClassInstance)(valType) || !types_1.ClassType.isBuiltIn(valType, 'int') || !(0, typeUtils_1.isLiteralType)(valType)) {
                return undefined;
            }
            value = valType.literalValue;
            const unboundedIndex = tupleTypeArgs.findIndex((typeArg) => typeArg.isUnbounded || (0, types_1.isVariadicTypeVar)(typeArg.type));
            if (value < 0) {
                value = tupleTypeArgs.length + value;
                if (value < 0) {
                    return undefined;
                }
                else if (unboundedIndex >= 0 && value <= unboundedIndex) {
                    return undefined;
                }
            }
            else {
                if (value > tupleTypeArgs.length) {
                    return undefined;
                }
                else if (unboundedIndex >= 0 && value > unboundedIndex) {
                    return undefined;
                }
            }
        }
        return value;
    }
    function getTypeArgs(node, flags, options) {
        const typeArgs = [];
        let adjFlags = flags;
        if ((options === null || options === void 0 ? void 0 : options.isFinalAnnotation) || (options === null || options === void 0 ? void 0 : options.isClassVarAnnotation)) {
            adjFlags |= 131072 /* EvaluatorFlags.DisallowClassVar */ | 16 /* EvaluatorFlags.DisallowFinal */;
        }
        else {
            adjFlags &= ~(2 /* EvaluatorFlags.DoNotSpecialize */ |
                32 /* EvaluatorFlags.DisallowParamSpec */ |
                64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                1048576 /* EvaluatorFlags.AllowRequired */ |
                16384 /* EvaluatorFlags.EnforceTypeVarVarianceConsistency */);
            if (!(options === null || options === void 0 ? void 0 : options.isAnnotatedClass)) {
                adjFlags |= 131072 /* EvaluatorFlags.DisallowClassVar */ | 16 /* EvaluatorFlags.DisallowFinal */;
            }
            adjFlags |= 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */ | 134217728 /* EvaluatorFlags.AllowConcatenate */;
        }
        // Create a local function that validates a single type argument.
        const getTypeArgTypeResult = (expr, argIndex) => {
            let typeResult;
            // If it's a custom __class_getitem__, none of the arguments should be
            // treated as types.
            if (options === null || options === void 0 ? void 0 : options.hasCustomClassGetItem) {
                adjFlags =
                    32 /* EvaluatorFlags.DisallowParamSpec */ |
                        64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                        2 /* EvaluatorFlags.DoNotSpecialize */ |
                        131072 /* EvaluatorFlags.DisallowClassVar */;
                typeResult = {
                    ...getTypeOfExpression(expr, adjFlags),
                    node: expr,
                };
            }
            else if ((options === null || options === void 0 ? void 0 : options.isAnnotatedClass) && argIndex > 0) {
                // If it's an Annotated[a, b, c], only the first index should be
                // treated as a type.The others can be regular(non - type) objects.
                adjFlags =
                    32 /* EvaluatorFlags.DisallowParamSpec */ |
                        64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                        2 /* EvaluatorFlags.DoNotSpecialize */ |
                        131072 /* EvaluatorFlags.DisallowClassVar */;
                if ((0, analyzerFileInfo_1.isAnnotationEvaluationPostponed)(AnalyzerNodeInfo.getFileInfo(node))) {
                    adjFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */;
                }
                typeResult = {
                    ...getTypeOfExpression(expr, adjFlags),
                    node: expr,
                };
            }
            else {
                typeResult = getTypeArg(expr, adjFlags, !!(options === null || options === void 0 ? void 0 : options.supportsTypedDictTypeArg) && argIndex === 0);
            }
            return typeResult;
        };
        // A single (non-empty) tuple is treated the same as a list of items in the index.
        if (node.items.length === 1 &&
            !node.trailingComma &&
            !node.items[0].name &&
            node.items[0].valueExpression.nodeType === 52 /* ParseNodeType.Tuple */ &&
            node.items[0].valueExpression.expressions.length > 0) {
            node.items[0].valueExpression.expressions.forEach((item, index) => {
                typeArgs.push(getTypeArgTypeResult(item, index));
            });
            // Set the node's type so it isn't reevaluated later.
            setTypeResultForNode(node.items[0].valueExpression, { type: types_1.UnknownType.create() });
        }
        else {
            node.items.forEach((arg, index) => {
                const typeResult = getTypeArgTypeResult(arg.valueExpression, index);
                if (arg.argumentCategory !== 0 /* ArgumentCategory.Simple */) {
                    if (arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                        if (!(options === null || options === void 0 ? void 0 : options.isAnnotatedClass) || index === 0) {
                            if ((0, types_1.isVariadicTypeVar)(typeResult.type) && !typeResult.type.isVariadicUnpacked) {
                                typeResult.type = types_1.TypeVarType.cloneForUnpacked(typeResult.type);
                            }
                            else if ((0, types_1.isInstantiableClass)(typeResult.type) &&
                                !typeResult.type.includeSubclasses &&
                                (0, typeUtils_1.isTupleClass)(typeResult.type)) {
                                typeResult.type = types_1.ClassType.cloneForUnpacked(typeResult.type);
                            }
                            else {
                                addError(localize_1.LocMessage.unpackNotAllowed(), arg.valueExpression);
                            }
                        }
                    }
                }
                if (arg.name) {
                    addError(localize_1.LocMessage.keywordArgInTypeArgument(), arg.valueExpression);
                }
                typeArgs.push(typeResult);
            });
        }
        return typeArgs;
    }
    function getTypeArg(node, flags, supportsDictExpression) {
        let typeResult;
        let adjustedFlags = flags |
            128 /* EvaluatorFlags.ExpectingInstantiableType */ |
            1 /* EvaluatorFlags.ConvertEllipsisToAny */ |
            8 /* EvaluatorFlags.EvaluateStringLiteralAsType */;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        if (fileInfo.isStubFile) {
            adjustedFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */;
        }
        if (node.nodeType === 31 /* ParseNodeType.List */) {
            typeResult = {
                type: types_1.UnknownType.create(),
                typeList: node.entries.map((entry) => {
                    return { ...getTypeOfExpression(entry, adjustedFlags), node: entry };
                }),
                node,
            };
            // Set the node's type so it isn't reevaluated later.
            setTypeResultForNode(node, { type: types_1.UnknownType.create() });
        }
        else if (node.nodeType === 15 /* ParseNodeType.Dictionary */ && supportsDictExpression) {
            const inlinedTypeDict = typedDictClassType && (0, types_1.isInstantiableClass)(typedDictClassType)
                ? (0, typedDicts_1.createTypedDictTypeInlined)(evaluatorInterface, node, typedDictClassType)
                : undefined;
            const keyTypeFallback = strClassType && (0, types_1.isInstantiableClass)(strClassType) ? strClassType : types_1.UnknownType.create();
            typeResult = {
                type: keyTypeFallback,
                inlinedTypeDict,
                node,
            };
        }
        else {
            typeResult = { ...getTypeOfExpression(node, adjustedFlags), node };
            if (node.nodeType === 15 /* ParseNodeType.Dictionary */) {
                addError(localize_1.LocMessage.dictInAnnotation(), node);
            }
            if ((flags & 131072 /* EvaluatorFlags.DisallowClassVar */) !== 0) {
                // "ClassVar" is not allowed as a type argument.
                if ((0, types_1.isClass)(typeResult.type) && types_1.ClassType.isBuiltIn(typeResult.type, 'ClassVar')) {
                    addError(localize_1.LocMessage.classVarNotAllowed(), node);
                }
            }
        }
        return typeResult;
    }
    function getTypeOfTuple(node, flags, inferenceContext) {
        var _a;
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0 &&
            ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 1 /* ParseNodeType.Argument */) {
            // This is allowed inside of an index trailer, specifically
            // to support Tuple[()], which is the documented way to annotate
            // a zero-length tuple.
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.useTupleInstead());
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.tupleInAnnotation() + diag.getString(), node);
            return { type: types_1.UnknownType.create() };
        }
        if ((flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0 &&
            node.expressions.length === 0 &&
            !inferenceContext) {
            return { type: makeTupleObject([]), isEmptyTupleShorthand: true };
        }
        // If the expected type is a union, recursively call for each of the subtypes
        // to find one that matches.
        let effectiveExpectedType = inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType;
        let expectedTypeContainsAny = inferenceContext && (0, types_1.isAny)(inferenceContext.expectedType);
        if (inferenceContext && (0, types_1.isUnion)(inferenceContext.expectedType)) {
            let matchingSubtype;
            (0, typeUtils_1.doForEachSubtype)(inferenceContext.expectedType, (subtype) => {
                if ((0, types_1.isAny)(subtype)) {
                    expectedTypeContainsAny = true;
                }
                if (!matchingSubtype) {
                    const subtypeResult = useSpeculativeMode(node, () => {
                        return getTypeOfTupleWithContext(node, (0, typeUtils_1.makeInferenceContext)(subtype));
                    });
                    if (subtypeResult && assignType(subtype, subtypeResult.type)) {
                        matchingSubtype = subtype;
                    }
                }
            }, 
            /* sortSubtypes */ true);
            effectiveExpectedType = matchingSubtype;
        }
        let expectedTypeDiagAddendum;
        if (effectiveExpectedType) {
            const result = getTypeOfTupleWithContext(node, (0, typeUtils_1.makeInferenceContext)(effectiveExpectedType, 
            /* isTypeIncomplete */ false, inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker));
            if (result && !result.typeErrors) {
                return result;
            }
            expectedTypeDiagAddendum = result === null || result === void 0 ? void 0 : result.expectedTypeDiagAddendum;
        }
        const typeResult = getTypeOfTupleInferred(node);
        // If there was an expected type of Any, replace the resulting type
        // with Any rather than return a type with unknowns.
        if (expectedTypeContainsAny) {
            typeResult.type = types_1.AnyType.create();
        }
        return { ...typeResult, expectedTypeDiagAddendum };
    }
    function getTypeOfTupleWithContext(node, inferenceContext) {
        inferenceContext.expectedType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(inferenceContext.expectedType);
        if (!(0, types_1.isClassInstance)(inferenceContext.expectedType)) {
            return undefined;
        }
        if (!tupleClassType || !(0, types_1.isInstantiableClass)(tupleClassType)) {
            return undefined;
        }
        // Build an array of expected types.
        let expectedTypes = [];
        if ((0, typeUtils_1.isTupleClass)(inferenceContext.expectedType) && inferenceContext.expectedType.tupleTypeArguments) {
            expectedTypes = inferenceContext.expectedType.tupleTypeArguments.map((t) => (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(t.type));
            const unboundedIndex = inferenceContext.expectedType.tupleTypeArguments.findIndex((t) => t.isUnbounded);
            if (unboundedIndex >= 0) {
                if (expectedTypes.length > node.expressions.length) {
                    expectedTypes.splice(unboundedIndex, 1);
                }
                else {
                    while (expectedTypes.length < node.expressions.length) {
                        expectedTypes.splice(unboundedIndex, 0, expectedTypes[unboundedIndex]);
                    }
                }
            }
        }
        else {
            const tupleTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(tupleClassType));
            if (!(0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluatorInterface, types_1.ClassType.cloneAsInstance(tupleClassType), inferenceContext.expectedType, tupleTypeVarContext, ParseTreeUtils.getTypeVarScopesForNode(node), node.start)) {
                return undefined;
            }
            const specializedTuple = (0, typeUtils_1.applySolvedTypeVars)(tupleClassType, tupleTypeVarContext);
            if (!specializedTuple.typeArguments || specializedTuple.typeArguments.length !== 1) {
                return undefined;
            }
            const homogenousType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(specializedTuple.typeArguments[0]);
            for (let i = 0; i < node.expressions.length; i++) {
                expectedTypes.push(homogenousType);
            }
        }
        const entryTypeResults = node.expressions.map((expr, index) => getTypeOfExpression(expr, 
        /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(index < expectedTypes.length ? expectedTypes[index] : undefined, inferenceContext.isTypeIncomplete, inferenceContext.signatureTracker)));
        const isIncomplete = entryTypeResults.some((result) => result.isIncomplete);
        const type = makeTupleObject(buildTupleTypesList(entryTypeResults));
        // Copy any expected type diag addenda for precision error reporting.
        let expectedTypeDiagAddendum;
        if (entryTypeResults.some((result) => result.expectedTypeDiagAddendum)) {
            expectedTypeDiagAddendum = new diagnostic_1.DiagnosticAddendum();
            entryTypeResults.forEach((result) => {
                if (result.expectedTypeDiagAddendum) {
                    expectedTypeDiagAddendum.addAddendum(result.expectedTypeDiagAddendum);
                }
            });
        }
        return { type, expectedTypeDiagAddendum, isIncomplete };
    }
    function getTypeOfTupleInferred(node) {
        const entryTypeResults = node.expressions.map((expr) => getTypeOfExpression(expr));
        const isIncomplete = entryTypeResults.some((result) => result.isIncomplete);
        const type = makeTupleObject(buildTupleTypesList(entryTypeResults));
        if (isIncomplete) {
            if ((0, typeUtils_1.getContainerDepth)(type) > maxInferredContainerDepth) {
                return { type: types_1.UnknownType.create() };
            }
        }
        return { type, isIncomplete };
    }
    function buildTupleTypesList(entryTypeResults) {
        const entryTypes = [];
        for (const typeResult of entryTypeResults) {
            let possibleUnpackedTuple;
            if (typeResult.unpackedType) {
                possibleUnpackedTuple = typeResult.unpackedType;
            }
            else if ((0, types_1.isUnpacked)(typeResult.type)) {
                possibleUnpackedTuple = typeResult.type;
            }
            // Is this an unpacked tuple? If so, we can append the individual
            // unpacked entries onto the new tuple. If it's not an upacked tuple
            // but some other iterator (e.g. a List), we won't know the number of
            // items, so we'll need to leave the Tuple open-ended.
            if (possibleUnpackedTuple &&
                (0, types_1.isClassInstance)(possibleUnpackedTuple) &&
                possibleUnpackedTuple.tupleTypeArguments) {
                const typeArgs = possibleUnpackedTuple.tupleTypeArguments;
                if (!typeArgs) {
                    entryTypes.push({ type: types_1.UnknownType.create(), isUnbounded: true });
                }
                else {
                    (0, collectionUtils_1.appendArray)(entryTypes, typeArgs);
                }
            }
            else if ((0, types_1.isNever)(typeResult.type) && typeResult.isIncomplete && !typeResult.unpackedType) {
                entryTypes.push({ type: types_1.UnknownType.create(/* isIncomplete */ true), isUnbounded: false });
            }
            else {
                entryTypes.push({ type: typeResult.type, isUnbounded: !!typeResult.unpackedType });
            }
        }
        // If there are multiple unbounded entries, combine all of them into a single
        // unbounded entry to avoid violating the invariant that there can be at most
        // one unbounded entry in a tuple.
        if (entryTypes.filter((t) => t.isUnbounded).length > 1) {
            const firstUnboundedEntryIndex = entryTypes.findIndex((t) => t.isUnbounded);
            const removedEntries = entryTypes.splice(firstUnboundedEntryIndex);
            entryTypes.push({ type: (0, types_1.combineTypes)(removedEntries.map((t) => t.type)), isUnbounded: true });
        }
        return entryTypes;
    }
    function getTypeOfCall(node, flags, inferenceContext) {
        var _a;
        let baseTypeResult;
        // Check for the use of `type(x)` within a type annotation. This isn't
        // allowed, and it's a common mistake, so we want to emit a diagnostic
        // that guides the user to the right solution.
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0 &&
            node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            node.leftExpression.value === 'type') {
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.useTypeInstead());
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.typeCallNotAllowed() + diag.getString(), node);
        }
        // Handle immediate calls of lambdas specially.
        if (node.leftExpression.nodeType === 30 /* ParseNodeType.Lambda */) {
            baseTypeResult = getTypeOfLambdaForCall(node, inferenceContext);
        }
        else {
            baseTypeResult = getTypeOfExpression(node.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */ | (flags & 4 /* EvaluatorFlags.AllowForwardReferences */));
        }
        const argList = ParseTreeUtils.getArgumentsByRuntimeOrder(node).map((arg) => {
            const functionArg = {
                valueExpression: arg.valueExpression,
                argumentCategory: arg.argumentCategory,
                node: arg,
                name: arg.name,
            };
            return functionArg;
        });
        let typeResult = { type: types_1.UnknownType.create() };
        // If the inference context has an associated signature tracker, make sure
        // the base type of this call is not the same as one of the tracked signatures.
        // This is important for nested generic calls (e.g. "foo(foo(x))").
        if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker) {
            baseTypeResult.type = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(baseTypeResult.type, inferenceContext.signatureTracker, node.leftExpression.start);
        }
        if (!(0, typeUtils_1.isTypeAliasPlaceholder)(baseTypeResult.type)) {
            if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ && node.leftExpression.value === 'super') {
                // Handle the built-in "super" call specially.
                typeResult = getTypeOfSuperCall(node);
            }
            else if ((0, types_1.isAnyOrUnknown)(baseTypeResult.type) &&
                node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                node.leftExpression.value === 'reveal_type') {
                // Handle the implicit "reveal_type" call.
                typeResult = getTypeOfRevealType(node, inferenceContext);
            }
            else if ((0, types_1.isFunction)(baseTypeResult.type) && baseTypeResult.type.details.builtInName === 'reveal_type') {
                // Handle the "typing.reveal_type" call.
                typeResult = getTypeOfRevealType(node, inferenceContext);
            }
            else if ((0, types_1.isFunction)(baseTypeResult.type) && baseTypeResult.type.details.builtInName === 'assert_type') {
                // Handle the "typing.assert_type" call.
                typeResult = getTypeOfAssertType(node, inferenceContext);
            }
            else if ((0, types_1.isAnyOrUnknown)(baseTypeResult.type) &&
                node.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                node.leftExpression.value === 'reveal_locals') {
                if (node.arguments.length === 0) {
                    // Handle the special-case "reveal_locals" call.
                    typeResult.type = getTypeOfRevealLocals(node);
                }
                else {
                    addError(localize_1.LocMessage.revealLocalsArgs(), node);
                }
            }
            else {
                const callResult = validateCallArguments(node, argList, baseTypeResult, 
                /* typeVarContext */ undefined, 
                /* skipUnknownArgCheck */ false, inferenceContext);
                typeResult.type = (_a = callResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
                if (callResult.argumentErrors) {
                    typeResult.typeErrors = true;
                }
                else {
                    typeResult.overloadsUsedForCall = callResult.overloadsUsedForCall;
                }
                if (callResult.isTypeIncomplete) {
                    typeResult.isIncomplete = true;
                }
            }
            if (baseTypeResult.isIncomplete) {
                typeResult.isIncomplete = true;
            }
        }
        else {
            typeResult.isIncomplete = true;
        }
        // Don't bother evaluating the arguments if we're speculatively evaluating the call
        // or the base type is incomplete.
        if (!isSpeculativeModeInUse(node) && !baseTypeResult.isIncomplete) {
            // Touch all of the args so they're marked accessed even if there were errors.
            // We skip this if it's a TypeVar() call in the typing.pyi module because
            // this results in a cyclical type resolution problem whereby we try to
            // retrieve the str class, which inherits from Sequence, which inherits from
            // Iterable, which uses a TypeVar. Without this, Iterable and Sequence classes
            // have invalid type parameters.
            const isCyclicalTypeVarCall = (0, types_1.isInstantiableClass)(baseTypeResult.type) &&
                types_1.ClassType.isBuiltIn(baseTypeResult.type, 'TypeVar') &&
                AnalyzerNodeInfo.getFileInfo(node).isTypingStubFile;
            if (!isCyclicalTypeVarCall) {
                argList.forEach((arg) => {
                    if (arg.valueExpression &&
                        arg.valueExpression.nodeType !== 48 /* ParseNodeType.StringList */ &&
                        !isTypeCached(arg.valueExpression)) {
                        getTypeOfExpression(arg.valueExpression);
                    }
                });
            }
        }
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.typeAnnotationCall(), node);
            typeResult = { type: types_1.UnknownType.create() };
        }
        return typeResult;
    }
    // This function is used in cases where a lambda is defined and immediately
    // called. In this case, we can't use normal bidirectional type inference
    // to determine the lambda's type. It needs to be inferred from the argument
    // types instead.
    function getTypeOfLambdaForCall(node, inferenceContext) {
        (0, debug_1.assert)(node.leftExpression.nodeType === 30 /* ParseNodeType.Lambda */);
        const expectedType = types_1.FunctionType.createSynthesizedInstance('');
        expectedType.details.declaredReturnType = inferenceContext
            ? inferenceContext.expectedType
            : types_1.UnknownType.create();
        let isArgTypeIncomplete = false;
        node.arguments.forEach((arg, index) => {
            const argTypeResult = getTypeOfExpression(arg.valueExpression);
            if (argTypeResult.isIncomplete) {
                isArgTypeIncomplete = true;
            }
            types_1.FunctionType.addParameter(expectedType, {
                category: 0 /* ParameterCategory.Simple */,
                name: `p${index.toString()}`,
                type: argTypeResult.type,
                hasDeclaredType: true,
            });
        });
        // If the lambda's param list ends with a "/" positional parameter separator,
        // add a corresponding separator to the expected type.
        const lambdaParams = node.leftExpression.parameters;
        if (lambdaParams.length > 0) {
            const lastParam = lambdaParams[lambdaParams.length - 1];
            if (lastParam.category === 0 /* ParameterCategory.Simple */ && !lastParam.name) {
                types_1.FunctionType.addPositionOnlyParameterSeparator(expectedType);
            }
        }
        function getLambdaType() {
            return getTypeOfExpression(node.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */, (0, typeUtils_1.makeInferenceContext)(expectedType));
        }
        // If one or more of the arguments are incomplete, use speculative mode
        // for the lambda evaluation because it may need to be reevaluated once
        // the arg types are complete.
        let typeResult = isArgTypeIncomplete || isSpeculativeModeInUse(node) || (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.isTypeIncomplete)
            ? useSpeculativeMode(node.leftExpression, getLambdaType)
            : getLambdaType();
        // If bidirectional type inference failed, use normal type inference instead.
        if (typeResult.typeErrors) {
            typeResult = getTypeOfExpression(node.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
        }
        return typeResult;
    }
    function getTypeOfAssertType(node, inferenceContext) {
        if (node.arguments.length !== 2 ||
            node.arguments[0].argumentCategory !== 0 /* ArgumentCategory.Simple */ ||
            node.arguments[0].name !== undefined ||
            node.arguments[0].argumentCategory !== 0 /* ArgumentCategory.Simple */ ||
            node.arguments[1].name !== undefined) {
            addError(localize_1.LocMessage.assertTypeArgs(), node);
            return { type: types_1.UnknownType.create() };
        }
        const arg0TypeResult = getTypeOfExpression(node.arguments[0].valueExpression, 
        /* flags */ undefined, inferenceContext);
        if (arg0TypeResult.isIncomplete) {
            return { type: types_1.UnknownType.create(/* isIncomplete */ true), isIncomplete: true };
        }
        const assertedType = (0, typeUtils_1.convertToInstance)(getTypeOfArgumentExpectingType(node.arguments[1]).type);
        if (!(0, types_1.isTypeSame)(assertedType, arg0TypeResult.type, { treatAnySameAsUnknown: true, ignorePseudoGeneric: true })) {
            const srcDestTypes = printSrcDestTypes(arg0TypeResult.type, assertedType, { expandTypeAlias: true });
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAssertTypeFailure, localize_1.LocMessage.assertTypeTypeMismatch().format({
                expected: srcDestTypes.destType,
                received: srcDestTypes.sourceType,
            }), node.arguments[0].valueExpression);
        }
        return { type: arg0TypeResult.type };
    }
    function getTypeOfRevealType(node, inferenceContext) {
        let arg0Value;
        let expectedRevealTypeNode;
        let expectedRevealType;
        let expectedTextNode;
        let expectedText;
        // Make sure there is only one positional argument passed as arg 0.
        node.arguments.forEach((arg, index) => {
            if (index === 0) {
                if (arg.argumentCategory === 0 /* ArgumentCategory.Simple */ && !arg.name) {
                    arg0Value = arg.valueExpression;
                }
            }
            else if (arg.argumentCategory !== 0 /* ArgumentCategory.Simple */ || !arg.name) {
                arg0Value = undefined;
            }
            else if (arg.name.value === 'expected_text') {
                expectedTextNode = arg.valueExpression;
                const expectedTextType = getTypeOfExpression(arg.valueExpression).type;
                if (!(0, types_1.isClassInstance)(expectedTextType) ||
                    !types_1.ClassType.isBuiltIn(expectedTextType, 'str') ||
                    typeof expectedTextType.literalValue !== 'string') {
                    addError(localize_1.LocMessage.revealTypeExpectedTextArg(), arg.valueExpression);
                }
                else {
                    expectedText = expectedTextType.literalValue;
                }
            }
            else if (arg.name.value === 'expected_type') {
                expectedRevealTypeNode = arg.valueExpression;
                expectedRevealType = (0, typeUtils_1.convertToInstance)(getTypeOfArgumentExpectingType(arg).type);
            }
        });
        if (!arg0Value) {
            addError(localize_1.LocMessage.revealTypeArgs(), node);
            return { type: types_1.UnknownType.create() };
        }
        const typeResult = getTypeOfExpression(arg0Value, /* flags */ undefined, inferenceContext);
        const type = typeResult.type;
        const exprString = ParseTreeUtils.printExpression(arg0Value);
        const typeString = printType(type, { expandTypeAlias: true });
        if (expectedText !== undefined) {
            if (expectedText !== typeString) {
                addError(localize_1.LocMessage.revealTypeExpectedTextMismatch().format({
                    expected: expectedText,
                    received: typeString,
                }), expectedTextNode !== null && expectedTextNode !== void 0 ? expectedTextNode : arg0Value);
            }
        }
        if (expectedRevealType) {
            if (!(0, types_1.isTypeSame)(expectedRevealType, type, { ignorePseudoGeneric: true })) {
                const expectedRevealTypeText = printType(expectedRevealType);
                addError(localize_1.LocMessage.revealTypeExpectedTypeMismatch().format({
                    expected: expectedRevealTypeText,
                    received: typeString,
                }), expectedRevealTypeNode !== null && expectedRevealTypeNode !== void 0 ? expectedRevealTypeNode : arg0Value);
            }
        }
        addInformation(localize_1.LocAddendum.typeOfSymbol().format({ name: exprString, type: typeString }), node.arguments[0]);
        return { type, isIncomplete: typeResult.isIncomplete };
    }
    function getTypeOfRevealLocals(node) {
        let curNode = node;
        let scope;
        while (curNode) {
            scope = ScopeUtils.getScopeForNode(curNode);
            // Stop when we get a valid scope that's not a list comprehension
            // scope. That includes lambdas, functions, classes, and modules.
            if (scope && scope.type !== 0 /* ScopeType.ListComprehension */) {
                break;
            }
            curNode = curNode.parent;
        }
        const infoMessages = [];
        if (scope) {
            scope.symbolTable.forEach((symbol, name) => {
                if (!symbol.isIgnoredForProtocolMatch()) {
                    const typeOfSymbol = getEffectiveTypeOfSymbol(symbol);
                    infoMessages.push(localize_1.LocAddendum.typeOfSymbol().format({
                        name,
                        type: printType(typeOfSymbol, { expandTypeAlias: true }),
                    }));
                }
            });
        }
        if (infoMessages.length > 0) {
            addInformation(infoMessages.join('\n'), node);
        }
        else {
            addInformation(localize_1.LocMessage.revealLocalsNone(), node);
        }
        return getNoneType();
    }
    function getTypeOfSuperCall(node) {
        var _a;
        if (node.arguments.length > 2) {
            addError(localize_1.LocMessage.superCallArgCount(), node.arguments[2]);
        }
        const enclosingFunction = ParseTreeUtils.getEnclosingFunctionEvaluationScope(node);
        const enclosingClass = enclosingFunction ? ParseTreeUtils.getEnclosingClass(enclosingFunction) : undefined;
        const enclosingClassType = enclosingClass ? (_a = getTypeOfClass(enclosingClass)) === null || _a === void 0 ? void 0 : _a.classType : undefined;
        // Determine which class the "super" call is applied to. If
        // there is no first argument, then the class is implicit.
        let targetClassType;
        if (node.arguments.length > 0) {
            targetClassType = getTypeOfExpression(node.arguments[0].valueExpression).type;
            const concreteTargetClassType = makeTopLevelTypeVarsConcrete(targetClassType);
            if (!(0, types_1.isAnyOrUnknown)(concreteTargetClassType) && !(0, types_1.isInstantiableClass)(concreteTargetClassType)) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.superCallFirstArg().format({ type: printType(targetClassType) }), node.arguments[0].valueExpression);
            }
        }
        else {
            if (enclosingClassType) {
                targetClassType = enclosingClassType !== null && enclosingClassType !== void 0 ? enclosingClassType : types_1.UnknownType.create();
                // Zero-argument forms of super are not allowed within static methods.
                // This results in a runtime exception.
                if (enclosingFunction) {
                    const functionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, enclosingFunction, 
                    /* isInClass */ true);
                    if (((functionInfo === null || functionInfo === void 0 ? void 0 : functionInfo.flags) & 4 /* FunctionTypeFlags.StaticMethod */) !== 0) {
                        addError(localize_1.LocMessage.superCallZeroArgFormStaticMethod(), node.leftExpression);
                        targetClassType = types_1.UnknownType.create();
                    }
                }
            }
            else {
                addError(localize_1.LocMessage.superCallZeroArgForm(), node.leftExpression);
                targetClassType = types_1.UnknownType.create();
            }
        }
        // Determine whether to further narrow the type.
        let bindToType;
        if (node.arguments.length > 1) {
            const secondArgType = makeTopLevelTypeVarsConcrete(getTypeOfExpression(node.arguments[1].valueExpression).type);
            let reportError = false;
            if ((0, types_1.isAnyOrUnknown)(secondArgType)) {
                // Ignore unknown or any types.
            }
            else if ((0, types_1.isClassInstance)(secondArgType)) {
                if ((0, types_1.isInstantiableClass)(targetClassType)) {
                    if (!(0, typeUtils_1.derivesFromClassRecursive)(types_1.ClassType.cloneAsInstantiable(secondArgType), targetClassType, 
                    /* ignoreUnknown */ true)) {
                        reportError = true;
                    }
                }
                bindToType = secondArgType;
            }
            else if ((0, types_1.isInstantiableClass)(secondArgType)) {
                if ((0, types_1.isInstantiableClass)(targetClassType)) {
                    if (!types_1.ClassType.isBuiltIn(targetClassType, 'type') &&
                        !(0, typeUtils_1.derivesFromClassRecursive)(secondArgType, targetClassType, /* ignoreUnknown */ true)) {
                        reportError = true;
                    }
                }
                bindToType = secondArgType;
            }
            else {
                reportError = true;
            }
            if (reportError) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.superCallSecondArg().format({ type: printType(targetClassType) }), node.arguments[1].valueExpression);
                return { type: types_1.UnknownType.create() };
            }
        }
        else if (enclosingClassType) {
            bindToType = types_1.ClassType.cloneAsInstance(enclosingClassType);
            // Get the type from the self or cls parameter if it is explicitly annotated.
            // If it's a TypeVar, change the bindToType into a conditional type.
            const enclosingMethod = ParseTreeUtils.getEnclosingFunction(node);
            let implicitBindToType;
            if (enclosingMethod) {
                const methodTypeInfo = getTypeOfFunction(enclosingMethod);
                if (methodTypeInfo) {
                    const methodType = methodTypeInfo.functionType;
                    if (types_1.FunctionType.isClassMethod(methodType) ||
                        types_1.FunctionType.isConstructorMethod(methodType) ||
                        types_1.FunctionType.isInstanceMethod(methodType)) {
                        if (methodType.details.parameters.length > 0 &&
                            methodType.details.parameters[0].hasDeclaredType) {
                            implicitBindToType = makeTopLevelTypeVarsConcrete(methodType.details.parameters[0].type);
                        }
                    }
                }
            }
            if (bindToType && implicitBindToType) {
                const typeCondition = (0, typeUtils_1.getTypeCondition)(implicitBindToType);
                if (typeCondition) {
                    bindToType = (0, typeUtils_1.addConditionToType)(bindToType, typeCondition);
                }
                else if ((0, types_1.isClass)(implicitBindToType)) {
                    bindToType = implicitBindToType;
                }
            }
        }
        // Determine whether super() should return an instance of the class or
        // the class itself. It depends on whether the super() call is located
        // within an instance method or not.
        let resultIsInstance = true;
        if (node.arguments.length <= 1) {
            const enclosingMethod = ParseTreeUtils.getEnclosingFunction(node);
            if (enclosingMethod) {
                const methodType = getTypeOfFunction(enclosingMethod);
                if (methodType) {
                    if (types_1.FunctionType.isStaticMethod(methodType.functionType) ||
                        types_1.FunctionType.isConstructorMethod(methodType.functionType) ||
                        types_1.FunctionType.isClassMethod(methodType.functionType)) {
                        resultIsInstance = false;
                    }
                }
            }
        }
        // Python docs indicate that super() isn't valid for
        // operations other than member accesses or attribute lookups.
        const parentNode = node.parent;
        if ((parentNode === null || parentNode === void 0 ? void 0 : parentNode.nodeType) === 35 /* ParseNodeType.MemberAccess */) {
            const memberName = parentNode.memberName.value;
            let effectiveTargetClass = (0, types_1.isClass)(targetClassType) ? targetClassType : undefined;
            // If the bind-to type is a protocol, don't use the effective target class.
            // This pattern is used for mixins, where the mixin type is a protocol class
            // that is used to decorate the "self" or "cls" parameter.
            let isProtocolClass = false;
            if (bindToType &&
                types_1.ClassType.isProtocolClass(bindToType) &&
                effectiveTargetClass &&
                !types_1.ClassType.isSameGenericClass(bindToType, effectiveTargetClass)) {
                isProtocolClass = true;
                effectiveTargetClass = undefined;
            }
            const lookupResults = bindToType
                ? (0, typeUtils_1.lookUpClassMember)(bindToType, memberName, 0 /* MemberAccessFlags.Default */, effectiveTargetClass)
                : undefined;
            let resultType;
            if (lookupResults && (0, types_1.isInstantiableClass)(lookupResults.classType)) {
                resultType = lookupResults.classType;
                if (isProtocolClass) {
                    // If the bindToType is a protocol class, set the "include subclasses" flag
                    // so we don't enforce that called methods are implemented within the protocol.
                    resultType = types_1.ClassType.cloneIncludeSubclasses(resultType);
                }
            }
            else if (effectiveTargetClass &&
                !(0, types_1.isAnyOrUnknown)(effectiveTargetClass) &&
                !(0, typeUtils_1.derivesFromAnyOrUnknown)(effectiveTargetClass) &&
                objectType &&
                (0, types_1.isClassInstance)(objectType)) {
                resultType = types_1.ClassType.cloneAsInstantiable(objectType);
            }
            else {
                resultType = types_1.UnknownType.create();
            }
            return {
                type: resultIsInstance ? (0, typeUtils_1.convertToInstance)(resultType, /* includeSubclasses */ false) : resultType,
                bindToSelfType: bindToType
                    ? types_1.TypeBase.cloneForCondition((0, typeUtils_1.synthesizeTypeVarForSelfCls)(types_1.ClassType.cloneIncludeSubclasses(bindToType, /* includeSubclasses */ false), 
                    /* isClsParam */ false), bindToType.condition)
                    : undefined,
            };
        }
        // Handle the super() call when used outside of a member access expression.
        if ((0, types_1.isInstantiableClass)(targetClassType)) {
            // We don't know which member is going to be accessed, so we cannot
            // deterministically determine the correct type in this case. We'll
            // use a heuristic that produces the "correct" (desired) behavior in
            // most cases. If there's a bindToType and the targetClassType is one
            // of the base classes of the bindToType, we'll return the next base
            // class.
            if (bindToType) {
                let nextBaseClassType;
                if (types_1.ClassType.isSameGenericClass(bindToType, targetClassType)) {
                    if (bindToType.details.baseClasses.length > 0) {
                        nextBaseClassType = bindToType.details.baseClasses[0];
                    }
                }
                else {
                    const baseClassIndex = bindToType.details.baseClasses.findIndex((baseClass) => (0, types_1.isClass)(baseClass) && types_1.ClassType.isSameGenericClass(baseClass, targetClassType));
                    if (baseClassIndex >= 0 && baseClassIndex < bindToType.details.baseClasses.length - 1) {
                        nextBaseClassType = bindToType.details.baseClasses[baseClassIndex + 1];
                    }
                }
                if (nextBaseClassType) {
                    if ((0, types_1.isInstantiableClass)(nextBaseClassType)) {
                        nextBaseClassType = (0, typeUtils_1.specializeForBaseClass)(bindToType, nextBaseClassType);
                    }
                    return { type: resultIsInstance ? (0, typeUtils_1.convertToInstance)(nextBaseClassType) : nextBaseClassType };
                }
                // There's not much we can say about the type. Simply return object or type.
                if (objectType && (0, types_1.isClassInstance)(objectType) && typeClassType && (0, types_1.isInstantiableClass)(typeClassType)) {
                    return {
                        type: resultIsInstance ? objectType : (0, typeUtils_1.convertToInstance)(typeClassType),
                    };
                }
            }
            else {
                // If the class derives from one or more unknown classes,
                // return unknown here to prevent spurious errors.
                if (targetClassType.details.mro.some((mroBase) => (0, types_1.isAnyOrUnknown)(mroBase))) {
                    return { type: types_1.UnknownType.create() };
                }
                const baseClasses = targetClassType.details.baseClasses;
                if (baseClasses.length > 0) {
                    const baseClassType = baseClasses[0];
                    if ((0, types_1.isInstantiableClass)(baseClassType)) {
                        return {
                            type: resultIsInstance ? types_1.ClassType.cloneAsInstance(baseClassType) : baseClassType,
                        };
                    }
                }
            }
        }
        return { type: types_1.UnknownType.create() };
    }
    // Attempts to find an overloaded function for each set of argument
    // types in the expandedArgTypes list. If an argument type is undefined,
    // its type is evaluated from the argument's expression using the
    // corresponding parameter's expected type. The first time this is called,
    // there will be only one argument list in expandedArgTypes, and all entries
    // (one for each argument) will be undefined. On subsequent calls, this
    // list will grow to include union expansions.
    function validateOverloadsWithExpandedTypes(errorNode, expandedArgTypes, argParamMatches, typeVarContext, skipUnknownArgCheck, inferenceContext) {
        var _a, _b;
        const returnTypes = [];
        const matchedOverloads = [];
        let isTypeIncomplete = false;
        let overloadsUsedForCall = [];
        let isDefinitiveMatchFound = false;
        for (let expandedTypesIndex = 0; expandedTypesIndex < expandedArgTypes.length; expandedTypesIndex++) {
            let matchedOverload;
            const argTypeOverride = expandedArgTypes[expandedTypesIndex];
            const hasArgTypeOverride = argTypeOverride.some((a) => a !== undefined);
            let possibleMatchResults = [];
            let possibleMatchInvolvesIncompleteUnknown = false;
            isDefinitiveMatchFound = false;
            for (let overloadIndex = 0; overloadIndex < argParamMatches.length; overloadIndex++) {
                const overload = argParamMatches[overloadIndex].overload;
                let matchResults = argParamMatches[overloadIndex];
                if (hasArgTypeOverride) {
                    matchResults = { ...argParamMatches[overloadIndex] };
                    matchResults.argParams = matchResults.argParams.map((argParam, argIndex) => {
                        if (!argTypeOverride[argIndex]) {
                            return argParam;
                        }
                        const argParamCopy = { ...argParam };
                        argParamCopy.argType = argTypeOverride[argIndex];
                        return argParamCopy;
                    });
                }
                // Clone the typeVarContext so we don't modify the original.
                const effectiveTypeVarContext = (_a = typeVarContext === null || typeVarContext === void 0 ? void 0 : typeVarContext.clone()) !== null && _a !== void 0 ? _a : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overload));
                effectiveTypeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeIds)(overload));
                effectiveTypeVarContext.unlock();
                // Use speculative mode so we don't output any diagnostics or
                // record any final types in the type cache.
                const callResult = useSpeculativeMode(errorNode, () => {
                    return validateFunctionArgumentTypesWithContext(errorNode, matchResults, effectiveTypeVarContext, 
                    /* skipUnknownArgCheck */ true, inferenceContext);
                });
                if (callResult.isTypeIncomplete) {
                    isTypeIncomplete = true;
                }
                if (!callResult.argumentErrors && callResult.returnType) {
                    overloadsUsedForCall.push(overload);
                    matchedOverload = overload;
                    const matchedOverloadInfo = {
                        overload: matchedOverload,
                        matchResults,
                        typeVarContext: effectiveTypeVarContext,
                        returnType: callResult.returnType,
                        argResults: (_b = callResult.argResults) !== null && _b !== void 0 ? _b : [],
                    };
                    matchedOverloads.push(matchedOverloadInfo);
                    if (callResult.anyOrUnknownArgument) {
                        possibleMatchResults.push(matchedOverloadInfo);
                        if ((0, typeUtils_1.isIncompleteUnknown)(callResult.anyOrUnknownArgument)) {
                            possibleMatchInvolvesIncompleteUnknown = true;
                        }
                    }
                    else {
                        returnTypes.push(callResult.returnType);
                        isDefinitiveMatchFound = true;
                        break;
                    }
                }
            }
            // If we didn't find a definitive match that doesn't depend on
            // an Any or Unknown argument, fall back on the possible match.
            // If there were multiple possible matches, evaluate the type as
            // Unknown, but include the "possible types" to allow for completion
            // suggestions.
            if (!isDefinitiveMatchFound && possibleMatchResults.length > 0) {
                possibleMatchResults = filterOverloadMatchesForAnyArgs(possibleMatchResults);
                // Did the filtering produce a single result? If so, we're done.
                if (possibleMatchResults.length === 1) {
                    overloadsUsedForCall = [possibleMatchResults[0].overload];
                    returnTypes.push(possibleMatchResults[0].returnType);
                }
                else {
                    // Eliminate any return types that are subsumed by other return types.
                    let dedupedMatchResults = [];
                    let dedupedResultsIncludeAny = false;
                    possibleMatchResults.forEach((result) => {
                        let isSubtypeSubsumed = false;
                        for (let dedupedIndex = 0; dedupedIndex < dedupedMatchResults.length; dedupedIndex++) {
                            if (assignType(dedupedMatchResults[dedupedIndex], result.returnType)) {
                                const anyOrUnknown = (0, typeUtils_1.containsAnyOrUnknown)(dedupedMatchResults[dedupedIndex], 
                                /* recurse */ false);
                                if (!anyOrUnknown) {
                                    isSubtypeSubsumed = true;
                                }
                                else if ((0, types_1.isAny)(anyOrUnknown)) {
                                    dedupedResultsIncludeAny = true;
                                }
                                break;
                            }
                            else if (assignType(result.returnType, dedupedMatchResults[dedupedIndex])) {
                                const anyOrUnknown = (0, typeUtils_1.containsAnyOrUnknown)(result.returnType, /* recurse */ false);
                                if (!anyOrUnknown) {
                                    dedupedMatchResults[dedupedIndex] = types_1.NeverType.createNever();
                                }
                                else if ((0, types_1.isAny)(anyOrUnknown)) {
                                    dedupedResultsIncludeAny = true;
                                }
                                break;
                            }
                        }
                        if (!isSubtypeSubsumed) {
                            dedupedMatchResults.push(result.returnType);
                        }
                    });
                    dedupedMatchResults = dedupedMatchResults.filter((t) => !(0, types_1.isNever)(t));
                    const combinedTypes = (0, types_1.combineTypes)(dedupedMatchResults);
                    let effectiveReturnType = combinedTypes;
                    if (dedupedMatchResults.length > 1) {
                        // If one or more of the deduped types is Any or contains Any,
                        // we will assume that the person who defined the overload really
                        // wanted Any rather than Unknown. In cases where the deduped types
                        // simply contains conflicting results without an Any, we'll use
                        // an UnknownType.
                        if (dedupedResultsIncludeAny) {
                            effectiveReturnType = types_1.AnyType.create();
                        }
                        else {
                            effectiveReturnType = types_1.UnknownType.createPossibleType(combinedTypes, possibleMatchInvolvesIncompleteUnknown);
                        }
                    }
                    returnTypes.push(effectiveReturnType);
                }
            }
            if (!matchedOverload) {
                return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall };
            }
        }
        // We found a match for all of the expanded argument lists. Copy the
        // resulting type var context back into the caller's type var context.
        // Use the type var context from the last matched overload because it
        // includes the type var solutions for all earlier matched overloads.
        if (typeVarContext && isDefinitiveMatchFound) {
            typeVarContext.copyFromClone(matchedOverloads[matchedOverloads.length - 1].typeVarContext);
        }
        // And run through the first expanded argument list one more time to
        // populate the type cache.
        const finalTypeVarContext = typeVarContext !== null && typeVarContext !== void 0 ? typeVarContext : matchedOverloads[0].typeVarContext;
        finalTypeVarContext.unlock();
        finalTypeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(matchedOverloads[0].overload));
        const finalCallResult = validateFunctionArgumentTypesWithContext(errorNode, matchedOverloads[0].matchResults, finalTypeVarContext, skipUnknownArgCheck, inferenceContext);
        if (finalCallResult.isTypeIncomplete) {
            isTypeIncomplete = true;
        }
        return {
            argumentErrors: finalCallResult.argumentErrors,
            anyOrUnknownArgument: finalCallResult.anyOrUnknownArgument,
            returnType: (0, types_1.combineTypes)(returnTypes),
            isTypeIncomplete,
            specializedInitSelfType: finalCallResult.specializedInitSelfType,
            overloadsUsedForCall,
        };
    }
    // This function determines whether multiple incompatible overloads match
    // due to an Any or Unknown argument type.
    function filterOverloadMatchesForAnyArgs(matches) {
        if (matches.length < 2) {
            return matches;
        }
        // If the relevance of some matches differs, filter out the ones that
        // are lower relevance. This favors *args parameters in cases where
        // a *args argument is used.
        if (matches[0].matchResults.relevance !== matches[matches.length - 1].matchResults.relevance) {
            matches = matches.filter((m) => m.matchResults.relevance === matches[0].matchResults.relevance);
            if (matches.length < 2) {
                return matches;
            }
        }
        // If all of the return types match, select the first one.
        if ((0, typeUtils_1.areTypesSame)(matches.map((match) => match.returnType), { treatAnySameAsUnknown: true })) {
            return [matches[0]];
        }
        const firstArgResults = matches[0].argResults;
        if (!firstArgResults) {
            return matches;
        }
        let foundAmbiguousAnyArg = false;
        for (let i = 0; i < firstArgResults.length; i++) {
            // If the arg is Any or Unknown, see if the corresponding
            // parameter types differ in any way.
            if ((0, types_1.isAnyOrUnknown)(firstArgResults[i].argType)) {
                const paramTypes = matches.map((match) => i < match.matchResults.argParams.length
                    ? match.matchResults.argParams[i].paramType
                    : types_1.UnknownType.create());
                if (!(0, typeUtils_1.areTypesSame)(paramTypes, { treatAnySameAsUnknown: true })) {
                    foundAmbiguousAnyArg = true;
                }
            }
        }
        // If the first overload has a different number of effective arguments
        // than latter overloads, don't filter any of them. This typically means
        // that one of the arguments is an unpacked iterator, and it maps to
        // an indeterminate number of parameters, which means that the overload
        // selection is ambiguous.
        if (foundAmbiguousAnyArg || matches.some((match) => match.argResults.length !== firstArgResults.length)) {
            return matches;
        }
        return [matches[0]];
    }
    function getBestOverloadForArguments(errorNode, typeResult, argList) {
        let overloadIndex = 0;
        let matches = [];
        const signatureTracker = new typeUtils_1.UniqueSignatureTracker();
        // Create a list of potential overload matches based on arguments.
        types_1.OverloadedFunctionType.getOverloads(typeResult.type).forEach((overload) => {
            useSpeculativeMode(errorNode, () => {
                const matchResults = matchFunctionArgumentsToParameters(errorNode, argList, { type: overload, isIncomplete: typeResult.isIncomplete }, overloadIndex);
                if (!matchResults.argumentErrors) {
                    matches.push(matchResults);
                }
                overloadIndex++;
            });
        });
        matches = sortOverloadsByBestMatch(matches);
        let winningOverloadIndex;
        matches.forEach((match, matchIndex) => {
            if (winningOverloadIndex === undefined) {
                useSpeculativeMode(errorNode, () => {
                    const callResult = validateFunctionArgumentTypes(errorNode, match, new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(match.overload)), signatureTracker, 
                    /* skipUnknownArgCheck */ true);
                    if (callResult && !callResult.argumentErrors) {
                        winningOverloadIndex = matchIndex;
                    }
                });
            }
        });
        return winningOverloadIndex === undefined ? undefined : matches[winningOverloadIndex].overload;
    }
    // Sorts the list of overloads based first on "relevance" and second on order.
    function sortOverloadsByBestMatch(matches) {
        return matches.sort((a, b) => {
            if (a.relevance !== b.relevance) {
                return b.relevance - a.relevance;
            }
            return a.overloadIndex - b.overloadIndex;
        });
    }
    function validateOverloadedFunctionArguments(errorNode, argList, typeResult, typeVarContext, skipUnknownArgCheck, inferenceContext) {
        let filteredMatchResults = [];
        let contextFreeArgTypes;
        let isTypeIncomplete = !!typeResult.isIncomplete;
        // Start by evaluating the types of the arguments without any expected
        // type. Also, filter the list of overloads based on the number of
        // positional and named arguments that are present. We do all of this
        // speculatively because we don't want to record any types in the type
        // cache or record any diagnostics at this stage.
        useSpeculativeMode(errorNode, () => {
            let overloadIndex = 0;
            types_1.OverloadedFunctionType.getOverloads(typeResult.type).forEach((overload) => {
                // Consider only the functions that have the @overload decorator,
                // not the final function that omits the overload. This is the
                // intended behavior according to PEP 484.
                const matchResults = matchFunctionArgumentsToParameters(errorNode, argList, { type: overload, isIncomplete: typeResult.isIncomplete }, overloadIndex);
                if (!matchResults.argumentErrors) {
                    filteredMatchResults.push(matchResults);
                }
                overloadIndex++;
            });
        });
        filteredMatchResults = sortOverloadsByBestMatch(filteredMatchResults);
        // If there are no possible arg/param matches among the overloads,
        // emit an error that includes the argument types.
        if (filteredMatchResults.length === 0) {
            // Skip the error message if we're in speculative mode because it's very
            // expensive, and we're going to suppress the diagnostic anyway.
            if (!isDiagnosticSuppressedForNode(errorNode)) {
                const functionName = typeResult.type.overloads[0].details.name || '<anonymous function>';
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                const argTypes = argList.map((t) => {
                    const typeString = printType(getTypeOfArgument(t).type);
                    if (t.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                        return `*${typeString}`;
                    }
                    if (t.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */) {
                        return `**${typeString}`;
                    }
                    return typeString;
                });
                diagAddendum.addMessage(localize_1.LocAddendum.argumentTypes().format({ types: argTypes.join(', ') }));
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.noOverload().format({ name: functionName }) + diagAddendum.getString(), errorNode);
            }
            return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall: [] };
        }
        // Create a helper function that evaluates the overload that best
        // matches the arg/param lists.
        function evaluateUsingBestMatchingOverload(skipUnknownArgCheck, emitNoOverloadFoundError) {
            // Find the match with the smallest argument match score. If there
            // are more than one with the same score, use the one with the
            // largest index. Later overloads tend to be more general.
            const bestMatch = filteredMatchResults.reduce((previous, current) => {
                if (current.argumentMatchScore === previous.argumentMatchScore) {
                    return current.overloadIndex > previous.overloadIndex ? current : previous;
                }
                return current.argumentMatchScore < previous.argumentMatchScore ? current : previous;
            });
            // If there is more than one filtered match, report that no match
            // was possible and emit a diagnostic that provides the most likely.
            if (emitNoOverloadFoundError) {
                const functionName = bestMatch.overload.details.name || '<anonymous function>';
                const diagnostic = addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.noOverload().format({ name: functionName }), errorNode);
                const overrideDecl = bestMatch.overload.details.declaration;
                if (diagnostic && overrideDecl) {
                    diagnostic.addRelatedInfo(localize_1.LocAddendum.overloadIndex().format({ index: bestMatch.overloadIndex + 1 }), overrideDecl.uri, overrideDecl.range);
                }
            }
            const effectiveTypeVarContext = typeVarContext !== null && typeVarContext !== void 0 ? typeVarContext : new typeVarContext_1.TypeVarContext();
            effectiveTypeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeIds)(bestMatch.overload));
            effectiveTypeVarContext.unlock();
            return validateFunctionArgumentTypesWithContext(errorNode, bestMatch, effectiveTypeVarContext, skipUnknownArgCheck, inferenceContext);
        }
        // If there is only one possible arg/param match among the overloads,
        // use the normal type matching mechanism because it is faster and
        // will provide a clearer error message.
        if (filteredMatchResults.length === 1) {
            return evaluateUsingBestMatchingOverload(
            /* skipUnknownArgCheck */ false, 
            /* emitNoOverloadFoundError */ false);
        }
        let expandedArgTypes = [argList.map((arg) => undefined)];
        while (true) {
            const callResult = validateOverloadsWithExpandedTypes(errorNode, expandedArgTypes, filteredMatchResults, typeVarContext, skipUnknownArgCheck, inferenceContext);
            if (callResult.isTypeIncomplete) {
                isTypeIncomplete = true;
            }
            if (!callResult.argumentErrors) {
                return callResult;
            }
            // We didn't find an overload match. Try to expand the next union
            // argument type into individual types and retry with the expanded types.
            if (!contextFreeArgTypes) {
                useSpeculativeMode(errorNode, () => {
                    // Evaluate the types of each argument expression without regard to
                    // the context. We'll use this to determine whether we need to do
                    // union expansion.
                    contextFreeArgTypes = argList.map((arg) => {
                        if (arg.typeResult) {
                            return arg.typeResult.type;
                        }
                        if (arg.valueExpression) {
                            const valueExpressionNode = arg.valueExpression;
                            return useSpeculativeMode(valueExpressionNode, () => {
                                return getTypeOfExpression(valueExpressionNode).type;
                            });
                        }
                        return types_1.AnyType.create();
                    });
                });
            }
            expandedArgTypes = expandArgumentUnionTypes(contextFreeArgTypes, expandedArgTypes);
            // Check for combinatoric explosion and break out of loop.
            if (!expandedArgTypes || expandedArgTypes.length > maxOverloadUnionExpansionCount) {
                break;
            }
        }
        // We couldn't find any valid overloads. Skip the error message if we're
        // in speculative mode because it's very expensive, and we're going to
        // suppress the diagnostic anyway.
        if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
            const result = evaluateUsingBestMatchingOverload(
            /* skipUnknownArgCheck */ true, 
            /* emitNoOverloadFoundError */ true);
            // Replace the result with an unknown type since we don't know
            // what overload should have been used.
            result.returnType = types_1.UnknownType.create();
            return { ...result, argumentErrors: true };
        }
        return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall: [] };
    }
    // Replaces each item in the expandedArgTypes with n items where n is
    // the number of subtypes in a union. The contextFreeArgTypes parameter
    // represents the types of the arguments evaluated with no bidirectional
    // type inference (i.e. without the help of the corresponding parameter's
    // expected type). If the function returns undefined, that indicates that
    // all unions have been expanded, and no more expansion is possible.
    function expandArgumentUnionTypes(contextFreeArgTypes, expandedArgTypes) {
        // Find the rightmost already-expanded argument.
        let indexToExpand = contextFreeArgTypes.length - 1;
        while (indexToExpand >= 0 && !expandedArgTypes[0][indexToExpand]) {
            indexToExpand--;
        }
        // Move to the next candidate for expansion.
        indexToExpand++;
        if (indexToExpand >= contextFreeArgTypes.length) {
            return undefined;
        }
        let unionToExpand;
        while (indexToExpand < contextFreeArgTypes.length) {
            // Is this a union type? If so, we can expand it.
            const argType = contextFreeArgTypes[indexToExpand];
            if ((0, types_1.isUnion)(argType)) {
                unionToExpand = makeTopLevelTypeVarsConcrete(argType);
                break;
            }
            else if ((0, types_1.isTypeVar)(argType) && argType.details.constraints.length > 1) {
                unionToExpand = makeTopLevelTypeVarsConcrete(argType);
                break;
            }
            indexToExpand++;
        }
        // We have nothing left to expand.
        if (!unionToExpand) {
            return undefined;
        }
        // Expand entry indexToExpand.
        const newExpandedArgTypes = [];
        expandedArgTypes.forEach((preExpandedTypes) => {
            (0, typeUtils_1.doForEachSubtype)(unionToExpand, (subtype) => {
                const expandedTypes = [...preExpandedTypes];
                expandedTypes[indexToExpand] = subtype;
                newExpandedArgTypes.push(expandedTypes);
            });
        });
        return newExpandedArgTypes;
    }
    // Validates that the arguments can be assigned to the call's parameter
    // list, specializes the call based on arg types, and returns the
    // specialized type of the return value. If it detects an error along
    // the way, it emits a diagnostic and sets argumentErrors to true.
    function validateCallArguments(errorNode, argList, callTypeResult, typeVarContext, skipUnknownArgCheck = false, inferenceContext, recursionCount = 0) {
        let argumentErrors = false;
        let isTypeIncomplete = false;
        let specializedInitSelfType;
        const overloadsUsedForCall = [];
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return { returnType: types_1.UnknownType.create(), argumentErrors: true, overloadsUsedForCall };
        }
        recursionCount++;
        // Special forms are not callable.
        if (callTypeResult.type.specialForm) {
            const exprNode = errorNode.nodeType === 9 /* ParseNodeType.Call */ ? errorNode.leftExpression : errorNode;
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.objectNotCallable().format({
                type: printType(callTypeResult.type.specialForm, { expandTypeAlias: true }),
            }), exprNode);
            return { returnType: types_1.UnknownType.create(), argumentErrors: true, overloadsUsedForCall };
        }
        let returnType = mapSubtypesExpandTypeVars(callTypeResult.type, { sortSubtypes: true }, (expandedSubtype, unexpandedSubtype, isLastIteration) => {
            return useSpeculativeMode(isLastIteration ? undefined : errorNode, () => {
                const callResult = validateCallArgumentsForSubtype(errorNode, argList, expandedSubtype, unexpandedSubtype, !!callTypeResult.isIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount);
                if (callResult.argumentErrors) {
                    argumentErrors = true;
                }
                if (callResult.isTypeIncomplete) {
                    isTypeIncomplete = true;
                }
                if (callResult.overloadsUsedForCall) {
                    (0, collectionUtils_1.appendArray)(overloadsUsedForCall, callResult.overloadsUsedForCall);
                }
                specializedInitSelfType = callResult.specializedInitSelfType;
                return callResult.returnType;
            }, {
                allowDiagnostics: true,
            });
        });
        // If we ended up with a "Never" type because all code paths returned
        // undefined due to argument errors, transform the result into an Unknown
        // to avoid subsequent false positives.
        if (argumentErrors && (0, types_1.isNever)(returnType) && !returnType.isNoReturn) {
            returnType = types_1.UnknownType.create();
        }
        return {
            argumentErrors,
            returnType,
            isTypeIncomplete,
            specializedInitSelfType,
            overloadsUsedForCall,
        };
    }
    function validateCallArgumentsForSubtype(errorNode, argList, expandedCallType, unexpandedCallType, isCallTypeIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount) {
        switch (expandedCallType.category) {
            case 3 /* TypeCategory.Never */:
            case 1 /* TypeCategory.Unknown */:
            case 2 /* TypeCategory.Any */: {
                // Touch all of the args so they're marked accessed. Don't bother
                // doing this if the call type is incomplete because this will need
                // to be done again once it is complete.
                if (!isCallTypeIncomplete) {
                    argList.forEach((arg) => {
                        if (arg.valueExpression && !isSpeculativeModeInUse(arg.valueExpression)) {
                            getTypeOfArgument(arg);
                        }
                    });
                }
                return { returnType: expandedCallType };
            }
            case 4 /* TypeCategory.Function */: {
                return validateCallForFunction(errorNode, argList, expandedCallType, isCallTypeIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext);
            }
            case 5 /* TypeCategory.OverloadedFunction */: {
                return validateCallForOverloadedFunction(errorNode, argList, expandedCallType, isCallTypeIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext);
            }
            case 6 /* TypeCategory.Class */: {
                if ((0, typeUtils_1.isNoneInstance)(expandedCallType)) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalCall, localize_1.LocMessage.noneNotCallable(), errorNode);
                    return { argumentErrors: true };
                }
                if (types_1.TypeBase.isInstantiable(expandedCallType)) {
                    return validateCallForInstantiableClass(errorNode, argList, expandedCallType, unexpandedCallType, skipUnknownArgCheck, inferenceContext);
                }
                return validateCallForClassInstance(errorNode, argList, expandedCallType, unexpandedCallType, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount);
            }
            // TypeVars should have been expanded in most cases,
            // but we still need to handle the case of Type[T] where
            // T is a constrained type that contains a union. We also
            // need to handle recursive type aliases.
            case 9 /* TypeCategory.TypeVar */: {
                return validateCallArguments(errorNode, argList, { type: (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(expandedCallType), isIncomplete: isCallTypeIncomplete }, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount);
            }
            case 7 /* TypeCategory.Module */: {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.moduleNotCallable(), errorNode);
                return { argumentErrors: true };
            }
        }
        return { argumentErrors: true };
    }
    function validateCallForFunction(errorNode, argList, expandedCallType, isCallTypeIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext) {
        var _a;
        if (types_1.TypeBase.isInstantiable(expandedCallType)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.callableNotInstantiable().format({
                type: printType(expandedCallType),
            }), errorNode);
            return { returnType: undefined, argumentErrors: true };
        }
        let effectiveTypeVarContext = typeVarContext;
        if (!effectiveTypeVarContext) {
            // If a typeVarContext wasn't provided by the caller, allocate one here.
            effectiveTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeIds)(expandedCallType));
        }
        // The stdlib collections/__init__.pyi stub file defines namedtuple
        // as a function rather than a class, so we need to check for it here.
        if (expandedCallType.details.builtInName === 'namedtuple') {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUntypedNamedTuple, localize_1.LocMessage.namedTupleNoTypes(), errorNode);
            const result = {
                returnType: (0, namedTuples_1.createNamedTupleType)(evaluatorInterface, errorNode, argList, /* includesTypes */ false),
            };
            validateFunctionArguments(errorNode, argList, { type: expandedCallType }, effectiveTypeVarContext, skipUnknownArgCheck);
            return result;
        }
        // Handle the NewType specially, replacing the normal return type.
        if (expandedCallType.details.builtInName === 'NewType') {
            return { returnType: createNewType(errorNode, argList) };
        }
        const functionResult = validateFunctionArguments(errorNode, argList, { type: expandedCallType, isIncomplete: isCallTypeIncomplete }, effectiveTypeVarContext, skipUnknownArgCheck, inferenceContext);
        let isTypeIncomplete = !!functionResult.isTypeIncomplete;
        let returnType = functionResult.returnType;
        let argumentErrors = !!functionResult.argumentErrors;
        if (!argumentErrors) {
            // Call the function transform logic to handle special-cased functions.
            const transformed = (0, functionTransform_1.applyFunctionTransform)(evaluatorInterface, errorNode, argList, expandedCallType, {
                argumentErrors: !!functionResult.argumentErrors,
                returnType: (_a = functionResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(isTypeIncomplete),
                isTypeIncomplete,
            });
            returnType = transformed.returnType;
            if (transformed.isTypeIncomplete) {
                isTypeIncomplete = true;
            }
            if (transformed.argumentErrors) {
                argumentErrors = true;
            }
        }
        if (expandedCallType.details.builtInName === '__import__') {
            // For the special __import__ type, we'll override the return type to be "Any".
            // This is required because we don't know what module was imported, and we don't
            // want to fail type checks when accessing members of the resulting module type.
            returnType = types_1.AnyType.create();
        }
        return {
            returnType,
            isTypeIncomplete,
            argumentErrors,
            overloadsUsedForCall: functionResult.overloadsUsedForCall,
            specializedInitSelfType: functionResult.specializedInitSelfType,
        };
    }
    // Determines whether a symbol is abstract. In an ABC class, this means a function
    // is specifically decorated with @abstractmethod. In a protocol class, the rules
    // are more complicated and depend on whether the method is defined in a stub file.
    function getAbstractSymbolInfo(classType, symbolName) {
        const isProtocolClass = types_1.ClassType.isProtocolClass(classType);
        const symbol = types_1.ClassType.getSymbolTable(classType).get(symbolName);
        if (!symbol) {
            return undefined;
        }
        // Ignore instance variables. Also, ignore named tuple members, which are
        // modeled in pyright as instance variables, but their runtime implementation
        // uses a descriptor object.
        if (!symbol.isClassMember() && !symbol.isNamedTupleMemberMember()) {
            return undefined;
        }
        const lastDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
        if (!lastDecl) {
            return undefined;
        }
        // Handle protocol variables specially.
        if (isProtocolClass && lastDecl.type === 1 /* DeclarationType.Variable */) {
            // If none of the declarations involve assignments, assume it's
            // not implemented in the protocol.
            const allDecls = symbol.getDeclarations();
            if (!allDecls.some((decl) => decl.type === 1 /* DeclarationType.Variable */ && !!decl.inferredTypeSource)) {
                return { symbol, symbolName, classType, hasImplementation: false };
            }
        }
        if (lastDecl.type !== 5 /* DeclarationType.Function */) {
            return undefined;
        }
        let isAbstract = false;
        const lastFunctionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, lastDecl.node, /* isInClass */ true);
        if ((lastFunctionInfo.flags & 8 /* FunctionTypeFlags.AbstractMethod */) !== 0) {
            isAbstract = true;
        }
        const isStubFile = AnalyzerNodeInfo.getFileInfo(lastDecl.node).isStubFile;
        // In an overloaded method, the first overload can also be marked abstract.
        // In stub files, there is no implementation, so this is the only way to mark
        // an overloaded method as abstract.
        const firstDecl = symbol.getDeclarations()[0];
        let firstFunctionInfo;
        if (firstDecl !== lastDecl && firstDecl.type === 5 /* DeclarationType.Function */) {
            firstFunctionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, firstDecl.node, /* isInClass */ true);
            if ((firstFunctionInfo.flags & 8 /* FunctionTypeFlags.AbstractMethod */) !== 0) {
                isAbstract = true;
            }
            // If there's no implementation, assume it's unimplemented.
            if (isProtocolClass && (lastFunctionInfo.flags & 256 /* FunctionTypeFlags.Overloaded */) !== 0) {
                // If this is a protocol class method defined in a stub file and
                // it's not marked abstract, assume it's not abstract and implemented.
                if (isProtocolClass && !isAbstract && isStubFile) {
                    return undefined;
                }
                return { symbol, symbolName, classType, hasImplementation: false };
            }
        }
        // In a non-protocol class, if the method isn't explicitly marked abstract,
        // then it's not abstract.
        if (!isProtocolClass && !isAbstract) {
            return undefined;
        }
        const hasImplementation = !ParseTreeUtils.isSuiteEmpty(lastDecl.node.suite) && !methodAlwaysRaisesNotImplemented(lastDecl);
        // If this is a protocol class, the method isn't explicitly marked
        // as abstract, and there is an implementation, then it's a default
        // implementation, and it's not considered abstract. If it's in a stub
        // file, assume it's implemented in this case.
        if (isProtocolClass && !isAbstract) {
            if (hasImplementation || isStubFile) {
                return undefined;
            }
        }
        return { symbol, symbolName, classType, hasImplementation };
    }
    function validateCallForOverloadedFunction(errorNode, argList, expandedCallType, isCallTypeIncomplete, typeVarContext, skipUnknownArgCheck, inferenceContext) {
        var _a, _b;
        // Handle the 'cast' call as a special case.
        if (expandedCallType.overloads[0].details.builtInName === 'cast' && argList.length === 2) {
            return { returnType: evaluateCastCall(argList, errorNode) };
        }
        const callResult = validateOverloadedFunctionArguments(errorNode, argList, { type: expandedCallType, isIncomplete: isCallTypeIncomplete }, typeVarContext, skipUnknownArgCheck, inferenceContext);
        let returnType = (_a = callResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        let isTypeIncomplete = !!callResult.isTypeIncomplete;
        let argumentErrors = !!callResult.argumentErrors;
        if (!argumentErrors) {
            // Call the function transform logic to handle special-cased functions.
            const transformed = (0, functionTransform_1.applyFunctionTransform)(evaluatorInterface, errorNode, argList, expandedCallType, {
                argumentErrors: !!callResult.argumentErrors,
                returnType: (_b = callResult.returnType) !== null && _b !== void 0 ? _b : types_1.UnknownType.create(isTypeIncomplete),
                isTypeIncomplete,
            });
            returnType = transformed.returnType;
            if (transformed.isTypeIncomplete) {
                isTypeIncomplete = true;
            }
            if (transformed.argumentErrors) {
                argumentErrors = true;
            }
        }
        return {
            returnType,
            isTypeIncomplete,
            argumentErrors,
            overloadsUsedForCall: callResult.overloadsUsedForCall,
            specializedInitSelfType: callResult.specializedInitSelfType,
        };
    }
    function validateCallForInstantiableClass(errorNode, argList, expandedCallType, unexpandedCallType, skipUnknownArgCheck, inferenceContext) {
        var _a, _b;
        if (expandedCallType.literalValue !== undefined) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.literalNotCallable(), errorNode);
            return { returnType: types_1.UnknownType.create(), argumentErrors: true };
        }
        if (types_1.ClassType.isBuiltIn(expandedCallType)) {
            const className = (_a = expandedCallType.aliasName) !== null && _a !== void 0 ? _a : expandedCallType.details.name;
            // Handle a call to a metaclass explicitly.
            if ((0, typeUtils_1.isInstantiableMetaclass)(expandedCallType)) {
                if (expandedCallType.typeArguments && expandedCallType.isTypeArgumentExplicit) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.objectNotCallable().format({
                        type: printType(expandedCallType),
                    }), errorNode);
                    return { returnType: types_1.UnknownType.create(), argumentErrors: true };
                }
                // Validate the constructor arguments.
                (0, constructors_1.validateConstructorArguments)(evaluatorInterface, errorNode, argList, expandedCallType, skipUnknownArgCheck, inferenceContext);
                // The one-parameter form of "type" returns the class
                // for the specified object.
                if (expandedCallType.details.name === 'type' && argList.length === 1) {
                    const argType = getTypeOfArgument(argList[0]).type;
                    const returnType = (0, typeUtils_1.mapSubtypes)(argType, (subtype) => {
                        var _a;
                        if ((0, types_1.isInstantiableClass)(subtype)) {
                            return (_a = subtype.details.effectiveMetaclass) !== null && _a !== void 0 ? _a : types_1.AnyType.create();
                        }
                        if ((0, types_1.isClassInstance)(subtype) ||
                            ((0, types_1.isTypeVar)(subtype) && types_1.TypeBase.isInstance(subtype)) ||
                            (0, typeUtils_1.isNoneInstance)(subtype)) {
                            return (0, typeUtils_1.convertToInstantiable)(stripLiteralValue(subtype));
                        }
                        if ((0, types_1.isFunction)(subtype) && types_1.TypeBase.isInstance(subtype)) {
                            return types_1.FunctionType.cloneAsInstantiable(subtype);
                        }
                        return types_1.AnyType.create();
                    });
                    return { returnType };
                }
                if (argList.length >= 2) {
                    // The two-parameter form of a call to a metaclass returns a new class
                    // built from the specified base types.
                    return {
                        returnType: createClassFromMetaclass(errorNode, argList, expandedCallType) || types_1.AnyType.create(),
                    };
                }
                // If the parameter to type() is not statically known,
                // fall back to Any.
                return { returnType: types_1.AnyType.create() };
            }
            if (className === 'TypeVar') {
                return {
                    returnType: createTypeVarType(errorNode, expandedCallType, argList),
                };
            }
            if (className === 'TypeVarTuple') {
                return {
                    returnType: createTypeVarTupleType(errorNode, expandedCallType, argList),
                };
            }
            if (className === 'ParamSpec') {
                return {
                    returnType: createParamSpecType(errorNode, expandedCallType, argList),
                };
            }
            if (className === 'TypeAliasType') {
                const newTypeAlias = createTypeAliasType(errorNode, argList);
                if (newTypeAlias) {
                    return { returnType: newTypeAlias };
                }
            }
            if (className === 'NamedTuple') {
                const result = {
                    returnType: (0, namedTuples_1.createNamedTupleType)(evaluatorInterface, errorNode, argList, /* includesTypes */ true),
                };
                const initTypeResult = (0, constructors_1.getBoundInitMethod)(evaluatorInterface, errorNode, types_1.ClassType.cloneAsInstance(expandedCallType), 
                /* diag */ undefined, 0 /* MemberAccessFlags.Default */);
                if (initTypeResult && (0, types_1.isOverloadedFunction)(initTypeResult.type)) {
                    validateOverloadedFunctionArguments(errorNode, argList, { type: initTypeResult.type }, 
                    /* typeVarContext */ undefined, skipUnknownArgCheck, 
                    /* inferenceContext */ undefined);
                }
                return result;
            }
            if (className === 'NewType') {
                return { returnType: createNewType(errorNode, argList) };
            }
            if (types_1.ClassType.isSpecialFormClass(expandedCallType)) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.typeNotIntantiable().format({ type: className }), errorNode);
                return { returnType: types_1.UnknownType.create(), argumentErrors: true };
            }
            if (className === 'TypedDict') {
                return { returnType: (0, typedDicts_1.createTypedDictType)(evaluatorInterface, errorNode, expandedCallType, argList) };
            }
            if (className === 'auto' && argList.length === 0) {
                return { returnType: (0, enums_1.getEnumAutoValueType)(evaluatorInterface, errorNode) };
            }
        }
        // Is it a call to an Enum class factory?
        if ((0, types_1.isClass)(expandedCallType) &&
            expandedCallType.details.effectiveMetaclass &&
            (0, types_1.isClass)(expandedCallType.details.effectiveMetaclass) &&
            (0, enums_1.isEnumMetaclass)(expandedCallType.details.effectiveMetaclass) &&
            !(0, enums_1.isEnumClassWithMembers)(evaluatorInterface, expandedCallType)) {
            return {
                returnType: (_b = (0, enums_1.createEnumType)(evaluatorInterface, errorNode, expandedCallType, argList)) !== null && _b !== void 0 ? _b : (0, typeUtils_1.convertToInstance)(unexpandedCallType),
            };
        }
        if (types_1.ClassType.supportsAbstractMethods(expandedCallType)) {
            const abstractSymbols = getAbstractSymbols(expandedCallType);
            if (abstractSymbols.length > 0 && !expandedCallType.includeSubclasses && !(0, types_1.isTypeVar)(unexpandedCallType)) {
                // If the class is abstract, it can't be instantiated.
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                const errorsToDisplay = 2;
                abstractSymbols.forEach((abstractMethod, index) => {
                    if (index === errorsToDisplay) {
                        diagAddendum.addMessage(localize_1.LocAddendum.memberIsAbstractMore().format({
                            count: abstractSymbols.length - errorsToDisplay,
                        }));
                    }
                    else if (index < errorsToDisplay) {
                        if ((0, types_1.isInstantiableClass)(abstractMethod.classType)) {
                            const className = abstractMethod.classType.details.name;
                            diagAddendum.addMessage(localize_1.LocAddendum.memberIsAbstract().format({
                                type: className,
                                name: abstractMethod.symbolName,
                            }));
                        }
                    }
                });
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAbstractUsage, localize_1.LocMessage.instantiateAbstract().format({
                    type: expandedCallType.details.name,
                }) + diagAddendum.getString(), errorNode);
            }
        }
        if (types_1.ClassType.isProtocolClass(expandedCallType) && !expandedCallType.includeSubclasses) {
            // If the class is a protocol, it can't be instantiated.
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAbstractUsage, localize_1.LocMessage.instantiateProtocol().format({
                type: expandedCallType.details.name,
            }), errorNode);
        }
        // Assume this is a call to the constructor.
        const constructorResult = (0, constructors_1.validateConstructorArguments)(evaluatorInterface, errorNode, argList, expandedCallType, skipUnknownArgCheck, inferenceContext);
        const overloadsUsedForCall = constructorResult.overloadsUsedForCall;
        const argumentErrors = constructorResult.argumentErrors;
        const isTypeIncomplete = constructorResult.isTypeIncomplete;
        let returnType = constructorResult.returnType;
        // If the expandedCallType originated from a TypeVar, convert
        // the constructed type back to the TypeVar. For example, if
        // we have `cls: Type[_T]` followed by `_T()`.
        if ((0, types_1.isTypeVar)(unexpandedCallType)) {
            returnType = (0, typeUtils_1.convertToInstance)(unexpandedCallType);
        }
        // If we instantiated a type, transform it into a class.
        // This can happen if someone directly instantiates a metaclass
        // deriving from type.
        if (returnType &&
            (0, types_1.isClassInstance)(returnType) &&
            returnType.details.mro.some((baseClass) => (0, types_1.isInstantiableClass)(baseClass) && types_1.ClassType.isBuiltIn(baseClass, 'type'))) {
            let newClassName = '__class_' + returnType.details.name;
            if (argList.length === 3) {
                const firstArgType = getTypeOfArgument(argList[0]).type;
                if ((0, types_1.isClassInstance)(firstArgType) &&
                    types_1.ClassType.isBuiltIn(firstArgType, 'str') &&
                    typeof firstArgType.literalValue === 'string') {
                    newClassName = firstArgType.literalValue;
                }
            }
            const newClassType = types_1.ClassType.createInstantiable(newClassName, '', '', AnalyzerNodeInfo.getFileInfo(errorNode).fileUri, 0 /* ClassTypeFlags.None */, ParseTreeUtils.getTypeSourceId(errorNode), types_1.ClassType.cloneAsInstantiable(returnType), types_1.ClassType.cloneAsInstantiable(returnType));
            newClassType.details.baseClasses.push(getBuiltInType(errorNode, 'object'));
            newClassType.details.effectiveMetaclass = expandedCallType;
            newClassType.details.declaration = returnType.details.declaration;
            (0, typeUtils_1.computeMroLinearization)(newClassType);
            returnType = newClassType;
        }
        return { returnType, overloadsUsedForCall, argumentErrors, isTypeIncomplete };
    }
    function validateCallForClassInstance(errorNode, argList, expandedCallType, unexpandedCallType, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount) {
        var _a;
        const callDiag = new diagnostic_1.DiagnosticAddendum();
        const callMethodResult = getTypeOfBoundMember(errorNode, expandedCallType, '__call__', 
        /* usage */ undefined, callDiag, 16 /* MemberAccessFlags.SkipInstanceMembers */ | 512 /* MemberAccessFlags.SkipAttributeAccessOverride */, 
        /* selfType */ undefined, recursionCount);
        const callMethodType = callMethodResult === null || callMethodResult === void 0 ? void 0 : callMethodResult.type;
        if (!callMethodType || callMethodResult.typeErrors) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.objectNotCallable().format({
                type: printType(expandedCallType),
            }) + callDiag.getString(), errorNode);
            return { returnType: types_1.UnknownType.create(), argumentErrors: true };
        }
        const callResult = validateCallArguments(errorNode, argList, { type: callMethodType }, typeVarContext, skipUnknownArgCheck, inferenceContext, recursionCount);
        let returnType = (_a = callResult.returnType) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        if ((0, types_1.isTypeVar)(unexpandedCallType) &&
            types_1.TypeBase.isInstantiable(unexpandedCallType) &&
            (0, types_1.isClass)(expandedCallType) &&
            types_1.ClassType.isBuiltIn(expandedCallType, 'type')) {
            // Handle the case where a type[T] is being called. We presume this
            // will instantiate an object of type T.
            returnType = (0, typeUtils_1.convertToInstance)(unexpandedCallType);
        }
        return {
            returnType,
            argumentErrors: callResult.argumentErrors,
            overloadsUsedForCall: callResult.overloadsUsedForCall,
        };
    }
    // Evaluates the type of the "cast" call.
    function evaluateCastCall(argList, errorNode) {
        // Verify that the cast is necessary.
        const castToType = getTypeOfArgumentExpectingType(argList[0], { enforceTypeAnnotationRules: true }).type;
        let castFromType = getTypeOfArgument(argList[1]).type;
        if (castFromType.specialForm) {
            castFromType = castFromType.specialForm;
        }
        const castToInstance = (0, typeUtils_1.convertToInstance)(castToType);
        const castFromInstance = (0, typeUtils_1.convertToInstance)(castFromType);
        if (types_1.TypeBase.isInstantiable(castToType) && !(0, types_1.isUnknown)(castToType)) {
            if ((0, types_1.isTypeSame)(castToInstance, castFromType, {
                ignorePseudoGeneric: true,
            })) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnnecessaryCast, localize_1.LocMessage.unnecessaryCast().format({
                    type: printType(castFromType),
                }), errorNode);
            }
        }
        if (!typesOverlap(castToInstance, castFromInstance, /* checkEq */ false)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidCast, localize_1.LocMessage.invalidCast().format({
                fromType: printType(castFromType),
                toType: printType(castToInstance),
            }), errorNode);
        }
        return castToInstance;
    }
    /**
     * determines whether two types are overlapping (ie. they can be compared or casted)
     */
    const typesOverlap = (leftType, rightType, checkEq) => {
        if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(rightType)) {
            return true;
        }
        let isComparable = false;
        (0, typeUtils_1.doForEachSubtype)(leftType, (leftSubtype) => {
            if (isComparable) {
                return;
            }
            leftSubtype = makeTopLevelTypeVarsConcrete(leftSubtype);
            (0, typeUtils_1.doForEachSubtype)(rightType, (rightSubtype) => {
                if (isComparable) {
                    return;
                }
                rightSubtype = makeTopLevelTypeVarsConcrete(rightSubtype);
                if (_isTypeComparable(leftSubtype, rightSubtype, checkEq)) {
                    isComparable = true;
                }
            });
        });
        return isComparable;
    };
    // Determines whether the two types are potentially comparable -- i.e.
    // their types overlap in such a way that it makes sense for them to
    // be compared with an == or != operator.
    const _isTypeComparable = (leftType, rightType, checkEq) => {
        if ((0, types_1.isAnyOrUnknown)(leftType) || (0, types_1.isAnyOrUnknown)(rightType)) {
            return true;
        }
        if ((0, types_1.isNever)(leftType) || (0, types_1.isNever)(rightType)) {
            return false;
        }
        if ((0, types_1.isModule)(leftType) || (0, types_1.isModule)(rightType)) {
            return (0, types_1.isTypeSame)(leftType, rightType);
        }
        if ((0, typeUtils_1.isNoneInstance)(leftType) || (0, typeUtils_1.isNoneInstance)(rightType)) {
            return (0, types_1.isTypeSame)(leftType, rightType);
        }
        const isLeftCallable = (0, types_1.isFunction)(leftType) || (0, types_1.isOverloadedFunction)(leftType);
        const isRightCallable = (0, types_1.isFunction)(rightType) || (0, types_1.isOverloadedFunction)(rightType);
        if (isLeftCallable !== isRightCallable) {
            return false;
        }
        if ((0, types_1.isInstantiableClass)(leftType) || ((0, types_1.isClassInstance)(leftType) && types_1.ClassType.isBuiltIn(leftType, 'type'))) {
            if ((0, types_1.isInstantiableClass)(rightType) ||
                ((0, types_1.isClassInstance)(rightType) && types_1.ClassType.isBuiltIn(rightType, 'type'))) {
                const genericLeftType = types_1.ClassType.cloneForSpecialization(leftType, 
                /* typeArguments */ undefined, 
                /* isTypeArgumentExplicit */ false);
                const genericRightType = types_1.ClassType.cloneForSpecialization(rightType, 
                /* typeArguments */ undefined, 
                /* isTypeArgumentExplicit */ false);
                if (assignType(genericLeftType, genericRightType) || assignType(genericRightType, genericLeftType)) {
                    return true;
                }
            }
            if (checkEq) {
                // Does the class have an operator overload for eq?
                const metaclass = leftType.details.effectiveMetaclass;
                if (metaclass && (0, types_1.isClass)(metaclass)) {
                    if ((0, typeUtils_1.lookUpClassMember)(metaclass, '__eq__', 4 /* MemberAccessFlags.SkipObjectBaseClass */)) {
                        return true;
                    }
                }
            }
            return false;
        }
        if ((0, types_1.isClassInstance)(leftType)) {
            if ((0, types_1.isClassInstance)(rightType)) {
                const genericLeftType = types_1.ClassType.cloneForSpecialization(leftType, 
                /* typeArguments */ undefined, 
                /* isTypeArgumentExplicit */ false);
                const genericRightType = types_1.ClassType.cloneForSpecialization(rightType, 
                /* typeArguments */ undefined, 
                /* isTypeArgumentExplicit */ false);
                if (assignType(genericLeftType, genericRightType) || assignType(genericRightType, genericLeftType)) {
                    return true;
                }
                // Assume that if the types are disjoint and built-in classes that they
                // will never be comparable.
                if (types_1.ClassType.isBuiltIn(leftType) && types_1.ClassType.isBuiltIn(rightType)) {
                    return false;
                }
            }
            if (checkEq) {
                // Does the class have an operator overload for eq?
                const eqMethod = (0, typeUtils_1.lookUpClassMember)(types_1.ClassType.cloneAsInstantiable(leftType), '__eq__', 4 /* MemberAccessFlags.SkipObjectBaseClass */);
                if (eqMethod) {
                    // If this is a synthesized method for a dataclass, we can assume
                    // that other dataclass types will not be comparable.
                    if (types_1.ClassType.isDataClass(leftType) && eqMethod.symbol.getSynthesizedType()) {
                        return false;
                    }
                    return true;
                }
            }
            return false;
        }
        return true;
    };
    // Expands any unpacked tuples within an argument list.
    function expandArgList(argList) {
        var _a;
        const expandedArgList = [];
        for (const arg of argList) {
            if (arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                const argType = getTypeOfArgument(arg).type;
                // If this is a tuple with specified element types, use those
                // specified types rather than using the more generic iterator
                // type which will be a union of all element types.
                const combinedArgType = (0, typeUtils_1.combineSameSizedTuples)(makeTopLevelTypeVarsConcrete(argType), tupleClassType);
                if ((0, types_1.isClassInstance)(combinedArgType) && (0, typeUtils_1.isTupleClass)(combinedArgType)) {
                    const tupleTypeArgs = (_a = combinedArgType.tupleTypeArguments) !== null && _a !== void 0 ? _a : [];
                    if (tupleTypeArgs.length !== 1 || !tupleTypeArgs[0].isUnbounded) {
                        for (const tupleTypeArg of tupleTypeArgs) {
                            if (tupleTypeArg.isUnbounded) {
                                expandedArgList.push({
                                    ...arg,
                                    argumentCategory: 1 /* ArgumentCategory.UnpackedList */,
                                    valueExpression: undefined,
                                    typeResult: {
                                        type: makeTupleObject([tupleTypeArg]),
                                    },
                                });
                            }
                            else {
                                expandedArgList.push({
                                    ...arg,
                                    argumentCategory: 0 /* ArgumentCategory.Simple */,
                                    valueExpression: undefined,
                                    typeResult: {
                                        type: tupleTypeArg.type,
                                    },
                                });
                            }
                        }
                        continue;
                    }
                }
            }
            expandedArgList.push(arg);
        }
        return expandedArgList;
    }
    // Matches the arguments passed to a function to the corresponding parameters in that
    // function. This matching is done based on positions and keywords. Type evaluation and
    // validation is left to the caller.
    // This logic is based on PEP 3102: https://www.python.org/dev/peps/pep-3102/
    function matchFunctionArgumentsToParameters(errorNode, argList, typeResult, overloadIndex) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        const paramDetails = (0, parameterUtils_1.getParameterListDetails)(typeResult.type);
        let argIndex = 0;
        let matchedUnpackedListOfUnknownLength = false;
        let reportedArgError = false;
        let isTypeIncomplete = !!typeResult.isIncomplete;
        let isVariadicTypeVarFullyMatched = false;
        // Expand any unpacked tuples in the arg list.
        argList = expandArgList(argList);
        // Build a map of parameters by name.
        const paramMap = new Map();
        paramDetails.params.forEach((paramInfo) => {
            (0, debug_1.assert)(paramInfo !== undefined, 'paramInfo is undefined for param name map');
            const param = paramInfo.param;
            if (param.name && param.category === 0 /* ParameterCategory.Simple */) {
                paramMap.set(param.name, {
                    argsNeeded: param.category === 0 /* ParameterCategory.Simple */ && !param.hasDefault ? 1 : 0,
                    argsReceived: 0,
                    isPositionalOnly: paramInfo.source === parameterUtils_1.ParameterSource.PositionOnly,
                });
            }
        });
        let positionalOnlyLimitIndex = paramDetails.positionOnlyParamCount;
        let positionParamLimitIndex = (_a = paramDetails.firstKeywordOnlyIndex) !== null && _a !== void 0 ? _a : paramDetails.params.length;
        const varArgListParamIndex = paramDetails.argsIndex;
        const varArgDictParamIndex = paramDetails.kwargsIndex;
        // Is this an function that uses the *args and **kwargs
        // from a param spec? If so, we need to treat all positional parameters
        // prior to the *args as positional-only according to PEP 612.
        let paramSpecArgList;
        let paramSpecTarget;
        let hasParamSpecArgsKwargs = false;
        if (varArgListParamIndex !== undefined && varArgDictParamIndex !== undefined) {
            (0, debug_1.assert)(paramDetails.params[varArgListParamIndex], 'varArgListParamIndex params entry is undefined');
            const varArgListParam = paramDetails.params[varArgListParamIndex].param;
            (0, debug_1.assert)(paramDetails.params[varArgDictParamIndex], 'varArgDictParamIndex params entry is undefined');
            const varArgDictParam = paramDetails.params[varArgDictParamIndex].param;
            if ((0, types_1.isParamSpec)(varArgListParam.type) &&
                varArgListParam.type.paramSpecAccess === 'args' &&
                (0, types_1.isParamSpec)(varArgDictParam.type) &&
                varArgDictParam.type.paramSpecAccess === 'kwargs' &&
                varArgListParam.type.details.name === varArgDictParam.type.details.name) {
                hasParamSpecArgsKwargs = true;
                // Does this function define the param spec, or is it an inner
                // function nested within another function that defines the param
                // spec? We need to handle these two cases differently.
                const paramSpecScopeId = varArgListParam.type.scopeId;
                if ((_b = (0, typeUtils_1.getTypeVarScopeIds)(typeResult.type)) === null || _b === void 0 ? void 0 : _b.some((id) => id === paramSpecScopeId)) {
                    paramSpecArgList = [];
                    paramSpecTarget = types_1.TypeVarType.cloneForParamSpecAccess(varArgListParam.type, /* access */ undefined);
                }
                else {
                    positionalOnlyLimitIndex = varArgListParamIndex;
                }
            }
        }
        else if (typeResult.type.details.paramSpec) {
            const paramSpecScopeId = typeResult.type.details.paramSpec.scopeId;
            if ((_c = (0, typeUtils_1.getTypeVarScopeIds)(typeResult.type)) === null || _c === void 0 ? void 0 : _c.some((id) => id === paramSpecScopeId)) {
                hasParamSpecArgsKwargs = true;
                paramSpecArgList = [];
                paramSpecTarget = types_1.TypeVarType.cloneForParamSpecAccess(typeResult.type.details.paramSpec, 
                /* access */ undefined);
            }
        }
        // If there are keyword arguments present after a *args argument,
        // the keyword arguments may target one or more parameters that are positional.
        // In this case, we will limit the number of positional parameters so the
        // *args doesn't consume them all.
        if (argList.some((arg) => arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */)) {
            argList.forEach((arg) => {
                if (arg.name) {
                    const keywordParamIndex = paramDetails.params.findIndex((paramInfo) => {
                        (0, debug_1.assert)(paramInfo, 'paramInfo entry is undefined fork kwargs check');
                        return (paramInfo.param.name === arg.name.value &&
                            paramInfo.param.category === 0 /* ParameterCategory.Simple */);
                    });
                    // Is this a parameter that can be interpreted as either a keyword or a positional?
                    // If so, we'll treat it as a keyword parameter in this case because it's being
                    // targeted by a keyword argument.
                    if (keywordParamIndex >= 0 && keywordParamIndex >= positionalOnlyLimitIndex) {
                        if (positionParamLimitIndex < 0 || keywordParamIndex < positionParamLimitIndex) {
                            positionParamLimitIndex = keywordParamIndex;
                        }
                    }
                }
            });
        }
        // If we didn't see any special cases, then all parameters are positional.
        if (positionParamLimitIndex < 0) {
            positionParamLimitIndex = paramDetails.params.length;
        }
        // Determine how many positional args are being passed before
        // we see a keyword arg.
        let positionalArgCount = argList.findIndex((arg) => arg.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */ || arg.name !== undefined);
        if (positionalArgCount < 0) {
            positionalArgCount = argList.length;
        }
        let validateArgTypeParams = [];
        let activeParam;
        function trySetActive(arg, param) {
            if (arg.active) {
                activeParam = param;
            }
        }
        const foundUnpackedListArg = argList.find((arg) => arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) !== undefined;
        // Map the positional args to parameters.
        let paramIndex = 0;
        while (argIndex < positionalArgCount) {
            if (argIndex < positionalOnlyLimitIndex && argList[argIndex].name) {
                const nameNode = argList[argIndex].name;
                if (nameNode) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.argPositional(), nameNode);
                    reportedArgError = true;
                }
            }
            const remainingArgCount = positionalArgCount - argIndex;
            const remainingParamCount = positionParamLimitIndex - paramIndex - 1;
            if (paramIndex >= positionParamLimitIndex) {
                if (paramSpecArgList) {
                    // Push the remaining positional args onto the param spec arg list.
                    while (argIndex < positionalArgCount) {
                        paramSpecArgList.push(argList[argIndex]);
                        argIndex++;
                    }
                }
                else {
                    let tooManyPositionals = false;
                    if (foundUnpackedListArg && argList[argIndex].argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                        // If this is an unpacked iterable, we will conservatively assume that it
                        // might have zero iterations unless we can tell from its type that it
                        // definitely has at least one iterable value.
                        const argType = getTypeOfArgument(argList[argIndex]).type;
                        if ((0, types_1.isClassInstance)(argType) &&
                            (0, typeUtils_1.isTupleClass)(argType) &&
                            !(0, typeUtils_1.isUnboundedTupleClass)(argType) &&
                            argType.tupleTypeArguments !== undefined &&
                            argType.tupleTypeArguments.length > 0) {
                            tooManyPositionals = true;
                        }
                    }
                    else {
                        tooManyPositionals = true;
                    }
                    if (tooManyPositionals) {
                        if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, positionParamLimitIndex === 1
                                ? localize_1.LocMessage.argPositionalExpectedOne()
                                : localize_1.LocMessage.argPositionalExpectedCount().format({
                                    expected: positionParamLimitIndex,
                                }), (_d = argList[argIndex].valueExpression) !== null && _d !== void 0 ? _d : errorNode);
                        }
                        reportedArgError = true;
                    }
                }
                break;
            }
            if (paramIndex >= paramDetails.params.length) {
                break;
            }
            (0, debug_1.assert)(paramDetails.params[paramIndex], 'paramIndex params entry is undefined');
            const paramType = paramDetails.params[paramIndex].type;
            const paramName = paramDetails.params[paramIndex].param.name;
            const isParamVariadic = paramDetails.params[paramIndex].param.category === 1 /* ParameterCategory.ArgsList */ &&
                (0, types_1.isVariadicTypeVar)(paramType);
            if (argList[argIndex].argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                let isArgCompatibleWithVariadic = false;
                const argTypeResult = getTypeOfArgument(argList[argIndex]);
                let listElementType;
                let advanceToNextArg = false;
                // Handle the case where *args is being passed to a function defined
                // with a ParamSpec and a Concatenate operator. PEP 612 indicates that
                // all positional parameters specified in the Concatenate must be
                // filled explicitly.
                if (paramIndex < positionParamLimitIndex) {
                    if ((0, types_1.isTypeVar)(argTypeResult.type) &&
                        argTypeResult.type.paramSpecAccess === 'args' &&
                        paramDetails.params[paramIndex].param.category !== 1 /* ParameterCategory.ArgsList */) {
                        if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, positionParamLimitIndex === 1
                                ? localize_1.LocMessage.argPositionalExpectedOne()
                                : localize_1.LocMessage.argPositionalExpectedCount().format({
                                    expected: positionParamLimitIndex,
                                }), (_e = argList[argIndex].valueExpression) !== null && _e !== void 0 ? _e : errorNode);
                        }
                        reportedArgError = true;
                    }
                }
                const argType = argTypeResult.type;
                if (isParamVariadic && (0, types_1.isUnpackedVariadicTypeVar)(argType)) {
                    // Allow an unpacked variadic type variable to satisfy an
                    // unpacked variadic type variable.
                    listElementType = argType;
                    isArgCompatibleWithVariadic = true;
                    advanceToNextArg = true;
                    isVariadicTypeVarFullyMatched = true;
                }
                else if ((0, types_1.isClassInstance)(argType) &&
                    (0, typeUtils_1.isTupleClass)(argType) &&
                    argType.tupleTypeArguments &&
                    argType.tupleTypeArguments.length === 1 &&
                    (0, types_1.isUnpackedVariadicTypeVar)(argType.tupleTypeArguments[0].type)) {
                    // Handle the case where an unpacked variadic type var has
                    // been packaged into a tuple.
                    listElementType = argType.tupleTypeArguments[0].type;
                    isArgCompatibleWithVariadic = true;
                    advanceToNextArg = true;
                    isVariadicTypeVarFullyMatched = true;
                }
                else if (isParamVariadic && (0, types_1.isClassInstance)(argType) && (0, typeUtils_1.isTupleClass)(argType)) {
                    // Handle the case where an unpacked tuple argument is
                    // matched to a TypeVarTuple parameter.
                    isArgCompatibleWithVariadic = true;
                    advanceToNextArg = true;
                    // Determine whether we should treat the variadic type as fully matched.
                    // This depends on how many args and unmatched parameters exist.
                    if (remainingArgCount < remainingParamCount) {
                        isVariadicTypeVarFullyMatched = true;
                    }
                    listElementType = types_1.ClassType.cloneForUnpacked(argType);
                }
                else if ((0, types_1.isParamSpec)(argType) && argType.paramSpecAccess === 'args') {
                    listElementType = undefined;
                }
                else {
                    listElementType = (_f = getTypeOfIterator({ type: argType, isIncomplete: argTypeResult.isIncomplete }, 
                    /* isAsync */ false, errorNode, 
                    /* emitNotIterableError */ false)) === null || _f === void 0 ? void 0 : _f.type;
                    if (paramDetails.params[paramIndex].param.category !== 1 /* ParameterCategory.ArgsList */) {
                        matchedUnpackedListOfUnknownLength = true;
                    }
                }
                const funcArg = listElementType
                    ? {
                        argumentCategory: 0 /* ArgumentCategory.Simple */,
                        typeResult: { type: listElementType, isIncomplete: argTypeResult.isIncomplete },
                    }
                    : { ...argList[argIndex] };
                if (argTypeResult.isIncomplete) {
                    isTypeIncomplete = true;
                }
                // It's not allowed to use unpacked arguments with a variadic *args
                // parameter unless the argument is a variadic arg as well.
                if (isParamVariadic && !isArgCompatibleWithVariadic) {
                    if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.unpackedArgWithVariadicParam(), argList[argIndex].valueExpression || errorNode);
                    }
                    reportedArgError = true;
                }
                else {
                    if (paramSpecArgList) {
                        paramSpecArgList.push(argList[argIndex]);
                    }
                    if (funcArg) {
                        validateArgTypeParams.push({
                            paramCategory: paramDetails.params[paramIndex].param.category,
                            paramType,
                            requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                            argument: funcArg,
                            errorNode: (_g = argList[argIndex].valueExpression) !== null && _g !== void 0 ? _g : errorNode,
                            paramName,
                            isParamNameSynthesized: paramDetails.params[paramIndex].param.isNameSynthesized,
                            mapsToVarArgList: isParamVariadic && remainingArgCount > remainingParamCount,
                        });
                    }
                }
                trySetActive(argList[argIndex], paramDetails.params[paramIndex].param);
                // Note that the parameter has received an argument.
                if (paramName &&
                    paramDetails.params[paramIndex].param.category === 0 /* ParameterCategory.Simple */ &&
                    paramMap.has(paramName)) {
                    paramMap.get(paramName).argsReceived++;
                }
                if (advanceToNextArg || paramDetails.params[paramIndex].param.category === 1 /* ParameterCategory.ArgsList */) {
                    argIndex++;
                }
                if (isVariadicTypeVarFullyMatched ||
                    paramDetails.params[paramIndex].param.category !== 1 /* ParameterCategory.ArgsList */) {
                    paramIndex++;
                }
            }
            else if (paramDetails.params[paramIndex].param.category === 1 /* ParameterCategory.ArgsList */) {
                trySetActive(argList[argIndex], paramDetails.params[paramIndex].param);
                if (paramSpecArgList) {
                    paramSpecArgList.push(argList[argIndex]);
                    argIndex++;
                }
                else {
                    let paramCategory = paramDetails.params[paramIndex].param.category;
                    let effectiveParamType = paramType;
                    const paramName = paramDetails.params[paramIndex].param.name;
                    if ((0, types_1.isUnpackedClass)(paramType) &&
                        paramType.tupleTypeArguments &&
                        paramType.tupleTypeArguments.length > 0) {
                        effectiveParamType = paramType.tupleTypeArguments[0].type;
                    }
                    paramCategory = (0, types_1.isVariadicTypeVar)(effectiveParamType)
                        ? 1 /* ParameterCategory.ArgsList */
                        : 0 /* ParameterCategory.Simple */;
                    if (remainingArgCount <= remainingParamCount) {
                        if (remainingArgCount < remainingParamCount) {
                            if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                // Have we run out of arguments and still have parameters left to fill?
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, remainingArgCount === 1
                                    ? localize_1.LocMessage.argMorePositionalExpectedOne()
                                    : localize_1.LocMessage.argMorePositionalExpectedCount().format({
                                        expected: remainingArgCount,
                                    }), argList[argIndex].valueExpression || errorNode);
                            }
                            reportedArgError = true;
                        }
                        paramIndex++;
                    }
                    else {
                        validateArgTypeParams.push({
                            paramCategory,
                            paramType: effectiveParamType,
                            requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                            argument: argList[argIndex],
                            errorNode: argList[argIndex].valueExpression || errorNode,
                            paramName,
                            isParamNameSynthesized: paramDetails.params[paramIndex].param.isNameSynthesized,
                            mapsToVarArgList: true,
                        });
                        argIndex++;
                    }
                }
            }
            else {
                const paramName = paramDetails.params[paramIndex].param.name;
                validateArgTypeParams.push({
                    paramCategory: paramDetails.params[paramIndex].param.category,
                    paramType,
                    requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                    argument: argList[argIndex],
                    errorNode: argList[argIndex].valueExpression || errorNode,
                    paramName,
                    isParamNameSynthesized: paramDetails.params[paramIndex].param.isNameSynthesized,
                });
                trySetActive(argList[argIndex], paramDetails.params[paramIndex].param);
                // Note that the parameter has received an argument.
                if (paramName && paramMap.has(paramName)) {
                    paramMap.get(paramName).argsReceived++;
                }
                argIndex++;
                paramIndex++;
            }
        }
        // If there weren't enough positional arguments to populate all of the
        // positional-only parameters and the next positional-only parameter is
        // an unbounded tuple, skip past it.
        let skippedArgsParam = false;
        if (positionalOnlyLimitIndex >= 0 &&
            paramIndex < positionalOnlyLimitIndex &&
            paramIndex < paramDetails.params.length &&
            paramDetails.params[paramIndex].param.category === 1 /* ParameterCategory.ArgsList */ &&
            !(0, types_1.isParamSpec)(paramDetails.params[paramIndex].param.type)) {
            paramIndex++;
            skippedArgsParam = true;
        }
        // Check if there weren't enough positional arguments to populate all of
        // the positional-only parameters.
        if (positionalOnlyLimitIndex >= 0 &&
            paramIndex < positionalOnlyLimitIndex &&
            (!foundUnpackedListArg || hasParamSpecArgsKwargs)) {
            const firstParamWithDefault = paramDetails.params.findIndex((paramInfo) => paramInfo.param.hasDefault);
            const positionOnlyWithoutDefaultsCount = firstParamWithDefault >= 0 && firstParamWithDefault < positionalOnlyLimitIndex
                ? firstParamWithDefault
                : positionalOnlyLimitIndex;
            // Calculate the number of remaining positional parameters to report.
            let argsRemainingCount = positionOnlyWithoutDefaultsCount - positionalArgCount;
            if (skippedArgsParam) {
                // If we skipped an args parameter above, reduce the count by one
                // because it's permitted to pass zero arguments to *args.
                argsRemainingCount--;
            }
            const firstArgsParam = paramDetails.params.findIndex((paramInfo) => paramInfo.param.category === 1 /* ParameterCategory.ArgsList */ && !(0, types_1.isParamSpec)(paramInfo.param.type));
            if (firstArgsParam >= paramIndex && firstArgsParam < positionalOnlyLimitIndex) {
                // If there is another args parameter beyond the current param index,
                // reduce the count by one because it's permitted to pass zero arguments
                // to *args.
                argsRemainingCount--;
            }
            if (argsRemainingCount > 0) {
                if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, argsRemainingCount === 1
                        ? localize_1.LocMessage.argMorePositionalExpectedOne()
                        : localize_1.LocMessage.argMorePositionalExpectedCount().format({
                            expected: argsRemainingCount,
                        }), argList.length > positionalArgCount
                        ? argList[positionalArgCount].valueExpression || errorNode
                        : errorNode);
                }
                reportedArgError = true;
            }
        }
        if (!reportedArgError) {
            let unpackedDictionaryArgType;
            // Now consume any keyword arguments.
            while (argIndex < argList.length) {
                if (argList[argIndex].argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */) {
                    // Verify that the type used in this expression is a SupportsKeysAndGetItem[str, T].
                    const argType = getTypeOfArgument(argList[argIndex], (0, typeUtils_1.makeInferenceContext)(paramDetails.unpackedKwargsTypedDictType)).type;
                    if ((0, types_1.isAnyOrUnknown)(argType)) {
                        unpackedDictionaryArgType = argType;
                    }
                    else if ((0, types_1.isClassInstance)(argType) && types_1.ClassType.isTypedDictClass(argType)) {
                        // Handle the special case where it is a TypedDict and we know which
                        // keys are present.
                        const typedDictEntries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluatorInterface, argType);
                        const diag = new diagnostic_1.DiagnosticAddendum();
                        typedDictEntries.knownItems.forEach((entry, name) => {
                            const paramEntry = paramMap.get(name);
                            if (paramEntry && !paramEntry.isPositionalOnly) {
                                if (paramEntry.argsReceived > 0) {
                                    diag.addMessage(localize_1.LocMessage.paramAlreadyAssigned().format({ name }));
                                }
                                else {
                                    paramEntry.argsReceived++;
                                    const paramInfoIndex = paramDetails.params.findIndex((paramInfo) => paramInfo.param.name === name);
                                    (0, debug_1.assert)(paramInfoIndex >= 0);
                                    const paramType = paramDetails.params[paramInfoIndex].type;
                                    validateArgTypeParams.push({
                                        paramCategory: 0 /* ParameterCategory.Simple */,
                                        paramType,
                                        requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                                        argument: {
                                            argumentCategory: 0 /* ArgumentCategory.Simple */,
                                            typeResult: { type: entry.valueType },
                                        },
                                        errorNode: argList[argIndex].valueExpression || errorNode,
                                        paramName: name,
                                    });
                                }
                            }
                            else if (paramDetails.kwargsIndex !== undefined) {
                                const paramType = paramDetails.params[paramDetails.kwargsIndex].type;
                                validateArgTypeParams.push({
                                    paramCategory: 2 /* ParameterCategory.KwargsDict */,
                                    paramType,
                                    requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                                    argument: {
                                        argumentCategory: 0 /* ArgumentCategory.Simple */,
                                        typeResult: { type: entry.valueType },
                                    },
                                    errorNode: argList[argIndex].valueExpression || errorNode,
                                    paramName: name,
                                });
                                // Remember that this parameter has already received a value.
                                paramMap.set(name, {
                                    argsNeeded: 1,
                                    argsReceived: 1,
                                    isPositionalOnly: false,
                                });
                            }
                            else {
                                // If the function doesn't have a **kwargs parameter, we need to emit an error.
                                // However, it's possible that there was a **kwargs but it was eliminated by
                                // getParameterListDetails because it was associated with an unpacked TypedDict.
                                // In this case, we can skip the error.
                                if (!paramDetails.hasUnpackedTypedDict) {
                                    diag.addMessage(localize_1.LocMessage.paramNameMissing().format({ name }));
                                }
                            }
                        });
                        if (!diag.isEmpty()) {
                            if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.unpackedTypedDictArgument() + diag.getString(), argList[argIndex].valueExpression || errorNode);
                            }
                            reportedArgError = true;
                        }
                    }
                    else if (typeResult.type.details.paramSpec &&
                        (0, parameterUtils_1.isParamSpecKwargsArgument)(typeResult.type.details.paramSpec, argType)) {
                        unpackedDictionaryArgType = types_1.AnyType.create();
                        if (!paramSpecArgList) {
                            validateArgTypeParams.push({
                                paramCategory: 2 /* ParameterCategory.KwargsDict */,
                                paramType: typeResult.type.details.paramSpec,
                                requiresTypeVarMatching: false,
                                argument: argList[argIndex],
                                argType: (0, types_1.isParamSpec)(argType) ? undefined : types_1.AnyType.create(),
                                errorNode: argList[argIndex].valueExpression || errorNode,
                            });
                        }
                    }
                    else {
                        const strObjType = getBuiltInObject(errorNode, 'str');
                        if (supportsKeysAndGetItemProtocolType &&
                            (0, types_1.isInstantiableClass)(supportsKeysAndGetItemProtocolType) &&
                            strObjType &&
                            (0, types_1.isClassInstance)(strObjType)) {
                            const mappingTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(supportsKeysAndGetItemProtocolType));
                            let isValidMappingType = false;
                            // If this was a TypeVar (e.g. for pseudo-generic classes),
                            // don't emit this error.
                            if ((0, types_1.isTypeVar)(argType)) {
                                isValidMappingType = true;
                            }
                            else if (assignType(types_1.ClassType.cloneAsInstance(supportsKeysAndGetItemProtocolType), argType, 
                            /* diag */ undefined, mappingTypeVarContext)) {
                                const specializedMapping = (0, typeUtils_1.applySolvedTypeVars)(supportsKeysAndGetItemProtocolType, mappingTypeVarContext);
                                const typeArgs = specializedMapping.typeArguments;
                                if (typeArgs && typeArgs.length >= 2) {
                                    if (assignType(strObjType, typeArgs[0])) {
                                        isValidMappingType = true;
                                    }
                                    unpackedDictionaryArgType = typeArgs[1];
                                }
                                else {
                                    isValidMappingType = true;
                                    unpackedDictionaryArgType = types_1.UnknownType.create();
                                }
                            }
                            if (paramDetails.kwargsIndex !== undefined && unpackedDictionaryArgType) {
                                const paramType = paramDetails.params[paramDetails.kwargsIndex].type;
                                validateArgTypeParams.push({
                                    paramCategory: 0 /* ParameterCategory.Simple */,
                                    paramType,
                                    requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                                    argType: unpackedDictionaryArgType,
                                    argument: argList[argIndex],
                                    errorNode: argList[argIndex].valueExpression || errorNode,
                                    paramName: paramDetails.params[paramDetails.kwargsIndex].param.name,
                                });
                            }
                            if (!isValidMappingType) {
                                if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.unpackedDictArgumentNotMapping(), argList[argIndex].valueExpression || errorNode);
                                }
                                reportedArgError = true;
                            }
                        }
                    }
                    if (paramSpecArgList) {
                        paramSpecArgList.push(argList[argIndex]);
                    }
                }
                else {
                    // Protect against the case where a non-keyword argument appears after
                    // a keyword argument. This will have already been reported as a parse
                    // error, but we need to protect against it here.
                    const paramName = argList[argIndex].name;
                    if (paramName) {
                        const paramNameValue = paramName.value;
                        const paramEntry = paramMap.get(paramNameValue);
                        if (paramEntry && !paramEntry.isPositionalOnly) {
                            if (paramEntry.argsReceived > 0) {
                                if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramAlreadyAssigned().format({ name: paramNameValue }), paramName);
                                }
                                reportedArgError = true;
                            }
                            else {
                                paramEntry.argsReceived++;
                                const paramInfoIndex = paramDetails.params.findIndex((paramInfo) => paramInfo.param.name === paramNameValue);
                                (0, debug_1.assert)(paramInfoIndex >= 0);
                                const paramType = paramDetails.params[paramInfoIndex].type;
                                validateArgTypeParams.push({
                                    paramCategory: 0 /* ParameterCategory.Simple */,
                                    paramType,
                                    requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                                    argument: argList[argIndex],
                                    errorNode: (_h = argList[argIndex].valueExpression) !== null && _h !== void 0 ? _h : errorNode,
                                    paramName: paramNameValue,
                                });
                                trySetActive(argList[argIndex], paramDetails.params[paramInfoIndex].param);
                            }
                        }
                        else if (paramSpecArgList) {
                            paramSpecArgList.push(argList[argIndex]);
                        }
                        else if (paramDetails.kwargsIndex !== undefined) {
                            const paramType = paramDetails.params[paramDetails.kwargsIndex].type;
                            validateArgTypeParams.push({
                                paramCategory: 2 /* ParameterCategory.KwargsDict */,
                                paramType,
                                requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                                argument: argList[argIndex],
                                errorNode: (_j = argList[argIndex].valueExpression) !== null && _j !== void 0 ? _j : errorNode,
                                paramName: paramNameValue,
                            });
                            // Remember that this parameter has already received a value.
                            paramMap.set(paramNameValue, {
                                argsNeeded: 1,
                                argsReceived: 1,
                                isPositionalOnly: false,
                            });
                            (0, debug_1.assert)(paramDetails.params[paramDetails.kwargsIndex], 'paramDetails.kwargsIndex params entry is undefined');
                            trySetActive(argList[argIndex], paramDetails.params[paramDetails.kwargsIndex].param);
                        }
                        else {
                            if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramNameMissing().format({ name: paramName.value }), paramName);
                            }
                            reportedArgError = true;
                        }
                    }
                    else if (argList[argIndex].argumentCategory === 0 /* ArgumentCategory.Simple */) {
                        if (paramSpecArgList) {
                            paramSpecArgList.push(argList[argIndex]);
                        }
                        else {
                            if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, positionParamLimitIndex === 1
                                    ? localize_1.LocMessage.argPositionalExpectedOne()
                                    : localize_1.LocMessage.argPositionalExpectedCount().format({
                                        expected: positionParamLimitIndex,
                                    }), argList[argIndex].valueExpression || errorNode);
                            }
                            reportedArgError = true;
                        }
                    }
                    else if (argList[argIndex].argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                        // Handle the case where a *args: P.args (or *args: Any) is passed as an
                        // argument to a function that accepts a ParamSpec.
                        if (typeResult.type.details.paramSpec) {
                            const argTypeResult = getTypeOfArgument(argList[argIndex]);
                            const argType = argTypeResult.type;
                            if (argTypeResult.isIncomplete) {
                                isTypeIncomplete = true;
                            }
                            if ((0, parameterUtils_1.isParamSpecArgsArgument)(typeResult.type.details.paramSpec, argType)) {
                                validateArgTypeParams.push({
                                    paramCategory: 1 /* ParameterCategory.ArgsList */,
                                    paramType: typeResult.type.details.paramSpec,
                                    requiresTypeVarMatching: false,
                                    argument: argList[argIndex],
                                    argType: (0, types_1.isParamSpec)(argType) ? undefined : types_1.AnyType.create(),
                                    errorNode: (_k = argList[argIndex].valueExpression) !== null && _k !== void 0 ? _k : errorNode,
                                });
                            }
                        }
                    }
                }
                argIndex++;
            }
            // If there are keyword-only parameters that haven't been matched but we
            // have an unpacked dictionary arg, assume that it applies to them.
            if (unpackedDictionaryArgType && (!foundUnpackedListArg || paramDetails.argsIndex !== undefined)) {
                // Don't consider any position-only parameters, since they cannot be matched to
                // **kwargs arguments. Consider parameters that are either positional or keyword
                // if there is no *args argument.
                paramDetails.params.forEach((paramInfo, paramIndex) => {
                    var _a, _b;
                    const param = paramInfo.param;
                    if (paramIndex >= paramDetails.firstPositionOrKeywordIndex &&
                        param.category === 0 /* ParameterCategory.Simple */ &&
                        param.name &&
                        paramMap.has(param.name) &&
                        paramMap.get(param.name).argsReceived === 0) {
                        const paramType = paramDetails.params[paramIndex].type;
                        validateArgTypeParams.push({
                            paramCategory: 0 /* ParameterCategory.Simple */,
                            paramType,
                            requiresTypeVarMatching: (0, typeUtils_1.requiresSpecialization)(paramType),
                            argument: {
                                argumentCategory: 0 /* ArgumentCategory.Simple */,
                                typeResult: { type: unpackedDictionaryArgType },
                            },
                            errorNode: (_b = (_a = argList.find((arg) => arg.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */)) === null || _a === void 0 ? void 0 : _a.valueExpression) !== null && _b !== void 0 ? _b : errorNode,
                            paramName: param.name,
                            isParamNameSynthesized: param.isNameSynthesized,
                        });
                        paramMap.get(param.name).argsReceived = 1;
                    }
                });
            }
            // Determine whether there are any parameters that require arguments
            // but have not yet received them. If we received a dictionary argument
            // (i.e. an arg starting with a "**"), we will assume that all parameters
            // are matched.
            if (!unpackedDictionaryArgType && !types_1.FunctionType.isDefaultParameterCheckDisabled(typeResult.type)) {
                const unassignedParams = Array.from(paramMap.keys()).filter((name) => {
                    const entry = paramMap.get(name);
                    return !entry || entry.argsReceived < entry.argsNeeded;
                });
                if (unassignedParams.length > 0) {
                    if (!isDiagnosticSuppressedForNode(errorNode)) {
                        const missingParamNames = unassignedParams.map((p) => `"${p}"`).join(', ');
                        if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, unassignedParams.length === 1
                                ? localize_1.LocMessage.argMissingForParam().format({ name: missingParamNames })
                                : localize_1.LocMessage.argMissingForParams().format({ names: missingParamNames }), errorNode);
                        }
                    }
                    reportedArgError = true;
                }
                // Add any implicit (default) arguments that are needed for resolving
                // generic types. For example, if the function is defined as
                // def foo(v1: _T = 'default')
                // and _T is a TypeVar, we need to match the TypeVar to the default
                // value's type if it's not provided by the caller.
                paramDetails.params.forEach((paramInfo) => {
                    var _a;
                    const param = paramInfo.param;
                    if (param.category === 0 /* ParameterCategory.Simple */ && param.name) {
                        const entry = paramMap.get(param.name);
                        if (entry.argsNeeded === 0 && entry.argsReceived === 0) {
                            const defaultArgType = (_a = paramInfo.defaultArgType) !== null && _a !== void 0 ? _a : param.defaultType;
                            if (defaultArgType &&
                                !(0, typeUtils_1.isEllipsisType)(defaultArgType) &&
                                (0, typeUtils_1.requiresSpecialization)(param.type)) {
                                validateArgTypeParams.push({
                                    paramCategory: param.category,
                                    paramType: paramInfo.type,
                                    requiresTypeVarMatching: true,
                                    argument: {
                                        argumentCategory: 0 /* ArgumentCategory.Simple */,
                                        typeResult: { type: defaultArgType },
                                    },
                                    isDefaultArg: true,
                                    errorNode,
                                    paramName: param.name,
                                    isParamNameSynthesized: param.isNameSynthesized,
                                });
                            }
                        }
                    }
                });
            }
        }
        // If we're in speculative mode and an arg/param mismatch has already been reported, don't
        // bother doing the extra work here. This occurs frequently when attempting to find the
        // correct overload.
        if (!reportedArgError || !isSpeculativeModeInUse(undefined)) {
            // If there are arguments that map to a variadic *args parameter that hasn't
            // already been matched, see if the type of that *args parameter is a variadic
            // type variable. If so, we'll preprocess those arguments and combine them
            // into a tuple.
            (0, debug_1.assert)(paramDetails.argsIndex === undefined || paramDetails.argsIndex < paramDetails.params.length, 'paramDetails.argsIndex params entry is invalid');
            if (paramDetails.argsIndex !== undefined &&
                paramDetails.argsIndex >= 0 &&
                paramDetails.params[paramDetails.argsIndex].param.hasDeclaredType &&
                !isVariadicTypeVarFullyMatched) {
                const paramType = paramDetails.params[paramDetails.argsIndex].type;
                const variadicArgs = validateArgTypeParams.filter((argParam) => argParam.mapsToVarArgList);
                if ((0, types_1.isVariadicTypeVar)(paramType) && !paramType.isVariadicInUnion) {
                    const tupleTypeArgs = variadicArgs.map((argParam) => {
                        var _a;
                        const argType = getTypeOfArgument(argParam.argument).type;
                        const containsVariadicTypeVar = (0, types_1.isUnpackedVariadicTypeVar)(argType) ||
                            ((0, types_1.isClassInstance)(argType) &&
                                (0, typeUtils_1.isTupleClass)(argType) &&
                                argType.tupleTypeArguments &&
                                argType.tupleTypeArguments.length === 1 &&
                                (0, types_1.isUnpackedVariadicTypeVar)(argType.tupleTypeArguments[0].type));
                        if (containsVariadicTypeVar &&
                            argParam.argument.argumentCategory !== 1 /* ArgumentCategory.UnpackedList */ &&
                            !argParam.mapsToVarArgList) {
                            if (!isDiagnosticSuppressedForNode(errorNode) && !isTypeIncomplete) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.typeVarTupleMustBeUnpacked(), (_a = argParam.argument.valueExpression) !== null && _a !== void 0 ? _a : errorNode);
                            }
                            reportedArgError = true;
                        }
                        return {
                            type: argType,
                            isUnbounded: argParam.argument.argumentCategory === 1 /* ArgumentCategory.UnpackedList */,
                        };
                    });
                    let specializedTuple;
                    if (tupleTypeArgs.length === 1 &&
                        !tupleTypeArgs[0].isUnbounded &&
                        ((0, types_1.isUnpackedClass)(tupleTypeArgs[0].type) || (0, types_1.isVariadicTypeVar)(tupleTypeArgs[0].type))) {
                        // If there is a single unpacked tuple or unpacked variadic type variable
                        // (including an unpacked TypeVarTuple union) within this tuple,
                        // simplify the type.
                        specializedTuple = tupleTypeArgs[0].type;
                    }
                    else {
                        specializedTuple = makeTupleObject(tupleTypeArgs, /* isUnpackedTuple */ true);
                    }
                    const combinedArg = {
                        paramCategory: 1 /* ParameterCategory.ArgsList */,
                        paramType,
                        requiresTypeVarMatching: true,
                        argument: {
                            argumentCategory: 0 /* ArgumentCategory.Simple */,
                            typeResult: { type: specializedTuple },
                        },
                        errorNode,
                        paramName: paramDetails.params[paramDetails.argsIndex].param.name,
                        isParamNameSynthesized: paramDetails.params[paramDetails.argsIndex].param.isNameSynthesized,
                        mapsToVarArgList: true,
                    };
                    validateArgTypeParams = [
                        ...validateArgTypeParams.filter((argParam) => !argParam.mapsToVarArgList),
                        combinedArg,
                    ];
                }
            }
        }
        let relevance = 0;
        if (matchedUnpackedListOfUnknownLength) {
            // Lower the relevance if we made assumptions about the length
            // of an unpacked argument. This will favor overloads that
            // associate this case with a *args parameter.
            relevance--;
        }
        // Special-case the builtin isinstance and issubclass functions.
        if (['isinstance', 'issubclass'].some((name) => name === typeResult.type.details.builtInName) &&
            validateArgTypeParams.length === 2) {
            validateArgTypeParams[1].isinstanceParam = true;
        }
        return {
            overload: typeResult.type,
            overloadIndex,
            argumentErrors: reportedArgError,
            isTypeIncomplete,
            argParams: validateArgTypeParams,
            paramSpecTarget,
            paramSpecArgList,
            activeParam,
            relevance,
            argumentMatchScore: 0,
        };
    }
    // After having matched arguments with parameters, this function evaluates the
    // types of each argument expression and validates that the resulting type is
    // compatible with the declared type of the corresponding parameter.
    function validateFunctionArgumentTypesWithContext(errorNode, matchResults, typeVarContext, skipUnknownArgCheck = false, inferenceContext) {
        var _a, _b;
        const type = matchResults.overload;
        const signatureTracker = (_a = inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker) !== null && _a !== void 0 ? _a : new typeUtils_1.UniqueSignatureTracker();
        matchResults.overload = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(matchResults.overload, signatureTracker, errorNode.start);
        // Can we safely ignore the inference context (either because it's not provided
        // or will have no effect)? If so, we can eliminate a bunch of extra work.
        if (!inferenceContext ||
            (0, types_1.isAnyOrUnknown)(inferenceContext.expectedType) ||
            (0, types_1.isNever)(inferenceContext.expectedType) ||
            !type.details.declaredReturnType ||
            !(0, typeUtils_1.requiresSpecialization)((_b = types_1.FunctionType.getSpecializedReturnType(type)) !== null && _b !== void 0 ? _b : types_1.UnknownType.create())) {
            return validateFunctionArgumentTypes(errorNode, matchResults, typeVarContext, signatureTracker, skipUnknownArgCheck);
        }
        const effectiveReturnType = getFunctionEffectiveReturnType(type);
        let effectiveExpectedType = inferenceContext.expectedType;
        let effectiveFlags = 2048 /* AssignTypeFlags.PopulatingExpectedType */;
        if ((0, typeUtils_1.containsLiteralType)(effectiveExpectedType, /* includeTypeArgs */ true)) {
            effectiveFlags |= 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */;
        }
        // If the expected type is a union, we don't know which type is expected.
        // We may or may not be able to make use of the expected type. We'll evaluate
        // speculatively to see if using the expected type works.
        if ((0, types_1.isUnion)(inferenceContext.expectedType)) {
            useSpeculativeMode(errorNode, () => {
                const typeVarContextCopy = typeVarContext.clone();
                assignType(effectiveReturnType, effectiveExpectedType, 
                /* diag */ undefined, typeVarContextCopy, 
                /* srcTypeVarContext */ undefined, effectiveFlags);
                const speculativeResults = validateFunctionArgumentTypes(errorNode, matchResults, typeVarContextCopy, signatureTracker, skipUnknownArgCheck);
                if (speculativeResults === null || speculativeResults === void 0 ? void 0 : speculativeResults.argumentErrors) {
                    effectiveExpectedType = undefined;
                }
            });
        }
        if (effectiveExpectedType) {
            const liveTypeVarScopes = ParseTreeUtils.getTypeVarScopesForNode(errorNode);
            // Prepopulate the typeVarContext based on the specialized expected type if the
            // callee has a declared return type. This will allow us to more closely match
            // the expected type if possible.
            // Determine which type arguments are needed to match the expected type.
            if ((0, types_1.isClassInstance)(effectiveReturnType)) {
                // If the return type is a class and the expected type is a union
                // that is type compatible with that class, filter the subtypes in
                // the union to see if we can find one that is potentially compatible.
                if ((0, types_1.isUnion)(effectiveExpectedType)) {
                    const filteredType = (0, typeUtils_1.mapSubtypes)(effectiveExpectedType, (subtype) => {
                        if (!(0, types_1.isClassInstance)(subtype) || subtype.details.typeParameters.length === 0) {
                            return undefined;
                        }
                        if (types_1.ClassType.isProtocolClass(subtype) ||
                            subtype.details.mro.some((mroClass) => {
                                return ((0, types_1.isClassInstance)(mroClass) &&
                                    mroClass.details.typeParameters.length > 0 &&
                                    types_1.ClassType.isSameGenericClass(effectiveReturnType, mroClass));
                            })) {
                            return subtype;
                        }
                        return undefined;
                    }, 
                    /* sortSubtypes */ true);
                    if ((0, types_1.isClassInstance)(filteredType)) {
                        effectiveExpectedType = filteredType;
                    }
                }
                if ((0, types_1.isClassInstance)(effectiveExpectedType) && !(0, types_1.isTypeSame)(effectiveReturnType, effectiveExpectedType)) {
                    const tempTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(effectiveReturnType));
                    if ((0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluatorInterface, effectiveReturnType, effectiveExpectedType, tempTypeVarContext, liveTypeVarScopes, errorNode.start)) {
                        const genericReturnType = types_1.ClassType.cloneForSpecialization(effectiveReturnType, 
                        /* typeArguments */ undefined, 
                        /* isTypeArgumentExplicit */ false);
                        effectiveExpectedType = (0, typeUtils_1.applySolvedTypeVars)(genericReturnType, tempTypeVarContext, {
                            unknownIfNotFound: true,
                        });
                        effectiveFlags |= 4096 /* AssignTypeFlags.SkipPopulateUnknownExpectedType */;
                    }
                }
            }
            else if ((0, types_1.isFunction)(effectiveReturnType)) {
                // If the return type is a callable and the expected type is a union that
                // includes one or more non-callables, filter those out.
                if ((0, types_1.isUnion)(effectiveExpectedType)) {
                    effectiveExpectedType = (0, typeUtils_1.mapSubtypes)(effectiveExpectedType, (subtype) => {
                        return (0, typeUtils_1.isCallableType)(subtype) ? subtype : undefined;
                    });
                }
            }
            effectiveExpectedType = (0, typeUtils_1.transformExpectedType)(effectiveExpectedType, liveTypeVarScopes, errorNode.start);
            assignType(effectiveReturnType, effectiveExpectedType, 
            /* diag */ undefined, typeVarContext, 
            /* srcTypeVarContext */ undefined, effectiveFlags);
        }
        return validateFunctionArgumentTypes(errorNode, matchResults, typeVarContext, signatureTracker, skipUnknownArgCheck);
    }
    function validateFunctionArgumentTypes(errorNode, matchResults, typeVarContext, signatureTracker, skipUnknownArgCheck = false) {
        const type = matchResults.overload;
        let isTypeIncomplete = matchResults.isTypeIncomplete;
        let argumentErrors = false;
        let argumentMatchScore = 0;
        let specializedInitSelfType;
        let anyOrUnknownArgument;
        const typeCondition = (0, typeUtils_1.getTypeCondition)(type);
        // Check for an attempt to invoke an unimplemented abstract method.
        if (type.boundToType && !type.boundToType.includeSubclasses && type.details.methodClass) {
            const abstractSymbolInfo = getAbstractSymbolInfo(type.details.methodClass, type.details.name);
            if (abstractSymbolInfo && !abstractSymbolInfo.hasImplementation) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAbstractUsage, localize_1.LocMessage.abstractMethodInvocation().format({
                    method: type.details.name,
                }), errorNode.nodeType === 9 /* ParseNodeType.Call */ ? errorNode.leftExpression : errorNode);
            }
        }
        if (type.boundTypeVarScopeId) {
            // If the function was bound to a class or object and was a constructor, a
            // static method or a class method, it's possible that some of that class's
            // type variables have not yet been solved. Add that class's TypeVar scope ID.
            if (type.preBoundFlags !== undefined && type.boundToType && (0, typeUtils_1.requiresSpecialization)(type.boundToType)) {
                if (type.preBoundFlags &
                    (4 /* FunctionTypeFlags.StaticMethod */ | 2 /* FunctionTypeFlags.ClassMethod */ | 4 /* FunctionTypeFlags.StaticMethod */)) {
                    typeVarContext.addSolveForScope(type.boundTypeVarScopeId);
                }
            }
            // The type annotation for the "self" parameter in an __init__ method to
            // can incluence the type being constructed.
            if (type.details.name === '__init__' &&
                type.strippedFirstParamType &&
                type.boundToType &&
                (0, types_1.isClassInstance)(type.strippedFirstParamType) &&
                (0, types_1.isClassInstance)(type.boundToType) &&
                types_1.ClassType.isSameGenericClass(type.strippedFirstParamType, type.boundToType) &&
                type.strippedFirstParamType.typeArguments) {
                const typeParams = type.strippedFirstParamType.details.typeParameters;
                specializedInitSelfType = type.strippedFirstParamType;
                type.strippedFirstParamType.typeArguments.forEach((typeArg, index) => {
                    if (index < typeParams.length) {
                        const typeParam = typeParams[index];
                        if (!(0, types_1.isTypeSame)(typeParam, typeArg, { ignorePseudoGeneric: true })) {
                            typeVarContext.setTypeVarType(typeParams[index], typeArg);
                        }
                    }
                });
            }
        }
        // Special-case a few built-in calls that are often used for
        // casting or checking for unknown types.
        if (['cast', 'isinstance', 'issubclass'].some((name) => name === type.details.builtInName)) {
            skipUnknownArgCheck = true;
        }
        // Run through all args and validate them against their matched parameter.
        // We'll do two passes. The first one will match any type arguments. The second
        // will perform the actual validation. We can skip the first pass if there
        // are no type vars to match.
        const typeVarMatchingCount = matchResults.argParams.filter((arg) => arg.requiresTypeVarMatching).length;
        if (typeVarMatchingCount > 0) {
            // In theory, we may need to do up to n passes where n is the number of
            // arguments that need type var matching. That's because later matches
            // can provide bidirectional type hints for earlier matches. The best
            // example of this is the built-in "map" method whose first parameter is
            // a lambda and second parameter indicates what type the lambda should accept.
            // In practice, we will limit the number of passes to 2 because it can get
            // very expensive to go beyond this, and we don't generally see cases
            // where more than two passes are needed.
            let passCount = Math.min(typeVarMatchingCount, 2);
            for (let i = 0; i < passCount; i++) {
                useSpeculativeMode(errorNode, () => {
                    matchResults.argParams.forEach((argParam) => {
                        if (!argParam.requiresTypeVarMatching) {
                            return;
                        }
                        // Populate the typeVarContext for the argument. If the argument
                        // is an overload function, skip it during the first pass
                        // because the selection of the proper overload may depend
                        // on type arguments supplied by other function arguments.
                        // We set useNarrowBoundOnly to true if this is the first
                        // (but not only) pass through the parameter list because a wide
                        // bound on a TypeVar (if a narrow bound has not yet been
                        // established) will unnecessarily constrain the expected type.
                        // If the param type is a "bare" TypeVar, don't use it as an
                        // expected type during the first pass. This causes problems for
                        // cases where the the call expression result can influence the
                        // type of the TypeVar, such as in the expression "min(1, max(2, 0.5))".
                        const argResult = validateArgType(argParam, typeVarContext, signatureTracker, { type, isIncomplete: matchResults.isTypeIncomplete }, {
                            skipUnknownArgCheck,
                            skipOverloadArg: i === 0,
                            skipBareTypeVarExpectedType: i === 0,
                            useNarrowBoundOnly: passCount > 1 && i === 0,
                            conditionFilter: typeCondition,
                        });
                        if (argResult.isTypeIncomplete) {
                            isTypeIncomplete = true;
                        }
                        // If we skipped an overload arg or a bare type var during the first pass,
                        // add another pass to ensure that we handle all of the type variables.
                        if (i === 0 && (argResult.skippedOverloadArg || argResult.skippedBareTypeVarExpectedType)) {
                            passCount++;
                        }
                    });
                });
            }
            // Lock the type var map so it cannot be modified when revalidating
            // the arguments in a second pass.
            typeVarContext.lock();
        }
        let sawParamSpecArgs = false;
        let sawParamSpecKwargs = false;
        let condition = [];
        const argResults = [];
        matchResults.argParams.forEach((argParam, argParamIndex) => {
            var _a;
            const argResult = validateArgType(argParam, typeVarContext, signatureTracker, { type, isIncomplete: matchResults.isTypeIncomplete }, {
                skipUnknownArgCheck,
                conditionFilter: typeCondition,
            });
            argResults.push(argResult);
            if (!argResult.isCompatible) {
                argumentErrors = true;
                // Add the inverse index so earlier parameters represent larger errors.
                // This will help the heuristics in the overload error paths to pick the
                // most likely intended overload if none of them match.
                argumentMatchScore += 1 + (matchResults.argParams.length - argParamIndex);
            }
            if (argResult.isTypeIncomplete) {
                isTypeIncomplete = true;
            }
            if (argResult.condition) {
                condition = (_a = types_1.TypeCondition.combine(condition, argResult.condition)) !== null && _a !== void 0 ? _a : [];
            }
            if ((0, types_1.isAnyOrUnknown)(argResult.argType)) {
                anyOrUnknownArgument = anyOrUnknownArgument
                    ? (0, typeUtils_1.preserveUnknown)(argResult.argType, anyOrUnknownArgument)
                    : argResult.argType;
            }
            if (type.details.paramSpec) {
                if (argParam.argument.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                    if ((0, parameterUtils_1.isParamSpecArgsArgument)(type.details.paramSpec, argResult.argType)) {
                        sawParamSpecArgs = true;
                    }
                }
                if (argParam.argument.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */) {
                    if ((0, parameterUtils_1.isParamSpecKwargsArgument)(type.details.paramSpec, argResult.argType)) {
                        sawParamSpecKwargs = true;
                    }
                }
            }
        });
        let paramSpecTypeVarContext = [];
        // Handle the assignment of additional arguments that map to a param spec.
        if (matchResults.paramSpecArgList && matchResults.paramSpecTarget) {
            const paramSpecArgResult = validateFunctionArgumentsForParamSpec(errorNode, matchResults.paramSpecArgList, matchResults.paramSpecTarget, typeVarContext, signatureTracker);
            if (paramSpecArgResult.argumentErrors) {
                argumentErrors = true;
                argumentMatchScore += 1;
            }
            paramSpecTypeVarContext = paramSpecArgResult.typeVarContexts;
        }
        else if (type.details.paramSpec) {
            if (!sawParamSpecArgs || !sawParamSpecKwargs) {
                if (!isTypeIncomplete) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramSpecArgsMissing().format({ type: printType(type.details.paramSpec) }), errorNode);
                }
                argumentErrors = true;
                argumentMatchScore += 1;
            }
        }
        // Calculate the return type.
        let returnType = getFunctionEffectiveReturnType(type, matchResults.argParams);
        if (condition.length > 0) {
            returnType = types_1.TypeBase.cloneForCondition(returnType, condition);
        }
        // Determine whether the expression being evaluated is within the current TypeVar
        // scope. If not, then the expression is invoking a function in another scope,
        // and we should eliminate unsolved type variables from union types that appear
        // in the return type. If we're within the same scope, we should retain these
        // extra type variables because they are still potentially relevant within this
        // scope.
        let eliminateUnsolvedInUnions = true;
        let curNode = errorNode;
        while (curNode) {
            const typeVarScopeNode = ParseTreeUtils.getTypeVarScopeNode(curNode);
            if (!typeVarScopeNode) {
                break;
            }
            const typeVarScopeId = ParseTreeUtils.getScopeIdForNode(typeVarScopeNode);
            if (typeVarContext.hasSolveForScope(typeVarScopeId)) {
                eliminateUnsolvedInUnions = false;
            }
            curNode = typeVarScopeNode.parent;
        }
        // If the function is returning a callable, don't eliminate unsolved
        // type vars within a union. There are legit uses for unsolved type vars
        // within a callable.
        if ((0, types_1.isFunction)(returnType) || (0, types_1.isOverloadedFunction)(returnType)) {
            eliminateUnsolvedInUnions = false;
        }
        // We'll leave TypeVars unsolved if the call is a recursive
        // call to a generic function or if this isn't a callable
        // return with type parameters that are rescoped from the original
        // function to the returned callable.
        const unknownIfNotFound = !ParseTreeUtils.getTypeVarScopesForNode(errorNode).some((typeVarScope) => typeVarContext.hasSolveForScope(typeVarScope)) && !type.details.rescopedTypeParameters;
        let specializedReturnType = (0, typeUtils_1.applySolvedTypeVars)(returnType, typeVarContext, {
            unknownIfNotFound,
            unknownExemptTypeVars: getUnknownExemptTypeVarsForReturnType(type, returnType),
            eliminateUnsolvedInUnions,
            applyInScopePlaceholders: true,
        });
        specializedReturnType = (0, typeUtils_1.addConditionToType)(specializedReturnType, typeCondition);
        // If the function includes a ParamSpec and the captured signature(s) includes
        // generic types, we may need to apply those solved TypeVars.
        if (paramSpecTypeVarContext.length > 0) {
            paramSpecTypeVarContext.forEach((paramSpecTypeVarContext) => {
                if (paramSpecTypeVarContext) {
                    specializedReturnType = (0, typeUtils_1.applySolvedTypeVars)(specializedReturnType, paramSpecTypeVarContext);
                }
            });
        }
        // If the final return type is an unpacked tuple, turn it into a normal (unpacked) tuple.
        if ((0, types_1.isUnpackedClass)(specializedReturnType)) {
            specializedReturnType = types_1.ClassType.cloneForUnpacked(specializedReturnType, /* isUnpackedTuple */ false);
        }
        // Handle 'TypeGuard' and 'TypeIs' specially. We'll transform the return type
        // into a 'bool' object with a type argument that reflects the narrowed type.
        if ((0, types_1.isClassInstance)(specializedReturnType) &&
            types_1.ClassType.isBuiltIn(specializedReturnType, ['TypeGuard', 'TypeIs']) &&
            specializedReturnType.typeArguments &&
            specializedReturnType.typeArguments.length > 0) {
            if (boolClassType && (0, types_1.isInstantiableClass)(boolClassType)) {
                let typeGuardType = specializedReturnType.typeArguments[0];
                // If the first argument is a simple (non-constrained) TypeVar,
                // associate that TypeVar with the resulting TypeGuard type.
                if (argResults.length > 0) {
                    const arg0Type = argResults[0].argType;
                    if ((0, types_1.isTypeVar)(arg0Type) &&
                        !arg0Type.details.isParamSpec &&
                        arg0Type.details.constraints.length === 0) {
                        typeGuardType = (0, typeUtils_1.addConditionToType)(typeGuardType, [
                            { typeVar: arg0Type, constraintIndex: 0 },
                        ]);
                    }
                }
                const useTypeIsSemantics = types_1.ClassType.isBuiltIn(specializedReturnType, 'TypeIs');
                specializedReturnType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForTypeGuard(boolClassType, typeGuardType, useTypeIsSemantics));
            }
        }
        const liveTypeVarScopes = ParseTreeUtils.getTypeVarScopesForNode(errorNode);
        specializedReturnType = adjustCallableReturnType(type, specializedReturnType, liveTypeVarScopes, signatureTracker.getTrackedSignatures());
        if (specializedInitSelfType) {
            specializedInitSelfType = (0, typeUtils_1.applySolvedTypeVars)(specializedInitSelfType, typeVarContext);
        }
        matchResults.argumentMatchScore = argumentMatchScore;
        return {
            argumentErrors,
            argResults,
            anyOrUnknownArgument,
            returnType: specializedReturnType,
            isTypeIncomplete,
            activeParam: matchResults.activeParam,
            specializedInitSelfType,
            overloadsUsedForCall: argumentErrors ? [] : [type],
        };
    }
    // In general, all in-scope type variables left in a return type should be
    // replaced with Unknown. However, if the return type is a callable that uses
    // type vars that are found nowhere within the function's input parameters,
    // we'll treat these as though they're scoped to the callable and leave them
    // unsolved.
    function getUnknownExemptTypeVarsForReturnType(functionType, returnType) {
        if ((0, types_1.isFunction)(returnType) && !returnType.details.name) {
            const returnTypeScopeId = returnType.details.typeVarScopeId;
            // If one or more type vars found within the return type are scoped to
            // the functionType but don't appear anywhere else within the functionType's
            // input parameters, rescope them to the return type callable so they are
            // not replaced with Unknown.
            if (returnTypeScopeId && functionType.details.typeVarScopeId) {
                let typeVarsInReturnType = (0, typeUtils_1.getTypeVarArgumentsRecursive)(returnType);
                // Remove any type variables that appear in the function's input parameters.
                functionType.details.parameters.forEach((param, index) => {
                    if (param.hasDeclaredType) {
                        const typeVarsInInputParam = (0, typeUtils_1.getTypeVarArgumentsRecursive)(param.type);
                        typeVarsInReturnType = typeVarsInReturnType.filter((returnTypeVar) => !typeVarsInInputParam.some((inputTypeVar) => (0, types_1.isTypeSame)(returnTypeVar, inputTypeVar)));
                    }
                });
                return typeVarsInReturnType;
            }
        }
        return [];
    }
    // If the return type includes a generic Callable type, set the type var
    // scope to the scope of the function it was originally associated with
    // to allow these type vars to be solved. This won't work with overloads
    // or unions of callables. It's intended for a specific use case. We may
    // need to make this more sophisticated in the future.
    // The trackedSignatures parameter supplies a list of function signatures
    // that were used for the function and the arguments passed to it. This is
    // important because the callable return value may be called again with
    // one of these signatures, so we may need to "uniquify" the type parameters
    // to avoid conflicts.
    function adjustCallableReturnType(callableType, returnType, liveTypeVarScopes, trackedSignatures) {
        if ((0, types_1.isFunction)(returnType) && !returnType.details.name && callableType.details.typeVarScopeId) {
            // What type variables are referenced in the callable return type? Do not include any live type variables.
            const typeVarsInReturnType = (0, typeUtils_1.getTypeVarArgumentsRecursive)(returnType).filter((t) => !liveTypeVarScopes.some((scopeId) => t.scopeId === scopeId));
            // If there are no unsolved type variables, we're done. If there are
            // unsolved type variables, treat them as though they are rescoped
            // to the callable.
            if (typeVarsInReturnType.length > 0) {
                return types_1.FunctionType.cloneWithNewTypeVarScopeId(returnType, callableType.details.typeVarScopeId, typeVarsInReturnType, trackedSignatures);
            }
        }
        return returnType;
    }
    // Tries to assign the call arguments to the function parameter
    // list and reports any mismatches in types or counts. Returns the
    // specialized return type of the call.
    function validateFunctionArguments(errorNode, argList, typeResult, typeVarContext, skipUnknownArgCheck = false, inferenceContext) {
        var _a;
        const signatureTracker = (_a = inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.signatureTracker) !== null && _a !== void 0 ? _a : new typeUtils_1.UniqueSignatureTracker();
        typeResult.type = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(typeResult.type, signatureTracker, errorNode.start);
        const matchResults = matchFunctionArgumentsToParameters(errorNode, argList, typeResult, 0);
        if (matchResults.argumentErrors) {
            // Evaluate types of all args. This will ensure that referenced symbols are
            // not reported as unaccessed.
            argList.forEach((arg) => {
                if (arg.valueExpression && !isSpeculativeModeInUse(arg.valueExpression)) {
                    getTypeOfExpression(arg.valueExpression);
                }
            });
            return {
                argumentErrors: true,
                activeParam: matchResults.activeParam,
                overloadsUsedForCall: [],
            };
        }
        return validateFunctionArgumentTypesWithContext(errorNode, matchResults, typeVarContext, skipUnknownArgCheck, (0, typeUtils_1.makeInferenceContext)(inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType, inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.isTypeIncomplete, signatureTracker));
    }
    // Determines whether the specified argument list satisfies the function
    // signature bound to the specified ParamSpec. Return value indicates success.
    function validateFunctionArgumentsForParamSpec(errorNode, argList, paramSpec, destTypeVarContext, signatureTracker) {
        const signatureContexts = destTypeVarContext.getSignatureContexts();
        // Handle the common case where there is only one signature context.
        if (signatureContexts.length === 1) {
            return validateFunctionArgumentsForParamSpecSignature(errorNode, argList, paramSpec, signatureContexts[0], signatureTracker);
        }
        const filteredSignatureContexts = [];
        const typeVarContexts = [];
        signatureContexts.forEach((context) => {
            // Use speculative mode to avoid emitting errors or caching types.
            useSpeculativeMode(errorNode, () => {
                const paramSpecArgResult = validateFunctionArgumentsForParamSpecSignature(errorNode, argList, paramSpec, context, signatureTracker);
                if (!paramSpecArgResult.argumentErrors) {
                    filteredSignatureContexts.push(context);
                }
                (0, collectionUtils_1.appendArray)(typeVarContexts, paramSpecArgResult.typeVarContexts);
            });
        });
        // Copy back any compatible signature contexts if any were compatible.
        if (filteredSignatureContexts.length > 0) {
            destTypeVarContext.copySignatureContexts(filteredSignatureContexts);
        }
        // Evaluate non-speculatively to produce a final result and cache types.
        const paramSpecArgResult = validateFunctionArgumentsForParamSpecSignature(errorNode, argList, paramSpec, filteredSignatureContexts.length > 0 ? filteredSignatureContexts[0] : signatureContexts[0], signatureTracker);
        return { argumentErrors: paramSpecArgResult.argumentErrors, typeVarContexts };
    }
    function validateFunctionArgumentsForParamSpecSignature(errorNode, argList, paramSpec, typeVarContext, signatureTracker) {
        var _a;
        let paramSpecType = typeVarContext.getParamSpecType(paramSpec);
        if (!paramSpecType) {
            paramSpecType = (0, typeUtils_1.convertTypeToParamSpecValue)(paramSpec);
        }
        const matchResults = matchFunctionArgumentsToParameters(errorNode, argList, { type: paramSpecType }, 0);
        const functionType = matchResults.overload;
        const srcTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeIds)(paramSpecType));
        if (matchResults.argumentErrors) {
            // Evaluate types of all args. This will ensure that referenced symbols are
            // not reported as unaccessed.
            argList.forEach((arg) => {
                if (arg.valueExpression && !isSpeculativeModeInUse(arg.valueExpression)) {
                    getTypeOfExpression(arg.valueExpression);
                }
            });
            return { argumentErrors: true, typeVarContexts: [srcTypeVarContext] };
        }
        // Handle the recursive case where we're passing (*args: P.args, **kwargs: P.args)
        // a remaining function of type (*P).
        if (functionType.details.paramSpec &&
            functionType.details.parameters.length === 0 &&
            (0, types_1.isTypeSame)(functionType.details.paramSpec, paramSpec)) {
            // If there are any arguments other than *args: P.args or **kwargs: P.kwargs,
            // report an error.
            let sawArgs = false;
            let sawKwargs = false;
            let argumentErrors = false;
            let argErrorNode;
            for (const arg of argList) {
                const argType = (_a = getTypeOfArgument(arg)) === null || _a === void 0 ? void 0 : _a.type;
                const isArgTypeCompatible = argType && ((0, types_1.isTypeSame)(argType, paramSpec, { ignoreTypeFlags: true }) || (0, types_1.isAnyOrUnknown)(argType));
                if (arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */ && !sawArgs && isArgTypeCompatible) {
                    sawArgs = true;
                }
                else if (arg.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */ &&
                    !sawKwargs &&
                    isArgTypeCompatible) {
                    sawKwargs = true;
                }
                else {
                    argErrorNode = argErrorNode !== null && argErrorNode !== void 0 ? argErrorNode : arg.valueExpression;
                    argumentErrors = true;
                }
            }
            if (!sawArgs || !sawKwargs) {
                argumentErrors = true;
            }
            if (argumentErrors) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.paramSpecArgsMissing().format({
                    type: printType(functionType.details.paramSpec),
                }), argErrorNode !== null && argErrorNode !== void 0 ? argErrorNode : errorNode);
            }
            return { argumentErrors, typeVarContexts: [srcTypeVarContext] };
        }
        const result = validateFunctionArgumentTypes(errorNode, matchResults, srcTypeVarContext, signatureTracker);
        return { argumentErrors: !!result.argumentErrors, typeVarContexts: [srcTypeVarContext] };
    }
    function validateArgType(argParam, typeVarContext, signatureTracker, typeResult, options) {
        var _a;
        let argType;
        let expectedTypeDiag;
        let isTypeIncomplete = !!(typeResult === null || typeResult === void 0 ? void 0 : typeResult.isIncomplete);
        let isCompatible = true;
        const functionName = typeResult === null || typeResult === void 0 ? void 0 : typeResult.type.details.name;
        let skippedBareTypeVarExpectedType = false;
        let skipSolveTypeVars = false;
        if (argParam.argument.valueExpression) {
            let expectedType;
            // Is the expected type a "bare" in-scope TypeVar or a union of bare in-scope TypeVars?
            let isExpectedTypeBareTypeVar = true;
            (0, typeUtils_1.doForEachSubtype)(argParam.paramType, (subtype) => {
                if (!(0, types_1.isTypeVar)(subtype) || subtype.scopeId !== (typeResult === null || typeResult === void 0 ? void 0 : typeResult.type.details.typeVarScopeId)) {
                    isExpectedTypeBareTypeVar = false;
                }
            });
            if (!options.skipBareTypeVarExpectedType || !isExpectedTypeBareTypeVar) {
                expectedType = argParam.paramType;
                // If the parameter type is a function with a ParamSpec, don't apply
                // the solved TypeVars if the typeVarContext has more than one signature.
                // This will expand the ParamSpec into an overload, which will cause problems.
                const skipApplySolvedTypeVars = (0, types_1.isFunction)(argParam.paramType) &&
                    !!argParam.paramType.details.paramSpec &&
                    typeVarContext.getSignatureContexts().length > 1;
                if (!skipApplySolvedTypeVars) {
                    expectedType = (0, typeUtils_1.applySolvedTypeVars)(expectedType, typeVarContext, {
                        useNarrowBoundOnly: !!options.useNarrowBoundOnly,
                    });
                }
            }
            else {
                skippedBareTypeVarExpectedType = true;
                // If the expected type is a union of bare TypeVars, it's not clear which of the two
                // (or both) should be constrained. We'll skip any attempt to solve the TypeVars during
                // this pass and hope that subsequent arg assignments will help us establish the correct
                // constraints.
                if ((0, types_1.isUnion)(argParam.paramType)) {
                    skipSolveTypeVars = true;
                }
            }
            // If the expected type is unknown, don't use an expected type. Instead,
            // use default rules for evaluating the expression type.
            if (expectedType && (0, types_1.isUnknown)(expectedType)) {
                expectedType = undefined;
            }
            // Was the argument's type precomputed by the caller?
            if (argParam.argType) {
                argType = argParam.argType;
            }
            else {
                const flags = argParam.isinstanceParam
                    ? 512 /* EvaluatorFlags.AllowMissingTypeArgs */ |
                        8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
                        32 /* EvaluatorFlags.DisallowParamSpec */ |
                        64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                        16 /* EvaluatorFlags.DisallowFinal */
                    : 2 /* EvaluatorFlags.DoNotSpecialize */ | 16 /* EvaluatorFlags.DisallowFinal */;
                const exprTypeResult = getTypeOfExpression(argParam.argument.valueExpression, flags, (0, typeUtils_1.makeInferenceContext)(expectedType, !!(typeResult === null || typeResult === void 0 ? void 0 : typeResult.isIncomplete), signatureTracker));
                argType = exprTypeResult.type;
                // If the type includes multiple instances of a generic function
                // signature, force the type arguments for the duplicates to have
                // unique names.
                argType = (0, typeUtils_1.ensureFunctionSignaturesAreUnique)(argType, signatureTracker, argParam.argument.valueExpression.start);
                if (exprTypeResult.isIncomplete) {
                    isTypeIncomplete = true;
                }
                if (exprTypeResult.typeErrors) {
                    isCompatible = false;
                }
                else if (expectedType && (0, typeUtils_1.requiresSpecialization)(expectedType)) {
                    // Assign the argument type back to the expected type to assign
                    // values to any in-scope placeholder type variables.
                    const typeVarContextClone = typeVarContext.clone();
                    if (assignType(expectedType, argType, /* diag */ undefined, typeVarContextClone)) {
                        typeVarContext.copyFromClone(typeVarContextClone);
                    }
                    else {
                        isCompatible = false;
                    }
                }
                expectedTypeDiag = exprTypeResult.expectedTypeDiagAddendum;
            }
            if (argParam.argument && argParam.argument.name && !isSpeculativeModeInUse(argParam.errorNode)) {
                writeTypeCache(argParam.argument.name, { type: expectedType !== null && expectedType !== void 0 ? expectedType : argType, isIncomplete: isTypeIncomplete }, 0 /* EvaluatorFlags.None */);
            }
        }
        else {
            // Was the argument's type precomputed by the caller?
            if (argParam.argType) {
                argType = argParam.argType;
            }
            else {
                const argTypeResult = getTypeOfArgument(argParam.argument);
                argType = argTypeResult.type;
                if (argTypeResult.isIncomplete) {
                    isTypeIncomplete = true;
                }
            }
            // If the argument came from a parameter's default argument value,
            // we may need to specialize the type.
            if (argParam.isDefaultArg) {
                argType = (0, typeUtils_1.applySolvedTypeVars)(argType, typeVarContext);
            }
        }
        // If we're assigning to a var arg dictionary with a TypeVar type,
        // strip literals before performing the assignment. This is used in
        // places like a dict constructor.
        if (argParam.paramCategory === 2 /* ParameterCategory.KwargsDict */ && (0, types_1.isTypeVar)(argParam.paramType)) {
            argType = stripLiteralValue(argType);
        }
        // If there's a constraint filter, apply it to top-level type variables
        // if appropriate. This doesn't properly handle non-top-level constrained
        // type variables.
        if (options.conditionFilter) {
            argType = mapSubtypesExpandTypeVars(argType, { conditionFilter: options.conditionFilter }, (expandedSubtype) => {
                return expandedSubtype;
            });
        }
        const condition = argType.condition;
        let diag = new diagnostic_1.DiagnosticAddendum();
        if ((0, types_1.isParamSpec)(argParam.paramType)) {
            // Handle the case where we're assigning a *args or **kwargs argument
            // to a *P.args or **P.kwargs parameter.
            if (argParam.paramType.paramSpecAccess !== undefined) {
                return { isCompatible, argType, isTypeIncomplete, condition };
            }
            // Handle the case where we're assigning a *P.args or **P.kwargs argument
            // to a *P.args or **P.kwargs parameter.
            if ((0, types_1.isParamSpec)(argType) && argType.paramSpecAccess !== undefined) {
                return { isCompatible, argType, isTypeIncomplete, condition };
            }
        }
        // If we are asked to skip overload arguments, determine whether the argument
        // is an explicit overload type, an overloaded class constructor, or a
        // an overloaded callback protocol.
        if (options.skipOverloadArg) {
            if ((0, types_1.isOverloadedFunction)(argType)) {
                return {
                    isCompatible,
                    argType,
                    isTypeIncomplete,
                    skippedOverloadArg: true,
                    skippedBareTypeVarExpectedType,
                    condition,
                };
            }
            const concreteParamType = makeTopLevelTypeVarsConcrete(argParam.paramType);
            if ((0, types_1.isFunction)(concreteParamType) || (0, types_1.isOverloadedFunction)(concreteParamType)) {
                if ((0, types_1.isInstantiableClass)(argType)) {
                    const constructor = (0, constructors_1.createFunctionFromConstructor)(evaluatorInterface, argType);
                    if (constructor) {
                        return {
                            isCompatible,
                            argType,
                            isTypeIncomplete,
                            skippedOverloadArg: true,
                            skippedBareTypeVarExpectedType,
                            condition,
                        };
                    }
                }
                if ((0, types_1.isClassInstance)(argType)) {
                    const callMember = (0, typeUtils_1.lookUpObjectMember)(argType, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
                    if (callMember) {
                        const memberType = getTypeOfMember(callMember);
                        if ((0, types_1.isOverloadedFunction)(memberType)) {
                            return {
                                isCompatible,
                                argType,
                                isTypeIncomplete,
                                skippedOverloadArg: true,
                                skippedBareTypeVarExpectedType,
                                condition,
                            };
                        }
                    }
                }
            }
        }
        let assignTypeFlags = skipSolveTypeVars ? 8 /* AssignTypeFlags.SkipSolveTypeVars */ : 0 /* AssignTypeFlags.Default */;
        if (argParam.isinstanceParam) {
            assignTypeFlags |= 32768 /* AssignTypeFlags.AllowIsinstanceSpecialForms */;
        }
        if (!assignType(argParam.paramType, argType, diag.createAddendum(), typeVarContext, 
        /* srcTypeVarContext */ undefined, assignTypeFlags)) {
            // Mismatching parameter types are common in untyped code; don't bother spending time
            // printing types if the diagnostic is disabled.
            const fileInfo = AnalyzerNodeInfo.getFileInfo(argParam.errorNode);
            if (fileInfo.diagnosticRuleSet.reportArgumentType !== 'none' &&
                !isDiagnosticSuppressedForNode(argParam.errorNode) &&
                !isTypeIncomplete) {
                const argTypeText = printType(argType);
                const paramTypeText = printType(argParam.paramType);
                let message;
                if (argParam.paramName && !argParam.isParamNameSynthesized) {
                    if (functionName) {
                        message = localize_1.LocMessage.argAssignmentParamFunction().format({
                            argType: argTypeText,
                            paramType: paramTypeText,
                            functionName,
                            paramName: argParam.paramName,
                        });
                    }
                    else {
                        message = localize_1.LocMessage.argAssignmentParam().format({
                            argType: argTypeText,
                            paramType: paramTypeText,
                            paramName: argParam.paramName,
                        });
                    }
                }
                else {
                    if (functionName) {
                        message = localize_1.LocMessage.argAssignmentFunction().format({
                            argType: argTypeText,
                            paramType: paramTypeText,
                            functionName,
                        });
                    }
                    else {
                        message = localize_1.LocMessage.argAssignment().format({
                            argType: argTypeText,
                            paramType: paramTypeText,
                        });
                    }
                }
                // If we have an expected type diagnostic addendum, use that
                // instead of the local diagnostic addendum because it will
                // be more informative.
                if (expectedTypeDiag) {
                    diag = expectedTypeDiag;
                }
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, message + diag.getString(), argParam.errorNode, (_a = diag.getEffectiveTextRange()) !== null && _a !== void 0 ? _a : argParam.errorNode);
            }
            return { isCompatible: false, argType, isTypeIncomplete, skippedBareTypeVarExpectedType, condition };
        }
        if (!options.skipUnknownArgCheck) {
            const simplifiedType = (0, types_1.removeUnbound)(argType);
            const fileInfo = AnalyzerNodeInfo.getFileInfo(argParam.errorNode);
            function getDiagAddendum() {
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                if (argParam.paramName) {
                    diagAddendum.addMessage((functionName
                        ? localize_1.LocAddendum.argParamFunction().format({
                            paramName: argParam.paramName,
                            functionName,
                        })
                        : localize_1.LocAddendum.argParam().format({ paramName: argParam.paramName })) +
                        diagAddendum.getString());
                }
                return diagAddendum;
            }
            // Do not check for unknown types if the expected type is "Any".
            // Don't print types if reportUnknownArgumentType is disabled for performance.
            if ((fileInfo.diagnosticRuleSet.reportUnknownArgumentType !== 'none' ||
                fileInfo.diagnosticRuleSet.reportAny !== 'none') &&
                !(0, types_1.isAny)(argParam.paramType) &&
                !isTypeIncomplete) {
                if ((0, types_1.isUnknown)(simplifiedType)) {
                    const diagAddendum = getDiagAddendum();
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownArgumentType, localize_1.LocMessage.argTypeUnknown() + diagAddendum.getString(), argParam.errorNode);
                }
                else if ((0, typeUtils_1.isPartlyUnknown)(simplifiedType)) {
                    // If the parameter type is also partially unknown, don't report
                    // the error because it's likely that the partially-unknown type
                    // arose due to bidirectional type matching.
                    if (!(0, typeUtils_1.isPartlyUnknown)(argParam.paramType)) {
                        const diagAddendum = getDiagAddendum();
                        diagAddendum.addMessage(localize_1.LocAddendum.argumentType().format({
                            type: printType(simplifiedType, { expandTypeAlias: true }),
                        }));
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnknownArgumentType, localize_1.LocMessage.argTypePartiallyUnknown() + diagAddendum.getString(), argParam.errorNode);
                    }
                }
                else if ((0, types_1.isAny)(simplifiedType)) {
                    const diagAddendum = getDiagAddendum();
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.argTypeAny() + diagAddendum.getString(), argParam.errorNode);
                }
            }
        }
        return { isCompatible, argType, isTypeIncomplete, skippedBareTypeVarExpectedType, condition };
    }
    function createTypeVarType(errorNode, classType, argList) {
        var _a, _b, _c, _d, _e, _f, _g;
        let typeVarName = '';
        let firstConstraintArg;
        let defaultValueNode;
        if (argList.length === 0) {
            addError(localize_1.LocMessage.typeVarFirstArg(), errorNode);
            return undefined;
        }
        const firstArg = argList[0];
        if (firstArg.valueExpression && firstArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            typeVarName = firstArg.valueExpression.strings.map((s) => s.value).join('');
        }
        else {
            addError(localize_1.LocMessage.typeVarFirstArg(), firstArg.valueExpression || errorNode);
        }
        const typeVar = types_1.TypeBase.cloneAsSpecialForm(types_1.TypeVarType.createInstantiable(typeVarName, /* isParamSpec */ false), types_1.ClassType.cloneAsInstance(classType));
        // Parse the remaining parameters.
        const paramNameMap = new Map();
        for (let i = 1; i < argList.length; i++) {
            const paramNameNode = argList[i].name;
            const paramName = paramNameNode ? paramNameNode.value : undefined;
            if (paramName) {
                if (paramNameMap.get(paramName)) {
                    addError(localize_1.LocMessage.duplicateParam().format({ name: paramName }), argList[i].valueExpression || errorNode);
                }
                if (paramName === 'bound') {
                    if (typeVar.details.constraints.length > 0) {
                        addError(localize_1.LocMessage.typeVarBoundAndConstrained(), argList[i].valueExpression || errorNode);
                    }
                    else {
                        const argType = (_b = (_a = argList[i].typeResult) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : getTypeOfExpressionExpectingType(argList[i].valueExpression, {
                            disallowProtocolAndTypedDict: true,
                        }).type;
                        if ((0, typeUtils_1.requiresSpecialization)(argType, { ignorePseudoGeneric: true, ignoreImplicitTypeArgs: true })) {
                            addError(localize_1.LocMessage.typeVarBoundGeneric(), argList[i].valueExpression || errorNode);
                        }
                        typeVar.details.boundType = (0, typeUtils_1.convertToInstance)(argType);
                    }
                }
                else if (paramName === 'covariant') {
                    if (argList[i].valueExpression && getBooleanValue(argList[i].valueExpression)) {
                        if (typeVar.details.declaredVariance === 4 /* Variance.Contravariant */ ||
                            typeVar.details.declaredVariance === 0 /* Variance.Auto */) {
                            addError(localize_1.LocMessage.typeVarVariance(), argList[i].valueExpression);
                        }
                        else {
                            typeVar.details.declaredVariance = 3 /* Variance.Covariant */;
                        }
                    }
                }
                else if (paramName === 'contravariant') {
                    if (argList[i].valueExpression && getBooleanValue(argList[i].valueExpression)) {
                        if (typeVar.details.declaredVariance === 3 /* Variance.Covariant */ ||
                            typeVar.details.declaredVariance === 0 /* Variance.Auto */) {
                            addError(localize_1.LocMessage.typeVarVariance(), argList[i].valueExpression);
                        }
                        else {
                            typeVar.details.declaredVariance = 4 /* Variance.Contravariant */;
                        }
                    }
                }
                else if (paramName === 'infer_variance') {
                    if (argList[i].valueExpression && getBooleanValue(argList[i].valueExpression)) {
                        if (typeVar.details.declaredVariance === 3 /* Variance.Covariant */ ||
                            typeVar.details.declaredVariance === 4 /* Variance.Contravariant */) {
                            addError(localize_1.LocMessage.typeVarVariance(), argList[i].valueExpression);
                        }
                        else {
                            typeVar.details.declaredVariance = 0 /* Variance.Auto */;
                        }
                    }
                }
                else if (paramName === 'default') {
                    defaultValueNode = argList[i].valueExpression;
                    const argType = (_d = (_c = argList[i].typeResult) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : getTypeOfExpressionExpectingType(defaultValueNode, {
                        allowTypeVarsWithoutScopeId: true,
                    }).type;
                    typeVar.details.defaultType = (0, typeUtils_1.convertToInstance)(argType);
                    typeVar.details.isDefaultExplicit = true;
                    const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
                    if (!fileInfo.isStubFile &&
                        fileInfo.executionEnvironment.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_13) &&
                        classType.details.moduleName !== 'typing_extensions') {
                        addError(localize_1.LocMessage.typeVarDefaultIllegal(), defaultValueNode);
                    }
                }
                else {
                    addError(localize_1.LocMessage.typeVarUnknownParam().format({ name: paramName }), ((_e = argList[i].node) === null || _e === void 0 ? void 0 : _e.name) || argList[i].valueExpression || errorNode);
                }
                paramNameMap.set(paramName, paramName);
            }
            else {
                if (typeVar.details.boundType) {
                    addError(localize_1.LocMessage.typeVarBoundAndConstrained(), argList[i].valueExpression || errorNode);
                }
                else {
                    const argType = (_g = (_f = argList[i].typeResult) === null || _f === void 0 ? void 0 : _f.type) !== null && _g !== void 0 ? _g : getTypeOfExpressionExpectingType(argList[i].valueExpression).type;
                    if ((0, typeUtils_1.requiresSpecialization)(argType, { ignorePseudoGeneric: true })) {
                        addError(localize_1.LocMessage.typeVarConstraintGeneric(), argList[i].valueExpression || errorNode);
                    }
                    types_1.TypeVarType.addConstraint(typeVar, (0, typeUtils_1.convertToInstance)(argType));
                    if (firstConstraintArg === undefined) {
                        firstConstraintArg = argList[i];
                    }
                }
            }
        }
        if (typeVar.details.constraints.length === 1 && firstConstraintArg) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarSingleConstraint(), firstConstraintArg.valueExpression || errorNode);
        }
        // If a default is provided, make sure it is compatible with the bound
        // or constraint.
        if (typeVar.details.isDefaultExplicit && defaultValueNode) {
            verifyTypeVarDefaultIsCompatible(typeVar, defaultValueNode);
        }
        return typeVar;
    }
    function verifyTypeVarDefaultIsCompatible(typeVar, defaultValueNode) {
        (0, debug_1.assert)(typeVar.details.isDefaultExplicit);
        const typeVarContext = new typeVarContext_1.TypeVarContext(typeVar.scopeId);
        const concreteDefaultType = makeTopLevelTypeVarsConcrete((0, typeUtils_1.applySolvedTypeVars)(typeVar.details.defaultType, typeVarContext, {
            unknownIfNotFound: true,
        }));
        if (typeVar.details.boundType) {
            if (!assignType(typeVar.details.boundType, concreteDefaultType)) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarDefaultBoundMismatch(), defaultValueNode);
            }
        }
        else if (typeVar.details.constraints.length > 0) {
            let isConstraintCompatible = true;
            // If the default type is a constrained TypeVar, make sure all of its constraints
            // are also constraints in typeVar. If the default type is not a constrained TypeVar,
            // use its concrete type to compare against the constraints.
            if ((0, types_1.isTypeVar)(typeVar.details.defaultType) && typeVar.details.defaultType.details.constraints.length > 0) {
                for (const constraint of typeVar.details.defaultType.details.constraints) {
                    if (!typeVar.details.constraints.some((c) => (0, types_1.isTypeSame)(c, constraint))) {
                        isConstraintCompatible = false;
                    }
                }
            }
            else if (!typeVar.details.constraints.some((constraint) => (0, types_1.isTypeSame)(constraint, concreteDefaultType, { ignoreConditions: true }))) {
                isConstraintCompatible = false;
            }
            if (!isConstraintCompatible) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarDefaultConstraintMismatch(), defaultValueNode);
            }
        }
    }
    function createTypeVarTupleType(errorNode, classType, argList) {
        var _a, _b;
        let typeVarName = '';
        if (argList.length === 0) {
            addError(localize_1.LocMessage.typeVarFirstArg(), errorNode);
            return undefined;
        }
        const firstArg = argList[0];
        if (firstArg.valueExpression && firstArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            typeVarName = firstArg.valueExpression.strings.map((s) => s.value).join('');
        }
        else {
            addError(localize_1.LocMessage.typeVarFirstArg(), firstArg.valueExpression || errorNode);
        }
        const typeVar = types_1.TypeBase.cloneAsSpecialForm(types_1.TypeVarType.createInstantiable(typeVarName, /* isParamSpec */ false), types_1.ClassType.cloneAsInstance(classType));
        typeVar.details.isVariadic = true;
        typeVar.details.defaultType = makeTupleObject([{ type: types_1.UnknownType.create(), isUnbounded: true }]);
        // Parse the remaining parameters.
        for (let i = 1; i < argList.length; i++) {
            const paramNameNode = argList[i].name;
            const paramName = paramNameNode ? paramNameNode.value : undefined;
            if (paramName) {
                if (paramName === 'default') {
                    const expr = argList[i].valueExpression;
                    if (expr) {
                        const defaultType = getTypeVarTupleDefaultType(expr, /* isPep695Syntax */ false);
                        if (defaultType) {
                            typeVar.details.defaultType = defaultType;
                            typeVar.details.isDefaultExplicit = true;
                        }
                    }
                    const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
                    if (!fileInfo.isStubFile &&
                        fileInfo.executionEnvironment.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_13) &&
                        classType.details.moduleName !== 'typing_extensions') {
                        addError(localize_1.LocMessage.typeVarDefaultIllegal(), expr);
                    }
                }
                else {
                    addError(localize_1.LocMessage.typeVarTupleUnknownParam().format({ name: ((_a = argList[i].name) === null || _a === void 0 ? void 0 : _a.value) || '?' }), ((_b = argList[i].node) === null || _b === void 0 ? void 0 : _b.name) || argList[i].valueExpression || errorNode);
                }
            }
            else {
                addError(localize_1.LocMessage.typeVarTupleConstraints(), argList[i].valueExpression || errorNode);
            }
        }
        return typeVar;
    }
    function getTypeVarTupleDefaultType(node, isPep695Syntax) {
        const argType = getTypeOfExpressionExpectingType(node, {
            allowUnpackedTuple: true,
            allowTypeVarsWithoutScopeId: true,
            allowForwardReference: isPep695Syntax,
        }).type;
        const isUnpackedTuple = (0, types_1.isClass)(argType) && (0, typeUtils_1.isTupleClass)(argType) && argType.isUnpacked;
        const isUnpackedTypeVarTuple = (0, types_1.isUnpackedVariadicTypeVar)(argType);
        if (!isUnpackedTuple && !isUnpackedTypeVarTuple) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarTupleDefaultNotUnpacked(), node);
            return undefined;
        }
        return (0, typeUtils_1.convertToInstance)(argType);
    }
    function createParamSpecType(errorNode, classType, argList) {
        if (argList.length === 0) {
            addError(localize_1.LocMessage.paramSpecFirstArg(), errorNode);
            return undefined;
        }
        const firstArg = argList[0];
        let paramSpecName = '';
        if (firstArg.valueExpression && firstArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            paramSpecName = firstArg.valueExpression.strings.map((s) => s.value).join('');
        }
        else {
            addError(localize_1.LocMessage.paramSpecFirstArg(), firstArg.valueExpression || errorNode);
        }
        const paramSpec = types_1.TypeBase.cloneAsSpecialForm(types_1.TypeVarType.createInstantiable(paramSpecName, /* isParamSpec */ true), types_1.ClassType.cloneAsInstance(classType));
        paramSpec.details.defaultType = (0, typeUtils_1.getUnknownTypeForParamSpec)();
        // Parse the remaining parameters.
        for (let i = 1; i < argList.length; i++) {
            const paramNameNode = argList[i].name;
            const paramName = paramNameNode ? paramNameNode.value : undefined;
            if (paramName) {
                if (paramName === 'default') {
                    const expr = argList[i].valueExpression;
                    if (expr) {
                        const defaultType = getParamSpecDefaultType(expr, /* isPep695Syntax */ false);
                        if (defaultType) {
                            paramSpec.details.defaultType = defaultType;
                            paramSpec.details.isDefaultExplicit = true;
                        }
                    }
                    const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
                    if (!fileInfo.isStubFile &&
                        fileInfo.executionEnvironment.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_13) &&
                        classType.details.moduleName !== 'typing_extensions') {
                        addError(localize_1.LocMessage.typeVarDefaultIllegal(), expr);
                    }
                }
                else {
                    addError(localize_1.LocMessage.paramSpecUnknownParam().format({ name: paramName }), paramNameNode || argList[i].valueExpression || errorNode);
                }
            }
            else {
                addError(localize_1.LocMessage.paramSpecUnknownArg(), argList[i].valueExpression || errorNode);
                break;
            }
        }
        return paramSpec;
    }
    function getParamSpecDefaultType(node, isPep695Syntax) {
        const functionType = types_1.FunctionType.createSynthesizedInstance('', 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */ | 65536 /* FunctionTypeFlags.ParamSpecValue */);
        if (node.nodeType === 18 /* ParseNodeType.Ellipsis */) {
            types_1.FunctionType.addDefaultParameters(functionType);
            return functionType;
        }
        if (node.nodeType === 31 /* ParseNodeType.List */) {
            node.entries.forEach((paramExpr, index) => {
                const typeResult = getTypeOfExpressionExpectingType(paramExpr, {
                    allowTypeVarsWithoutScopeId: true,
                    allowForwardReference: isPep695Syntax,
                });
                types_1.FunctionType.addParameter(functionType, {
                    category: 0 /* ParameterCategory.Simple */,
                    name: `__p${index}`,
                    isNameSynthesized: true,
                    hasDeclaredType: true,
                    type: (0, typeUtils_1.convertToInstance)(typeResult.type),
                });
            });
            if (node.entries.length > 0) {
                types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
            }
            // Update the type cache so we don't attempt to re-evaluate this node.
            // The type doesn't matter, so use Any.
            writeTypeCache(node, { type: types_1.AnyType.create() }, /* flags */ undefined);
            return functionType;
        }
        else {
            const typeResult = getTypeOfExpressionExpectingType(node, {
                allowParamSpec: true,
                allowTypeVarsWithoutScopeId: true,
            });
            if (typeResult.typeErrors) {
                return undefined;
            }
            if ((0, types_1.isParamSpec)(typeResult.type)) {
                functionType.details.paramSpec = typeResult.type;
                return functionType;
            }
            if ((0, types_1.isClassInstance)(typeResult.type) &&
                types_1.ClassType.isBuiltIn(typeResult.type, ['EllipsisType', 'ellipsis'])) {
                types_1.FunctionType.addDefaultParameters(functionType);
                return functionType;
            }
        }
        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramSpecDefaultNotTuple(), node);
        return undefined;
    }
    // Handles a call to TypeAliasType(). This special form allows a caller to programmatically
    // create a type alias as defined in PEP 695. If one or more of the arguments is incorrect,
    // it returns undefined so the normal constructor evaluation can be performed (and type errors
    // emitted).
    function createTypeAliasType(errorNode, argList) {
        if (errorNode.nodeType !== 9 /* ParseNodeType.Call */ || !errorNode.parent || argList.length < 2) {
            return undefined;
        }
        if (errorNode.parent.nodeType !== 3 /* ParseNodeType.Assignment */ ||
            errorNode.parent.rightExpression !== errorNode ||
            errorNode.parent.leftExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasTypeMustBeAssigned(), errorNode);
            return undefined;
        }
        const nameNode = errorNode.parent.leftExpression;
        const firstArg = argList[0];
        if (firstArg.valueExpression && firstArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            const typeAliasName = firstArg.valueExpression.strings.map((s) => s.value).join('');
            if (typeAliasName !== nameNode.value) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasTypeNameMismatch(), firstArg.valueExpression);
            }
        }
        else {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasTypeNameArg(), firstArg.valueExpression || errorNode);
            return undefined;
        }
        let valueExpr;
        let typeParamsExpr;
        // Parse the remaining parameters.
        for (let i = 1; i < argList.length; i++) {
            const paramNameNode = argList[i].name;
            const paramName = paramNameNode ? paramNameNode.value : undefined;
            if (paramName) {
                if (paramName === 'type_params' && !typeParamsExpr) {
                    typeParamsExpr = argList[i].valueExpression;
                }
                else if (paramName === 'value' && !valueExpr) {
                    valueExpr = argList[i].valueExpression;
                }
                else {
                    return undefined;
                }
            }
            else if (i === 1) {
                valueExpr = argList[i].valueExpression;
            }
            else {
                return undefined;
            }
        }
        // The value expression is not optional, so bail if it's not present.
        if (!valueExpr) {
            return undefined;
        }
        let typeParameters;
        if (typeParamsExpr) {
            if (typeParamsExpr.nodeType !== 52 /* ParseNodeType.Tuple */) {
                addError(localize_1.LocMessage.typeAliasTypeParamInvalid(), typeParamsExpr);
                return undefined;
            }
            typeParameters = [];
            let isTypeParamListValid = true;
            typeParamsExpr.expressions.map((expr) => {
                let entryType = getTypeOfExpression(expr, 128 /* EvaluatorFlags.ExpectingInstantiableType */ | 4096 /* EvaluatorFlags.AllowTypeVarsWithoutScopeId */).type;
                if ((0, types_1.isTypeVar)(entryType)) {
                    if (entryType.scopeId || entryType.isVariadicUnpacked) {
                        isTypeParamListValid = false;
                    }
                    else {
                        entryType = types_1.TypeVarType.cloneForScopeId(entryType, ParseTreeUtils.getScopeIdForNode(nameNode), nameNode.value, 2 /* TypeVarScopeType.TypeAlias */);
                    }
                    typeParameters.push(entryType);
                }
                else {
                    isTypeParamListValid = false;
                }
            });
            if (!isTypeParamListValid) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasTypeParamInvalid(), typeParamsExpr);
                return undefined;
            }
        }
        return getTypeOfTypeAliasCommon(nameNode, nameNode, valueExpr, 
        /* isPep695Syntax */ true, 
        /* typeParamNodes */ undefined, () => typeParameters);
    }
    function getBooleanValue(node) {
        if (node.nodeType === 11 /* ParseNodeType.Constant */) {
            if (node.constType === 15 /* KeywordType.False */) {
                return false;
            }
            else if (node.constType === 33 /* KeywordType.True */) {
                return true;
            }
        }
        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.expectedBoolLiteral(), node);
        return false;
    }
    function getFunctionFullName(functionNode, moduleName, functionName) {
        const nameParts = [functionName];
        let curNode = functionNode;
        // Walk the parse tree looking for classes or functions.
        while (curNode) {
            curNode = ParseTreeUtils.getEnclosingClassOrFunction(curNode);
            if (curNode) {
                nameParts.push(curNode.name.value);
            }
        }
        nameParts.push(moduleName);
        return nameParts.reverse().join('.');
    }
    // Implements the semantics of the NewType call as documented
    // in the Python specification: The static type checker will treat
    // the new type as if it were a subclass of the original type.
    function createNewType(errorNode, argList) {
        var _a, _b, _c;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
        let className = '';
        if (argList.length !== 2) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.newTypeParamCount(), errorNode);
            return undefined;
        }
        const nameArg = argList[0];
        if (nameArg.argumentCategory === 0 /* ArgumentCategory.Simple */ &&
            nameArg.valueExpression &&
            nameArg.valueExpression.nodeType === 48 /* ParseNodeType.StringList */) {
            className = nameArg.valueExpression.strings.map((s) => s.value).join('');
        }
        if (!className) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.newTypeBadName(), (_a = argList[0].node) !== null && _a !== void 0 ? _a : errorNode);
            return undefined;
        }
        if (((_b = errorNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 3 /* ParseNodeType.Assignment */ &&
            errorNode.parent.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            errorNode.parent.leftExpression.value !== className) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeNameMismatch(), errorNode.parent.leftExpression);
            return undefined;
        }
        let baseClass = getTypeOfArgumentExpectingType(argList[1]).type;
        let isBaseClassAny = false;
        if ((0, types_1.isAnyOrUnknown)(baseClass)) {
            if (objectType && (0, types_1.isClassInstance)(objectType)) {
                baseClass = types_1.ClassType.cloneAsInstantiable(objectType);
            }
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeAnyOrUnknown(), (_c = argList[1].node) !== null && _c !== void 0 ? _c : errorNode);
            isBaseClassAny = true;
        }
        // Specifically disallow Annotated.
        if (baseClass.specialForm &&
            (0, types_1.isInstantiableClass)(baseClass.specialForm) &&
            types_1.ClassType.isBuiltIn(baseClass.specialForm, 'Annotated')) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeNotAClass(), argList[1].node || errorNode);
            return undefined;
        }
        if (!(0, types_1.isInstantiableClass)(baseClass)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeNotAClass(), argList[1].node || errorNode);
            return undefined;
        }
        if (types_1.ClassType.isProtocolClass(baseClass) || types_1.ClassType.isTypedDictClass(baseClass)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeProtocolClass(), argList[1].node || errorNode);
        }
        else if (baseClass.literalValue !== undefined) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.newTypeLiteral(), argList[1].node || errorNode);
        }
        let classFlags = baseClass.details.flags & ~(1 /* ClassTypeFlags.BuiltInClass */ | 2 /* ClassTypeFlags.SpecialBuiltIn */);
        classFlags |= 8192 /* ClassTypeFlags.Final */ | 536870912 /* ClassTypeFlags.NewTypeClass */ | 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */;
        const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, classFlags, ParseTreeUtils.getTypeSourceId(errorNode), 
        /* declaredMetaclass */ undefined, baseClass.details.effectiveMetaclass);
        classType.details.baseClasses.push(isBaseClassAny ? types_1.AnyType.create() : baseClass);
        (0, typeUtils_1.computeMroLinearization)(classType);
        if (!isBaseClassAny) {
            // Synthesize an __init__ method that accepts only the specified type.
            const initType = types_1.FunctionType.createSynthesizedInstance('__init__');
            types_1.FunctionType.addParameter(initType, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'self',
                type: types_1.ClassType.cloneAsInstance(classType),
                hasDeclaredType: true,
            });
            types_1.FunctionType.addParameter(initType, {
                category: 0 /* ParameterCategory.Simple */,
                name: '_x',
                type: types_1.ClassType.cloneAsInstance(baseClass),
                hasDeclaredType: true,
            });
            initType.details.declaredReturnType = getNoneType();
            types_1.ClassType.getSymbolTable(classType).set('__init__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, initType));
            // Synthesize a trivial __new__ method.
            const newType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* FunctionTypeFlags.ConstructorMethod */);
            types_1.FunctionType.addParameter(newType, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'cls',
                type: classType,
                hasDeclaredType: true,
            });
            types_1.FunctionType.addDefaultParameters(newType);
            newType.details.declaredReturnType = types_1.ClassType.cloneAsInstance(classType);
            newType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
            types_1.ClassType.getSymbolTable(classType).set('__new__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, newType));
        }
        return classType;
    }
    // Implements the semantics of the multi-parameter variant of the "type" call.
    function createClassFromMetaclass(errorNode, argList, metaclass) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
        const arg0Type = getTypeOfArgument(argList[0]).type;
        if (!(0, types_1.isClassInstance)(arg0Type) || !types_1.ClassType.isBuiltIn(arg0Type, 'str')) {
            return undefined;
        }
        const className = arg0Type.literalValue || '_';
        const arg1Type = getTypeOfArgument(argList[1]).type;
        // TODO - properly handle case where tuple of base classes is provided.
        if (!(0, types_1.isClassInstance)(arg1Type) || !(0, typeUtils_1.isTupleClass)(arg1Type) || arg1Type.tupleTypeArguments === undefined) {
            return undefined;
        }
        const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */, ParseTreeUtils.getTypeSourceId(errorNode), 
        /* declaredMetaclass */ undefined, arg1Type.details.effectiveMetaclass);
        arg1Type.tupleTypeArguments.forEach((typeArg) => {
            const specializedType = makeTopLevelTypeVarsConcrete(typeArg.type);
            if ((0, typeUtils_1.isEffectivelyInstantiable)(specializedType)) {
                classType.details.baseClasses.push(specializedType);
            }
            else {
                addExpectedClassDiagnostic(typeArg.type, argList[1].valueExpression || errorNode);
            }
        });
        if (!(0, typeUtils_1.computeMroLinearization)(classType)) {
            addError(localize_1.LocMessage.methodOrdering(), errorNode);
        }
        return classType;
    }
    function getTypeOfConstant(node, flags) {
        let type;
        if (node.constType === 26 /* KeywordType.None */) {
            type = (flags & 128 /* EvaluatorFlags.ExpectingInstantiableType */) !== 0 ? noneClassType : noneType;
        }
        else if (node.constType === 33 /* KeywordType.True */ ||
            node.constType === 15 /* KeywordType.False */ ||
            node.constType === 9 /* KeywordType.Debug */) {
            type = getBuiltInObject(node, 'bool');
            // For True and False, we can create truthy and falsy
            // versions of 'bool'.
            if (type && (0, types_1.isClassInstance)(type)) {
                if (node.constType === 33 /* KeywordType.True */) {
                    type = types_1.ClassType.cloneWithLiteral(type, /* value */ true);
                }
                else if (node.constType === 15 /* KeywordType.False */) {
                    type = types_1.ClassType.cloneWithLiteral(type, /* value */ false);
                }
            }
        }
        return { type: type !== null && type !== void 0 ? type : types_1.UnknownType.create() };
    }
    function getTypeOfMagicMethodCall(objType, methodName, argList, errorNode, inferenceContext, diag) {
        let magicMethodSupported = true;
        // Create a helper lambda for object subtypes.
        const handleSubtype = (subtype) => {
            let magicMethodType;
            const concreteSubtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isClass)(concreteSubtype)) {
                magicMethodType = getBoundMagicMethod(concreteSubtype, methodName, subtype, diag);
            }
            if (magicMethodType) {
                const functionArgs = argList.map((arg) => {
                    return {
                        argumentCategory: 0 /* ArgumentCategory.Simple */,
                        typeResult: arg,
                    };
                });
                let callResult;
                callResult = useSpeculativeMode(errorNode, () => {
                    (0, debug_1.assert)(magicMethodType !== undefined);
                    return validateCallArguments(errorNode, functionArgs, { type: magicMethodType }, 
                    /* typeVarContext */ undefined, 
                    /* skipUnknownArgCheck */ true, inferenceContext);
                });
                // If there were errors with the expected type, try
                // to evaluate without the expected type.
                if (callResult.argumentErrors && inferenceContext) {
                    callResult = useSpeculativeMode(errorNode, () => {
                        (0, debug_1.assert)(magicMethodType !== undefined);
                        return validateCallArguments(errorNode, functionArgs, { type: magicMethodType }, 
                        /* typeVarContext */ undefined, 
                        /* skipUnknownArgCheck */ true);
                    });
                }
                if (callResult.argumentErrors) {
                    magicMethodSupported = false;
                }
                return callResult.returnType;
            }
            magicMethodSupported = false;
            return undefined;
        };
        const returnType = (0, typeUtils_1.mapSubtypes)(objType, (subtype) => {
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return subtype;
            }
            if ((0, types_1.isClassInstance)(subtype) || (0, types_1.isInstantiableClass)(subtype) || (0, types_1.isTypeVar)(subtype)) {
                return handleSubtype(subtype);
            }
            if ((0, typeUtils_1.isNoneInstance)(subtype)) {
                if (objectType && (0, types_1.isClassInstance)(objectType)) {
                    // Use 'object' for 'None'.
                    return handleSubtype(objectType);
                }
            }
            if ((0, typeUtils_1.isNoneTypeClass)(subtype)) {
                if (typeClassType && (0, types_1.isInstantiableClass)(typeClassType)) {
                    // Use 'type' for 'type[None]'.
                    return handleSubtype(types_1.ClassType.cloneAsInstance(typeClassType));
                }
            }
            magicMethodSupported = false;
            return undefined;
        });
        if (!magicMethodSupported) {
            return undefined;
        }
        return returnType;
    }
    function getTypeOfDictionary(node, flags, inferenceContext) {
        var _a;
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0 &&
            ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 1 /* ParseNodeType.Argument */) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.useDictInstead());
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.dictInAnnotation() + diag.getString(), node);
        }
        // If the expected type is a union, analyze for each of the subtypes
        // to find one that matches.
        let effectiveExpectedType = inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType;
        if (inferenceContext && (0, types_1.isUnion)(inferenceContext.expectedType)) {
            let matchingSubtype;
            let matchingSubtypeResult;
            (0, typeUtils_1.doForEachSubtype)(inferenceContext.expectedType, (subtype) => {
                // Use shortcut if we've already found a match.
                if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) {
                    return;
                }
                const subtypeResult = useSpeculativeMode(node, () => {
                    return getTypeOfDictionaryWithContext(node, (0, typeUtils_1.makeInferenceContext)(subtype));
                });
                if (subtypeResult && assignType(subtype, subtypeResult.type)) {
                    // If this is the first result we're seeing or it's the first result
                    // without errors, select it as the match.
                    if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) {
                        matchingSubtype = subtype;
                        matchingSubtypeResult = subtypeResult;
                    }
                }
            }, 
            /* sortSubtypes */ true);
            effectiveExpectedType = matchingSubtype;
        }
        let expectedTypeDiagAddendum = undefined;
        if (effectiveExpectedType) {
            expectedTypeDiagAddendum = new diagnostic_1.DiagnosticAddendum();
            const result = getTypeOfDictionaryWithContext(node, (0, typeUtils_1.makeInferenceContext)(effectiveExpectedType), expectedTypeDiagAddendum);
            if (result) {
                return result;
            }
        }
        const result = getTypeOfDictionaryInferred(node, /* hasExpectedType */ !!inferenceContext);
        return { ...result, expectedTypeDiagAddendum };
    }
    function getTypeOfDictionaryWithContext(node, inferenceContext, expectedDiagAddendum) {
        inferenceContext.expectedType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(inferenceContext.expectedType);
        let concreteExpectedType = makeTopLevelTypeVarsConcrete(inferenceContext.expectedType);
        if (!(0, types_1.isClassInstance)(concreteExpectedType)) {
            return undefined;
        }
        const keyTypes = [];
        const valueTypes = [];
        let isIncomplete = false;
        // Handle TypedDict's as a special case.
        if (types_1.ClassType.isTypedDictClass(concreteExpectedType)) {
            // Remove any conditions associated with the type so the resulting type isn't
            // considered compatible with a bound TypeVar.
            concreteExpectedType = types_1.TypeBase.cloneForCondition(concreteExpectedType, undefined);
            const expectedTypedDictEntries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluatorInterface, concreteExpectedType);
            // Infer the key and value types if possible.
            if (getKeyAndValueTypesFromDictionary(node, keyTypes, valueTypes, 
            /* forceStrictInference */ true, 
            /* isValueTypeInvariant */ true, 
            /* expectedKeyType */ undefined, 
            /* expectedValueType */ undefined, expectedTypedDictEntries, expectedDiagAddendum)) {
                isIncomplete = true;
            }
            const resultTypedDict = (0, typedDicts_1.assignToTypedDict)(evaluatorInterface, concreteExpectedType, keyTypes, valueTypes, 
            // Don't overwrite existing expectedDiagAddendum messages if they were
            // already provided by getKeyValueTypesFromDictionary.
            (expectedDiagAddendum === null || expectedDiagAddendum === void 0 ? void 0 : expectedDiagAddendum.isEmpty()) ? expectedDiagAddendum : undefined);
            if (resultTypedDict) {
                return {
                    type: resultTypedDict,
                    isIncomplete,
                };
            }
            return undefined;
        }
        let expectedKeyType;
        let expectedValueType;
        if ((0, types_1.isAnyOrUnknown)(inferenceContext.expectedType)) {
            expectedKeyType = inferenceContext.expectedType;
            expectedValueType = inferenceContext.expectedType;
        }
        else {
            const builtInDict = getBuiltInObject(node, 'dict');
            if (!(0, types_1.isClassInstance)(builtInDict)) {
                return undefined;
            }
            const dictTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(builtInDict));
            if (!(0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluatorInterface, builtInDict, inferenceContext.expectedType, dictTypeVarContext, ParseTreeUtils.getTypeVarScopesForNode(node), node.start)) {
                return undefined;
            }
            const specializedDict = (0, typeUtils_1.applySolvedTypeVars)(types_1.ClassType.cloneAsInstantiable(builtInDict), dictTypeVarContext);
            if (!specializedDict.typeArguments || specializedDict.typeArguments.length !== 2) {
                return undefined;
            }
            expectedKeyType = specializedDict.typeArguments[0];
            expectedValueType = specializedDict.typeArguments[1];
        }
        // Dict and MutableMapping types have invariant value types, so they
        // cannot be narrowed further. Other super-types like Mapping, Collection,
        // and Iterable use covariant value types, so they can be narrowed.
        let isValueTypeInvariant = false;
        if ((0, types_1.isClassInstance)(inferenceContext.expectedType)) {
            if (inferenceContext.expectedType.details.typeParameters.length >= 2) {
                const valueTypeParam = inferenceContext.expectedType.details.typeParameters[1];
                if (types_1.TypeVarType.getVariance(valueTypeParam) === 2 /* Variance.Invariant */) {
                    isValueTypeInvariant = true;
                }
            }
        }
        // Infer the key and value types if possible.
        if (getKeyAndValueTypesFromDictionary(node, keyTypes, valueTypes, 
        /* forceStrictInference */ true, isValueTypeInvariant, expectedKeyType, expectedValueType, undefined, expectedDiagAddendum)) {
            isIncomplete = true;
        }
        const specializedKeyType = inferTypeArgFromExpectedEntryType((0, typeUtils_1.makeInferenceContext)(expectedKeyType), keyTypes.map((result) => result.type), 
        /* isNarrowable */ false);
        const specializedValueType = inferTypeArgFromExpectedEntryType((0, typeUtils_1.makeInferenceContext)(expectedValueType), valueTypes.map((result) => result.type), !isValueTypeInvariant);
        if (!specializedKeyType || !specializedValueType) {
            return undefined;
        }
        const type = getBuiltInObject(node, 'dict', [specializedKeyType, specializedValueType]);
        return { type, isIncomplete };
    }
    // Attempts to infer the type of a dictionary statement. If hasExpectedType
    // is true, strict inference is used for the subexpressions.
    function getTypeOfDictionaryInferred(node, hasExpectedType) {
        const fallbackType = hasExpectedType ? types_1.AnyType.create() : types_1.UnknownType.create();
        let keyType = fallbackType;
        let valueType = fallbackType;
        const keyTypeResults = [];
        const valueTypeResults = [];
        let isEmptyContainer = false;
        let isIncomplete = false;
        // Infer the key and value types if possible.
        if (getKeyAndValueTypesFromDictionary(node, keyTypeResults, valueTypeResults, 
        /* forceStrictInference */ hasExpectedType, 
        /* isValueTypeInvariant */ false)) {
            isIncomplete = true;
        }
        // Strip any literal values.
        const keyTypes = keyTypeResults.map((t) => stripLiteralValue(t.type));
        const valueTypes = valueTypeResults.map((t) => stripLiteralValue(t.type));
        keyType = keyTypes.length > 0 ? (0, types_1.combineTypes)(keyTypes) : fallbackType;
        // If the value type differs and we're not using "strict inference mode",
        // we need to back off because we can't properly represent the mappings
        // between different keys and associated value types. If all the values
        // are the same type, we'll assume that all values in this dictionary should
        // be the same.
        if (valueTypes.length > 0) {
            if (AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.strictDictionaryInference || hasExpectedType) {
                valueType = (0, types_1.combineTypes)(valueTypes);
            }
            else {
                valueType = (0, typeUtils_1.areTypesSame)(valueTypes, { ignorePseudoGeneric: true }) ? valueTypes[0] : fallbackType;
            }
        }
        else {
            valueType = fallbackType;
            isEmptyContainer = true;
        }
        const dictClass = getBuiltInType(node, 'dict');
        const type = (0, types_1.isInstantiableClass)(dictClass)
            ? types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictClass, [keyType, valueType], 
            /* isTypeArgumentExplicit */ true, 
            /* includeSubclasses */ undefined, 
            /* TupleTypeArguments */ undefined, isEmptyContainer))
            : types_1.UnknownType.create();
        if (isIncomplete) {
            if ((0, typeUtils_1.getContainerDepth)(type) > maxInferredContainerDepth) {
                return { type: types_1.UnknownType.create() };
            }
        }
        return { type, isIncomplete };
    }
    function getKeyAndValueTypesFromDictionary(node, keyTypes, valueTypes, forceStrictInference, isValueTypeInvariant, expectedKeyType, expectedValueType, expectedTypedDictEntries, expectedDiagAddendum) {
        let isIncomplete = false;
        // Infer the key and value types if possible.
        node.entries.forEach((entryNode, index) => {
            var _a, _b, _c, _d;
            let addUnknown = true;
            if (entryNode.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */) {
                const keyTypeResult = getTypeOfExpression(entryNode.keyExpression, 
                /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedKeyType !== null && expectedKeyType !== void 0 ? expectedKeyType : (forceStrictInference ? types_1.NeverType.createNever() : undefined)));
                if (keyTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                const keyType = keyTypeResult.type;
                if (!keyTypeResult.isIncomplete && !keyTypeResult.typeErrors) {
                    verifySetEntryOrDictKeyIsHashable(entryNode.keyExpression, keyType, /* isDictKey */ true);
                }
                if (expectedDiagAddendum && keyTypeResult.expectedTypeDiagAddendum) {
                    expectedDiagAddendum.addAddendum(keyTypeResult.expectedTypeDiagAddendum);
                }
                let valueTypeResult;
                let entryInferenceContext;
                if (expectedTypedDictEntries &&
                    (0, types_1.isClassInstance)(keyType) &&
                    types_1.ClassType.isBuiltIn(keyType, 'str') &&
                    (0, typeUtils_1.isLiteralType)(keyType) &&
                    expectedTypedDictEntries.knownItems.has(keyType.literalValue)) {
                    const effectiveValueType = expectedTypedDictEntries.knownItems.get(keyType.literalValue).valueType;
                    entryInferenceContext = (0, typeUtils_1.makeInferenceContext)(effectiveValueType);
                    valueTypeResult = getTypeOfExpression(entryNode.valueExpression, 
                    /* flags */ undefined, entryInferenceContext);
                }
                else {
                    const effectiveValueType = expectedValueType !== null && expectedValueType !== void 0 ? expectedValueType : (forceStrictInference ? types_1.NeverType.createNever() : undefined);
                    entryInferenceContext = (0, typeUtils_1.makeInferenceContext)(effectiveValueType);
                    valueTypeResult = getTypeOfExpression(entryNode.valueExpression, 
                    /* flags */ undefined, entryInferenceContext);
                }
                if (entryInferenceContext && !valueTypeResult.typeErrors) {
                    const fromExpectedType = inferTypeArgFromExpectedEntryType(entryInferenceContext, [valueTypeResult.type], !isValueTypeInvariant);
                    if (fromExpectedType) {
                        valueTypeResult = { ...valueTypeResult, type: fromExpectedType };
                    }
                }
                if (expectedDiagAddendum && valueTypeResult.expectedTypeDiagAddendum) {
                    expectedDiagAddendum.addAddendum(valueTypeResult.expectedTypeDiagAddendum);
                }
                const valueType = valueTypeResult.type;
                if (valueTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                if (forceStrictInference || index < maxEntriesToUseForInference) {
                    // If an existing key has the same literal type, delete the previous
                    // key since we're overwriting it here.
                    if ((0, types_1.isClass)(keyType) && (0, typeUtils_1.isLiteralType)(keyType)) {
                        const existingIndex = keyTypes.findIndex((kt) => (0, types_1.isTypeSame)(keyType, kt.type));
                        if (existingIndex >= 0) {
                            keyTypes.splice(existingIndex, 1);
                            valueTypes.splice(existingIndex, 1);
                        }
                    }
                    keyTypes.push({ node: entryNode.keyExpression, type: keyType });
                    valueTypes.push({ node: entryNode.valueExpression, type: valueType });
                }
                addUnknown = false;
            }
            else if (entryNode.nodeType === 16 /* ParseNodeType.DictionaryExpandEntry */) {
                let expectedType;
                if (expectedKeyType && expectedValueType) {
                    if (supportsKeysAndGetItemProtocolType && (0, types_1.isInstantiableClass)(supportsKeysAndGetItemProtocolType)) {
                        expectedType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(supportsKeysAndGetItemProtocolType, [expectedKeyType, expectedValueType], 
                        /* isTypeArgumentExplicit */ true));
                    }
                }
                const entryInferenceContext = (0, typeUtils_1.makeInferenceContext)(expectedType);
                let unexpandedTypeResult = getTypeOfExpression(entryNode.expandExpression, 
                /* flags */ undefined, entryInferenceContext);
                if (entryInferenceContext && !unexpandedTypeResult.typeErrors) {
                    const fromExpectedType = inferTypeArgFromExpectedEntryType(entryInferenceContext, [unexpandedTypeResult.type], !isValueTypeInvariant);
                    if (fromExpectedType) {
                        unexpandedTypeResult = { ...unexpandedTypeResult, type: fromExpectedType };
                    }
                }
                if (unexpandedTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                const unexpandedType = unexpandedTypeResult.type;
                if ((0, types_1.isAnyOrUnknown)(unexpandedType)) {
                    addUnknown = false;
                }
                else if ((0, types_1.isClassInstance)(unexpandedType) && types_1.ClassType.isTypedDictClass(unexpandedType)) {
                    // Handle dictionary expansion for a TypedDict.
                    if (strClassType && (0, types_1.isInstantiableClass)(strClassType)) {
                        const strObject = types_1.ClassType.cloneAsInstance(strClassType);
                        const tdEntries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluatorInterface, unexpandedType, 
                        /* allowNarrowed */ true);
                        tdEntries.knownItems.forEach((entry, name) => {
                            if (entry.isRequired || entry.isProvided) {
                                keyTypes.push({
                                    node: entryNode,
                                    type: types_1.ClassType.cloneWithLiteral(strObject, name),
                                });
                                valueTypes.push({ node: entryNode, type: entry.valueType });
                            }
                        });
                        if (!expectedTypedDictEntries) {
                            keyTypes.push({ node: entryNode, type: types_1.ClassType.cloneAsInstance(strObject) });
                            valueTypes.push({
                                node: entryNode,
                                type: (_c = (_b = (_a = tdEntries.extraItems) === null || _a === void 0 ? void 0 : _a.valueType) !== null && _b !== void 0 ? _b : objectType) !== null && _c !== void 0 ? _c : types_1.UnknownType.create(),
                            });
                        }
                        addUnknown = false;
                    }
                }
                else if (supportsKeysAndGetItemProtocolType &&
                    (0, types_1.isInstantiableClass)(supportsKeysAndGetItemProtocolType)) {
                    const mappingTypeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(supportsKeysAndGetItemProtocolType));
                    supportsKeysAndGetItemProtocolType = (0, typeUtils_1.selfSpecializeClass)(supportsKeysAndGetItemProtocolType);
                    if (assignType(types_1.ClassType.cloneAsInstance(supportsKeysAndGetItemProtocolType), unexpandedType, 
                    /* diag */ undefined, mappingTypeVarContext, 
                    /* srcTypeVarContext */ undefined, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */)) {
                        const specializedMapping = (0, typeUtils_1.applySolvedTypeVars)(supportsKeysAndGetItemProtocolType, mappingTypeVarContext);
                        const typeArgs = specializedMapping.typeArguments;
                        if (typeArgs && typeArgs.length >= 2) {
                            if (forceStrictInference || index < maxEntriesToUseForInference) {
                                keyTypes.push({ node: entryNode, type: typeArgs[0] });
                                valueTypes.push({ node: entryNode, type: typeArgs[1] });
                            }
                            addUnknown = false;
                        }
                    }
                    else {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.dictUnpackIsNotMapping(), entryNode);
                    }
                }
            }
            else if (entryNode.nodeType === 32 /* ParseNodeType.ListComprehension */) {
                const dictEntryTypeResult = getElementTypeFromListComprehension(entryNode, expectedValueType, expectedKeyType);
                const dictEntryType = dictEntryTypeResult.type;
                if (dictEntryTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                // The result should be a tuple.
                if ((0, types_1.isClassInstance)(dictEntryType) && (0, typeUtils_1.isTupleClass)(dictEntryType)) {
                    const typeArgs = (_d = dictEntryType.tupleTypeArguments) === null || _d === void 0 ? void 0 : _d.map((t) => t.type);
                    if (typeArgs && typeArgs.length === 2) {
                        if (forceStrictInference || index < maxEntriesToUseForInference) {
                            keyTypes.push({ node: entryNode, type: typeArgs[0] });
                            valueTypes.push({ node: entryNode, type: typeArgs[1] });
                        }
                        addUnknown = false;
                    }
                }
            }
            if (addUnknown) {
                if (forceStrictInference || index < maxEntriesToUseForInference) {
                    keyTypes.push({ node: entryNode, type: types_1.UnknownType.create() });
                    valueTypes.push({ node: entryNode, type: types_1.UnknownType.create() });
                }
            }
        });
        return isIncomplete;
    }
    function getTypeOfListOrSet(node, flags, inferenceContext) {
        var _a;
        if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0 &&
            node.nodeType === 31 /* ParseNodeType.List */ &&
            ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 1 /* ParseNodeType.Argument */) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.useListInstead());
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.listInAnnotation() + diag.getString(), node);
        }
        // If the expected type is a union, recursively call for each of the subtypes
        // to find one that matches.
        let effectiveExpectedType = inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType;
        if (inferenceContext && (0, types_1.isUnion)(inferenceContext.expectedType)) {
            let matchingSubtype;
            let matchingSubtypeResult;
            (0, typeUtils_1.doForEachSubtype)(inferenceContext.expectedType, (subtype) => {
                // Use shortcut if we've already found a match.
                if (matchingSubtypeResult && !matchingSubtypeResult.typeErrors) {
                    return;
                }
                const subtypeResult = useSpeculativeMode(node, () => {
                    return getTypeOfListOrSetWithContext(node, (0, typeUtils_1.makeInferenceContext)(subtype));
                });
                if (subtypeResult && assignType(subtype, subtypeResult.type)) {
                    // If this is the first result we're seeing or it's the first result
                    // without errors, select it as the match.
                    if (!matchingSubtypeResult || (matchingSubtypeResult.typeErrors && !subtypeResult.typeErrors)) {
                        matchingSubtype = subtype;
                        matchingSubtypeResult = subtypeResult;
                    }
                }
            }, 
            /* sortSubtypes */ true);
            effectiveExpectedType = matchingSubtype;
        }
        let expectedTypeDiagAddendum;
        if (effectiveExpectedType) {
            const result = getTypeOfListOrSetWithContext(node, (0, typeUtils_1.makeInferenceContext)(effectiveExpectedType));
            if (result && !result.typeErrors) {
                return result;
            }
            expectedTypeDiagAddendum = result === null || result === void 0 ? void 0 : result.expectedTypeDiagAddendum;
        }
        const typeResult = getTypeOfListOrSetInferred(node, /* hasExpectedType */ inferenceContext !== undefined);
        return { ...typeResult, expectedTypeDiagAddendum };
    }
    // Attempts to determine the type of a list or set statement based on an expected type.
    // Returns undefined if that type cannot be honored.
    function getTypeOfListOrSetWithContext(node, inferenceContext) {
        const builtInClassName = node.nodeType === 31 /* ParseNodeType.List */ ? 'list' : 'set';
        inferenceContext.expectedType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(inferenceContext.expectedType);
        let isIncomplete = false;
        let typeErrors = false;
        const verifyHashable = node.nodeType === 45 /* ParseNodeType.Set */;
        const expectedEntryType = getExpectedEntryTypeForIterable(node, getBuiltInType(node, builtInClassName), inferenceContext);
        if (!expectedEntryType) {
            return undefined;
        }
        const entryTypes = [];
        const expectedTypeDiagAddendum = new diagnostic_1.DiagnosticAddendum();
        node.entries.forEach((entry) => {
            let entryTypeResult;
            if (entry.nodeType === 32 /* ParseNodeType.ListComprehension */) {
                entryTypeResult = getElementTypeFromListComprehension(entry, expectedEntryType);
            }
            else {
                entryTypeResult = getTypeOfExpression(entry, 
                /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedEntryType));
            }
            entryTypes.push(entryTypeResult.type);
            if (entryTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (entryTypeResult.typeErrors) {
                typeErrors = true;
            }
            if (entryTypeResult.expectedTypeDiagAddendum) {
                expectedTypeDiagAddendum.addAddendum(entryTypeResult.expectedTypeDiagAddendum);
            }
            if (verifyHashable && !entryTypeResult.isIncomplete && !entryTypeResult.typeErrors) {
                verifySetEntryOrDictKeyIsHashable(entry, entryTypeResult.type, /* isDictKey */ false);
            }
        });
        let isTypeInvariant = false;
        if ((0, types_1.isClassInstance)(inferenceContext.expectedType)) {
            inferTypeParameterVarianceForClass(inferenceContext.expectedType);
            if (inferenceContext.expectedType.details.typeParameters.some((t) => types_1.TypeVarType.getVariance(t) === 2 /* Variance.Invariant */)) {
                isTypeInvariant = true;
            }
        }
        const specializedEntryType = inferTypeArgFromExpectedEntryType((0, typeUtils_1.makeInferenceContext)(expectedEntryType), entryTypes, !isTypeInvariant);
        if (!specializedEntryType) {
            return { type: types_1.UnknownType.create(), isIncomplete, typeErrors: true, expectedTypeDiagAddendum };
        }
        const type = getBuiltInObject(node, builtInClassName, [specializedEntryType]);
        return { type, isIncomplete, typeErrors, expectedTypeDiagAddendum };
    }
    function getExpectedEntryTypeForIterable(node, expectedClassType, inferenceContext) {
        if (!inferenceContext) {
            return undefined;
        }
        if (!expectedClassType || !(0, types_1.isInstantiableClass)(expectedClassType)) {
            return undefined;
        }
        if ((0, types_1.isAnyOrUnknown)(inferenceContext.expectedType)) {
            return inferenceContext.expectedType;
        }
        if (!(0, types_1.isClassInstance)(inferenceContext.expectedType)) {
            return undefined;
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(expectedClassType));
        if (!(0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluatorInterface, types_1.ClassType.cloneAsInstance(expectedClassType), inferenceContext.expectedType, typeVarContext, ParseTreeUtils.getTypeVarScopesForNode(node), node.start)) {
            return undefined;
        }
        const specializedListOrSet = (0, typeUtils_1.applySolvedTypeVars)(expectedClassType, typeVarContext);
        if (!specializedListOrSet.typeArguments) {
            return undefined;
        }
        return specializedListOrSet.typeArguments[0];
    }
    // Attempts to infer the type of a list or set statement with no "expected type".
    function getTypeOfListOrSetInferred(node, hasExpectedType) {
        const builtInClassName = node.nodeType === 31 /* ParseNodeType.List */ ? 'list' : 'set';
        const verifyHashable = node.nodeType === 45 /* ParseNodeType.Set */;
        let isEmptyContainer = false;
        let isIncomplete = false;
        let typeErrors = false;
        let entryTypes = [];
        node.entries.forEach((entry, index) => {
            let entryTypeResult;
            if (entry.nodeType === 32 /* ParseNodeType.ListComprehension */ && !entry.isGenerator) {
                entryTypeResult = getElementTypeFromListComprehension(entry);
            }
            else {
                entryTypeResult = getTypeOfExpression(entry);
            }
            if (entryTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (entryTypeResult.typeErrors) {
                typeErrors = true;
            }
            if (index < maxEntriesToUseForInference) {
                entryTypes.push(entryTypeResult.type);
            }
            if (verifyHashable && !entryTypeResult.isIncomplete && !entryTypeResult.typeErrors) {
                verifySetEntryOrDictKeyIsHashable(entry, entryTypeResult.type, /* isDictKey */ false);
            }
        });
        entryTypes = entryTypes.map((t) => stripLiteralValue(t));
        let inferredEntryType = hasExpectedType ? types_1.AnyType.create() : types_1.UnknownType.create();
        if (entryTypes.length > 0) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            // If there was an expected type or we're using strict list inference,
            // combine the types into a union.
            if ((builtInClassName === 'list' && fileInfo.diagnosticRuleSet.strictListInference) ||
                (builtInClassName === 'set' && fileInfo.diagnosticRuleSet.strictSetInference) ||
                hasExpectedType) {
                inferredEntryType = (0, types_1.combineTypes)(entryTypes, typeEvaluatorTypes_1.maxSubtypesForInferredType);
            }
            else {
                // Is the list or set homogeneous? If so, use stricter rules. Otherwise relax the rules.
                inferredEntryType = (0, typeUtils_1.areTypesSame)(entryTypes, { ignorePseudoGeneric: true })
                    ? entryTypes[0]
                    : inferredEntryType;
            }
        }
        else {
            isEmptyContainer = true;
        }
        const listOrSetClass = getBuiltInType(node, builtInClassName);
        const type = (0, types_1.isInstantiableClass)(listOrSetClass)
            ? types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(listOrSetClass, [inferredEntryType], 
            /* isTypeArgumentExplicit */ true, 
            /* includeSubclasses */ undefined, 
            /* TupleTypeArguments */ undefined, isEmptyContainer))
            : types_1.UnknownType.create();
        if (isIncomplete) {
            if ((0, typeUtils_1.getContainerDepth)(type) > maxInferredContainerDepth) {
                return { type: types_1.UnknownType.create() };
            }
        }
        return { type, isIncomplete, typeErrors };
    }
    function verifySetEntryOrDictKeyIsHashable(entry, type, isDictKey) {
        // Verify that the type is hashable.
        if (!isTypeHashable(type)) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.unhashableType().format({ type: printType(type) }));
            const message = isDictKey ? localize_1.LocMessage.unhashableDictKey() : localize_1.LocMessage.unhashableSetEntry();
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUnhashable, message + diag.getString(), entry);
        }
    }
    function inferTypeArgFromExpectedEntryType(inferenceContext, entryTypes, isNarrowable) {
        // If the expected type is Any, the resulting type becomes Any.
        if ((0, types_1.isAny)(inferenceContext.expectedType)) {
            return inferenceContext.expectedType;
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(inferenceContext.expectedType));
        const expectedType = inferenceContext.expectedType;
        let isCompatible = true;
        entryTypes.forEach((entryType) => {
            if (isCompatible && !assignType(expectedType, entryType, /* diag */ undefined, typeVarContext)) {
                isCompatible = false;
            }
        });
        if (!isCompatible) {
            return undefined;
        }
        if (isNarrowable && entryTypes.length > 0) {
            const combinedTypes = (0, types_1.combineTypes)(entryTypes);
            return (0, typeUtils_1.containsLiteralType)(inferenceContext.expectedType)
                ? combinedTypes
                : stripLiteralValue(combinedTypes);
        }
        return (0, typeUtils_1.mapSubtypes)((0, typeUtils_1.applySolvedTypeVars)(inferenceContext.expectedType, typeVarContext, { applyInScopePlaceholders: true }), (subtype) => {
            if (entryTypes.length !== 1) {
                return subtype;
            }
            const entryType = entryTypes[0];
            // If the entry type is a TypedDict instance, clone it with additional information.
            if ((0, types_1.isTypeSame)(subtype, entryType, { ignoreTypedDictNarrowEntries: true }) &&
                (0, types_1.isClass)(subtype) &&
                (0, types_1.isClass)(entryType) &&
                types_1.ClassType.isTypedDictClass(entryType)) {
                return types_1.ClassType.cloneForNarrowedTypedDictEntries(subtype, entryType.typedDictNarrowedEntries);
            }
            return subtype;
        });
    }
    function getTypeOfYield(node) {
        let expectedYieldType;
        let sentType;
        let isIncomplete = false;
        const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node);
        if (enclosingFunction) {
            const functionTypeInfo = getTypeOfFunction(enclosingFunction);
            if (functionTypeInfo) {
                const returnType = types_1.FunctionType.getSpecializedReturnType(functionTypeInfo.functionType);
                if (returnType) {
                    expectedYieldType = (0, typeUtils_1.getGeneratorYieldType)(returnType, !!enclosingFunction.isAsync);
                    const generatorTypeArgs = (0, typeUtils_1.getGeneratorTypeArgs)(returnType);
                    if (generatorTypeArgs && generatorTypeArgs.length >= 2) {
                        sentType = generatorTypeArgs[1];
                    }
                }
            }
        }
        if (node.expression) {
            const exprResult = getTypeOfExpression(node.expression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedYieldType));
            if (exprResult.isIncomplete) {
                isIncomplete = true;
            }
        }
        return { type: sentType || types_1.UnknownType.create(), isIncomplete };
    }
    function getTypeOfYieldFrom(node) {
        const yieldFromTypeResult = getTypeOfExpression(node.expression);
        const yieldFromType = yieldFromTypeResult.type;
        const returnedType = (0, typeUtils_1.mapSubtypes)(yieldFromType, (yieldFromSubtype) => {
            var _a, _b;
            // Is the expression a Generator type?
            let generatorTypeArgs = (0, typeUtils_1.getGeneratorTypeArgs)(yieldFromSubtype);
            if (generatorTypeArgs) {
                return generatorTypeArgs.length >= 2 ? generatorTypeArgs[2] : types_1.UnknownType.create();
            }
            // Handle old-style (pre-await) Coroutines as a special case.
            if ((0, types_1.isClassInstance)(yieldFromSubtype) && types_1.ClassType.isBuiltIn(yieldFromSubtype, 'Coroutine')) {
                return types_1.UnknownType.create();
            }
            // Handle simple iterables.
            const iterableType = (_b = (_a = getTypeOfIterable(yieldFromTypeResult, /* isAsync */ false, node)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
            // Does the iterable return a Generator?
            generatorTypeArgs = (0, typeUtils_1.getGeneratorTypeArgs)(iterableType);
            return generatorTypeArgs && generatorTypeArgs.length >= 2 ? generatorTypeArgs[2] : types_1.UnknownType.create();
        });
        return { type: returnedType };
    }
    function getTypeOfLambda(node, inferenceContext) {
        let expectedFunctionTypes = [];
        if (inferenceContext) {
            (0, typeUtils_1.mapSubtypes)(inferenceContext.expectedType, (subtype) => {
                if ((0, types_1.isFunction)(subtype)) {
                    expectedFunctionTypes.push(subtype);
                }
                if ((0, types_1.isClassInstance)(subtype)) {
                    const boundMethod = getBoundMagicMethod(subtype, '__call__');
                    if (boundMethod && (0, types_1.isFunction)(boundMethod)) {
                        expectedFunctionTypes.push(boundMethod);
                    }
                }
                return undefined;
            });
        }
        if (expectedFunctionTypes.length <= 1) {
            return getTypeOfLambdaWithExpectedType(node, expectedFunctionTypes.length > 0 ? expectedFunctionTypes[0] : undefined, inferenceContext, 
            /* forceSpeculative */ false);
        }
        // Sort the expected types for deterministic results.
        expectedFunctionTypes = (0, typeUtils_1.sortTypes)(expectedFunctionTypes);
        // If there's more than one type, try each in turn until we find one that works.
        for (const expectedFunctionType of expectedFunctionTypes) {
            const result = getTypeOfLambdaWithExpectedType(node, expectedFunctionType, inferenceContext, 
            /* forceSpeculative */ true);
            if (!result.typeErrors) {
                return getTypeOfLambdaWithExpectedType(node, expectedFunctionType, inferenceContext, 
                /* forceSpeculative */ false);
            }
        }
        return getTypeOfLambdaWithExpectedType(node, expectedFunctionTypes[0], inferenceContext, 
        /* forceSpeculative */ true);
    }
    function getTypeOfLambdaWithExpectedType(node, expectedType, inferenceContext, forceSpeculative) {
        let isIncomplete = !!(inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.isTypeIncomplete);
        let paramsArePositionOnly = true;
        let expectedReturnType;
        let expectedParamDetails;
        if (expectedType) {
            const liveTypeVarScopes = ParseTreeUtils.getTypeVarScopesForNode(node);
            expectedType = (0, typeUtils_1.transformExpectedType)(expectedType, liveTypeVarScopes, node.start);
            expectedParamDetails = (0, parameterUtils_1.getParameterListDetails)(expectedType);
            expectedReturnType = getFunctionEffectiveReturnType(expectedType);
        }
        let functionType = types_1.FunctionType.createInstance('', '', '', 131072 /* FunctionTypeFlags.PartiallyEvaluated */);
        functionType.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node);
        // Pre-cache the incomplete function type in case the evaluation of the
        // lambda depends on itself.
        writeTypeCache(node, { type: functionType, isIncomplete: true }, 0 /* EvaluatorFlags.None */);
        // We assume for simplicity that the parameter signature of the lambda is
        // the same as the expected type. If this isn't the case, we'll use
        // object for any lambda parameters that don't match. We could make this
        // more sophisticated in the future, but it becomes very complex to handle
        // all of the permutations.
        let sawParamMismatch = false;
        node.parameters.forEach((param, index) => {
            let paramType;
            if (expectedParamDetails && !sawParamMismatch) {
                if (index < expectedParamDetails.params.length) {
                    const expectedParam = expectedParamDetails.params[index];
                    // If the parameter category matches and both of the parameters are
                    // either separators (/ or *) or not separators, copy the type
                    // from the expected parameter.
                    if (expectedParam.param.category === param.category && !param.name === !expectedParam.param.name) {
                        paramType = expectedParam.type;
                    }
                    else {
                        sawParamMismatch = true;
                    }
                }
                else if (param.defaultValue) {
                    // If the lambda param has a default value but there is no associated
                    // parameter in the expected type, assume that the default value is
                    // being used to explicitly capture a value from an outer scope. Infer
                    // its type from the default value expression.
                    paramType = getTypeOfExpression(param.defaultValue, undefined, inferenceContext).type;
                }
            }
            else if (param.defaultValue) {
                // If there is no inference context but we have a default value,
                // use the default value to infer the parameter's type.
                paramType = inferParameterTypeFromDefaultValue(param.defaultValue);
            }
            if (param.name) {
                writeTypeCache(param.name, { type: transformVariadicParamType(node, param.category, paramType !== null && paramType !== void 0 ? paramType : types_1.UnknownType.create()) }, 0 /* EvaluatorFlags.None */);
            }
            if (param.defaultValue) {
                // Evaluate the default value if it's present.
                getTypeOfExpression(param.defaultValue, 1 /* EvaluatorFlags.ConvertEllipsisToAny */);
            }
            // Determine whether we need to insert an implied position-only parameter.
            // This is needed when a function's parameters are named using the old-style
            // way of specifying position-only parameters.
            if (index >= 0) {
                let isImplicitPositionOnlyParam = false;
                if (param.category === 0 /* ParameterCategory.Simple */ && param.name) {
                    if ((0, symbolNameUtils_1.isPrivateName)(param.name.value)) {
                        isImplicitPositionOnlyParam = true;
                    }
                }
                else {
                    paramsArePositionOnly = false;
                }
                if (paramsArePositionOnly &&
                    !isImplicitPositionOnlyParam &&
                    functionType.details.parameters.length > 0) {
                    types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                }
                if (!isImplicitPositionOnlyParam) {
                    paramsArePositionOnly = false;
                }
            }
            const functionParam = {
                category: param.category,
                name: param.name ? param.name.value : undefined,
                hasDefault: !!param.defaultValue,
                defaultValueExpression: param.defaultValue,
                hasDeclaredType: true,
                type: paramType !== null && paramType !== void 0 ? paramType : types_1.UnknownType.create(),
            };
            types_1.FunctionType.addParameter(functionType, functionParam);
        });
        if (paramsArePositionOnly && functionType.details.parameters.length > 0) {
            types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
        }
        let typeErrors = false;
        // If we're speculatively evaluating the lambda, create another speculative
        // evaluation scope for the return expression and do not allow retention
        // of the cached types.
        // We need to set allowCacheRetention to false because we don't want to
        // cache the type of the lambda return expression because it depends on
        // the parameter types that we set above, and the speculative type cache
        // doesn't know about that context.
        useSpeculativeMode(forceSpeculative || isSpeculativeModeInUse(node) || (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.isTypeIncomplete)
            ? node.expression
            : undefined, () => {
            const returnTypeResult = getTypeOfExpression(node.expression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedReturnType));
            functionType.inferredReturnType = returnTypeResult.type;
            if (returnTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (returnTypeResult.typeErrors) {
                typeErrors = true;
            }
            else if (expectedReturnType) {
                // If the expectedReturnType is generic, see if the actual return type
                // provides types for some or all type variables.
                if ((0, typeUtils_1.requiresSpecialization)(expectedReturnType)) {
                    const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(functionType));
                    if (assignType(expectedReturnType, returnTypeResult.type, /* diag */ undefined, typeVarContext)) {
                        functionType = (0, typeUtils_1.applySolvedTypeVars)(functionType, typeVarContext, {
                            applyInScopePlaceholders: true,
                        });
                    }
                }
            }
        }, {
            dependentType: inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.expectedType,
            allowDiagnostics: !forceSpeculative && !isDiagnosticSuppressedForNode(node) && !(inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.isTypeIncomplete),
        });
        // Mark the function type as no longer being evaluated.
        functionType.details.flags &= ~131072 /* FunctionTypeFlags.PartiallyEvaluated */;
        // Is the resulting function compatible with the expected type?
        if (expectedType && !assignType(expectedType, functionType)) {
            typeErrors = true;
        }
        return { type: functionType, isIncomplete, typeErrors };
    }
    function getTypeOfListComprehension(node, inferenceContext) {
        let isIncomplete = false;
        let typeErrors = false;
        // If any of the "for" clauses are marked async or any of the "if" clauses
        // or any clause other than the leftmost "for" contain an "await" operator,
        // it is treated as an async generator.
        let isAsync = node.forIfNodes.some((comp, index) => {
            if (comp.nodeType === 33 /* ParseNodeType.ListComprehensionFor */ && comp.isAsync) {
                return true;
            }
            return index > 0 && ParseTreeUtils.containsAwaitNode(comp);
        });
        let type = types_1.UnknownType.create();
        if (ParseTreeUtils.containsAwaitNode(node.expression)) {
            isAsync = true;
        }
        const builtInIteratorType = getTypingType(node, isAsync ? 'AsyncGenerator' : 'Generator');
        const expectedEntryType = getExpectedEntryTypeForIterable(node, builtInIteratorType, inferenceContext);
        const elementTypeResult = getElementTypeFromListComprehension(node, expectedEntryType);
        if (elementTypeResult.isIncomplete) {
            isIncomplete = true;
        }
        if (elementTypeResult.typeErrors) {
            typeErrors = true;
        }
        let elementType = elementTypeResult.type;
        if (!expectedEntryType || !(0, typeUtils_1.containsLiteralType)(expectedEntryType)) {
            elementType = stripLiteralValue(elementType);
        }
        if (builtInIteratorType && (0, types_1.isInstantiableClass)(builtInIteratorType)) {
            type = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(builtInIteratorType, isAsync ? [elementType, getNoneType()] : [elementType, getNoneType(), getNoneType()], 
            /* isTypeArgumentExplicit */ true));
        }
        return { type, isIncomplete, typeErrors };
    }
    function reportPossibleUnknownAssignment(ruleset, rule, target, type, errorNode, ignoreEmptyContainers) {
        // Don't bother if the features are disabled.
        if (ruleset[rule] === 'none' && ruleset.reportAny === 'none') {
            return;
        }
        const nameValue = target.value;
        // Sometimes variables contain an "unbound" type if they're
        // assigned only within conditional statements. Remove this
        // to avoid confusion.
        const simplifiedType = (0, types_1.removeUnbound)(type);
        if ((0, types_1.isUnknown)(simplifiedType)) {
            addDiagnostic(rule, localize_1.LocMessage.typeUnknown().format({ name: nameValue }), errorNode);
        }
        else if ((0, typeUtils_1.isPartlyUnknown)(simplifiedType)) {
            // If ignoreEmptyContainers is true, don't report the problem for
            // empty containers (lists or dictionaries). We'll report the problem
            // only if the assigned value is used later.
            if (!ignoreEmptyContainers || !(0, types_1.isClassInstance)(type) || !type.isEmptyContainer) {
                const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                diagAddendum.addMessage(localize_1.LocAddendum.typeOfSymbol().format({
                    name: nameValue,
                    type: printType(simplifiedType, { expandTypeAlias: true }),
                }));
                addDiagnostic(rule, localize_1.LocMessage.typePartiallyUnknown().format({ name: nameValue }) + diagAddendum.getString(), errorNode);
            }
        }
        else if ((0, types_1.isAny)(simplifiedType)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.typeAny().format({ name: nameValue }), errorNode);
        }
    }
    function evaluateListComprehensionForIf(node) {
        var _a;
        let isIncomplete = false;
        if (node.nodeType === 33 /* ParseNodeType.ListComprehensionFor */) {
            const iterableTypeResult = getTypeOfExpression(node.iterableExpression);
            if (iterableTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            const iterableType = stripLiteralValue(iterableTypeResult.type);
            const itemTypeResult = (_a = getTypeOfIterator({ type: iterableType, isIncomplete: iterableTypeResult.isIncomplete }, !!node.isAsync, node.iterableExpression)) !== null && _a !== void 0 ? _a : { type: types_1.UnknownType.create(), isIncomplete: iterableTypeResult.isIncomplete };
            const targetExpr = node.targetExpression;
            assignTypeToExpression(targetExpr, itemTypeResult.type, !!itemTypeResult.isIncomplete, node.iterableExpression);
        }
        else {
            (0, debug_1.assert)(node.nodeType === 34 /* ParseNodeType.ListComprehensionIf */);
            // Evaluate the test expression to validate it and mark symbols
            // as referenced. Don't bother doing this if we're in speculative
            // mode because it doesn't affect the element type.
            if (!isSpeculativeModeInUse(node.testExpression)) {
                getTypeOfExpression(node.testExpression);
            }
        }
        return isIncomplete;
    }
    // Returns the type of one entry returned by the list comprehension,
    // as opposed to the entire list.
    function getElementTypeFromListComprehension(node, expectedValueOrElementType, expectedKeyType) {
        let isIncomplete = false;
        let typeErrors = false;
        // "Execute" the list comprehensions from start to finish.
        for (const forIfNode of node.forIfNodes) {
            if (evaluateListComprehensionForIf(forIfNode)) {
                isIncomplete = true;
            }
        }
        let type = types_1.UnknownType.create();
        if (node.expression.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */) {
            // Create a tuple with the key/value types.
            const keyTypeResult = getTypeOfExpression(node.expression.keyExpression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedKeyType));
            if (keyTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (keyTypeResult.typeErrors) {
                typeErrors = true;
            }
            let keyType = keyTypeResult.type;
            if (!expectedKeyType || !(0, typeUtils_1.containsLiteralType)(expectedKeyType)) {
                keyType = stripLiteralValue(keyType);
            }
            const valueTypeResult = getTypeOfExpression(node.expression.valueExpression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedValueOrElementType));
            if (valueTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (valueTypeResult.typeErrors) {
                typeErrors = true;
            }
            let valueType = valueTypeResult.type;
            if (!expectedValueOrElementType || !(0, typeUtils_1.containsLiteralType)(expectedValueOrElementType)) {
                valueType = stripLiteralValue(valueType);
            }
            type = makeTupleObject([
                { type: keyType, isUnbounded: false },
                { type: valueType, isUnbounded: false },
            ]);
        }
        else if (node.expression.nodeType === 16 /* ParseNodeType.DictionaryExpandEntry */) {
            // The parser should have reported an error in this case because it's not allowed.
            getTypeOfExpression(node.expression.expandExpression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedValueOrElementType));
        }
        else if ((0, parseNodes_1.isExpressionNode)(node)) {
            const exprTypeResult = getTypeOfExpression(node.expression, 
            /* flags */ undefined, (0, typeUtils_1.makeInferenceContext)(expectedValueOrElementType));
            if (exprTypeResult.isIncomplete) {
                isIncomplete = true;
            }
            if (exprTypeResult.typeErrors) {
                typeErrors = true;
            }
            type = exprTypeResult.type;
        }
        return { type, isIncomplete, typeErrors };
    }
    function getTypeOfSlice(node) {
        // Evaluate the expressions to report errors and record symbol
        // references. We can skip this if we're executing speculatively.
        if (!isSpeculativeModeInUse(node)) {
            if (node.startValue) {
                getTypeOfExpression(node.startValue);
            }
            if (node.endValue) {
                getTypeOfExpression(node.endValue);
            }
            if (node.stepValue) {
                getTypeOfExpression(node.stepValue);
            }
        }
        return { type: getBuiltInObject(node, 'slice') };
    }
    // Verifies that a type argument's type is not disallowed.
    function validateTypeArg(argResult, options) {
        if (argResult.typeList) {
            if (!(options === null || options === void 0 ? void 0 : options.allowTypeArgList)) {
                addError(localize_1.LocMessage.typeArgListNotAllowed(), argResult.node);
                return false;
            }
            else {
                argResult.typeList.forEach((typeArg) => {
                    validateTypeArg(typeArg);
                });
            }
        }
        if ((0, typeUtils_1.isEllipsisType)(argResult.type)) {
            if (!(options === null || options === void 0 ? void 0 : options.allowTypeArgList)) {
                addError(localize_1.LocMessage.ellipsisContext(), argResult.node);
                return false;
            }
        }
        if ((0, types_1.isModule)(argResult.type)) {
            addError(localize_1.LocMessage.moduleAsType(), argResult.node);
            return false;
        }
        if ((0, types_1.isParamSpec)(argResult.type)) {
            if (!(options === null || options === void 0 ? void 0 : options.allowParamSpec)) {
                addError(localize_1.LocMessage.paramSpecContext(), argResult.node);
                return false;
            }
        }
        if ((0, types_1.isVariadicTypeVar)(argResult.type) && !argResult.type.isVariadicInUnion) {
            if (!(options === null || options === void 0 ? void 0 : options.allowVariadicTypeVar)) {
                addError(localize_1.LocMessage.typeVarTupleContext(), argResult.node);
                return false;
            }
            else {
                validateVariadicTypeVarIsUnpacked(argResult.type, argResult.node);
            }
        }
        if (!(options === null || options === void 0 ? void 0 : options.allowEmptyTuple) && argResult.isEmptyTupleShorthand) {
            addError(localize_1.LocMessage.zeroLengthTupleNotAllowed(), argResult.node);
            return false;
        }
        if ((0, types_1.isUnpackedClass)(argResult.type)) {
            if (!(options === null || options === void 0 ? void 0 : options.allowUnpackedTuples)) {
                addError(localize_1.LocMessage.unpackedArgInTypeArgument(), argResult.node);
                return false;
            }
        }
        return true;
    }
    // Evaluates the type arguments for a Callable type. It should have zero
    // to two arguments.The first argument, if present, should be an ellipsis,
    // a ParamSpec, a Concatenate, or a list of positional parameter types.
    // The second argument, if present, should specify the return type.
    function createCallableType(classType, typeArgs, errorNode) {
        const functionType = types_1.FunctionType.createInstantiable(0 /* FunctionTypeFlags.None */);
        functionType.specialForm = classType;
        functionType.details.declaredReturnType = types_1.UnknownType.create();
        functionType.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(errorNode);
        if (typeArgs && typeArgs.length > 0) {
            functionType.isCallableWithTypeArgs = true;
            if (typeArgs[0].typeList) {
                const typeList = typeArgs[0].typeList;
                let sawUnpacked = false;
                let reportedUnpackedError = false;
                const noteSawUnpacked = (entry) => {
                    // Make sure we have at most one unpacked variadic type variable.
                    if (sawUnpacked) {
                        if (!reportedUnpackedError) {
                            addError(localize_1.LocMessage.variadicTypeArgsTooMany(), entry.node);
                            reportedUnpackedError = true;
                        }
                    }
                    sawUnpacked = true;
                };
                typeList.forEach((entry, index) => {
                    var _a;
                    let entryType = entry.type;
                    let paramCategory = 0 /* ParameterCategory.Simple */;
                    const paramName = `__p${index.toString()}`;
                    if ((0, types_1.isVariadicTypeVar)(entryType)) {
                        validateVariadicTypeVarIsUnpacked(entryType, entry.node);
                        paramCategory = 1 /* ParameterCategory.ArgsList */;
                        noteSawUnpacked(entry);
                    }
                    else if (validateTypeArg(entry, { allowUnpackedTuples: true })) {
                        if ((0, types_1.isUnpackedClass)(entryType)) {
                            paramCategory = 1 /* ParameterCategory.ArgsList */;
                            if ((_a = entryType.tupleTypeArguments) === null || _a === void 0 ? void 0 : _a.some((typeArg) => (0, types_1.isVariadicTypeVar)(typeArg.type) || typeArg.isUnbounded)) {
                                noteSawUnpacked(entry);
                            }
                        }
                    }
                    else {
                        entryType = types_1.UnknownType.create();
                    }
                    types_1.FunctionType.addParameter(functionType, {
                        category: paramCategory,
                        name: paramName,
                        isNameSynthesized: true,
                        type: (0, typeUtils_1.convertToInstance)(entryType),
                        hasDeclaredType: true,
                    });
                });
                if (typeList.length > 0) {
                    types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                }
            }
            else if ((0, typeUtils_1.isEllipsisType)(typeArgs[0].type)) {
                types_1.FunctionType.addDefaultParameters(functionType);
                functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
            }
            else if ((0, types_1.isParamSpec)(typeArgs[0].type)) {
                functionType.details.paramSpec = typeArgs[0].type;
            }
            else {
                if ((0, types_1.isInstantiableClass)(typeArgs[0].type) && types_1.ClassType.isBuiltIn(typeArgs[0].type, 'Concatenate')) {
                    const concatTypeArgs = typeArgs[0].type.typeArguments;
                    if (concatTypeArgs && concatTypeArgs.length > 0) {
                        concatTypeArgs.forEach((typeArg, index) => {
                            if (index === concatTypeArgs.length - 1) {
                                types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                                if ((0, types_1.isParamSpec)(typeArg)) {
                                    functionType.details.paramSpec = typeArg;
                                }
                                else if ((0, typeUtils_1.isEllipsisType)(typeArg)) {
                                    types_1.FunctionType.addDefaultParameters(functionType);
                                    functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
                                }
                            }
                            else {
                                types_1.FunctionType.addParameter(functionType, {
                                    category: 0 /* ParameterCategory.Simple */,
                                    name: `__p${index}`,
                                    isNameSynthesized: true,
                                    hasDeclaredType: true,
                                    type: typeArg,
                                });
                            }
                        });
                    }
                }
                else {
                    addError(localize_1.LocMessage.callableFirstArg(), typeArgs[0].node);
                }
            }
            if (typeArgs.length > 1) {
                let typeArg1Type = typeArgs[1].type;
                if (!validateTypeArg(typeArgs[1])) {
                    typeArg1Type = types_1.UnknownType.create();
                }
                functionType.details.declaredReturnType = (0, typeUtils_1.convertToInstance)(typeArg1Type);
            }
            else {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument, localize_1.LocMessage.callableSecondArg(), errorNode);
                functionType.details.declaredReturnType = types_1.UnknownType.create();
            }
            if (typeArgs.length > 2) {
                addError(localize_1.LocMessage.callableExtraArgs(), typeArgs[2].node);
            }
        }
        else {
            types_1.FunctionType.addDefaultParameters(functionType, /* useUnknown */ true);
            functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
        }
        return functionType;
    }
    // Creates an Optional[X] type.
    function createOptionalType(classType, errorNode, typeArgs, flags) {
        if (!typeArgs) {
            // If no type arguments are provided, the resulting type
            // depends on whether we're evaluating a type annotation or
            // we're in some other context.
            if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                addError(localize_1.LocMessage.optionalExtraArgs(), errorNode);
                return types_1.UnknownType.create();
            }
            return classType;
        }
        if (typeArgs.length > 1) {
            addError(localize_1.LocMessage.optionalExtraArgs(), errorNode);
            return types_1.UnknownType.create();
        }
        let typeArg0Type = typeArgs[0].type;
        if (!validateTypeArg(typeArgs[0])) {
            typeArg0Type = types_1.UnknownType.create();
        }
        else if (!(0, typeUtils_1.isEffectivelyInstantiable)(typeArg0Type)) {
            addExpectedClassDiagnostic(typeArg0Type, typeArgs[0].node);
            typeArg0Type = types_1.UnknownType.create();
        }
        let optionalType = (0, types_1.combineTypes)([typeArg0Type, noneClassType !== null && noneClassType !== void 0 ? noneClassType : types_1.UnknownType.create()]);
        if (unionClassType && (0, types_1.isInstantiableClass)(unionClassType)) {
            optionalType = types_1.TypeBase.cloneAsSpecialForm(optionalType, types_1.ClassType.cloneAsInstance(unionClassType));
        }
        return optionalType;
    }
    function cloneBuiltinObjectWithLiteral(node, builtInName, value) {
        const type = getBuiltInObject(node, builtInName);
        if ((0, types_1.isClassInstance)(type)) {
            return types_1.ClassType.cloneWithLiteral(types_1.ClassType.cloneRemoveTypePromotions(type), value);
        }
        return types_1.UnknownType.create();
    }
    function cloneBuiltinClassWithLiteral(node, literalClassType, builtInName, value) {
        const type = getBuiltInType(node, builtInName);
        if ((0, types_1.isInstantiableClass)(type)) {
            const literalType = types_1.ClassType.cloneWithLiteral(type, value);
            literalType.specialForm = literalClassType;
            return literalType;
        }
        return types_1.UnknownType.create();
    }
    // Creates a type that represents a Literal.
    function createLiteralType(classType, node, flags) {
        if (node.items.length === 0) {
            addError(localize_1.LocMessage.literalEmptyArgs(), node.baseExpression);
            return types_1.UnknownType.create();
        }
        // As per the specification, we support None, int, bool, str, bytes literals
        // plus enum values.
        const literalTypes = [];
        for (const item of node.items) {
            let type;
            const itemExpr = item.valueExpression;
            if (item.argumentCategory !== 0 /* ArgumentCategory.Simple */) {
                addError(localize_1.LocMessage.unpackedArgInTypeArgument(), itemExpr);
                type = types_1.UnknownType.create();
            }
            else if (item.name) {
                addError(localize_1.LocMessage.keywordArgInTypeArgument(), itemExpr);
                type = types_1.UnknownType.create();
            }
            else if (itemExpr.nodeType === 48 /* ParseNodeType.StringList */) {
                const isBytes = (itemExpr.strings[0].token.flags & 32 /* StringTokenFlags.Bytes */) !== 0;
                const value = itemExpr.strings.map((s) => s.value).join('');
                if (isBytes) {
                    type = cloneBuiltinClassWithLiteral(node, classType, 'bytes', value);
                }
                else {
                    type = cloneBuiltinClassWithLiteral(node, classType, 'str', value);
                }
                itemExpr.strings.forEach((stringNode) => {
                    if ((stringNode.token.flags & 512 /* StringTokenFlags.NamedUnicodeEscape */) !== 0) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.literalNamedUnicodeEscape(), stringNode);
                    }
                });
            }
            else if (itemExpr.nodeType === 40 /* ParseNodeType.Number */) {
                if (!itemExpr.isImaginary && itemExpr.isInteger) {
                    type = cloneBuiltinClassWithLiteral(node, classType, 'int', itemExpr.value);
                }
            }
            else if (itemExpr.nodeType === 11 /* ParseNodeType.Constant */) {
                if (itemExpr.constType === 33 /* KeywordType.True */) {
                    type = cloneBuiltinClassWithLiteral(node, classType, 'bool', true);
                }
                else if (itemExpr.constType === 15 /* KeywordType.False */) {
                    type = cloneBuiltinClassWithLiteral(node, classType, 'bool', false);
                }
                else if (itemExpr.constType === 26 /* KeywordType.None */) {
                    type = noneClassType !== null && noneClassType !== void 0 ? noneClassType : types_1.UnknownType.create();
                }
            }
            else if (itemExpr.nodeType === 55 /* ParseNodeType.UnaryOperation */) {
                if (itemExpr.operator === 33 /* OperatorType.Subtract */ || itemExpr.operator === 0 /* OperatorType.Add */) {
                    if (itemExpr.expression.nodeType === 40 /* ParseNodeType.Number */) {
                        if (!itemExpr.expression.isImaginary && itemExpr.expression.isInteger) {
                            type = cloneBuiltinClassWithLiteral(node, classType, 'int', itemExpr.operator === 33 /* OperatorType.Subtract */
                                ? -itemExpr.expression.value
                                : itemExpr.expression.value);
                        }
                    }
                }
            }
            if (!type) {
                const exprType = getTypeOfExpression(itemExpr, flags & 4 /* EvaluatorFlags.AllowForwardReferences */);
                // Is this an enum type?
                if ((0, types_1.isClassInstance)(exprType.type) &&
                    types_1.ClassType.isEnumClass(exprType.type) &&
                    exprType.type.literalValue !== undefined) {
                    type = types_1.ClassType.cloneAsInstantiable(exprType.type);
                }
                else {
                    // Is this a type alias to an existing literal type?
                    let isLiteralType = true;
                    (0, typeUtils_1.doForEachSubtype)(exprType.type, (subtype) => {
                        if (!(0, types_1.isInstantiableClass)(subtype) || subtype.literalValue === undefined) {
                            if (!(0, typeUtils_1.isNoneTypeClass)(subtype)) {
                                isLiteralType = false;
                            }
                        }
                    });
                    if (isLiteralType) {
                        type = exprType.type;
                    }
                }
            }
            if (!type) {
                addError(localize_1.LocMessage.literalUnsupportedType(), item);
                type = types_1.UnknownType.create();
            }
            literalTypes.push(type);
        }
        return (0, types_1.combineTypes)(literalTypes);
    }
    // Creates a ClassVar type.
    function createClassVarType(classType, errorNode, typeArgs, flags) {
        var _a;
        if (flags & 131072 /* EvaluatorFlags.DisallowClassVar */) {
            addError(localize_1.LocMessage.classVarNotAllowed(), errorNode);
            return types_1.AnyType.create();
        }
        if (!typeArgs) {
            return classType;
        }
        else if (typeArgs.length === 0) {
            addError(localize_1.LocMessage.classVarFirstArgMissing(), errorNode);
            return types_1.UnknownType.create();
        }
        else if (typeArgs.length > 1) {
            addError(localize_1.LocMessage.classVarTooManyArgs(), typeArgs[1].node);
            return types_1.UnknownType.create();
        }
        const type = typeArgs[0].type;
        // A ClassVar should not allow TypeVars or generic types parameterized
        // by TypeVars.
        if ((0, typeUtils_1.requiresSpecialization)(type, { ignorePseudoGeneric: true, ignoreSelf: true })) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.classVarWithTypeVar(), (_a = typeArgs[0].node) !== null && _a !== void 0 ? _a : errorNode);
        }
        return type;
    }
    // Creates a "TypeGuard" and "TypeIs" type. This is an alias for 'bool', which
    // isn't a generic type and therefore doesn't have a typeParameter.
    // We'll abuse our internal types a bit by specializing it with
    // a type argument anyway.
    function createTypeGuardType(classType, errorNode, typeArgs, flags) {
        // If no type arguments are provided, the resulting type
        // depends on whether we're evaluating a type annotation or
        // we're in some other context.
        if (!typeArgs) {
            if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                addError(localize_1.LocMessage.typeGuardArgCount(), errorNode);
            }
            return classType;
        }
        else if (typeArgs.length !== 1) {
            addError(localize_1.LocMessage.typeGuardArgCount(), errorNode);
            return types_1.UnknownType.create();
        }
        const convertedTypeArgs = typeArgs.map((typeArg) => {
            return (0, typeUtils_1.convertToInstance)(validateTypeArg(typeArg) ? typeArg.type : types_1.UnknownType.create());
        });
        return types_1.ClassType.cloneForSpecialization(classType, convertedTypeArgs, /* isTypeArgumentExplicit */ true);
    }
    function createSelfType(classType, errorNode, typeArgs, flags) {
        var _a;
        // Self doesn't support any type arguments.
        if (typeArgs) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsExpectingNone().format({
                name: classType.details.name,
            }), (_a = typeArgs[0].node) !== null && _a !== void 0 ? _a : errorNode);
        }
        let enclosingClass = ParseTreeUtils.getEnclosingClass(errorNode);
        // If `Self` appears anywhere outside of the class body (e.g. a decorator,
        // base class list, metaclass argument, type parameter list), it is
        // considered illegal.
        if (enclosingClass && !ParseTreeUtils.isNodeContainedWithin(errorNode, enclosingClass.suite)) {
            enclosingClass = undefined;
        }
        const enclosingClassTypeResult = enclosingClass ? getTypeOfClass(enclosingClass) : undefined;
        if (!enclosingClassTypeResult) {
            if ((flags & (256 /* EvaluatorFlags.ExpectingTypeAnnotation */ | 128 /* EvaluatorFlags.ExpectingInstantiableType */)) !== 0) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.selfTypeContext(), errorNode);
            }
            return types_1.UnknownType.create();
        }
        else if ((0, typeUtils_1.isInstantiableMetaclass)(enclosingClassTypeResult.classType)) {
            // If `Self` appears within a metaclass, it is considered illegal.
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.selfTypeMetaclass(), errorNode);
            return types_1.UnknownType.create();
        }
        const enclosingFunction = ParseTreeUtils.getEnclosingFunction(errorNode);
        if (enclosingFunction) {
            const functionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, enclosingFunction, 
            /* isInClass */ true);
            const isInnerFunction = !!ParseTreeUtils.getEnclosingFunction(enclosingFunction);
            if (!isInnerFunction) {
                // Check for static methods.
                if (functionInfo.flags & 4 /* FunctionTypeFlags.StaticMethod */) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.selfTypeContext(), errorNode);
                    return types_1.UnknownType.create();
                }
                if (enclosingFunction.parameters.length > 0) {
                    const firstParamTypeAnnotation = ParseTreeUtils.getTypeAnnotationForParameter(enclosingFunction, 0);
                    if (firstParamTypeAnnotation &&
                        !ParseTreeUtils.isNodeContainedWithin(errorNode, firstParamTypeAnnotation)) {
                        const annotationType = getTypeOfAnnotation(firstParamTypeAnnotation, {
                            associateTypeVarsWithScope: true,
                        });
                        if (!(0, types_1.isTypeVar)(annotationType) || !annotationType.details.isSynthesizedSelf) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.selfTypeWithTypedSelfOrCls(), errorNode);
                        }
                    }
                }
            }
        }
        return (0, typeUtils_1.synthesizeTypeVarForSelfCls)(enclosingClassTypeResult.classType, /* isClsParam */ true);
    }
    function createRequiredOrReadOnlyType(classType, errorNode, typeArgs, flags) {
        // If no type arguments are provided, the resulting type
        // depends on whether we're evaluating a type annotation or
        // we're in some other context.
        if (!typeArgs && (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) === 0) {
            return { type: classType };
        }
        if (!typeArgs || typeArgs.length !== 1) {
            addError(classType.details.name === 'ReadOnly'
                ? localize_1.LocMessage.readOnlyArgCount()
                : classType.details.name === 'Required'
                    ? localize_1.LocMessage.requiredArgCount()
                    : localize_1.LocMessage.notRequiredArgCount(), errorNode);
            return { type: classType };
        }
        const typeArgType = typeArgs[0].type;
        // Make sure this is used only in a dataclass.
        const containingClassNode = ParseTreeUtils.getEnclosingClass(errorNode, /* stopAtFunction */ true);
        const classTypeInfo = containingClassNode ? getTypeOfClass(containingClassNode) : undefined;
        let isUsageLegal = false;
        if (classTypeInfo &&
            (0, types_1.isInstantiableClass)(classTypeInfo.classType) &&
            types_1.ClassType.isTypedDictClass(classTypeInfo.classType)) {
            // The only legal usage is when used in a type annotation statement.
            if (ParseTreeUtils.isNodeContainedWithinNodeType(errorNode, 54 /* ParseNodeType.TypeAnnotation */)) {
                isUsageLegal = true;
            }
        }
        if ((flags & 1048576 /* EvaluatorFlags.AllowRequired */) !== 0) {
            isUsageLegal = true;
        }
        let isReadOnly = typeArgs[0].isReadOnly;
        let isRequired = typeArgs[0].isRequired;
        let isNotRequired = typeArgs[0].isNotRequired;
        if (classType.details.name === 'ReadOnly') {
            // Nested ReadOnly are not allowed.
            if (typeArgs[0].isReadOnly) {
                isUsageLegal = false;
            }
            isReadOnly = true;
        }
        else {
            // Nested Required/NotRequired are not allowed.
            if (typeArgs[0].isRequired || typeArgs[0].isNotRequired) {
                isUsageLegal = false;
            }
            isRequired = classType.details.name === 'Required';
            isNotRequired = classType.details.name === 'NotRequired';
        }
        if (!isUsageLegal) {
            addError(classType.details.name === 'ReadOnly'
                ? localize_1.LocMessage.readOnlyNotInTypedDict()
                : classType.details.name === 'Required'
                    ? localize_1.LocMessage.requiredNotInTypedDict()
                    : localize_1.LocMessage.notRequiredNotInTypedDict(), errorNode);
            return { type: types_1.ClassType.cloneForSpecialization(classType, [(0, typeUtils_1.convertToInstance)(typeArgType)], !!typeArgs) };
        }
        return { type: typeArgType, isReadOnly, isRequired, isNotRequired };
    }
    function createUnpackType(classType, errorNode, typeArgs, flags) {
        // If no type arguments are provided, the resulting type
        // depends on whether we're evaluating a type annotation or
        // we're in some other context.
        if (!typeArgs && (flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) === 0) {
            return classType;
        }
        if (!typeArgs || typeArgs.length !== 1) {
            addError(localize_1.LocMessage.unpackArgCount(), errorNode);
            return types_1.UnknownType.create();
        }
        let typeArgType = typeArgs[0].type;
        if ((0, types_1.isUnion)(typeArgType) && typeArgType.subtypes.length === 1) {
            typeArgType = typeArgType.subtypes[0];
        }
        if ((flags & 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */) !== 0) {
            if ((0, types_1.isInstantiableClass)(typeArgType) && !typeArgType.includeSubclasses && (0, typeUtils_1.isTupleClass)(typeArgType)) {
                return types_1.ClassType.cloneForUnpacked(typeArgType);
            }
            if ((0, types_1.isVariadicTypeVar)(typeArgType) && !typeArgType.isVariadicUnpacked) {
                return types_1.TypeVarType.cloneForUnpacked(typeArgType);
            }
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unpackExpectedTypeVarTuple(), errorNode);
            return types_1.UnknownType.create();
        }
        if ((flags & 8388608 /* EvaluatorFlags.AllowUnpackedTypedDict */) !== 0) {
            if ((0, types_1.isInstantiableClass)(typeArgType) && types_1.ClassType.isTypedDictClass(typeArgType)) {
                return types_1.ClassType.cloneForUnpacked(typeArgType);
            }
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unpackExpectedTypedDict(), errorNode);
            return types_1.UnknownType.create();
        }
        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unpackNotAllowed(), errorNode);
        return types_1.UnknownType.create();
    }
    // Creates a "Final" type.
    function createFinalType(classType, errorNode, typeArgs, flags) {
        if (flags & 16 /* EvaluatorFlags.DisallowFinal */) {
            addError(localize_1.LocMessage.finalContext(), errorNode);
            return classType;
        }
        if (!typeArgs || typeArgs.length === 0) {
            return classType;
        }
        if (typeArgs.length > 1) {
            addError(localize_1.LocMessage.finalTooManyArgs(), errorNode);
        }
        return types_1.TypeBase.cloneAsSpecialForm(typeArgs[0].type, classType);
    }
    function createConcatenateType(classType, errorNode, typeArgs, flags) {
        if ((flags & 134217728 /* EvaluatorFlags.AllowConcatenate */) === 0) {
            addError(localize_1.LocMessage.concatenateContext(), errorNode);
            return types_1.AnyType.create();
        }
        if (!typeArgs || typeArgs.length === 0) {
            addError(localize_1.LocMessage.concatenateTypeArgsMissing(), errorNode);
        }
        else {
            typeArgs.forEach((typeArg, index) => {
                if (index === typeArgs.length - 1) {
                    if (!(0, types_1.isParamSpec)(typeArg.type) && !(0, typeUtils_1.isEllipsisType)(typeArg.type)) {
                        addError(localize_1.LocMessage.concatenateParamSpecMissing(), typeArg.node);
                    }
                }
                else {
                    if ((0, types_1.isParamSpec)(typeArg.type)) {
                        addError(localize_1.LocMessage.paramSpecContext(), typeArg.node);
                    }
                    else if ((0, types_1.isUnpackedVariadicTypeVar)(typeArg.type)) {
                        addError(localize_1.LocMessage.typeVarTupleContext(), typeArg.node);
                    }
                    else if ((0, types_1.isUnpackedClass)(typeArg.type)) {
                        addError(localize_1.LocMessage.unpackedArgInTypeArgument(), typeArg.node);
                    }
                }
            });
        }
        return createSpecialType(classType, typeArgs, /* paramLimit */ undefined, /* allowParamSpec */ true);
    }
    function createAnnotatedType(classType, errorNode, typeArgs) {
        if (typeArgs && typeArgs.length < 2) {
            addError(localize_1.LocMessage.annotatedTypeArgMissing(), errorNode);
        }
        if (!typeArgs || typeArgs.length === 0) {
            return { type: types_1.AnyType.create() };
        }
        if (typeArgs[0].typeList) {
            addError(localize_1.LocMessage.typeArgListNotAllowed(), typeArgs[0].node);
        }
        return {
            type: types_1.TypeBase.cloneAsSpecialForm(typeArgs[0].type, classType),
            isReadOnly: typeArgs[0].isReadOnly,
            isRequired: typeArgs[0].isRequired,
            isNotRequired: typeArgs[0].isNotRequired,
        };
    }
    // Creates one of several "special" types that are defined in typing.pyi
    // but not declared in their entirety. This includes the likes of "Tuple",
    // "Dict", etc.
    function createSpecialType(classType, typeArgs, paramLimit, allowParamSpec = false, isSpecialForm = true) {
        const isTupleTypeParam = types_1.ClassType.isTupleClass(classType);
        if (typeArgs) {
            if (isTupleTypeParam && typeArgs.length === 1 && typeArgs[0].isEmptyTupleShorthand) {
                typeArgs = [];
            }
            else {
                let sawUnpacked = false;
                const noteSawUnpacked = (typeArg) => {
                    if (sawUnpacked) {
                        if (!reportedUnpackedError) {
                            addError(localize_1.LocMessage.variadicTypeArgsTooMany(), typeArg.node);
                            reportedUnpackedError = true;
                        }
                    }
                    sawUnpacked = true;
                };
                let reportedUnpackedError = false;
                // Verify that we didn't receive any inappropriate types.
                typeArgs.forEach((typeArg, index) => {
                    var _a;
                    (0, debug_1.assert)(typeArgs !== undefined);
                    if ((0, typeUtils_1.isEllipsisType)(typeArg.type)) {
                        if (!isTupleTypeParam) {
                            if (!allowParamSpec) {
                                addError(localize_1.LocMessage.ellipsisContext(), typeArg.node);
                            }
                        }
                        else if (typeArgs.length !== 2 || index !== 1) {
                            addError(localize_1.LocMessage.ellipsisSecondArg(), typeArg.node);
                        }
                        else {
                            if ((0, types_1.isVariadicTypeVar)(typeArgs[0].type) && !typeArgs[0].type.isVariadicInUnion) {
                                addError(localize_1.LocMessage.typeVarTupleContext(), typeArgs[0].node);
                            }
                            else if ((0, types_1.isUnpackedClass)(typeArgs[0].type)) {
                                addError(localize_1.LocMessage.ellipsisAfterUnpacked(), typeArg.node);
                            }
                        }
                    }
                    else if ((0, types_1.isParamSpec)(typeArg.type) && allowParamSpec) {
                        // Nothing to do - this is allowed.
                    }
                    else if (paramLimit === undefined && (0, types_1.isVariadicTypeVar)(typeArg.type)) {
                        if (!typeArg.type.isVariadicInUnion) {
                            noteSawUnpacked(typeArg);
                        }
                        validateVariadicTypeVarIsUnpacked(typeArg.type, typeArg.node);
                    }
                    else if (paramLimit === undefined && (0, types_1.isUnpackedClass)(typeArg.type)) {
                        if ((_a = typeArg.type.tupleTypeArguments) === null || _a === void 0 ? void 0 : _a.some((typeArg) => (0, types_1.isVariadicTypeVar)(typeArg.type) || typeArg.isUnbounded)) {
                            noteSawUnpacked(typeArg);
                        }
                        validateTypeArg(typeArg, { allowUnpackedTuples: true });
                    }
                    else {
                        validateTypeArg(typeArg);
                    }
                });
            }
        }
        let typeArgTypes = typeArgs ? typeArgs.map((t) => (0, typeUtils_1.convertToInstance)(t.type)) : [];
        // Make sure the argument list count is correct.
        if (paramLimit !== undefined) {
            if (typeArgs && typeArgTypes.length > paramLimit) {
                addError(localize_1.LocMessage.typeArgsTooMany().format({
                    name: classType.aliasName || classType.details.name,
                    expected: paramLimit,
                    received: typeArgTypes.length,
                }), typeArgs[paramLimit].node);
                typeArgTypes = typeArgTypes.slice(0, paramLimit);
            }
            else if (typeArgTypes.length < paramLimit) {
                // Fill up the remainder of the slots with unknown types.
                while (typeArgTypes.length < paramLimit) {
                    typeArgTypes.push(types_1.UnknownType.create());
                }
            }
        }
        // Handle tuple type params as a special case.
        let returnType;
        if (isTupleTypeParam) {
            const tupleTypeArgTypes = [];
            // If no type args are provided and it's a tuple, default to [Unknown, ...].
            if (!typeArgs) {
                tupleTypeArgTypes.push({ type: types_1.UnknownType.create(), isUnbounded: true });
            }
            else {
                typeArgs.forEach((typeArg, index) => {
                    if (index === 1 && (0, typeUtils_1.isEllipsisType)(typeArgTypes[index])) {
                        if (tupleTypeArgTypes.length === 1 && !tupleTypeArgTypes[0].isUnbounded) {
                            tupleTypeArgTypes[0] = { type: tupleTypeArgTypes[0].type, isUnbounded: true };
                        }
                    }
                    else if ((0, types_1.isUnpackedClass)(typeArg.type) && typeArg.type.tupleTypeArguments) {
                        (0, collectionUtils_1.appendArray)(tupleTypeArgTypes, typeArg.type.tupleTypeArguments);
                    }
                    else {
                        tupleTypeArgTypes.push({ type: typeArgTypes[index], isUnbounded: false });
                    }
                });
            }
            returnType = (0, typeUtils_1.specializeTupleClass)(classType, tupleTypeArgTypes, typeArgs !== undefined);
        }
        else {
            returnType = types_1.ClassType.cloneForSpecialization(classType, typeArgTypes, typeArgs !== undefined);
        }
        if (isSpecialForm) {
            returnType = types_1.TypeBase.cloneAsSpecialForm(returnType, classType);
        }
        return returnType;
    }
    // Unpacks the index expression for a "Union[X, Y, Z]" type annotation.
    function createUnionType(classType, errorNode, typeArgs, flags) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
        const types = [];
        let allowSingleTypeArg = false;
        if (!typeArgs) {
            // If no type arguments are provided, the resulting type
            // depends on whether we're evaluating a type annotation or
            // we're in some other context.
            if ((flags & 256 /* EvaluatorFlags.ExpectingTypeAnnotation */) !== 0) {
                addError(localize_1.LocMessage.unionTypeArgCount(), errorNode);
                return types_1.NeverType.createNever();
            }
            return classType;
        }
        for (const typeArg of typeArgs) {
            let typeArgType = typeArg.type;
            if (!validateTypeArg(typeArg, { allowVariadicTypeVar: true, allowUnpackedTuples: true })) {
                typeArgType = types_1.UnknownType.create();
            }
            else if (!(0, typeUtils_1.isEffectivelyInstantiable)(typeArgType)) {
                addExpectedClassDiagnostic(typeArgType, typeArg.node);
                typeArgType = types_1.UnknownType.create();
            }
            // If this is an unpacked tuple, explode out the individual items.
            if ((0, types_1.isUnpackedClass)(typeArg.type) && typeArg.type.tupleTypeArguments) {
                if (fileInfo.diagnosticRuleSet.enableExperimentalFeatures) {
                    typeArg.type.tupleTypeArguments.forEach((tupleTypeArg) => {
                        types.push((0, typeUtils_1.convertToInstantiable)(tupleTypeArg.type));
                    });
                    allowSingleTypeArg = true;
                }
                else {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unionUnpackedTuple(), errorNode);
                    types.push(types_1.UnknownType.create());
                }
            }
            else {
                if ((0, types_1.isTypeVar)(typeArgType) && (0, types_1.isUnpackedVariadicTypeVar)(typeArgType)) {
                    if (fileInfo.diagnosticRuleSet.enableExperimentalFeatures) {
                        // If this is an unpacked TypeVar, note that it is in a union so we can
                        // differentiate between Unpack[Vs] and Union[Unpack[Vs]].
                        typeArgType = types_1.TypeVarType.cloneForUnpacked(typeArgType, /* isInUnion */ true);
                        allowSingleTypeArg = true;
                    }
                    else {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.unionUnpackedTypeVarTuple(), errorNode);
                        typeArgType = types_1.UnknownType.create();
                    }
                }
                types.push(typeArgType);
            }
        }
        // Validate that we received at least two type arguments. One type argument
        // is allowed if it's an unpacked variadic type var or tuple. None is also allowed
        // since it is used to define NoReturn in typeshed stubs).
        if (types.length === 1 && !allowSingleTypeArg && !(0, typeUtils_1.isNoneInstance)(types[0])) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.unionTypeArgCount(), errorNode);
        }
        let unionType = (0, types_1.combineTypes)(types);
        if (unionClassType && (0, types_1.isInstantiableClass)(unionClassType)) {
            unionType = types_1.TypeBase.cloneAsSpecialForm(unionType, types_1.ClassType.cloneAsInstance(unionClassType));
        }
        return unionType;
    }
    // Creates a type that represents "Generic[T1, T2, ...]", used in the
    // definition of a generic class.
    function createGenericType(classType, errorNode, typeArgs, flags) {
        if (!typeArgs) {
            // If no type arguments are provided, the resulting type
            // depends on whether we're evaluating a type annotation or
            // we're in some other context.
            if ((flags & (256 /* EvaluatorFlags.ExpectingTypeAnnotation */ | 262144 /* EvaluatorFlags.DisallowNakedGeneric */)) !== 0) {
                addError(localize_1.LocMessage.genericTypeArgMissing(), errorNode);
            }
            return classType;
        }
        const uniqueTypeVars = [];
        if (typeArgs) {
            // Make sure there's at least one type arg.
            if (typeArgs.length === 0) {
                addError(localize_1.LocMessage.genericTypeArgMissing(), errorNode);
            }
            // Make sure that all of the type args are typeVars and are unique.
            typeArgs.forEach((typeArg) => {
                if (!(0, types_1.isTypeVar)(typeArg.type)) {
                    addError(localize_1.LocMessage.genericTypeArgTypeVar(), typeArg.node);
                }
                else {
                    if (uniqueTypeVars.some((t) => (0, types_1.isTypeSame)(t, typeArg.type))) {
                        addError(localize_1.LocMessage.genericTypeArgUnique(), typeArg.node);
                    }
                    uniqueTypeVars.push(typeArg.type);
                }
            });
        }
        return createSpecialType(classType, typeArgs, /* paramLimit */ undefined, /* allowParamSpec */ true);
    }
    function transformTypeForTypeAlias(type, name, errorNode, isPep695Syntax, isPep695TypeVarType, typeParameters, typeParamNodes) {
        if (!types_1.TypeBase.isInstantiable(type)) {
            return type;
        }
        // If this is a recursive type alias that hasn't yet been fully resolved
        // (i.e. there is no boundType associated with it), don't apply the transform.
        if ((0, typeUtils_1.isTypeAliasPlaceholder)(type)) {
            return type;
        }
        if (!typeParameters) {
            // Determine if there are any generic type parameters associated
            // with this type alias.
            typeParameters = [];
            (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                (0, debug_1.assert)(typeParameters !== undefined);
                (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParameters, (0, typeUtils_1.getTypeVarArgumentsRecursive)(subtype));
            });
            // Don't include any synthesized type variables.
            typeParameters = typeParameters.filter((typeVar) => !typeVar.details.isSynthesized);
        }
        // Convert all type variables to instances.
        typeParameters = typeParameters.map((typeVar) => {
            if (types_1.TypeBase.isInstance(typeVar)) {
                return typeVar;
            }
            return (0, typeUtils_1.convertToInstance)(typeVar);
        });
        // See if the type alias includes a TypeVarTuple followed by a TypeVar
        // with a default value. This isn't allowed.
        const firstTypeVarTupleIndex = typeParameters.findIndex((typeVar) => (0, types_1.isVariadicTypeVar)(typeVar));
        if (firstTypeVarTupleIndex >= 0) {
            const typeVarWithDefaultIndex = typeParameters.findIndex((typeVar, index) => index > firstTypeVarTupleIndex && !typeVar.details.isParamSpec && typeVar.details.isDefaultExplicit);
            if (typeVarWithDefaultIndex >= 0) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarWithDefaultFollowsVariadic().format({
                    typeVarName: typeParameters[typeVarWithDefaultIndex].details.name,
                    variadicName: typeParameters[firstTypeVarTupleIndex].details.name,
                }), typeParamNodes ? typeParamNodes[typeVarWithDefaultIndex].name : name);
            }
        }
        const typeAliasScopeId = ParseTreeUtils.getScopeIdForNode(name);
        // Validate the default types for all type parameters.
        typeParameters.forEach((typeParam, index) => {
            var _a;
            (0, debug_1.assert)(typeParameters !== undefined);
            let bestErrorNode = errorNode;
            if (typeParamNodes && index < typeParamNodes.length) {
                bestErrorNode = (_a = typeParamNodes[index].defaultExpression) !== null && _a !== void 0 ? _a : typeParamNodes[index].name;
            }
            validateTypeParameterDefault(bestErrorNode, typeParam, typeParameters.slice(0, index), typeAliasScopeId);
        });
        // Verify that we have at most one variadic type variable.
        const variadics = typeParameters.filter((param) => (0, types_1.isVariadicTypeVar)(param));
        if (variadics.length > 1) {
            addError(localize_1.LocMessage.variadicTypeParamTooManyAlias().format({
                names: variadics.map((v) => `"${v.details.name}"`).join(', '),
            }), errorNode);
        }
        if (!isPep695Syntax && !isPep695TypeVarType) {
            const boundTypeVars = typeParameters.filter((typeVar) => typeVar.scopeId !== typeAliasScopeId && typeVar.scopeType === 0 /* TypeVarScopeType.Class */);
            if (boundTypeVars.length > 0) {
                addError(localize_1.LocMessage.genericTypeAliasBoundTypeVar().format({
                    names: boundTypeVars.map((t) => `${t.details.name}`).join(', '),
                }), errorNode);
            }
        }
        const fileInfo = AnalyzerNodeInfo.getFileInfo(name);
        let typeAlias = types_1.TypeBase.cloneForTypeAlias(type, name.value, ParseTreeUtils.getClassFullName(name, fileInfo.moduleName, name.value), fileInfo.moduleName, fileInfo.fileUri, typeAliasScopeId, isPep695Syntax, typeParameters.length > 0 ? typeParameters : undefined);
        // All PEP 695 type aliases are special forms because they are
        // TypeAliasType objects at runtime.
        if (isPep695Syntax || isPep695TypeVarType) {
            const typeAliasTypeClass = getTypingType(errorNode, 'TypeAliasType');
            if (typeAliasTypeClass && (0, types_1.isInstantiableClass)(typeAliasTypeClass)) {
                typeAlias = types_1.TypeBase.cloneAsSpecialForm(typeAlias, types_1.ClassType.cloneAsInstance(typeAliasTypeClass));
            }
        }
        return typeAlias;
    }
    function createSpecialBuiltInClass(node, assignedName, aliasMapEntry) {
        var _a;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        let specialClassType = types_1.ClassType.createInstantiable(assignedName, ParseTreeUtils.getClassFullName(node, fileInfo.moduleName, assignedName), fileInfo.moduleName, fileInfo.fileUri, 1 /* ClassTypeFlags.BuiltInClass */ | 2 /* ClassTypeFlags.SpecialBuiltIn */, 
        /* typeSourceId */ 0, 
        /* declaredMetaclass */ undefined, 
        /* effectiveMetaclass */ undefined);
        if (aliasMapEntry.isSpecialForm) {
            specialClassType.details.flags |= -2147483648 /* ClassTypeFlags.SpecialFormClass */;
        }
        // Synthesize a single type parameter with the specified variance if
        // specified in the alias map entry.
        if (aliasMapEntry.typeParamVariance !== undefined) {
            let typeParam = types_1.TypeVarType.createInstance('T');
            typeParam = types_1.TypeVarType.cloneForScopeId(typeParam, ParseTreeUtils.getScopeIdForNode(node), assignedName, 0 /* TypeVarScopeType.Class */);
            typeParam.details.declaredVariance = aliasMapEntry.typeParamVariance;
            specialClassType.details.typeParameters.push(typeParam);
        }
        const specialBuiltInClassDeclaration = ((_a = AnalyzerNodeInfo.getDeclaration(node)) !== null && _a !== void 0 ? _a : (node.parent ? AnalyzerNodeInfo.getDeclaration(node.parent) : undefined));
        specialClassType.details.declaration = specialBuiltInClassDeclaration;
        if (fileInfo.isTypingExtensionsStubFile) {
            specialClassType.details.flags |= 131072 /* ClassTypeFlags.TypingExtensionClass */;
        }
        const baseClassName = aliasMapEntry.alias || 'object';
        let baseClass;
        if (aliasMapEntry.module === 'builtins') {
            baseClass = getBuiltInType(node, baseClassName);
        }
        else if (aliasMapEntry.module === 'collections' || aliasMapEntry.module === 'contextlib') {
            // The typing.pyi file imports collections.
            baseClass = getTypeOfModule(node, baseClassName, [aliasMapEntry.module]);
        }
        else if (aliasMapEntry.module === 'self') {
            const symbolWithScope = lookUpSymbolRecursive(node, baseClassName, /* honorCodeFlow */ false);
            if (symbolWithScope) {
                baseClass = getEffectiveTypeOfSymbol(symbolWithScope.symbol);
                // The _TypedDict class is marked as abstract, but the
                // methods that are abstract are overridden and shouldn't
                // cause the TypedDict to be marked as abstract.
                if ((0, types_1.isInstantiableClass)(baseClass) && types_1.ClassType.isBuiltIn(baseClass, '_TypedDict')) {
                    baseClass = types_1.ClassType.cloneWithNewFlags(baseClass, baseClass.details.flags &
                        ~(2048 /* ClassTypeFlags.SupportsAbstractMethods */ | 268435456 /* ClassTypeFlags.TypeCheckOnly */));
                }
            }
        }
        else {
            aliasMapEntry.module;
        }
        if (baseClass && (0, types_1.isInstantiableClass)(baseClass)) {
            if (aliasMapEntry.alias) {
                specialClassType = types_1.ClassType.cloneForTypingAlias(baseClass, assignedName);
            }
            else {
                specialClassType.details.baseClasses.push(baseClass);
                specialClassType.details.effectiveMetaclass = baseClass.details.effectiveMetaclass;
                (0, typeUtils_1.computeMroLinearization)(specialClassType);
            }
        }
        else {
            specialClassType.details.baseClasses.push(types_1.UnknownType.create());
            specialClassType.details.effectiveMetaclass = types_1.UnknownType.create();
            (0, typeUtils_1.computeMroLinearization)(specialClassType);
        }
        return specialClassType;
    }
    // Handles some special-case type annotations that are found
    // within the typings.pyi file.
    function handleTypingStubTypeAnnotation(node) {
        if (!node.parent || node.parent.nodeType !== 54 /* ParseNodeType.TypeAnnotation */) {
            return undefined;
        }
        if (node.parent.valueExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            return undefined;
        }
        const nameNode = node.parent.valueExpression;
        const assignedName = nameNode.value;
        const specialTypes = new Map([
            ['Tuple', { alias: 'tuple', module: 'builtins' }],
            ['Generic', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Protocol', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Callable', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Type', { alias: 'type', module: 'builtins' }],
            ['ClassVar', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Final', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Literal', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['TypedDict', { alias: '_TypedDict', module: 'self' }],
            ['Union', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Optional', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Annotated', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['TypeAlias', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Concatenate', { alias: '', module: 'builtins', isSpecialForm: true }],
            [
                'TypeGuard',
                { alias: '', module: 'builtins', isSpecialForm: true, typeParamVariance: 3 /* Variance.Covariant */ },
            ],
            ['Unpack', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Required', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['NotRequired', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Self', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['NoReturn', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['Never', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['LiteralString', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['ReadOnly', { alias: '', module: 'builtins', isSpecialForm: true }],
            ['TypeIs', { alias: '', module: 'builtins', isSpecialForm: true, typeParamVariance: 2 /* Variance.Invariant */ }],
        ]);
        const aliasMapEntry = specialTypes.get(assignedName);
        if (aliasMapEntry) {
            const cachedType = readTypeCache(node, 0 /* EvaluatorFlags.None */);
            if (cachedType) {
                (0, debug_1.assert)((0, types_1.isInstantiableClass)(cachedType));
                return cachedType;
            }
            const specialType = createSpecialBuiltInClass(node, assignedName, aliasMapEntry);
            // Handle 'LiteralString' specially because we want it to act as
            // though it derives from 'str'.
            if (assignedName === 'LiteralString') {
                specialType.details.baseClasses.push(strClassType !== null && strClassType !== void 0 ? strClassType : types_1.AnyType.create());
                (0, typeUtils_1.computeMroLinearization)(specialType);
            }
            writeTypeCache(node, { type: specialType }, 0 /* EvaluatorFlags.None */);
            return specialType;
        }
        return undefined;
    }
    // Handles some special-case assignment statements that are found
    // within the typings.pyi file.
    function handleTypingStubAssignment(node) {
        if (node.leftExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            return undefined;
        }
        const nameNode = node.leftExpression;
        const assignedName = nameNode.value;
        if (assignedName === 'Any') {
            return types_1.AnyType.createSpecialForm();
        }
        const specialTypes = new Map([
            ['overload', { alias: '', module: 'builtins' }],
            ['TypeVar', { alias: '', module: 'builtins' }],
            ['_promote', { alias: '', module: 'builtins' }],
            ['no_type_check', { alias: '', module: 'builtins' }],
            ['NoReturn', { alias: '', module: 'builtins' }],
            ['Never', { alias: '', module: 'builtins' }],
            ['Counter', { alias: 'Counter', module: 'collections' }],
            ['List', { alias: 'list', module: 'builtins' }],
            ['Dict', { alias: 'dict', module: 'builtins' }],
            ['DefaultDict', { alias: 'defaultdict', module: 'collections' }],
            ['Set', { alias: 'set', module: 'builtins' }],
            ['FrozenSet', { alias: 'frozenset', module: 'builtins' }],
            ['Deque', { alias: 'deque', module: 'collections' }],
            ['ChainMap', { alias: 'ChainMap', module: 'collections' }],
            ['OrderedDict', { alias: 'OrderedDict', module: 'collections' }],
            ['ContextManager', { alias: 'AbstractContextManager', module: 'contextlib' }],
            ['AsyncContextManager', { alias: 'AbstractAsyncContextManager', module: 'contextlib' }],
        ]);
        const aliasMapEntry = specialTypes.get(assignedName);
        if (aliasMapEntry) {
            // Evaluate the expression so symbols are marked as accessed.
            getTypeOfExpression(node.rightExpression);
            return createSpecialBuiltInClass(node, assignedName, aliasMapEntry);
        }
        return undefined;
    }
    function evaluateTypesForAssignmentStatement(node) {
        var _a, _b;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        // If the entire statement has already been evaluated, don't
        // re-evaluate it.
        if (isTypeCached(node)) {
            return;
        }
        let flags = 0 /* EvaluatorFlags.None */;
        if (fileInfo.isStubFile) {
            // An assignment of ellipsis means "Any" within a type stub file.
            flags |= 1 /* EvaluatorFlags.ConvertEllipsisToAny */;
        }
        if (node.rightExpression.nodeType === 38 /* ParseNodeType.Name */ ||
            node.rightExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            // Don't specialize a generic class on assignment (e.g. "x = list"
            // or "x = collections.OrderedDict") because we may want to later
            // specialize it (e.g. "x[int]").
            flags |= 2 /* EvaluatorFlags.DoNotSpecialize */;
        }
        if (isDeclaredTypeAlias(node.leftExpression)) {
            flags |=
                128 /* EvaluatorFlags.ExpectingInstantiableType */ |
                    256 /* EvaluatorFlags.ExpectingTypeAnnotation */ |
                    8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
                    32 /* EvaluatorFlags.DisallowParamSpec */ |
                    64 /* EvaluatorFlags.DisallowTypeVarTuple */ |
                    131072 /* EvaluatorFlags.DisallowClassVar */;
            flags &= ~2 /* EvaluatorFlags.DoNotSpecialize */;
        }
        // Is this type already cached?
        let rightHandType = readTypeCache(node.rightExpression, flags);
        let isIncomplete = false;
        let expectedTypeDiagAddendum;
        if (!rightHandType) {
            // Special-case the typing.pyi file, which contains some special
            // types that the type analyzer needs to interpret differently.
            if (fileInfo.isTypingStubFile || fileInfo.isTypingExtensionsStubFile) {
                rightHandType = handleTypingStubAssignment(node);
                if (rightHandType) {
                    writeTypeCache(node.rightExpression, { type: rightHandType }, 0 /* EvaluatorFlags.None */);
                }
            }
            if (!rightHandType) {
                // Determine whether there is a declared type.
                const declaredType = getDeclaredTypeForExpression(node.leftExpression, {
                    method: 'set',
                });
                let typeAliasNameNode;
                let isSpeculativeTypeAlias = false;
                if (isDeclaredTypeAlias(node.leftExpression)) {
                    typeAliasNameNode = node.leftExpression.valueExpression;
                    if (!isLegalTypeAliasExpressionForm(node.rightExpression)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.typeAliasIllegalExpressionForm(), node.rightExpression);
                    }
                }
                else if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    const symbolWithScope = lookUpSymbolRecursive(node.leftExpression, node.leftExpression.value, 
                    /* honorCodeFlow */ false);
                    if (symbolWithScope) {
                        const decls = symbolWithScope.symbol.getDeclarations();
                        if (decls.length === 1 && isPossibleTypeAliasOrTypedDict(decls[0])) {
                            typeAliasNameNode = node.leftExpression;
                            isSpeculativeTypeAlias = true;
                        }
                    }
                }
                // Synthesize a type variable that represents the type alias while we're
                // evaluating it. This allows us to handle recursive definitions.
                let typeAliasTypeVar;
                if (typeAliasNameNode) {
                    typeAliasTypeVar = types_1.TypeVarType.createInstantiable(`__type_alias_${typeAliasNameNode.value}`);
                    typeAliasTypeVar.details.isSynthesized = true;
                    typeAliasTypeVar.details.recursiveTypeAliasName = typeAliasNameNode.value;
                    const scopeId = ParseTreeUtils.getScopeIdForNode(typeAliasNameNode);
                    typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId;
                    typeAliasTypeVar.details.recursiveTypeAliasIsPep695Syntax = false;
                    typeAliasTypeVar.scopeId = scopeId;
                    // Write the type back to the type cache. It will be replaced below.
                    writeTypeCache(node, { type: typeAliasTypeVar }, /* flags */ undefined);
                    writeTypeCache(node.leftExpression, { type: typeAliasTypeVar }, /* flags */ undefined);
                    if (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
                        writeTypeCache(node.leftExpression.valueExpression, { type: typeAliasTypeVar }, 
                        /* flags */ undefined);
                    }
                }
                const srcTypeResult = getTypeOfExpression(node.rightExpression, flags, (0, typeUtils_1.makeInferenceContext)(declaredType));
                let srcType = srcTypeResult.type;
                expectedTypeDiagAddendum = srcTypeResult.expectedTypeDiagAddendum;
                if (srcTypeResult.isIncomplete) {
                    isIncomplete = true;
                }
                // If the RHS is a constant boolean expression, assign it a literal type.
                const constExprValue = (0, staticExpressions_1.evaluateStaticBoolExpression)(node.rightExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                if (constExprValue !== undefined) {
                    const boolType = getBuiltInObject(node, 'bool');
                    if ((0, types_1.isClassInstance)(boolType)) {
                        srcType = types_1.ClassType.cloneWithLiteral(boolType, constExprValue);
                    }
                }
                // If this is an enum, transform the type as required.
                rightHandType = srcType;
                let targetName;
                if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    targetName = node.leftExpression;
                }
                else if (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */ &&
                    node.leftExpression.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    targetName = node.leftExpression.valueExpression;
                }
                if (targetName) {
                    rightHandType =
                        (_a = (0, enums_1.transformTypeForPossibleEnumClass)(evaluatorInterface, node, targetName, () => {
                            return { assignedType: rightHandType };
                        })) !== null && _a !== void 0 ? _a : rightHandType;
                }
                if (typeAliasNameNode) {
                    // If this was a speculative type alias, it becomes a real type alias
                    // only if the evaluated type is an instantiable type.
                    if (!isSpeculativeTypeAlias || isLegalImplicitTypeAliasType(rightHandType)) {
                        // If this is a type alias, record its name based on the assignment target.
                        rightHandType = transformTypeForTypeAlias(rightHandType, typeAliasNameNode, typeAliasNameNode, 
                        /* isPep695Syntax */ false, 
                        /* isPep695TypeVarType */ false);
                        (0, debug_1.assert)(typeAliasTypeVar !== undefined);
                        if ((0, typeUtils_1.isTypeAliasRecursive)(typeAliasTypeVar, rightHandType)) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasIsRecursiveDirect().format({
                                name: typeAliasNameNode.value,
                            }), node.rightExpression);
                            rightHandType = types_1.UnknownType.create();
                        }
                        // Set the resulting type to the boundType of the original type alias
                        // to support recursive type aliases.
                        typeAliasTypeVar.details.boundType = rightHandType;
                        // Record the type parameters within the recursive type alias so it
                        // can be specialized.
                        typeAliasTypeVar.details.recursiveTypeParameters = (_b = rightHandType.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.typeParameters;
                    }
                }
            }
        }
        assignTypeToExpression(node.leftExpression, rightHandType, isIncomplete, node.rightExpression, 
        /* ignoreEmptyContainers */ true, 
        /* allowAssignmentToFinalVar */ true, expectedTypeDiagAddendum);
        writeTypeCache(node, { type: rightHandType, isIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function isPossibleTypeAliasOrTypedDict(decl) {
        var _a;
        if (isPossibleTypeAliasDeclaration(decl)) {
            return true;
        }
        if (decl.type === 1 /* DeclarationType.Variable */ &&
            decl.node.parent &&
            decl.node.parent.nodeType === 3 /* ParseNodeType.Assignment */ &&
            ((_a = decl.node.parent.rightExpression) === null || _a === void 0 ? void 0 : _a.nodeType) === 9 /* ParseNodeType.Call */) {
            const callLeftNode = decl.node.parent.rightExpression.leftExpression;
            // Use a simple heuristic to determine whether this is potentially
            // a call to the TypedDict call. This avoids the expensive (and potentially
            // recursive) call to getTypeOfExpression in cases where it's not needed.
            if ((callLeftNode.nodeType === 38 /* ParseNodeType.Name */ && callLeftNode.value) === 'TypedDict' ||
                (callLeftNode.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                    callLeftNode.memberName.value === 'TypedDict' &&
                    callLeftNode.leftExpression.nodeType === 38 /* ParseNodeType.Name */)) {
                // See if this is a call to TypedDict. We want to support
                // recursive type references in a TypedDict call.
                const callType = getTypeOfExpression(callLeftNode, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                if ((0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, 'TypedDict')) {
                    return true;
                }
            }
        }
        return false;
    }
    // Evaluates the type of a type alias (i.e. "type") statement. This code
    // path does not handle traditional type aliases, which are treated as
    // variables since they use normal variable assignment syntax.
    function getTypeOfTypeAlias(node) {
        var _a;
        return getTypeOfTypeAliasCommon(node, node.name, node.expression, 
        /* isPep695Syntax */ true, (_a = node.typeParameters) === null || _a === void 0 ? void 0 : _a.parameters, () => {
            if (node.typeParameters) {
                return evaluateTypeParameterList(node.typeParameters);
            }
            return undefined;
        });
    }
    // This function is common to the handling of "type" statements and explicit
    // calls to the TypeAliasType constructor.
    function getTypeOfTypeAliasCommon(declNode, nameNode, valueNode, isPep695Syntax, typeParamNodes, getTypeParamCallback) {
        const cachedType = readTypeCache(nameNode, 0 /* EvaluatorFlags.None */);
        if (cachedType) {
            return cachedType;
        }
        // Synthesize a type variable that represents the type alias while we're
        // evaluating it. This allows us to handle recursive definitions.
        const typeAliasTypeVar = types_1.TypeVarType.createInstantiable(`__type_alias_${nameNode.value}`);
        typeAliasTypeVar.details.isSynthesized = true;
        typeAliasTypeVar.details.recursiveTypeAliasName = nameNode.value;
        const scopeId = ParseTreeUtils.getScopeIdForNode(nameNode);
        typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId;
        typeAliasTypeVar.details.recursiveTypeAliasIsPep695Syntax = isPep695Syntax;
        typeAliasTypeVar.scopeId = scopeId;
        // Write the type to the type cache. It will be replaced below.
        writeTypeCache(nameNode, { type: typeAliasTypeVar }, /* flags */ undefined);
        // Set a partial type to handle recursive (self-referential) type aliases.
        const scope = ScopeUtils.getScopeForNode(declNode);
        const typeAliasSymbol = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbolRecursive(nameNode.value);
        const typeAliasDecl = AnalyzerNodeInfo.getDeclaration(declNode);
        if (typeAliasDecl && typeAliasSymbol) {
            setSymbolResolutionPartialType(typeAliasSymbol.symbol, typeAliasDecl, typeAliasTypeVar);
        }
        const typeParameters = getTypeParamCallback();
        typeAliasTypeVar.details.recursiveTypeParameters = typeParameters || [];
        const aliasTypeResult = getTypeOfExpressionExpectingType(valueNode, {
            allowForwardReference: true,
            enforceTypeAnnotationRules: true,
        });
        let isIncomplete = false;
        let aliasType = aliasTypeResult.type;
        if (aliasTypeResult.isIncomplete) {
            isIncomplete = true;
        }
        aliasType = transformTypeForTypeAlias(aliasType, nameNode, nameNode, isPep695Syntax, 
        /* isPep695TypeVarType */ true, typeParameters, typeParamNodes);
        // See if the type alias relies on itself in a way that cannot be resolved.
        if ((0, typeUtils_1.isTypeAliasRecursive)(typeAliasTypeVar, aliasType)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeAliasIsRecursiveDirect().format({
                name: nameNode.value,
            }), valueNode);
            aliasType = types_1.UnknownType.create();
        }
        // Set the resulting type to the boundType of the original type alias
        // to support recursive type aliases.
        typeAliasTypeVar.details.boundType = aliasType;
        writeTypeCache(nameNode, { type: aliasType, isIncomplete }, 0 /* EvaluatorFlags.None */);
        return aliasType;
    }
    function evaluateTypesForAugmentedAssignment(node) {
        if (isTypeCached(node)) {
            return;
        }
        const destTypeResult = (0, operations_1.getTypeOfAugmentedAssignment)(evaluatorInterface, node, /* inferenceContext */ undefined);
        writeTypeCache(node, destTypeResult, 0 /* EvaluatorFlags.None */);
    }
    function getPseudoGenericTypeVarName(paramName) {
        return `__type_of_${paramName}`;
    }
    function getTypeOfClass(node) {
        initializedBasicTypes(node);
        // Is this type already cached?
        const cachedClassType = readTypeCache(node.name, 0 /* EvaluatorFlags.None */);
        if (cachedClassType) {
            if (!(0, types_1.isInstantiableClass)(cachedClassType)) {
                // This can happen in rare circumstances where the class declaration
                // is located in an unreachable code block.
                return undefined;
            }
            return {
                classType: cachedClassType,
                decoratedType: readTypeCache(node, 0 /* EvaluatorFlags.None */) || types_1.UnknownType.create(),
            };
        }
        // The type wasn't cached, so we need to create a new one.
        const scope = ScopeUtils.getScopeForNode(node);
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        let classFlags = 0 /* ClassTypeFlags.None */;
        if ((scope === null || scope === void 0 ? void 0 : scope.type) === 4 /* ScopeType.Builtin */ ||
            fileInfo.isTypingStubFile ||
            fileInfo.isTypingExtensionsStubFile ||
            fileInfo.isBuiltInStubFile ||
            fileInfo.isTypeshedStubFile) {
            classFlags |= 1 /* ClassTypeFlags.BuiltInClass */;
            if (fileInfo.isTypingExtensionsStubFile) {
                classFlags |= 131072 /* ClassTypeFlags.TypingExtensionClass */;
            }
            if (node.name.value === 'property') {
                classFlags |= 4096 /* ClassTypeFlags.PropertyClass */;
            }
            if (node.name.value === 'tuple') {
                classFlags |= 1048576 /* ClassTypeFlags.TupleClass */;
            }
        }
        if (fileInfo.isStubFile) {
            classFlags |= 16777216 /* ClassTypeFlags.DefinedInStub */;
        }
        const classType = types_1.ClassType.createInstantiable(node.name.value, ParseTreeUtils.getClassFullName(node, fileInfo.moduleName, node.name.value), fileInfo.moduleName, fileInfo.fileUri, classFlags, 
        /* typeSourceId */ 0, 
        /* declaredMetaclass */ undefined, 
        /* effectiveMetaclass */ undefined, ParseTreeUtils.getDocString(node.suite.statements));
        classType.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node);
        // Is this a special type that supports type promotions according to PEP 484?
        if (typePromotions.has(classType.details.fullName)) {
            classType.includePromotions = true;
        }
        // Some classes refer to themselves within type arguments used within
        // base classes. We'll register the partially-constructed class type
        // to allow these to be resolved.
        const classSymbol = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbol(node.name.value);
        let classDecl;
        const decl = AnalyzerNodeInfo.getDeclaration(node);
        if (decl) {
            classDecl = decl;
        }
        if (classDecl && classSymbol) {
            setSymbolResolutionPartialType(classSymbol, classDecl, classType);
        }
        classType.details.flags |= 262144 /* ClassTypeFlags.PartiallyEvaluated */;
        classType.details.declaration = classDecl;
        try {
            writeTypeCache(node, { type: classType }, /* flags */ undefined);
            writeTypeCache(node.name, { type: classType }, /* flags */ undefined);
            // Keep a list of unique type parameters that are used in the
            // base class arguments.
            let typeParameters = [];
            if (node.typeParameters) {
                typeParameters = evaluateTypeParameterList(node.typeParameters).map((t) => types_1.TypeVarType.cloneAsInstance(t));
            }
            // If the class derives from "Generic" directly, it will provide
            // all of the type parameters in the specified order.
            let genericTypeParameters;
            let protocolTypeParameters;
            let isNamedTupleSubclass = false;
            const initSubclassArgs = [];
            let metaclassNode;
            let exprFlags = 128 /* EvaluatorFlags.ExpectingInstantiableType */ |
                1024 /* EvaluatorFlags.AllowGenericClassType */ |
                262144 /* EvaluatorFlags.DisallowNakedGeneric */ |
                2048 /* EvaluatorFlags.DisallowTypeVarsWithScopeId */ |
                8192 /* EvaluatorFlags.AssociateTypeVarsWithCurrentScope */ |
                16384 /* EvaluatorFlags.EnforceTypeVarVarianceConsistency */;
            if (fileInfo.isStubFile) {
                exprFlags |= 4 /* EvaluatorFlags.AllowForwardReferences */;
            }
            node.arguments.forEach((arg) => {
                // Ignore unpacked arguments.
                if (arg.argumentCategory === 2 /* ArgumentCategory.UnpackedDictionary */) {
                    // Evaluate the expression's type so symbols are marked accessed
                    // and errors are reported.
                    getTypeOfExpression(arg.valueExpression);
                    return;
                }
                if (!arg.name) {
                    let argType;
                    if (arg.argumentCategory === 1 /* ArgumentCategory.UnpackedList */) {
                        getTypeOfExpression(arg.valueExpression);
                        argType = types_1.UnknownType.create();
                    }
                    else {
                        argType = getTypeOfExpression(arg.valueExpression, exprFlags).type;
                        if ((0, types_1.isTypeVar)(argType) && argType.specialForm && types_1.TypeBase.isInstance(argType.specialForm)) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.baseClassInvalid(), arg);
                            argType = types_1.UnknownType.create();
                        }
                        argType = makeTopLevelTypeVarsConcrete(argType);
                    }
                    // In some stub files, classes are conditionally defined (e.g. based
                    // on platform type). We'll assume that the conditional logic is correct
                    // and strip off the "unbound" union.
                    if ((0, types_1.isUnion)(argType)) {
                        argType = (0, types_1.removeUnbound)(argType);
                    }
                    // Any is allowed as a base class. Remove its "special form" flag to avoid
                    // false positive errors.
                    if ((0, types_1.isAny)(argType) && argType.specialForm) {
                        argType = types_1.AnyType.create();
                    }
                    if (!(0, types_1.isAnyOrUnknown)(argType) && !(0, types_1.isUnbound)(argType)) {
                        if ((0, typeUtils_1.isMetaclassInstance)(argType)) {
                            (0, debug_1.assert)((0, types_1.isClassInstance)(argType));
                            argType =
                                argType.typeArguments && argType.typeArguments.length > 0
                                    ? argType.typeArguments[0]
                                    : types_1.UnknownType.create();
                        }
                        else if (!(0, types_1.isInstantiableClass)(argType)) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.baseClassInvalid(), arg);
                            argType = types_1.UnknownType.create();
                        }
                        else {
                            if (types_1.ClassType.isPartiallyEvaluated(argType) ||
                                argType.details.mro.some((t) => (0, types_1.isClass)(t) && types_1.ClassType.isPartiallyEvaluated(t))) {
                                // If the base class is partially evaluated, install a callback
                                // so we can fix up this class (e.g. compute the MRO) when the
                                // dependent class is completed.
                                registerDeferredClassCompletion(node, argType);
                            }
                            if (types_1.ClassType.isBuiltIn(argType, 'Protocol')) {
                                if (!fileInfo.isStubFile &&
                                    !types_1.ClassType.isTypingExtensionClass(argType) &&
                                    fileInfo.executionEnvironment.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_7)) {
                                    addError(localize_1.LocMessage.protocolIllegal(), arg.valueExpression);
                                }
                                classType.details.flags |= 16384 /* ClassTypeFlags.ProtocolClass */;
                            }
                            if (types_1.ClassType.isBuiltIn(argType, 'property')) {
                                classType.details.flags |= 4096 /* ClassTypeFlags.PropertyClass */;
                            }
                            // If the class directly derives from NamedTuple (in Python 3.6 or
                            // newer), it's considered a (read-only) dataclass.
                            if (fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_6)) {
                                if (types_1.ClassType.isBuiltIn(argType, 'NamedTuple')) {
                                    isNamedTupleSubclass = true;
                                    classType.details.flags |=
                                        4 /* ClassTypeFlags.DataClass */ |
                                            32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */ |
                                            33554432 /* ClassTypeFlags.ReadOnlyInstanceVariables */;
                                }
                            }
                            // If the class directly derives from TypedDict or from a class that is
                            // a TypedDict, it is considered a TypedDict.
                            if (types_1.ClassType.isBuiltIn(argType, 'TypedDict') || types_1.ClassType.isTypedDictClass(argType)) {
                                classType.details.flags |= 128 /* ClassTypeFlags.TypedDictClass */;
                                // Propagate the "effectively closed" flag from base classes.
                                if (types_1.ClassType.isTypedDictEffectivelyClosed(argType)) {
                                    classType.details.flags |= 512 /* ClassTypeFlags.TypedDictEffectivelyClosed */;
                                }
                            }
                            // Validate that the class isn't deriving from itself, creating a
                            // circular dependency.
                            if ((0, typeUtils_1.derivesFromClassRecursive)(argType, classType, /* ignoreUnknown */ true)) {
                                addError(localize_1.LocMessage.baseClassCircular(), arg);
                                argType = types_1.UnknownType.create();
                            }
                            // If the class is attempting to derive from a TypeAliasType,
                            // generate an error.
                            if (argType.specialForm && types_1.ClassType.isBuiltIn(argType.specialForm, 'TypeAliasType')) {
                                addError(localize_1.LocMessage.typeAliasTypeBaseClass(), arg);
                                argType = types_1.UnknownType.create();
                            }
                        }
                    }
                    if ((0, types_1.isUnknown)(argType)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUntypedBaseClass, localize_1.LocMessage.baseClassUnknown(), arg);
                    }
                    else if ((0, types_1.isAny)(argType)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.baseClassAny(), arg);
                    }
                    // Check for a duplicate class.
                    if (classType.details.baseClasses.some((prevBaseClass) => {
                        return ((0, types_1.isInstantiableClass)(prevBaseClass) &&
                            (0, types_1.isInstantiableClass)(argType) &&
                            types_1.ClassType.isSameGenericClass(argType, prevBaseClass));
                    })) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.duplicateBaseClass(), arg.name || arg);
                    }
                    classType.details.baseClasses.push(argType);
                    if ((0, types_1.isInstantiableClass)(argType)) {
                        if (types_1.ClassType.isEnumClass(argType)) {
                            classType.details.flags |= 2097152 /* ClassTypeFlags.EnumClass */;
                        }
                        // Determine if the class is abstract. Protocol classes support abstract methods
                        // because they are constructed by the _ProtocolMeta metaclass, which derives
                        // from ABCMeta. We'll exclude built-in protocol classes because these are known
                        // not to contain any abstract methods and getAbstractMethods causes problems
                        // because of dependencies on some of these built-in protocol classes.
                        if (types_1.ClassType.supportsAbstractMethods(argType) ||
                            (types_1.ClassType.isProtocolClass(argType) && !types_1.ClassType.isBuiltIn(argType))) {
                            classType.details.flags |= 2048 /* ClassTypeFlags.SupportsAbstractMethods */;
                        }
                        if (types_1.ClassType.isPropertyClass(argType)) {
                            classType.details.flags |= 4096 /* ClassTypeFlags.PropertyClass */;
                        }
                        if (types_1.ClassType.isFinal(argType)) {
                            const className = printObjectTypeForClass(argType);
                            addError(localize_1.LocMessage.baseClassFinal().format({ type: className }), arg.valueExpression);
                        }
                    }
                    (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParameters, (0, typeUtils_1.getTypeVarArgumentsRecursive)(argType));
                    if ((0, types_1.isInstantiableClass)(argType)) {
                        if (types_1.ClassType.isBuiltIn(argType, 'Generic')) {
                            // 'Generic' is implicitly added if type parameter syntax is used.
                            if (node.typeParameters) {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.genericBaseClassNotAllowed(), arg.valueExpression);
                            }
                            else {
                                if (!genericTypeParameters) {
                                    if (protocolTypeParameters) {
                                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.duplicateGenericAndProtocolBase(), arg.valueExpression);
                                    }
                                    genericTypeParameters = [];
                                    (0, typeUtils_1.addTypeVarsToListIfUnique)(genericTypeParameters, (0, typeUtils_1.getTypeVarArgumentsRecursive)(argType));
                                }
                            }
                        }
                        else if (types_1.ClassType.isBuiltIn(argType, 'Protocol') &&
                            argType.typeArguments &&
                            argType.typeArguments.length > 0) {
                            if (!protocolTypeParameters) {
                                if (genericTypeParameters) {
                                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.duplicateGenericAndProtocolBase(), arg.valueExpression);
                                }
                                protocolTypeParameters = [];
                                (0, typeUtils_1.addTypeVarsToListIfUnique)(protocolTypeParameters, (0, typeUtils_1.getTypeVarArgumentsRecursive)(argType));
                                if (node.typeParameters && protocolTypeParameters.length > 0) {
                                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.protocolBaseClassWithTypeArgs(), arg.valueExpression);
                                    protocolTypeParameters = [];
                                }
                            }
                        }
                    }
                }
                else if (types_1.ClassType.isTypedDictClass(classType)) {
                    if (arg.name.value === 'total' || arg.name.value === 'closed') {
                        // The "total" and "readonly" parameters apply only for TypedDict classes.
                        // PEP 589 specifies that the parameter must be either True or False.
                        const constArgValue = (0, staticExpressions_1.evaluateStaticBoolExpression)(arg.valueExpression, fileInfo.executionEnvironment, fileInfo.definedConstants);
                        if (constArgValue === undefined) {
                            addError(localize_1.LocMessage.typedDictBoolParam().format({ name: arg.name.value }), arg.valueExpression);
                        }
                        else if (arg.name.value === 'total' && !constArgValue) {
                            classType.details.flags |= 1024 /* ClassTypeFlags.CanOmitDictValues */;
                        }
                        else if (arg.name.value === 'closed' && constArgValue) {
                            if (AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.enableExperimentalFeatures) {
                                classType.details.flags |=
                                    256 /* ClassTypeFlags.TypedDictMarkedClosed */ | 512 /* ClassTypeFlags.TypedDictEffectivelyClosed */;
                            }
                        }
                    }
                    else {
                        addError(localize_1.LocMessage.typedDictInitsubclassParameter().format({ name: arg.name.value }), arg);
                    }
                }
                else if (arg.name.value === 'metaclass') {
                    if (metaclassNode) {
                        addError(localize_1.LocMessage.metaclassDuplicate(), arg);
                    }
                    else {
                        metaclassNode = arg.valueExpression;
                    }
                }
                else {
                    // Collect arguments that will be passed to the `__init_subclass__`
                    // method described in PEP 487.
                    initSubclassArgs.push({
                        argumentCategory: 0 /* ArgumentCategory.Simple */,
                        node: arg,
                        name: arg.name,
                        valueExpression: arg.valueExpression,
                    });
                }
            });
            // Check for NamedTuple multiple inheritance.
            if (classType.details.baseClasses.length > 1) {
                let derivesFromNamedTuple = false;
                let foundIllegalBaseClass = false;
                classType.details.baseClasses.forEach((baseClass) => {
                    if ((0, types_1.isInstantiableClass)(baseClass)) {
                        if (types_1.ClassType.isBuiltIn(baseClass, 'NamedTuple')) {
                            derivesFromNamedTuple = true;
                        }
                        else if (!types_1.ClassType.isBuiltIn(baseClass, 'Generic')) {
                            foundIllegalBaseClass = true;
                        }
                    }
                });
                if (derivesFromNamedTuple && foundIllegalBaseClass) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.namedTupleMultipleInheritance(), node.name);
                }
            }
            // Make sure we don't have 'object' derive from itself. Infinite
            // recursion will result.
            if (!types_1.ClassType.isBuiltIn(classType, 'object') &&
                classType.details.baseClasses.filter((baseClass) => (0, types_1.isClass)(baseClass)).length === 0) {
                // If there are no other (known) base classes, the class implicitly derives from object.
                classType.details.baseClasses.push(getBuiltInType(node, 'object'));
            }
            // If genericTypeParameters or protocolTypeParameters are provided,
            // make sure that typeParameters is a proper subset.
            genericTypeParameters = genericTypeParameters !== null && genericTypeParameters !== void 0 ? genericTypeParameters : protocolTypeParameters;
            if (genericTypeParameters && !node.typeParameters) {
                verifyGenericTypeParameters(node.name, typeParameters, genericTypeParameters);
            }
            classType.details.typeParameters = genericTypeParameters !== null && genericTypeParameters !== void 0 ? genericTypeParameters : typeParameters;
            // Determine if one or more type parameters is autovariance.
            if (classType.details.typeParameters.some((param) => param.details.declaredVariance === 0 /* Variance.Auto */ && param.computedVariance === undefined)) {
                classType.details.requiresVarianceInference = true;
            }
            // Make sure there's at most one variadic type parameter.
            const variadics = typeParameters.filter((param) => (0, types_1.isVariadicTypeVar)(param));
            if (variadics.length > 1) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.variadicTypeParamTooManyClass().format({
                    names: variadics.map((v) => `"${v.details.name}"`).join(', '),
                }), node.name, textRange_1.TextRange.combine(node.arguments) || node.name);
            }
            else if (variadics.length > 0) {
                // Make sure a TypeVar with a default doesn't come after a variadic type parameter.
                const firstVariadicIndex = classType.details.typeParameters.findIndex((param) => (0, types_1.isVariadicTypeVar)(param));
                const typeVarWithDefaultIndex = classType.details.typeParameters.findIndex((param, index) => index > firstVariadicIndex && !param.details.isParamSpec && param.details.isDefaultExplicit);
                if (typeVarWithDefaultIndex >= 0) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarWithDefaultFollowsVariadic().format({
                        typeVarName: typeParameters[typeVarWithDefaultIndex].details.name,
                        variadicName: typeParameters[firstVariadicIndex].details.name,
                    }), node.typeParameters ? node.typeParameters.parameters[typeVarWithDefaultIndex].name : node.name);
                }
            }
            // Validate the default types for all type parameters.
            classType.details.typeParameters.forEach((typeParam, index) => {
                var _a;
                let bestErrorNode = node.name;
                if (node.typeParameters && index < node.typeParameters.parameters.length) {
                    const typeParamNode = node.typeParameters.parameters[index];
                    bestErrorNode = (_a = typeParamNode.defaultExpression) !== null && _a !== void 0 ? _a : typeParamNode.name;
                }
                validateTypeParameterDefault(bestErrorNode, typeParam, classType.details.typeParameters.slice(0, index), classType.details.typeVarScopeId);
            });
            if (!(0, typeUtils_1.computeMroLinearization)(classType)) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.methodOrdering(), node.name);
            }
            // The scope for this class becomes the "fields" for the corresponding type.
            const innerScope = ScopeUtils.getScopeForNode(node.suite);
            classType.details.fields = (innerScope === null || innerScope === void 0 ? void 0 : innerScope.symbolTable)
                ? new Map(innerScope.symbolTable)
                : new Map();
            // Determine whether the class should inherit __hash__. If a class defines
            // __eq__ but doesn't define __hash__ then __hash__ is set to None.
            if (classType.details.fields.has('__eq__') && !classType.details.fields.has('__hash__')) {
                classType.details.fields.set('__hash__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ |
                    128 /* SymbolFlags.ClassVar */ |
                    64 /* SymbolFlags.IgnoredForProtocolMatch */ |
                    4096 /* SymbolFlags.IgnoredForOverrideChecks */, getNoneType()));
            }
            // Determine whether the class's instance variables are constrained
            // to those defined by __slots__. We need to do this prior to dataclass
            // processing because dataclasses can implicitly add to the slots
            // list.
            const slotsNames = innerScope === null || innerScope === void 0 ? void 0 : innerScope.getSlotsNames();
            if (slotsNames) {
                classType.details.localSlotsNames = slotsNames;
            }
            // Determine if the class should be a "pseudo-generic" class, characterized
            // by having an __init__ method with parameters that lack type annotations.
            // For such classes, we'll treat them as generic, with the type arguments provided
            // by the callers of the constructor.
            if (!fileInfo.isStubFile && classType.details.typeParameters.length === 0) {
                const initMethod = classType.details.fields.get('__init__');
                if (initMethod) {
                    const initDecls = initMethod.getTypedDeclarations();
                    if (initDecls.length === 1 && initDecls[0].type === 5 /* DeclarationType.Function */) {
                        const initDeclNode = initDecls[0].node;
                        const initParams = initDeclNode.parameters;
                        if (initParams.length > 1 &&
                            !initParams.some((param, index) => !!ParseTreeUtils.getTypeAnnotationForParameter(initDeclNode, index))) {
                            const genericParams = initParams.filter((param, index) => index > 0 &&
                                param.name &&
                                param.category === 0 /* ParameterCategory.Simple */ &&
                                !param.defaultValue);
                            if (genericParams.length > 0) {
                                classType.details.flags |= 32768 /* ClassTypeFlags.PseudoGenericClass */;
                                // Create a type parameter for each simple, named parameter
                                // in the __init__ method.
                                classType.details.typeParameters = genericParams.map((param) => {
                                    const typeVar = types_1.TypeVarType.createInstance(getPseudoGenericTypeVarName(param.name.value));
                                    typeVar.details.isSynthesized = true;
                                    typeVar.scopeId = ParseTreeUtils.getScopeIdForNode(initDeclNode);
                                    typeVar.details.boundType = types_1.UnknownType.create();
                                    return types_1.TypeVarType.cloneForScopeId(typeVar, ParseTreeUtils.getScopeIdForNode(node), node.name.value, 0 /* TypeVarScopeType.Class */);
                                });
                            }
                        }
                    }
                }
            }
            // Determine if the class has a custom __class_getitem__ method. This applies
            // only to classes that have no type parameters, since those with type parameters
            // are assumed to follow normal subscripting semantics for generic classes.
            if (classType.details.typeParameters.length === 0 && !types_1.ClassType.isBuiltIn(classType, 'type')) {
                if (classType.details.baseClasses.some((baseClass) => (0, types_1.isInstantiableClass)(baseClass) && types_1.ClassType.hasCustomClassGetItem(baseClass)) ||
                    classType.details.fields.has('__class_getitem__')) {
                    classType.details.flags |= 524288 /* ClassTypeFlags.HasCustomClassGetItem */;
                }
            }
            // Determine the effective metaclass.
            if (metaclassNode) {
                const metaclassType = getTypeOfExpression(metaclassNode, exprFlags).type;
                if ((0, types_1.isInstantiableClass)(metaclassType) || (0, types_1.isUnknown)(metaclassType)) {
                    if ((0, typeUtils_1.requiresSpecialization)(metaclassType, { ignorePseudoGeneric: true })) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.metaclassIsGeneric(), metaclassNode);
                    }
                    classType.details.declaredMetaclass = metaclassType;
                    if ((0, types_1.isInstantiableClass)(metaclassType)) {
                        if ((0, enums_1.isEnumMetaclass)(metaclassType)) {
                            classType.details.flags |= 2097152 /* ClassTypeFlags.EnumClass */;
                        }
                        if (types_1.ClassType.isBuiltIn(metaclassType, 'ABCMeta')) {
                            classType.details.flags |= 2048 /* ClassTypeFlags.SupportsAbstractMethods */;
                        }
                    }
                }
            }
            const effectiveMetaclass = computeEffectiveMetaclass(classType, node.name);
            // Clear the "partially constructed" flag.
            classType.details.flags &= ~262144 /* ClassTypeFlags.PartiallyEvaluated */;
            // Now determine the decorated type of the class.
            let decoratedType = classType;
            let foundUnknown = false;
            for (let i = node.decorators.length - 1; i >= 0; i--) {
                const decorator = node.decorators[i];
                const newDecoratedType = (0, decorators_1.applyClassDecorator)(evaluatorInterface, decoratedType, classType, decorator);
                const unknownOrAny = (0, typeUtils_1.containsAnyOrUnknown)(newDecoratedType, /* recurse */ false);
                const unknown = unknownOrAny && (0, types_1.isUnknown)(unknownOrAny);
                if (unknownOrAny && !foundUnknown) {
                    if (unknown) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUntypedClassDecorator, localize_1.LocMessage.classDecoratorTypeUnknown(), node.decorators[i].expression);
                        foundUnknown = true;
                    }
                    else {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.classDecoratorTypeAny(), node.decorators[i].expression);
                    }
                }
                if (!unknown) {
                    // Apply the decorator only if the type is known (or Any).
                    decoratedType = newDecoratedType;
                }
            }
            // Determine whether this class derives from (or has a metaclass) that imbues
            // it with dataclass-like behaviors. If so, we'll apply those here.
            let dataClassBehaviors;
            if ((0, types_1.isInstantiableClass)(effectiveMetaclass) && effectiveMetaclass.details.classDataClassTransform) {
                dataClassBehaviors = effectiveMetaclass.details.classDataClassTransform;
            }
            else {
                const baseClassDataTransform = classType.details.mro.find((mroClass) => {
                    return ((0, types_1.isClass)(mroClass) &&
                        mroClass.details.classDataClassTransform !== undefined &&
                        !types_1.ClassType.isSameGenericClass(mroClass, classType));
                });
                if (baseClassDataTransform) {
                    dataClassBehaviors = baseClassDataTransform.details.classDataClassTransform;
                }
            }
            if (dataClassBehaviors) {
                (0, dataClasses_1.applyDataClassDefaultBehaviors)(classType, dataClassBehaviors);
                (0, dataClasses_1.applyDataClassClassBehaviorOverrides)(evaluatorInterface, node.name, classType, initSubclassArgs, dataClassBehaviors);
            }
            // Run any deferred class completions that depend on this class.
            runDeferredClassCompletions(classType);
            // If there are any outstanding deferred class completions registered that
            // were not removed by the call to runDeferredClassCompletions, assume that
            // the current class may depend on them and register for deferred completion.
            registerDeferredClassCompletion(node, /* dependsUpon */ undefined);
            // Synthesize TypedDict methods.
            if (types_1.ClassType.isTypedDictClass(classType)) {
                // TypedDict classes must derive only from other TypedDict classes.
                let foundInvalidBaseClass = false;
                const diag = new diagnostic_1.DiagnosticAddendum();
                classType.details.baseClasses.forEach((baseClass) => {
                    if ((0, types_1.isClass)(baseClass) &&
                        !types_1.ClassType.isTypedDictClass(baseClass) &&
                        !types_1.ClassType.isBuiltIn(baseClass, ['_TypedDict', 'Generic'])) {
                        foundInvalidBaseClass = true;
                        diag.addMessage(localize_1.LocAddendum.typedDictBaseClass().format({ type: baseClass.details.name }));
                    }
                });
                if (foundInvalidBaseClass) {
                    addError(localize_1.LocMessage.typedDictBaseClass() + diag.getString(), node.name);
                }
                (0, typedDicts_1.synthesizeTypedDictClassMethods)(evaluatorInterface, node, classType);
            }
            // Synthesize dataclass methods.
            if (types_1.ClassType.isDataClass(classType)) {
                const skipSynthesizedInit = types_1.ClassType.isSkipSynthesizedDataClassInit(classType);
                let hasExistingInitMethod = skipSynthesizedInit;
                // See if there's already a non-synthesized __init__ method.
                // We shouldn't override it.
                if (!skipSynthesizedInit) {
                    const initSymbol = classType.details.fields.get('__init__');
                    if (initSymbol && initSymbol.isClassMember()) {
                        hasExistingInitMethod = true;
                    }
                }
                let skipSynthesizeHash = false;
                const hashSymbol = classType.details.fields.get('__hash__');
                // If there is a hash symbol defined in the class (i.e. one that we didn't
                // synthesize above), then we shouldn't synthesize a new one for the dataclass.
                if (hashSymbol && hashSymbol.isClassMember() && !hashSymbol.getSynthesizedType()) {
                    skipSynthesizeHash = true;
                }
                const synthesizeMethods = () => (0, dataClasses_1.synthesizeDataClassMethods)(evaluatorInterface, node, classType, skipSynthesizedInit, hasExistingInitMethod, skipSynthesizeHash);
                // If this is a NamedTuple subclass, immediately synthesize dataclass methods
                // because we also need to update the MRO classes in this case. For regular
                // dataclasses, we'll defer the  method synthesis to avoid circular dependencies.
                if (isNamedTupleSubclass) {
                    synthesizeMethods();
                }
                else {
                    classType.details.synthesizeMethodsDeferred = () => {
                        delete classType.details.synthesizeMethodsDeferred;
                        synthesizeMethods();
                    };
                }
            }
            // Build a complete list of all slots names defined by the class hierarchy.
            // This needs to be done after dataclass processing.
            classType.details.calculateInheritedSlotsNamesDeferred = () => {
                delete classType.details.calculateInheritedSlotsNamesDeferred;
                if (classType.details.localSlotsNames) {
                    let isLimitedToSlots = true;
                    const extendedSlotsNames = Array.from(classType.details.localSlotsNames);
                    classType.details.baseClasses.forEach((baseClass) => {
                        if ((0, types_1.isInstantiableClass)(baseClass)) {
                            if (!types_1.ClassType.isBuiltIn(baseClass, 'object') &&
                                !types_1.ClassType.isBuiltIn(baseClass, 'type') &&
                                !types_1.ClassType.isBuiltIn(baseClass, 'Generic')) {
                                const inheritedSlotsNames = types_1.ClassType.getInheritedSlotsNames(baseClass);
                                if (inheritedSlotsNames) {
                                    (0, collectionUtils_1.appendArray)(extendedSlotsNames, inheritedSlotsNames);
                                }
                                else {
                                    isLimitedToSlots = false;
                                }
                            }
                        }
                        else {
                            isLimitedToSlots = false;
                        }
                    });
                    if (isLimitedToSlots) {
                        classType.details.inheritedSlotsNamesCached = extendedSlotsNames;
                    }
                }
            };
            // Update the undecorated class type.
            writeTypeCache(node.name, { type: classType }, 0 /* EvaluatorFlags.None */);
            // Update the decorated class type.
            writeTypeCache(node, { type: decoratedType }, 0 /* EvaluatorFlags.None */);
            return { classType, decoratedType };
        }
        catch (e) {
            if (cancellationUtils_1.OperationCanceledException.is(e)) {
                // If the work was canceled before the class types were updated, the
                // class type in the type cache is in an invalid, partially-constructed state.
                e.isTypeCacheInvalid = true;
            }
            throw e;
        }
    }
    // Determines whether the type parameters has a default that refers to another
    // type parameter. If so, validates that it is in the list of "live" type
    // parameters and updates the scope of the type parameter referred to in the
    // default type expression.
    function validateTypeParameterDefault(errorNode, typeParam, otherLiveTypeParams, scopeId) {
        if (!typeParam.details.isDefaultExplicit &&
            !typeParam.details.isSynthesized &&
            !typeParam.details.isSynthesizedSelf) {
            const typeVarWithDefault = otherLiveTypeParams.find((param) => param.details.isDefaultExplicit && param.scopeId === scopeId);
            if (typeVarWithDefault) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarWithoutDefault().format({
                    name: typeParam.details.name,
                    other: typeVarWithDefault.details.name,
                }), errorNode);
            }
            return;
        }
        const invalidTypeVars = new Set();
        (0, typeUtils_1.validateTypeVarDefault)(typeParam, otherLiveTypeParams, invalidTypeVars);
        // If we found one or more unapplied type variable, report an error.
        if (invalidTypeVars.size > 0) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            invalidTypeVars.forEach((name) => {
                diag.addMessage(localize_1.LocAddendum.typeVarDefaultOutOfScope().format({ name }));
            });
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarDefaultInvalidTypeVar().format({
                name: typeParam.details.name,
            }) + diag.getString(), errorNode);
        }
    }
    function inferTypeParameterVarianceForClass(classType) {
        if (!classType.details.requiresVarianceInference) {
            return;
        }
        if (!objectType || !(0, types_1.isClassInstance)(objectType)) {
            return;
        }
        // Presumptively mark the variance inference as complete. This
        // prevents potential recursion.
        classType.details.requiresVarianceInference = false;
        // Presumptively mark the computed variance to "unknown". We'll
        // replace this below once the variance has been inferred.
        classType.details.typeParameters.forEach((param) => {
            if (param.details.declaredVariance === 0 /* Variance.Auto */) {
                param.computedVariance = 1 /* Variance.Unknown */;
            }
        });
        const dummyTypeObject = types_1.ClassType.createInstantiable('__varianceDummy', '', '', uri_1.Uri.empty(), 0, 0, undefined, undefined);
        classType.details.typeParameters.forEach((param, paramIndex) => {
            // Skip variadics and ParamSpecs.
            if (param.details.isVariadic || param.details.isParamSpec) {
                return;
            }
            // Skip type variables without auto-variance.
            if (param.details.declaredVariance !== 0 /* Variance.Auto */) {
                return;
            }
            // Replace all type arguments with a dummy type except for the
            // TypeVar of interest, which is replaced with an object instance.
            const srcTypeArgs = classType.details.typeParameters.map((p, i) => {
                if (p.details.isVariadic) {
                    return p;
                }
                (0, debug_1.assert)(objectType !== undefined);
                return i === paramIndex ? objectType : dummyTypeObject;
            });
            // Replace all type arguments with a dummy type except for the
            // TypeVar of interest, which is replaced with itself.
            const destTypeArgs = classType.details.typeParameters.map((p, i) => {
                return i === paramIndex || p.details.isVariadic ? p : dummyTypeObject;
            });
            const srcType = types_1.ClassType.cloneForSpecialization(classType, srcTypeArgs, /* isTypeArgumentExplicit */ true);
            const destType = types_1.ClassType.cloneForSpecialization(classType, destTypeArgs, 
            /* isTypeArgumentExplicit */ true);
            const isDestSubtypeOfSrc = assignClassToSelf(srcType, destType, 3 /* Variance.Covariant */, 
            /* ignoreBaseClassVariance */ false);
            let inferredVariance;
            if (isDestSubtypeOfSrc) {
                inferredVariance = 3 /* Variance.Covariant */;
            }
            else {
                const isSrcSubtypeOfDest = assignClassToSelf(destType, srcType, 4 /* Variance.Contravariant */, 
                /* ignoreBaseClassVariance */ false);
                if (isSrcSubtypeOfDest) {
                    inferredVariance = 4 /* Variance.Contravariant */;
                }
                else {
                    inferredVariance = 2 /* Variance.Invariant */;
                }
            }
            // We assume here that we don't need to clone the type var object
            // because it was already cloned when it was associated with this
            // class scope.
            classType.details.typeParameters[paramIndex].computedVariance = inferredVariance;
        });
    }
    function evaluateTypeParameterList(node) {
        const paramTypes = [];
        node.parameters.forEach((param) => {
            var _a;
            const paramSymbol = AnalyzerNodeInfo.getTypeParameterSymbol(param.name);
            if (!paramSymbol) {
                // This can happen if the code is unreachable.
                return;
            }
            const typeOfParam = (_a = getDeclaredTypeOfSymbol(paramSymbol, param.name)) === null || _a === void 0 ? void 0 : _a.type;
            if (!typeOfParam || !(0, types_1.isTypeVar)(typeOfParam)) {
                return;
            }
            writeTypeCache(param.name, { type: typeOfParam }, 0 /* EvaluatorFlags.None */);
            paramTypes.push(typeOfParam);
        });
        return paramTypes;
    }
    function computeEffectiveMetaclass(classType, errorNode) {
        let effectiveMetaclass = classType.details.declaredMetaclass;
        let reportedMetaclassConflict = false;
        if (!effectiveMetaclass || (0, types_1.isInstantiableClass)(effectiveMetaclass)) {
            for (const baseClass of classType.details.baseClasses) {
                if ((0, types_1.isInstantiableClass)(baseClass)) {
                    const baseClassMeta = baseClass.details.effectiveMetaclass || typeClassType;
                    if (baseClassMeta && (0, types_1.isInstantiableClass)(baseClassMeta)) {
                        // Make sure there is no metaclass conflict.
                        if (!effectiveMetaclass) {
                            effectiveMetaclass = baseClassMeta;
                        }
                        else if ((0, typeUtils_1.derivesFromClassRecursive)(baseClassMeta, effectiveMetaclass, /* ignoreUnknown */ false)) {
                            effectiveMetaclass = baseClassMeta;
                        }
                        else if (!(0, typeUtils_1.derivesFromClassRecursive)(effectiveMetaclass, baseClassMeta, /* ignoreUnknown */ false)) {
                            if (!reportedMetaclassConflict) {
                                const diag = new diagnostic_1.DiagnosticAddendum();
                                diag.addMessage(localize_1.LocAddendum.metaclassConflict().format({
                                    metaclass1: printType((0, typeUtils_1.convertToInstance)(effectiveMetaclass)),
                                    metaclass2: printType((0, typeUtils_1.convertToInstance)(baseClassMeta)),
                                }));
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.metaclassConflict() + diag.getString(), errorNode);
                                // Don't report more than once.
                                reportedMetaclassConflict = true;
                            }
                        }
                    }
                    else {
                        effectiveMetaclass = baseClassMeta ? types_1.UnknownType.create() : undefined;
                        break;
                    }
                }
                else {
                    // If one of the base classes is unknown, then the effective
                    // metaclass is also unknowable.
                    effectiveMetaclass = types_1.UnknownType.create();
                    break;
                }
            }
        }
        // If we haven't found an effective metaclass, assume "type", which
        // is the metaclass for "object".
        if (!effectiveMetaclass) {
            const typeMetaclass = getBuiltInType(errorNode, 'type');
            effectiveMetaclass =
                typeMetaclass && (0, types_1.isInstantiableClass)(typeMetaclass) ? typeMetaclass : types_1.UnknownType.create();
        }
        classType.details.effectiveMetaclass = effectiveMetaclass;
        return effectiveMetaclass;
    }
    // Verifies that the type variables provided outside of "Generic"
    // or "Protocol" are also provided within the "Generic". For example:
    //    class Foo(Mapping[K, V], Generic[V])
    // is illegal because K is not included in Generic.
    function verifyGenericTypeParameters(errorNode, typeVars, genericTypeVars) {
        const missingFromGeneric = typeVars.filter((typeVar) => {
            return !genericTypeVars.some((genericTypeVar) => genericTypeVar.details.name === typeVar.details.name);
        });
        if (missingFromGeneric.length > 0) {
            const diag = new diagnostic_1.DiagnosticAddendum();
            diag.addMessage(localize_1.LocAddendum.typeVarsMissing().format({
                names: missingFromGeneric.map((typeVar) => `"${typeVar.details.name}"`).join(', '),
            }));
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarsNotInGenericOrProtocol() + diag.getString(), errorNode);
        }
    }
    // Records the fact that the specified class requires "deferred completion" because
    // one of its base classes has not yet been fully evaluated. If the caller passes
    // undefined for "dependsUpon", then the class is added to all outstanding deferred
    // completions.
    function registerDeferredClassCompletion(classToComplete, dependsUpon) {
        if (dependsUpon) {
            // See if there is an existing entry for this dependency.
            const entry = deferredClassCompletions.find((e) => types_1.ClassType.isSameGenericClass(e.dependsUpon, dependsUpon));
            if (entry) {
                entry.classesToComplete.push(classToComplete);
            }
            else {
                deferredClassCompletions.push({ dependsUpon, classesToComplete: [classToComplete] });
            }
        }
        else {
            deferredClassCompletions.forEach((e) => {
                e.classesToComplete.push(classToComplete);
            });
        }
    }
    // Runs any registered "deferred class completions" that depend on the specified
    // class type. This allows us to complete any work that requires dependent classes
    // to be completed.
    function runDeferredClassCompletions(type) {
        deferredClassCompletions.forEach((e) => {
            if (types_1.ClassType.isSameGenericClass(e.dependsUpon, type)) {
                e.classesToComplete.forEach((classNode) => {
                    const classType = readTypeCache(classNode.name, 0 /* EvaluatorFlags.None */);
                    if (classType) {
                        completeClassTypeDeferred(classType, classNode.name);
                    }
                });
            }
        });
        // Remove any completions that depend on this type.
        deferredClassCompletions = deferredClassCompletions.filter((e) => !types_1.ClassType.isSameGenericClass(e.dependsUpon, type));
    }
    // Recomputes the MRO and effective metaclass for the class after dependent
    // classes have been fully constructed.
    function completeClassTypeDeferred(type, errorNode) {
        // Recompute the MRO linearization.
        if (!(0, typeUtils_1.computeMroLinearization)(type)) {
            addError(localize_1.LocMessage.methodOrdering(), errorNode);
        }
        // Recompute the effective metaclass.
        computeEffectiveMetaclass(type, errorNode);
    }
    function validateInitSubclassArgs(node, classType) {
        var _a, _b;
        // Collect arguments that will be passed to the `__init_subclass__`
        // method described in PEP 487 and validate it.
        const argList = [];
        node.arguments.forEach((arg) => {
            if (arg.name && arg.name.value !== 'metaclass') {
                argList.push({
                    argumentCategory: 0 /* ArgumentCategory.Simple */,
                    node: arg,
                    name: arg.name,
                    valueExpression: arg.valueExpression,
                });
            }
        });
        const errorNode = argList.length > 0 ? (_b = (_a = argList[0].node) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : node.name : node.name;
        let newMethodMember;
        if (classType.details.effectiveMetaclass && (0, types_1.isClass)(classType.details.effectiveMetaclass)) {
            // See if the metaclass has a `__new__` method that accepts keyword parameters.
            newMethodMember = (0, typeUtils_1.lookUpClassMember)(classType.details.effectiveMetaclass, '__new__', 8 /* MemberAccessFlags.SkipTypeBaseClass */);
        }
        if (newMethodMember) {
            const newMethodType = getTypeOfMember(newMethodMember);
            if ((0, types_1.isFunction)(newMethodType)) {
                const paramListDetails = (0, parameterUtils_1.getParameterListDetails)(newMethodType);
                if (paramListDetails.firstKeywordOnlyIndex !== undefined) {
                    // Build a map of the keyword-only parameters.
                    const paramMap = new Map();
                    for (let i = paramListDetails.firstKeywordOnlyIndex; i < paramListDetails.params.length; i++) {
                        const paramInfo = paramListDetails.params[i];
                        if (paramInfo.param.category === 0 /* ParameterCategory.Simple */ && paramInfo.param.name) {
                            paramMap.set(paramInfo.param.name, i);
                        }
                    }
                    argList.forEach((arg) => {
                        var _a, _b, _c;
                        const signatureTracker = new typeUtils_1.UniqueSignatureTracker();
                        if (arg.argumentCategory === 0 /* ArgumentCategory.Simple */ && arg.name) {
                            const paramIndex = (_a = paramMap.get(arg.name.value)) !== null && _a !== void 0 ? _a : paramListDetails.kwargsIndex;
                            if (paramIndex !== undefined) {
                                const paramInfo = paramListDetails.params[paramIndex];
                                const argParam = {
                                    paramCategory: paramInfo.param.category,
                                    paramType: paramInfo.type,
                                    requiresTypeVarMatching: false,
                                    argument: arg,
                                    errorNode: (_b = arg.valueExpression) !== null && _b !== void 0 ? _b : errorNode,
                                };
                                validateArgType(argParam, new typeVarContext_1.TypeVarContext(), signatureTracker, { type: newMethodType }, { skipUnknownArgCheck: true, skipOverloadArg: true });
                                paramMap.delete(arg.name.value);
                            }
                            else {
                                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.paramNameMissing().format({ name: arg.name.value }), (_c = arg.name) !== null && _c !== void 0 ? _c : errorNode);
                            }
                        }
                    });
                    // See if we have any remaining unmatched parameters without
                    // default values.
                    const unassignedParams = [];
                    paramMap.forEach((index, paramName) => {
                        const paramInfo = paramListDetails.params[index];
                        if (!paramInfo.param.hasDefault) {
                            unassignedParams.push(paramName);
                        }
                    });
                    if (unassignedParams.length > 0) {
                        const missingParamNames = unassignedParams.map((p) => `"${p}"`).join(', ');
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, unassignedParams.length === 1
                            ? localize_1.LocMessage.argMissingForParam().format({ name: missingParamNames })
                            : localize_1.LocMessage.argMissingForParams().format({ names: missingParamNames }), errorNode);
                    }
                }
            }
        }
        else {
            // If there was no custom metaclass __new__ method, see if there is an __init_subclass__
            // method present somewhere in the class hierarchy.
            const initSubclassMethodInfo = getTypeOfBoundMember(errorNode, classType, '__init_subclass__', 
            /* usage */ undefined, 
            /* diag */ undefined, 32 /* MemberAccessFlags.SkipClassMembers */ |
                1 /* MemberAccessFlags.SkipOriginalClass */ |
                512 /* MemberAccessFlags.SkipAttributeAccessOverride */);
            if (initSubclassMethodInfo) {
                const initSubclassMethodType = initSubclassMethodInfo.type;
                if (initSubclassMethodType && initSubclassMethodInfo.classType) {
                    const callResult = validateCallArguments(errorNode, argList, { type: initSubclassMethodType }, 
                    /* typeVarContext */ undefined, 
                    /* skipUnknownArgCheck */ false, (0, typeUtils_1.makeInferenceContext)(getNoneType()));
                    if (callResult.argumentErrors) {
                        const diag = addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.initSubclassCallFailed(), node.name);
                        const initSubclassFunction = (0, types_1.isOverloadedFunction)(initSubclassMethodType)
                            ? types_1.OverloadedFunctionType.getOverloads(initSubclassMethodType)[0]
                            : initSubclassMethodType;
                        const initSubclassDecl = (0, types_1.isFunction)(initSubclassFunction)
                            ? initSubclassFunction.details.declaration
                            : undefined;
                        if (diag && initSubclassDecl) {
                            diag.addRelatedInfo(localize_1.LocAddendum.initSubclassLocation().format({
                                name: printType((0, typeUtils_1.convertToInstance)(initSubclassMethodInfo.classType)),
                            }), initSubclassDecl.uri, initSubclassDecl.range);
                        }
                    }
                }
            }
        }
        // Evaluate all of the expressions so they are checked and marked referenced.
        argList.forEach((arg) => {
            if (arg.valueExpression) {
                getTypeOfExpression(arg.valueExpression);
            }
        });
    }
    function getTypeOfFunction(node) {
        var _a;
        initializedBasicTypes(node);
        // Is this predecorated function type cached?
        let functionType = readTypeCache(node.name, 0 /* EvaluatorFlags.None */);
        if (functionType) {
            if (!(0, types_1.isFunction)(functionType)) {
                // This can happen in certain rare circumstances where the
                // function declaration falls within an unreachable code block.
                return undefined;
            }
            if (types_1.FunctionType.isPartiallyEvaluated(functionType)) {
                return { functionType, decoratedType: functionType };
            }
        }
        else {
            functionType = getTypeOfFunctionPredecorated(node);
        }
        // Is the decorated function type cached?
        let decoratedType = readTypeCache(node, 0 /* EvaluatorFlags.None */);
        if (decoratedType) {
            return { functionType, decoratedType };
        }
        // Populate the cache with a temporary value to handle recursion.
        writeTypeCache(node, { type: functionType }, /* flags */ undefined);
        // If it's an async function, wrap the return type in an Awaitable or Generator.
        // Set the "partially evaluated" flag around this logic to detect recursion.
        functionType.details.flags |= 131072 /* FunctionTypeFlags.PartiallyEvaluated */;
        const preDecoratedType = node.isAsync ? createAsyncFunction(node, functionType) : functionType;
        functionType.details.flags &= ~131072 /* FunctionTypeFlags.PartiallyEvaluated */;
        // Apply all of the decorators in reverse order.
        decoratedType = preDecoratedType;
        let foundUnknown = false;
        for (let i = node.decorators.length - 1; i >= 0; i--) {
            const decorator = node.decorators[i];
            const newDecoratedType = (0, decorators_1.applyFunctionDecorator)(evaluatorInterface, decoratedType, functionType, decorator, node);
            const unknownOrAny = (0, typeUtils_1.containsAnyOrUnknown)(newDecoratedType, /* recurse */ false);
            const unknown = unknownOrAny && (0, types_1.isUnknown)(unknownOrAny);
            if (unknownOrAny && !foundUnknown) {
                if (unknown) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportUntypedFunctionDecorator, localize_1.LocMessage.functionDecoratorTypeUnknown(), node.decorators[i].expression);
                    foundUnknown = true;
                }
                else {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAny, localize_1.LocMessage.functionDecoratorTypeAny(), node.decorators[i].expression);
                }
            }
            if (!unknown) {
                // Apply the decorator only if the type is known (or Any).
                decoratedType = newDecoratedType;
            }
        }
        // In case this is an enum class and a method wrapped in an enum.member.
        decoratedType =
            (_a = (0, enums_1.transformTypeForPossibleEnumClass)(evaluatorInterface, node, node.name, () => {
                return { assignedType: decoratedType };
            })) !== null && _a !== void 0 ? _a : decoratedType;
        // See if there are any overloads provided by previous function declarations.
        if ((0, types_1.isFunction)(decoratedType)) {
            decoratedType.details.deprecatedMessage = functionType.details.deprecatedMessage;
            if (types_1.FunctionType.isOverloaded(decoratedType)) {
                // Mark all the parameters as accessed.
                node.parameters.forEach((param) => {
                    markParamAccessed(param);
                });
            }
            decoratedType = (0, decorators_1.addOverloadsToFunctionType)(evaluatorInterface, node, decoratedType);
        }
        writeTypeCache(node, { type: decoratedType }, 0 /* EvaluatorFlags.None */);
        return { functionType, decoratedType };
    }
    // Evaluates the type of a "def" statement without applying an async
    // modifier or any decorators.
    function getTypeOfFunctionPredecorated(node) {
        var _a, _b, _c;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        // Is this type already cached?
        const cachedFunctionType = readTypeCache(node.name, 0 /* EvaluatorFlags.None */);
        if (cachedFunctionType && (0, types_1.isFunction)(cachedFunctionType)) {
            return cachedFunctionType;
        }
        let functionDecl;
        const decl = AnalyzerNodeInfo.getDeclaration(node);
        if (decl) {
            functionDecl = decl;
        }
        // There was no cached type, so create a new one.
        // Retrieve the containing class node if the function is a method.
        const containingClassNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true);
        let containingClassType;
        if (containingClassNode) {
            containingClassType = (_a = getTypeOfClass(containingClassNode)) === null || _a === void 0 ? void 0 : _a.classType;
        }
        const functionInfo = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, node, !!containingClassNode);
        let functionFlags = functionInfo.flags;
        if (functionDecl === null || functionDecl === void 0 ? void 0 : functionDecl.isGenerator) {
            functionFlags |= 16 /* FunctionTypeFlags.Generator */;
        }
        if (fileInfo.isStubFile) {
            functionFlags |= 2048 /* FunctionTypeFlags.StubDefinition */;
        }
        else if (fileInfo.isInPyTypedPackage) {
            functionFlags |= 4096 /* FunctionTypeFlags.PyTypedDefinition */;
        }
        if (node.isAsync) {
            functionFlags |= 512 /* FunctionTypeFlags.Async */;
        }
        const functionType = types_1.FunctionType.createInstance(node.name.value, getFunctionFullName(node, fileInfo.moduleName, node.name.value), fileInfo.moduleName, functionFlags | 131072 /* FunctionTypeFlags.PartiallyEvaluated */, ParseTreeUtils.getDocString(node.suite.statements));
        functionType.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node);
        functionType.details.deprecatedMessage = functionInfo.deprecationMessage;
        functionType.details.methodClass = containingClassType;
        if (node.name.value === '__init__' || node.name.value === '__new__') {
            if (containingClassNode) {
                functionType.details.constructorTypeVarScopeId = ParseTreeUtils.getScopeIdForNode(containingClassNode);
            }
        }
        if (fileInfo.isBuiltInStubFile || fileInfo.isTypingStubFile || fileInfo.isTypingExtensionsStubFile) {
            // Stash away the name of the function since we need to handle
            // 'namedtuple', 'abstractmethod', 'dataclass' and 'NewType'
            // specially.
            functionType.details.builtInName = node.name.value;
        }
        functionType.details.declaration = functionDecl;
        // Allow recursion by caching and registering the partially-constructed function type.
        const scope = ScopeUtils.getScopeForNode(node);
        const functionSymbol = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbolRecursive(node.name.value);
        if (functionDecl && functionSymbol) {
            setSymbolResolutionPartialType(functionSymbol.symbol, functionDecl, functionType);
        }
        writeTypeCache(node.name, { type: functionType }, /* flags */ undefined);
        // Is this an "__init__" method within a pseudo-generic class? If so,
        // we'll add generic types to the constructor's parameters.
        const addGenericParamTypes = containingClassType &&
            types_1.ClassType.isPseudoGenericClass(containingClassType) &&
            node.name.value === '__init__';
        const paramTypes = [];
        // Determine if the first parameter should be skipped for comment-based
        // function annotations.
        let firstCommentAnnotationIndex = 0;
        if (containingClassType && (functionType.details.flags & 4 /* FunctionTypeFlags.StaticMethod */) === 0) {
            firstCommentAnnotationIndex = 1;
        }
        // If there is a function annotation comment, validate that it has the correct
        // number of parameter annotations.
        if (node.functionAnnotationComment && !node.functionAnnotationComment.isParamListEllipsis) {
            const expected = node.parameters.length - firstCommentAnnotationIndex;
            const received = node.functionAnnotationComment.paramTypeAnnotations.length;
            // For methods with "self" or "cls" parameters, the annotation list
            // can either include or exclude the annotation for the first parameter.
            if (firstCommentAnnotationIndex > 0 && received === node.parameters.length) {
                firstCommentAnnotationIndex = 0;
            }
            else if (received !== expected) {
                addError(localize_1.LocMessage.annotatedParamCountMismatch().format({
                    expected,
                    received,
                }), node.functionAnnotationComment);
            }
        }
        // If this function uses PEP 695 syntax for type parameters,
        // accumulate the list of type parameters upfront.
        const typeParametersSeen = [];
        if (node.typeParameters) {
            functionType.details.typeParameters = evaluateTypeParameterList(node.typeParameters).map((typeParam) => (0, typeUtils_1.convertToInstance)(typeParam));
        }
        else {
            functionType.details.typeParameters = typeParametersSeen;
        }
        let paramsArePositionOnly = true;
        const isFirstParamClsOrSelf = containingClassType &&
            (types_1.FunctionType.isClassMethod(functionType) ||
                types_1.FunctionType.isInstanceMethod(functionType) ||
                types_1.FunctionType.isConstructorMethod(functionType));
        const firstNonClsSelfParamIndex = isFirstParamClsOrSelf ? 1 : 0;
        node.parameters.forEach((param, index) => {
            let paramType;
            let annotatedType;
            let paramTypeNode;
            if (param.name) {
                if (index === 0 && isFirstParamClsOrSelf) {
                    // Mark "self/cls" as accessed.
                    markParamAccessed(param);
                }
                else if (types_1.FunctionType.isAbstractMethod(functionType)) {
                    // Mark all parameters in abstract methods as accessed.
                    markParamAccessed(param);
                }
                else if (containingClassType && types_1.ClassType.isProtocolClass(containingClassType)) {
                    // Mark all parameters in protocol methods as accessed.
                    markParamAccessed(param);
                }
            }
            if (param.typeAnnotation) {
                paramTypeNode = param.typeAnnotation;
            }
            else if (param.typeAnnotationComment) {
                paramTypeNode = param.typeAnnotationComment;
            }
            else if (node.functionAnnotationComment && !node.functionAnnotationComment.isParamListEllipsis) {
                const adjustedIndex = index - firstCommentAnnotationIndex;
                if (adjustedIndex >= 0 && adjustedIndex < node.functionAnnotationComment.paramTypeAnnotations.length) {
                    paramTypeNode = node.functionAnnotationComment.paramTypeAnnotations[adjustedIndex];
                }
            }
            if (paramTypeNode) {
                if ((functionInfo.flags & 524288 /* FunctionTypeFlags.NoTypeCheck */) !== 0) {
                    annotatedType = types_1.UnknownType.create();
                }
                else {
                    annotatedType = getTypeOfParameterAnnotation(paramTypeNode, param.category);
                }
                if (annotatedType) {
                    (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersSeen, (0, typeUtils_1.getTypeVarArgumentsRecursive)(annotatedType), functionType.details.typeVarScopeId);
                }
                if ((0, types_1.isVariadicTypeVar)(annotatedType) && !annotatedType.isVariadicUnpacked) {
                    addError(localize_1.LocMessage.unpackedTypeVarTupleExpected().format({
                        name1: annotatedType.details.name,
                        name2: annotatedType.details.name,
                    }), paramTypeNode);
                    annotatedType = types_1.UnknownType.create();
                }
            }
            if (!annotatedType && addGenericParamTypes) {
                if (index > 0 && param.category === 0 /* ParameterCategory.Simple */ && param.name && !param.defaultValue) {
                    const typeParamName = getPseudoGenericTypeVarName(param.name.value);
                    annotatedType = containingClassType.details.typeParameters.find((param) => param.details.name === typeParamName);
                }
            }
            if (annotatedType) {
                const adjustedAnnotatedType = adjustParameterAnnotatedType(param, annotatedType);
                if (adjustedAnnotatedType !== annotatedType) {
                    annotatedType = adjustedAnnotatedType;
                }
            }
            let defaultValueType;
            if (param.defaultValue) {
                // If this is a stub file, a protocol, an overload, or a class
                // whose body is a placeholder implementation, treat a "...", as
                // an "Any" value.
                let treatEllipsisAsAny = fileInfo.isStubFile || ParseTreeUtils.isSuiteEmpty(node.suite);
                if (containingClassType && types_1.ClassType.isProtocolClass(containingClassType)) {
                    treatEllipsisAsAny = true;
                }
                if (types_1.FunctionType.isOverloaded(functionType) || types_1.FunctionType.isAbstractMethod(functionType)) {
                    treatEllipsisAsAny = true;
                }
                defaultValueType = getTypeOfExpression(param.defaultValue, treatEllipsisAsAny ? 1 /* EvaluatorFlags.ConvertEllipsisToAny */ : 0 /* EvaluatorFlags.None */, (0, typeUtils_1.makeInferenceContext)(annotatedType)).type;
            }
            if (annotatedType) {
                // If there was both a type annotation and a default value, verify
                // that the default value matches the annotation.
                if (param.defaultValue && defaultValueType) {
                    const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    const typeVarContext = new typeVarContext_1.TypeVarContext(functionType.details.typeVarScopeId);
                    if (containingClassType && containingClassType.details.typeVarScopeId !== undefined) {
                        if (node.name.value === '__init__' || node.name.value === '__new__') {
                            typeVarContext.addSolveForScope(containingClassType.details.typeVarScopeId);
                        }
                    }
                    if (!assignType(annotatedType, defaultValueType, diagAddendum, typeVarContext)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.paramAssignmentMismatch().format({
                            sourceType: printType(defaultValueType),
                            paramType: printType(annotatedType),
                        }) + diagAddendum.getString(), param.defaultValue);
                    }
                }
                paramType = annotatedType;
            }
            // Determine whether we need to insert an implied position-only parameter.
            // This is needed when a function's parameters are named using the old-style
            // way of specifying position-only parameters.
            if (index >= firstNonClsSelfParamIndex) {
                let isImplicitPositionOnlyParam = false;
                if (param.category === 0 /* ParameterCategory.Simple */ && param.name) {
                    if ((0, symbolNameUtils_1.isPrivateName)(param.name.value) &&
                        !node.parameters.some((p) => p.category === 0 /* ParameterCategory.Simple */ && !p.name)) {
                        isImplicitPositionOnlyParam = true;
                        // If the parameter name indicates an implicit position-only parameter
                        // but we have already seen non-position-only parameters, report an error.
                        if (!paramsArePositionOnly &&
                            functionType.details.parameters.every((p) => p.category === 0 /* ParameterCategory.Simple */)) {
                            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.positionOnlyAfterNon(), param.name);
                        }
                    }
                }
                else {
                    paramsArePositionOnly = false;
                }
                if (paramsArePositionOnly &&
                    !isImplicitPositionOnlyParam &&
                    functionType.details.parameters.length > firstNonClsSelfParamIndex) {
                    types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                }
                if (!isImplicitPositionOnlyParam) {
                    paramsArePositionOnly = false;
                }
            }
            // If there was no annotation for the parameter, infer its type if possible.
            let isTypeInferred = false;
            if (!paramTypeNode) {
                isTypeInferred = true;
                const inferredType = inferParameterType(node, functionType.details.flags, index, containingClassType);
                if (inferredType) {
                    paramType = inferredType;
                }
            }
            const functionParam = {
                category: param.category,
                name: param.name ? param.name.value : undefined,
                hasDefault: !!param.defaultValue,
                defaultValueExpression: param.defaultValue,
                defaultType: defaultValueType,
                type: paramType !== null && paramType !== void 0 ? paramType : types_1.UnknownType.create(),
                typeAnnotation: paramTypeNode,
                hasDeclaredType: !!paramTypeNode,
                isTypeInferred,
            };
            types_1.FunctionType.addParameter(functionType, functionParam);
            if (functionParam.hasDeclaredType) {
                (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersSeen, (0, typeUtils_1.getTypeVarArgumentsRecursive)(functionParam.type), functionType.details.typeVarScopeId);
            }
            if (param.name) {
                const variadicParamType = transformVariadicParamType(node, param.category, functionParam.type);
                paramTypes.push(variadicParamType);
            }
            else {
                paramTypes.push(functionParam.type);
            }
        });
        if (paramsArePositionOnly && functionType.details.parameters.length > firstNonClsSelfParamIndex) {
            types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
        }
        // Update the types for the nodes associated with the parameters.
        paramTypes.forEach((paramType, index) => {
            const paramNameNode = node.parameters[index].name;
            if (paramNameNode) {
                if ((0, types_1.isUnknown)(paramType)) {
                    functionType.details.flags |= 16384 /* FunctionTypeFlags.UnannotatedParams */;
                }
                writeTypeCache(paramNameNode, { type: paramType }, 0 /* EvaluatorFlags.None */);
            }
        });
        // If the function ends in P.args and P.kwargs parameters, make it exempt from
        // args/kwargs compatibility checks. This is important for protocol comparisons.
        if (paramTypes.length >= 2) {
            const paramType1 = paramTypes[paramTypes.length - 2];
            const paramType2 = paramTypes[paramTypes.length - 1];
            if ((0, types_1.isParamSpec)(paramType1) &&
                paramType1.paramSpecAccess === 'args' &&
                (0, types_1.isParamSpec)(paramType2) &&
                paramType2.paramSpecAccess === 'kwargs') {
                functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
            }
        }
        // If there was a defined return type, analyze that first so when we
        // walk the contents of the function, return statements can be
        // validated against this type.
        const returnTypeAnnotationNode = (_b = node.returnTypeAnnotation) !== null && _b !== void 0 ? _b : (_c = node.functionAnnotationComment) === null || _c === void 0 ? void 0 : _c.returnTypeAnnotation;
        if (returnTypeAnnotationNode) {
            // Temporarily set the return type to unknown in case of recursion.
            functionType.details.declaredReturnType = types_1.UnknownType.create();
            const returnType = getTypeOfAnnotation(returnTypeAnnotationNode, {
                associateTypeVarsWithScope: true,
            });
            functionType.details.declaredReturnType = returnType;
        }
        else {
            // If there was no return type annotation and this is a type stub,
            // we have no opportunity to infer the return type, so we'll indicate
            // that it's unknown.
            if (fileInfo.isStubFile) {
                // Special-case the __init__ method, which is commonly left without
                // an annotated return type, but we can assume it returns None.
                if (node.name.value === '__init__') {
                    functionType.details.declaredReturnType = getNoneType();
                }
                else {
                    functionType.details.declaredReturnType = types_1.UnknownType.create();
                }
            }
        }
        // Accumulate any type parameters used in the return type.
        if (functionType.details.declaredReturnType && returnTypeAnnotationNode) {
            rescopeTypeVarsForCallableReturnType(functionType.details.declaredReturnType, functionType, typeParametersSeen);
        }
        // If the return type is explicitly annotated as a generator, mark the
        // function as a generator even though it may not contain a "yield" statement.
        // This is important for generator functions declared in stub files, abstract
        // methods or protocol definitions.
        if (fileInfo.isStubFile || ParseTreeUtils.isSuiteEmpty(node.suite)) {
            if (functionType.details.declaredReturnType &&
                (0, types_1.isClassInstance)(functionType.details.declaredReturnType) &&
                types_1.ClassType.isBuiltIn(functionType.details.declaredReturnType, [
                    'Generator',
                    'AsyncGenerator',
                    'AwaitableGenerator',
                ])) {
                functionType.details.flags |= 16 /* FunctionTypeFlags.Generator */;
            }
        }
        // Validate the default types for all type parameters.
        functionType.details.typeParameters.forEach((typeParam, index) => {
            var _a;
            let bestErrorNode = node.name;
            if (node.typeParameters && index < node.typeParameters.parameters.length) {
                const typeParamNode = node.typeParameters.parameters[index];
                bestErrorNode = (_a = typeParamNode.defaultExpression) !== null && _a !== void 0 ? _a : typeParamNode.name;
            }
            validateTypeParameterDefault(bestErrorNode, typeParam, functionType.details.typeParameters.slice(0, index), functionType.details.typeVarScopeId);
        });
        // Clear the "partially evaluated" flag to indicate that the functionType
        // is fully evaluated.
        functionType.details.flags &= ~131072 /* FunctionTypeFlags.PartiallyEvaluated */;
        writeTypeCache(node.name, { type: functionType }, 0 /* EvaluatorFlags.None */);
        return functionType;
    }
    function markParamAccessed(param) {
        if (param.name) {
            const symbolWithScope = lookUpSymbolRecursive(param.name, param.name.value, /* honorCodeFlow */ false);
            if (symbolWithScope) {
                setSymbolAccessed(AnalyzerNodeInfo.getFileInfo(param), symbolWithScope.symbol, param.name);
            }
        }
    }
    // If the declared return type of a function contains type variables that
    // are found nowhere else in the signature and are contained within a
    // Callable, these type variables are "rescoped" from the function to
    // the Callable.
    function rescopeTypeVarsForCallableReturnType(returnType, functionType, typeParametersSeen) {
        const typeVarsInReturnType = (0, typeUtils_1.getTypeVarArgumentsRecursive)(returnType).filter((t) => t.scopeId === functionType.details.typeVarScopeId);
        const rescopedTypeVars = [];
        typeVarsInReturnType.forEach((typeVar) => {
            if (types_1.TypeBase.isInstantiable(typeVar)) {
                typeVar = types_1.TypeVarType.cloneAsInstance(typeVar);
            }
            // If this type variable was already seen in one or more input parameters,
            // don't attempt to rescope it.
            if (typeParametersSeen.some((tp) => (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(tp), typeVar))) {
                return;
            }
            // Is this type variable seen outside of a single callable?
            if ((0, typeUtils_1.isTypeVarLimitedToCallable)(returnType, typeVar)) {
                rescopedTypeVars.push(typeVar);
            }
        });
        (0, typeUtils_1.addTypeVarsToListIfUnique)(typeParametersSeen, typeVarsInReturnType);
        // Note that the type parameters have been rescoped so they are not
        // considered valid for the body of this function.
        if (rescopedTypeVars.length > 0) {
            functionType.details.rescopedTypeParameters = rescopedTypeVars;
        }
    }
    function adjustParameterAnnotatedType(param, type) {
        var _a;
        // PEP 484 indicates that if a parameter has a default value of 'None'
        // the type checker should assume that the type is optional (i.e. a union
        // of the specified type and 'None'). Skip this step if the type is already
        // optional to avoid losing alias names when combining the types.
        if (((_a = param.defaultValue) === null || _a === void 0 ? void 0 : _a.nodeType) === 11 /* ParseNodeType.Constant */ &&
            param.defaultValue.constType === 26 /* KeywordType.None */ &&
            !(0, typeUtils_1.isOptionalType)(type) &&
            !AnalyzerNodeInfo.getFileInfo(param).diagnosticRuleSet.strictParameterNoneValue) {
            return (0, types_1.combineTypes)([type, getNoneType()]);
        }
        return type;
    }
    // Attempts to infer an unannotated parameter type from available context.
    function inferParameterType(functionNode, functionFlags, paramIndex, containingClassType) {
        var _a;
        // Is the function a method within a class? If so, see if a base class
        // defines the same method and provides annotations.
        if (containingClassType) {
            if (paramIndex === 0) {
                if ((functionFlags & 4 /* FunctionTypeFlags.StaticMethod */) === 0) {
                    const hasClsParam = (functionFlags & (2 /* FunctionTypeFlags.ClassMethod */ | 1 /* FunctionTypeFlags.ConstructorMethod */)) !== 0;
                    return (0, typeUtils_1.synthesizeTypeVarForSelfCls)(containingClassType, hasClsParam);
                }
            }
            const methodName = functionNode.name.value;
            const baseClassMemberInfo = (0, typeUtils_1.lookUpClassMember)(containingClassType, methodName, 1 /* MemberAccessFlags.SkipOriginalClass */);
            if (baseClassMemberInfo) {
                const memberDecls = baseClassMemberInfo.symbol.getDeclarations();
                if (memberDecls.length === 1 && memberDecls[0].type === 5 /* DeclarationType.Function */) {
                    const baseClassMethodNode = memberDecls[0].node;
                    // Does the signature match exactly with the exception of annotations?
                    if (baseClassMethodNode.parameters.length === functionNode.parameters.length &&
                        baseClassMethodNode.parameters.every((param, index) => {
                            var _a, _b;
                            const overrideParam = functionNode.parameters[index];
                            return (((_a = overrideParam.name) === null || _a === void 0 ? void 0 : _a.value) === ((_b = param.name) === null || _b === void 0 ? void 0 : _b.value) &&
                                overrideParam.category === param.category);
                        })) {
                        const baseClassParam = baseClassMethodNode.parameters[paramIndex];
                        const baseClassParamAnnotation = (_a = baseClassParam.typeAnnotation) !== null && _a !== void 0 ? _a : baseClassParam.typeAnnotationComment;
                        if (baseClassParamAnnotation) {
                            let inferredParamType = getTypeOfParameterAnnotation(baseClassParamAnnotation, functionNode.parameters[paramIndex].category);
                            // If the parameter type is generic, specialize it in the context
                            // of the child class.
                            if ((0, typeUtils_1.requiresSpecialization)(inferredParamType) && (0, types_1.isClass)(baseClassMemberInfo.classType)) {
                                const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(baseClassMemberInfo.classType);
                                // Add the scope of the method to handle any function-scoped TypeVars.
                                typeVarContext.addSolveForScope(ParseTreeUtils.getScopeIdForNode(baseClassMethodNode));
                                // Replace any unsolved TypeVars with Unknown (including all function-scoped TypeVars).
                                inferredParamType = (0, typeUtils_1.applySolvedTypeVars)(inferredParamType, typeVarContext, {
                                    unknownIfNotFound: true,
                                });
                            }
                            const fileInfo = AnalyzerNodeInfo.getFileInfo(functionNode);
                            if (fileInfo.isInPyTypedPackage && !fileInfo.isStubFile) {
                                inferredParamType = types_1.TypeBase.cloneForAmbiguousType(inferredParamType);
                            }
                            return inferredParamType;
                        }
                    }
                }
            }
        }
        // If the parameter has a default argument value, we may be able to infer its
        // type from this information.
        const paramValueExpr = functionNode.parameters[paramIndex].defaultValue;
        if (paramValueExpr) {
            return inferParameterTypeFromDefaultValue(paramValueExpr);
        }
        return undefined;
    }
    function inferParameterTypeFromDefaultValue(paramValueExpr) {
        const defaultValueType = getTypeOfExpression(paramValueExpr, 1 /* EvaluatorFlags.ConvertEllipsisToAny */).type;
        let inferredParamType;
        // Is the default value a "None" or an instance of some private class (one
        // whose name starts with an underscore)? If so, we will assume that the
        // value is a singleton sentinel. The actual supported type is going to be
        // a union of this type and Unknown.
        if ((0, typeUtils_1.isNoneInstance)(defaultValueType) ||
            ((0, types_1.isClassInstance)(defaultValueType) && (0, symbolNameUtils_1.isPrivateOrProtectedName)(defaultValueType.details.name))) {
            inferredParamType = (0, types_1.combineTypes)([defaultValueType, types_1.UnknownType.create()]);
        }
        else {
            let skipInference = false;
            if ((0, types_1.isFunction)(defaultValueType) || (0, types_1.isOverloadedFunction)(defaultValueType)) {
                // Do not infer parameter types that use a lambda or another function as a
                // default value. We're likely to generate false positives in this case.
                // It's not clear whether parameters should be positional-only or not.
                skipInference = true;
            }
            else if ((0, types_1.isClassInstance)(defaultValueType) &&
                types_1.ClassType.isBuiltIn(defaultValueType, ['tuple', 'list', 'set', 'dict'])) {
                // Do not infer certain types like tuple because it's likely to be
                // more restrictive (narrower) than intended.
                skipInference = true;
            }
            if (!skipInference) {
                inferredParamType = stripLiteralValue(defaultValueType);
            }
        }
        if (inferredParamType) {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(paramValueExpr);
            if (fileInfo.isInPyTypedPackage && !fileInfo.isStubFile) {
                inferredParamType = types_1.TypeBase.cloneForAmbiguousType(inferredParamType);
            }
        }
        return inferredParamType;
    }
    // Transforms the parameter type based on its category. If it's a simple parameter,
    // no transform is applied. If it's a var-arg or keyword-arg parameter, the type
    // is wrapped in a List or Dict.
    function transformVariadicParamType(node, paramCategory, type) {
        switch (paramCategory) {
            case 0 /* ParameterCategory.Simple */: {
                return type;
            }
            case 1 /* ParameterCategory.ArgsList */: {
                if ((0, types_1.isTypeVar)(type) && type.paramSpecAccess) {
                    return type;
                }
                if ((0, types_1.isUnpackedClass)(type)) {
                    return types_1.ClassType.cloneForUnpacked(type, /* isUnpackedTuple */ false);
                }
                return makeTupleObject([{ type, isUnbounded: !(0, types_1.isVariadicTypeVar)(type) }]);
            }
            case 2 /* ParameterCategory.KwargsDict */: {
                // Leave a ParamSpec alone.
                if ((0, types_1.isTypeVar)(type) && type.paramSpecAccess) {
                    return type;
                }
                // Is this an unpacked TypedDict? If so, return it unmodified.
                if ((0, types_1.isClassInstance)(type) && types_1.ClassType.isTypedDictClass(type) && type.isUnpacked) {
                    return type;
                }
                // Wrap the type in a dict with str keys.
                const dictType = getBuiltInType(node, 'dict');
                const strType = getBuiltInObject(node, 'str');
                if ((0, types_1.isInstantiableClass)(dictType) && (0, types_1.isClassInstance)(strType)) {
                    return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictType, [strType, type], /* isTypeArgumentExplicit */ true));
                }
                return types_1.UnknownType.create();
            }
        }
    }
    function createAsyncFunction(node, functionType) {
        (0, debug_1.assert)(types_1.FunctionType.isAsync(functionType));
        // Clone the original function and replace its return type with an
        // Awaitable[<returnType>]. Mark the new function as no longer async.
        const awaitableFunctionType = types_1.FunctionType.cloneWithNewFlags(functionType, functionType.details.flags & ~(512 /* FunctionTypeFlags.Async */ | 131072 /* FunctionTypeFlags.PartiallyEvaluated */));
        if (functionType.details.declaredReturnType) {
            awaitableFunctionType.details.declaredReturnType = createAwaitableReturnType(node, functionType.details.declaredReturnType, types_1.FunctionType.isGenerator(functionType));
        }
        else {
            awaitableFunctionType.inferredReturnType = createAwaitableReturnType(node, getFunctionInferredReturnType(functionType), types_1.FunctionType.isGenerator(functionType));
        }
        return awaitableFunctionType;
    }
    function createAwaitableReturnType(node, returnType, isGenerator, useCoroutine = true) {
        let awaitableReturnType;
        if ((0, types_1.isClassInstance)(returnType)) {
            if (types_1.ClassType.isBuiltIn(returnType)) {
                if (returnType.details.name === 'Generator') {
                    // If the return type is a Generator, change it to an AsyncGenerator.
                    const asyncGeneratorType = getTypingType(node, 'AsyncGenerator');
                    if (asyncGeneratorType && (0, types_1.isInstantiableClass)(asyncGeneratorType)) {
                        const typeArgs = [];
                        const generatorTypeArgs = returnType.typeArguments;
                        if (generatorTypeArgs && generatorTypeArgs.length > 0) {
                            typeArgs.push(generatorTypeArgs[0]);
                        }
                        if (generatorTypeArgs && generatorTypeArgs.length > 1) {
                            typeArgs.push(generatorTypeArgs[1]);
                        }
                        awaitableReturnType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(asyncGeneratorType, typeArgs, 
                        /* isTypeArgumentExplicit */ true));
                    }
                }
                else if (['AsyncGenerator', 'AsyncIterator', 'AsyncIterable'].some((name) => name === returnType.details.name)) {
                    // If it's already an AsyncGenerator, AsyncIterator or AsyncIterable,
                    // leave it as is.
                    awaitableReturnType = returnType;
                }
            }
        }
        if (!awaitableReturnType || !isGenerator) {
            // Wrap in either an Awaitable or a Coroutine, which is a subclass of Awaitable.
            const awaitableType = getTypingType(node, useCoroutine ? 'Coroutine' : 'Awaitable');
            if (awaitableType && (0, types_1.isInstantiableClass)(awaitableType)) {
                awaitableReturnType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(awaitableType, useCoroutine ? [types_1.AnyType.create(), types_1.AnyType.create(), returnType] : [returnType], 
                /* isTypeArgumentExplicit */ true));
            }
            else {
                awaitableReturnType = types_1.UnknownType.create();
            }
        }
        return awaitableReturnType;
    }
    function inferFunctionReturnType(node, isAbstract) {
        var _a;
        const returnAnnotation = node.returnTypeAnnotation || ((_a = node.functionAnnotationComment) === null || _a === void 0 ? void 0 : _a.returnTypeAnnotation);
        // This shouldn't be called if there is a declared return type, but it
        // can happen if there are unexpected cycles between decorators and
        // classes that they decorate. We'll just return an undefined type
        // in this case.
        if (returnAnnotation) {
            return undefined;
        }
        // Is this type already cached?
        let inferredReturnType = readTypeCache(node.suite, 0 /* EvaluatorFlags.None */);
        let isIncomplete = false;
        if (inferredReturnType) {
            return { type: inferredReturnType, isIncomplete };
        }
        if (functionRecursionMap.has(node.id) || functionRecursionMap.size >= maxInferFunctionReturnRecursionCount) {
            inferredReturnType = types_1.UnknownType.create();
            isIncomplete = true;
        }
        else {
            functionRecursionMap.add(node.id);
            try {
                let functionDecl;
                const decl = AnalyzerNodeInfo.getDeclaration(node);
                if (decl) {
                    functionDecl = decl;
                }
                const functionNeverReturns = !isAfterNodeReachable(node);
                const implicitlyReturnsNone = isAfterNodeReachable(node.suite);
                // Infer the return type based on all of the return statements in the function's body.
                if (AnalyzerNodeInfo.getFileInfo(node).isStubFile) {
                    // If a return type annotation is missing in a stub file, assume
                    // it's an "unknown" type. In normal source files, we can infer the
                    // type from the implementation.
                    inferredReturnType = types_1.UnknownType.create();
                }
                else {
                    if (functionNeverReturns) {
                        // If the function always raises and never returns, assume a "NoReturn" type.
                        // Skip this for abstract methods which often are implemented with "raise
                        // NotImplementedError()".
                        if (isAbstract || methodAlwaysRaisesNotImplemented(functionDecl)) {
                            inferredReturnType = types_1.UnknownType.create();
                        }
                        else {
                            inferredReturnType = types_1.NeverType.createNoReturn();
                        }
                    }
                    else {
                        const inferredReturnTypes = [];
                        if (functionDecl === null || functionDecl === void 0 ? void 0 : functionDecl.returnStatements) {
                            functionDecl.returnStatements.forEach((returnNode) => {
                                if (isNodeReachable(returnNode)) {
                                    if (returnNode.returnExpression) {
                                        const returnTypeResult = getTypeOfExpression(returnNode.returnExpression);
                                        if (returnTypeResult.isIncomplete) {
                                            isIncomplete = true;
                                        }
                                        let returnType = returnTypeResult.type;
                                        // If the type is a special form, use the special form instead.
                                        if (returnType.specialForm) {
                                            returnType = returnType.specialForm;
                                        }
                                        // If the return type includes an instance of a class with isEmptyContainer
                                        // set, clear that because we don't want this flag to "leak" into the
                                        // inferred return type.
                                        returnType = (0, typeUtils_1.mapSubtypes)(returnType, (subtype) => {
                                            if ((0, types_1.isClassInstance)(subtype) && subtype.isEmptyContainer) {
                                                return types_1.ClassType.cloneForSpecialization(subtype, subtype.typeArguments, !!subtype.isTypeArgumentExplicit, subtype.includeSubclasses, subtype.tupleTypeArguments, 
                                                /* isEmptyContainer */ false);
                                            }
                                            return subtype;
                                        });
                                        inferredReturnTypes.push(returnType);
                                    }
                                    else {
                                        inferredReturnTypes.push(getNoneType());
                                    }
                                }
                            });
                        }
                        if (!functionNeverReturns && implicitlyReturnsNone) {
                            inferredReturnTypes.push(getNoneType());
                        }
                        inferredReturnType = (0, types_1.combineTypes)(inferredReturnTypes);
                        // Remove any unbound values since those would generate an exception
                        // before being returned.
                        inferredReturnType = (0, types_1.removeUnbound)(inferredReturnType);
                    }
                    // Is it a generator?
                    if (functionDecl === null || functionDecl === void 0 ? void 0 : functionDecl.isGenerator) {
                        const inferredYieldTypes = [];
                        let useAwaitableGenerator = false;
                        let isYieldResultUsed = false;
                        if (functionDecl.yieldStatements) {
                            functionDecl.yieldStatements.forEach((yieldNode) => {
                                var _a, _b;
                                if (isNodeReachable(yieldNode)) {
                                    if (yieldNode.nodeType === 61 /* ParseNodeType.YieldFrom */) {
                                        isYieldResultUsed = true;
                                        const iteratorTypeResult = getTypeOfExpression(yieldNode.expression);
                                        if ((0, types_1.isClassInstance)(iteratorTypeResult.type) &&
                                            types_1.ClassType.isBuiltIn(iteratorTypeResult.type, 'Coroutine')) {
                                            // Handle old-style (pre-await) Coroutines.
                                            inferredYieldTypes.push();
                                            useAwaitableGenerator = true;
                                        }
                                        else {
                                            const yieldType = (_a = getTypeOfIterator(iteratorTypeResult, 
                                            /* isAsync */ false, yieldNode)) === null || _a === void 0 ? void 0 : _a.type;
                                            inferredYieldTypes.push(yieldType !== null && yieldType !== void 0 ? yieldType : types_1.UnknownType.create());
                                        }
                                    }
                                    else {
                                        // If the yield expression is not by itself in a statement list,
                                        // assume that its result is consumed.
                                        if (((_b = yieldNode === null || yieldNode === void 0 ? void 0 : yieldNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) !== 47 /* ParseNodeType.StatementList */) {
                                            isYieldResultUsed = true;
                                        }
                                        if (yieldNode.expression) {
                                            const yieldType = getTypeOfExpression(yieldNode.expression).type;
                                            inferredYieldTypes.push(yieldType !== null && yieldType !== void 0 ? yieldType : types_1.UnknownType.create());
                                        }
                                        else {
                                            inferredYieldTypes.push(getNoneType());
                                        }
                                    }
                                }
                            });
                        }
                        if (inferredYieldTypes.length === 0) {
                            inferredYieldTypes.push(getNoneType());
                        }
                        const inferredYieldType = (0, types_1.combineTypes)(inferredYieldTypes);
                        // Inferred yield types need to be wrapped in a Generator or
                        // AwaitableGenerator to produce the final result.
                        const generatorType = getTypingType(node, useAwaitableGenerator ? 'AwaitableGenerator' : 'Generator');
                        if (generatorType && (0, types_1.isInstantiableClass)(generatorType)) {
                            const typeArgs = [];
                            // The "send type" for the generator (the second type argument) is
                            // not generally inferrable, but we can assume that it's Any
                            // if the function never uses the value and Unknown if it does.
                            // This eliminates any "partially unknown" errors in strict mode
                            // in the common case.
                            const sendType = isYieldResultUsed ? types_1.UnknownType.create() : types_1.AnyType.create();
                            typeArgs.push(inferredYieldType, sendType, inferredReturnType);
                            if (useAwaitableGenerator) {
                                typeArgs.push(types_1.AnyType.create());
                            }
                            inferredReturnType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(generatorType, typeArgs, 
                            /* isTypeArgumentExplicit */ true));
                        }
                        else {
                            inferredReturnType = types_1.UnknownType.create();
                        }
                    }
                }
                writeTypeCache(node.suite, { type: inferredReturnType, isIncomplete }, 0 /* EvaluatorFlags.None */);
            }
            finally {
                functionRecursionMap.delete(node.id);
            }
        }
        return inferredReturnType ? { type: inferredReturnType, isIncomplete } : undefined;
    }
    // Determines whether the method consists only of a "raise" statement
    // and the exception type raised is a NotImplementedError or a subclass
    // thereof. This is commonly used for abstract methods.
    function methodAlwaysRaisesNotImplemented(functionDecl) {
        if (!functionDecl ||
            !functionDecl.isMethod ||
            functionDecl.returnStatements ||
            functionDecl.yieldStatements ||
            !functionDecl.raiseStatements) {
            return false;
        }
        for (const raiseStatement of functionDecl.raiseStatements) {
            if (!raiseStatement.typeExpression || raiseStatement.valueExpression) {
                return false;
            }
            const raiseType = getTypeOfExpression(raiseStatement.typeExpression).type;
            const classType = (0, types_1.isInstantiableClass)(raiseType)
                ? raiseType
                : (0, types_1.isClassInstance)(raiseType)
                    ? raiseType
                    : undefined;
            if (!classType || !(0, typeUtils_1.derivesFromStdlibClass)(classType, 'NotImplementedError')) {
                return false;
            }
        }
        return true;
    }
    function evaluateTypesForForStatement(node) {
        var _a, _b;
        if (isTypeCached(node)) {
            return;
        }
        const iteratorTypeResult = getTypeOfExpression(node.iterableExpression);
        const iteratedType = (_b = (_a = getTypeOfIterator(iteratorTypeResult, !!node.isAsync, node.iterableExpression)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
        assignTypeToExpression(node.targetExpression, iteratedType, !!iteratorTypeResult.isIncomplete, node.targetExpression);
        writeTypeCache(node, { type: iteratedType, isIncomplete: !!iteratorTypeResult.isIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForExceptStatement(node) {
        // This should be called only if the except node has a target exception.
        (0, debug_1.assert)(node.typeExpression !== undefined);
        if (isTypeCached(node)) {
            return;
        }
        const exceptionTypeResult = getTypeOfExpression(node.typeExpression);
        const exceptionTypes = exceptionTypeResult.type;
        function getExceptionType(exceptionType, errorNode) {
            var _a, _b;
            exceptionType = makeTopLevelTypeVarsConcrete(exceptionType);
            if ((0, types_1.isAnyOrUnknown)(exceptionType)) {
                return exceptionType;
            }
            if ((0, types_1.isInstantiableClass)(exceptionType)) {
                return types_1.ClassType.cloneAsInstance(exceptionType);
            }
            if ((0, types_1.isClassInstance)(exceptionType)) {
                const iterableType = (_b = (_a = getTypeOfIterator({ type: exceptionType, isIncomplete: exceptionTypeResult.isIncomplete }, 
                /* isAsync */ false, errorNode)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create();
                return (0, typeUtils_1.mapSubtypes)(iterableType, (subtype) => {
                    if ((0, types_1.isAnyOrUnknown)(subtype)) {
                        return subtype;
                    }
                    return types_1.UnknownType.create();
                });
            }
            return types_1.UnknownType.create();
        }
        let targetType = (0, typeUtils_1.mapSubtypes)(exceptionTypes, (subType) => {
            // If more than one type was specified for the exception, we'll receive
            // a specialized tuple object here.
            const tupleType = (0, typeUtils_1.getSpecializedTupleType)(subType);
            if (tupleType && tupleType.tupleTypeArguments) {
                const entryTypes = tupleType.tupleTypeArguments.map((t) => {
                    return getExceptionType(t.type, node.typeExpression);
                });
                return (0, types_1.combineTypes)(entryTypes);
            }
            return getExceptionType(subType, node.typeExpression);
        });
        // If this is an except group, wrap the exception type in an BaseExceptionGroup.
        if (node.isExceptGroup) {
            targetType = getBuiltInObject(node, 'BaseExceptionGroup', [targetType]);
        }
        if (node.name) {
            assignTypeToExpression(node.name, targetType, /* isIncomplete */ false, node.name);
        }
        writeTypeCache(node, { type: targetType }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForWithStatement(node) {
        if (isTypeCached(node)) {
            return;
        }
        const exprTypeResult = getTypeOfExpression(node.expression);
        let exprType = exprTypeResult.type;
        const isAsync = node.parent && node.parent.nodeType === 58 /* ParseNodeType.With */ && !!node.parent.isAsync;
        if ((0, typeUtils_1.isOptionalType)(exprType)) {
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportOptionalContextManager, localize_1.LocMessage.noneNotUsableWith(), node.expression);
            exprType = (0, typeUtils_1.removeNoneFromUnion)(exprType);
        }
        // Verify that the target has an __enter__ or __aenter__ method defined.
        const enterMethodName = isAsync ? '__aenter__' : '__enter__';
        const scopedType = (0, typeUtils_1.mapSubtypes)(exprType, (subtype) => {
            subtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return subtype;
            }
            const additionalHelp = new diagnostic_1.DiagnosticAddendum();
            if ((0, types_1.isClass)(subtype)) {
                let enterType = getTypeOfMagicMethodCall(subtype, enterMethodName, [], node.expression, 
                /* inferenceContext */ undefined, additionalHelp.createAddendum());
                if (enterType) {
                    // For "async while", an implicit "await" is performed.
                    if (isAsync) {
                        enterType = getTypeOfAwaitable(enterType, node.expression);
                    }
                    return enterType;
                }
                if (!isAsync) {
                    if (getTypeOfMagicMethodCall(subtype, '__aenter__', [], node.expression, 
                    /* inferenceContext */ undefined)) {
                        additionalHelp.addMessage(localize_1.LocAddendum.asyncHelp());
                    }
                }
            }
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeNotUsableWith().format({ type: printType(subtype), method: enterMethodName }) +
                additionalHelp.getString(), node.expression);
            return types_1.UnknownType.create();
        });
        // Verify that the target has an __exit__ or __aexit__ method defined.
        const exitMethodName = isAsync ? '__aexit__' : '__exit__';
        (0, typeUtils_1.doForEachSubtype)(exprType, (subtype) => {
            subtype = makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isAnyOrUnknown)(subtype)) {
                return;
            }
            if ((0, types_1.isClass)(subtype)) {
                const anyArg = { type: types_1.AnyType.create() };
                const exitType = getTypeOfMagicMethodCall(subtype, exitMethodName, [anyArg, anyArg, anyArg], node.expression, 
                /* inferenceContext */ undefined);
                if (exitType) {
                    return;
                }
            }
            addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeNotUsableWith().format({ type: printType(subtype), method: exitMethodName }), node.expression);
        });
        if (node.target) {
            assignTypeToExpression(node.target, scopedType, !!exprTypeResult.isIncomplete, node.target);
        }
        writeTypeCache(node, { type: scopedType, isIncomplete: !!exprTypeResult.isIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForImportAs(node) {
        var _a;
        if (isTypeCached(node)) {
            return;
        }
        let symbolNameNode;
        if (node.alias) {
            // The symbol name is defined by the alias.
            symbolNameNode = node.alias;
        }
        else {
            // There was no alias, so we need to use the first element of
            // the name parts as the symbol.
            symbolNameNode = node.module.nameParts[0];
        }
        if (!symbolNameNode) {
            // This can happen in certain cases where there are parse errors.
            return;
        }
        // Look up the symbol to find the alias declaration.
        let symbolType = (_a = getAliasedSymbolTypeForName(node, symbolNameNode.value)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
        // Is there a cached module type associated with this node? If so, use
        // it instead of the type we just created.
        const cachedModuleType = readTypeCache(node, 0 /* EvaluatorFlags.None */);
        if (cachedModuleType && (0, types_1.isModule)(cachedModuleType) && symbolType) {
            if ((0, types_1.isTypeSame)(symbolType, cachedModuleType)) {
                symbolType = cachedModuleType;
            }
        }
        assignTypeToNameNode(symbolNameNode, symbolType, /* isIncomplete */ false, /* ignoreEmptyContainers */ false);
        writeTypeCache(node, { type: symbolType }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForImportFromAs(node) {
        var _a;
        if (isTypeCached(node)) {
            return;
        }
        const aliasNode = node.alias || node.name;
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        // If this is a redundant form of an import, assume it is an intentional
        // export and mark the symbol as accessed.
        if (((_a = node.alias) === null || _a === void 0 ? void 0 : _a.value) === node.name.value) {
            const symbolInScope = lookUpSymbolRecursive(node, node.name.value, /* honorCodeFlow */ true);
            if (symbolInScope) {
                setSymbolAccessed(fileInfo, symbolInScope.symbol, node);
            }
        }
        // If this is an import into a class scope, mark the symbol as accessed.
        const classNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true);
        if (classNode) {
            const symbolInScope = lookUpSymbolRecursive(node, aliasNode.value, /* honorCodeFlow */ true);
            if (symbolInScope) {
                setSymbolAccessed(fileInfo, symbolInScope.symbol, node);
            }
        }
        let symbolType = getAliasedSymbolTypeForName(node, aliasNode.value);
        if (!symbolType) {
            const parentNode = node.parent;
            (0, debug_1.assert)(parentNode && parentNode.nodeType === 22 /* ParseNodeType.ImportFrom */);
            (0, debug_1.assert)(!parentNode.isWildcardImport);
            const importInfo = AnalyzerNodeInfo.getImportInfo(parentNode.module);
            if (importInfo && importInfo.isImportFound && !importInfo.isNativeLib) {
                const resolvedPath = importInfo.resolvedUris[importInfo.resolvedUris.length - 1];
                const importLookupInfo = importLookup(resolvedPath);
                let reportError = false;
                // If we were able to resolve the import, report the error as
                // an unresolved symbol.
                if (importLookupInfo) {
                    reportError = true;
                    // Handle PEP 562 support for module-level __getattr__ function,
                    // introduced in Python 3.7.
                    if (fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_7) ||
                        fileInfo.isStubFile) {
                        const getAttrSymbol = importLookupInfo.symbolTable.get('__getattr__');
                        if (getAttrSymbol) {
                            const getAttrType = getEffectiveTypeOfSymbol(getAttrSymbol);
                            if ((0, types_1.isFunction)(getAttrType)) {
                                symbolType = getFunctionEffectiveReturnType(getAttrType);
                                reportError = false;
                            }
                        }
                    }
                }
                else if (resolvedPath.isEmpty()) {
                    // This corresponds to the "from . import a" form.
                    reportError = true;
                }
                if (reportError) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAttributeAccessIssue, localize_1.LocMessage.importSymbolUnknown().format({ name: node.name.value }), node.name);
                }
            }
            if (!symbolType) {
                symbolType = types_1.UnknownType.create();
            }
        }
        assignTypeToNameNode(aliasNode, symbolType, /* isIncomplete */ false, /* ignoreEmptyContainers */ false);
        writeTypeCache(node, { type: symbolType }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForMatchStatement(node) {
        if (isTypeCached(node)) {
            return;
        }
        const subjectTypeResult = getTypeOfExpression(node.subjectExpression);
        let subjectType = subjectTypeResult.type;
        // Apply negative narrowing for each of the cases that doesn't have a guard statement.
        for (const caseStatement of node.cases) {
            if (!caseStatement.guardExpression) {
                subjectType = (0, patternMatching_1.narrowTypeBasedOnPattern)(evaluatorInterface, subjectType, caseStatement.pattern, 
                /* isPositiveTest */ false);
            }
        }
        writeTypeCache(node, { type: subjectType, isIncomplete: !!subjectTypeResult.isIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForCaseStatement(node) {
        if (isTypeCached(node)) {
            return;
        }
        if (!node.parent || node.parent.nodeType !== 63 /* ParseNodeType.Match */) {
            (0, debug_1.fail)('Expected parent of case statement to be match statement');
            return;
        }
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const subjectTypeResult = getTypeOfExpression(node.parent.subjectExpression);
        let subjectType = subjectTypeResult.type;
        // Apply negative narrowing for each of the cases prior to the current one
        // except for those that have a guard expression.
        for (const caseStatement of node.parent.cases) {
            if (caseStatement === node) {
                if (fileInfo.diagnosticRuleSet.reportUnnecessaryComparison !== 'none') {
                    if (!subjectTypeResult.isIncomplete) {
                        (0, patternMatching_1.checkForUnusedPattern)(evaluatorInterface, node.pattern, subjectType);
                    }
                }
                break;
            }
            if (!caseStatement.guardExpression) {
                subjectType = (0, patternMatching_1.narrowTypeBasedOnPattern)(evaluatorInterface, subjectType, caseStatement.pattern, 
                /* isPositiveTest */ false);
            }
        }
        const narrowedSubjectType = (0, patternMatching_1.assignTypeToPatternTargets)(evaluatorInterface, subjectType, !!subjectTypeResult.isIncomplete, node.pattern);
        writeTypeCache(node, { type: narrowedSubjectType, isIncomplete: !!subjectTypeResult.isIncomplete }, 0 /* EvaluatorFlags.None */);
    }
    function evaluateTypesForImportFrom(node) {
        if (isTypeCached(node)) {
            return;
        }
        if (node.isWildcardImport) {
            // Write back a dummy type so we don't evaluate this node again.
            writeTypeCache(node, { type: types_1.AnyType.create() }, 0 /* EvaluatorFlags.None */);
            const flowNode = AnalyzerNodeInfo.getFlowNode(node);
            if (flowNode && (flowNode.flags & codeFlowTypes_1.FlowFlags.WildcardImport) !== 0) {
                const wildcardFlowNode = flowNode;
                wildcardFlowNode.names.forEach((name) => {
                    var _a, _b;
                    const importedSymbolType = getAliasedSymbolTypeForName(node, name);
                    if (!importedSymbolType) {
                        return;
                    }
                    const symbolWithScope = lookUpSymbolRecursive(node, name, /* honorCodeFlow */ false);
                    if (!symbolWithScope) {
                        return;
                    }
                    const declaredType = (_a = getDeclaredTypeOfSymbol(symbolWithScope.symbol)) === null || _a === void 0 ? void 0 : _a.type;
                    if (!declaredType) {
                        return;
                    }
                    const diagAddendum = new diagnostic_1.DiagnosticAddendum();
                    if (!assignType(declaredType, importedSymbolType, diagAddendum)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportAssignmentType, localize_1.LocMessage.typeAssignmentMismatchWildcard().format({
                            ...printSrcDestTypes(importedSymbolType, declaredType),
                            name,
                        }) + diagAddendum.getString(), node, (_b = node.wildcardToken) !== null && _b !== void 0 ? _b : node);
                    }
                });
            }
        }
        else {
            // Use the first element of the name parts as the symbol.
            const symbolNameNode = node.module.nameParts[0];
            // Look up the symbol to find the alias declaration.
            let symbolType = getAliasedSymbolTypeForName(node, symbolNameNode.value);
            if (!symbolType) {
                return;
            }
            // Is there a cached module type associated with this node? If so, use
            // it instead of the type we just created.
            const cachedModuleType = readTypeCache(node, 0 /* EvaluatorFlags.None */);
            if (cachedModuleType && (0, types_1.isModule)(cachedModuleType) && symbolType) {
                if ((0, types_1.isTypeSame)(symbolType, cachedModuleType)) {
                    symbolType = cachedModuleType;
                }
            }
            assignTypeToNameNode(symbolNameNode, symbolType, 
            /* isIncomplete */ false, 
            /* ignoreEmptyContainers */ false);
            writeTypeCache(node, { type: symbolType }, 0 /* EvaluatorFlags.None */);
        }
    }
    function evaluateTypesForTypeAnnotationNode(node) {
        var _a;
        // If this node is part of an assignment statement, use specialized
        // logic that performs bidirectional inference and assignment
        // type narrowing.
        if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */) {
            evaluateTypesForAssignmentStatement(node.parent);
        }
        else {
            const annotationType = getTypeOfAnnotation(node.typeAnnotation, {
                isVariableAnnotation: true,
                allowFinal: ParseTreeUtils.isFinalAllowedForAssignmentTarget(node.valueExpression),
                allowClassVar: ParseTreeUtils.isClassVarAllowedForAssignmentTarget(node.valueExpression),
            });
            writeTypeCache(node.valueExpression, { type: annotationType }, 0 /* EvaluatorFlags.None */);
        }
    }
    function getAliasedSymbolTypeForName(node, name) {
        const symbolWithScope = lookUpSymbolRecursive(node, name, /* honorCodeFlow */ true);
        if (!symbolWithScope) {
            return undefined;
        }
        // Normally there will be at most one decl associated with the import node, but
        // there can be multiple in the case of the "from .X import X" statement. In such
        // case, we want to choose the last declaration.
        const filteredDecls = symbolWithScope.symbol
            .getDeclarations()
            .filter((decl) => ParseTreeUtils.isNodeContainedWithin(node, decl.node) && decl.type === 8 /* DeclarationType.Alias */);
        let aliasDecl = filteredDecls.length > 0 ? filteredDecls[filteredDecls.length - 1] : undefined;
        // If we didn't find an exact match, look for any alias associated with
        // this symbol. In cases where we have multiple ImportAs nodes that share
        // the same first-part name (e.g. "import asyncio" and "import asyncio.tasks"),
        // we may not find the declaration associated with this node.
        if (!aliasDecl) {
            aliasDecl = symbolWithScope.symbol.getDeclarations().find((decl) => decl.type === 8 /* DeclarationType.Alias */);
        }
        if (!aliasDecl) {
            return undefined;
        }
        (0, debug_1.assert)(aliasDecl.type === 8 /* DeclarationType.Alias */);
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        // Try to resolve the alias while honoring external visibility.
        const resolvedAliasInfo = resolveAliasDeclarationWithInfo(aliasDecl, /* resolveLocalNames */ true, {
            allowExternallyHiddenAccess: fileInfo.isStubFile,
        });
        if (!resolvedAliasInfo) {
            return undefined;
        }
        if (!resolvedAliasInfo.declaration) {
            return evaluatorOptions.evaluateUnknownImportsAsAny ? types_1.AnyType.create() : types_1.UnknownType.create();
        }
        if (node.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
            if (resolvedAliasInfo.isPrivate) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportPrivateUsage, localize_1.LocMessage.privateUsedOutsideOfModule().format({
                    name: node.name.value,
                }), node.name);
            }
            const privateImporter = resolvedAliasInfo.privatePyTypedImporter || resolvedAliasInfo.privateNonPyTypedImporter;
            if (privateImporter) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                if (resolvedAliasInfo.privateImported) {
                    diag.addMessage(localize_1.LocAddendum.privateImportFromPyTypedSource().format({
                        module: resolvedAliasInfo.privateImported,
                    }));
                }
                addDiagnostic(resolvedAliasInfo.privatePyTypedImporter
                    ? diagnosticRules_1.DiagnosticRule.reportPrivateImportUsage
                    : diagnosticRules_1.DiagnosticRule.reportPrivateLocalImportUsage, localize_1.LocMessage.privateImportFromPyTypedModule().format({
                    name: node.name.value,
                    module: privateImporter,
                }) + diag.getString(), node.name);
            }
        }
        return getInferredTypeOfDeclaration(symbolWithScope.symbol, aliasDecl);
    }
    // In some cases, an expression must be evaluated in the context of another
    // expression or statement that contains it. This contextual evaluation
    // allows for bidirectional type evaluation.
    function evaluateTypesForExpressionInContext(node) {
        var _a, _b, _c, _d, _e, _f;
        // Check for a couple of special cases where the node is a NameNode but
        // is technically not part of an expression. We'll handle these here so
        // callers don't need to include special-case logic.
        if (node.nodeType === 38 /* ParseNodeType.Name */ && node.parent) {
            if (node.parent.nodeType === 28 /* ParseNodeType.Function */ && node.parent.name === node) {
                getTypeOfFunction(node.parent);
                return;
            }
            if (node.parent.nodeType === 10 /* ParseNodeType.Class */ && node.parent.name === node) {
                getTypeOfClass(node.parent);
                return;
            }
            if (node.parent.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
                evaluateTypesForImportFromAs(node.parent);
                return;
            }
            if (node.parent.nodeType === 21 /* ParseNodeType.ImportAs */) {
                evaluateTypesForImportAs(node.parent);
                return;
            }
            if (node.parent.nodeType === 77 /* ParseNodeType.TypeAlias */ && node.parent.name === node) {
                getTypeOfTypeAlias(node.parent);
                return;
            }
            if (node.parent.nodeType === 29 /* ParseNodeType.Global */ || node.parent.nodeType === 39 /* ParseNodeType.Nonlocal */) {
                // For global and nonlocal statements, allow forward references so
                // we don't use code flow during symbol lookups.
                getTypeOfExpression(node, 4 /* EvaluatorFlags.AllowForwardReferences */);
                return;
            }
            if (node.parent.nodeType === 37 /* ParseNodeType.ModuleName */) {
                // A name within a module name isn't an expression,
                // so there's nothing we can evaluate here.
                return;
            }
        }
        // If the expression is part of a type annotation, we need to evaluate
        // it with special evaluation flags.
        const annotationNode = ParseTreeUtils.getParentAnnotationNode(node);
        if (annotationNode) {
            // Annotations need to be evaluated with specialized evaluation flags.
            const annotationParent = annotationNode.parent;
            (0, debug_1.assert)(annotationParent !== undefined);
            if (annotationParent.nodeType === 3 /* ParseNodeType.Assignment */) {
                if (annotationNode === annotationParent.typeAnnotationComment) {
                    getTypeOfAnnotation(annotationNode, {
                        isVariableAnnotation: true,
                        allowFinal: ParseTreeUtils.isFinalAllowedForAssignmentTarget(annotationParent.leftExpression),
                        allowClassVar: ParseTreeUtils.isClassVarAllowedForAssignmentTarget(annotationParent.leftExpression),
                    });
                }
                else {
                    evaluateTypesForAssignmentStatement(annotationParent);
                }
                return;
            }
            if (annotationParent.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
                evaluateTypesForTypeAnnotationNode(annotationParent);
                return;
            }
            if (annotationParent.nodeType === 28 /* ParseNodeType.Function */ &&
                annotationNode === annotationParent.returnTypeAnnotation) {
                getTypeOfAnnotation(annotationNode, {
                    associateTypeVarsWithScope: true,
                });
                return;
            }
            getTypeOfAnnotation(annotationNode, {
                isVariableAnnotation: ((_a = annotationNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 54 /* ParseNodeType.TypeAnnotation */,
                allowUnpackedTuple: annotationParent.nodeType === 41 /* ParseNodeType.Parameter */ &&
                    annotationParent.category === 1 /* ParameterCategory.ArgsList */,
                allowUnpackedTypedDict: annotationParent.nodeType === 41 /* ParseNodeType.Parameter */ &&
                    annotationParent.category === 2 /* ParameterCategory.KwargsDict */,
            });
            return;
        }
        // See if the expression is part of a pattern used in a case statement.
        const possibleCaseNode = ParseTreeUtils.getParentNodeOfType(node, 64 /* ParseNodeType.Case */);
        if (possibleCaseNode) {
            if (ParseTreeUtils.isNodeContainedWithin(node, possibleCaseNode.pattern)) {
                evaluateTypesForCaseStatement(possibleCaseNode);
                return;
            }
        }
        // Scan up the parse tree until we find a node that doesn't
        // require any context to be evaluated.
        let nodeToEvaluate = node;
        let flags = 0 /* EvaluatorFlags.None */;
        while (true) {
            // If we're within an argument node in a call or index expression, skip
            // all of the nodes between because the entire argument expression
            // needs to be evaluated contextually.
            const argumentNode = ParseTreeUtils.getParentNodeOfType(nodeToEvaluate, 1 /* ParseNodeType.Argument */);
            if (argumentNode && argumentNode !== nodeToEvaluate) {
                (0, debug_1.assert)(argumentNode.parent !== undefined);
                if (argumentNode.parent.nodeType === 9 /* ParseNodeType.Call */ ||
                    argumentNode.parent.nodeType === 24 /* ParseNodeType.Index */) {
                    nodeToEvaluate = argumentNode.parent;
                    continue;
                }
                if (argumentNode.parent.nodeType === 10 /* ParseNodeType.Class */) {
                    // If this is an argument node within a class declaration,
                    // evaluate the full class declaration node.
                    getTypeOfClass(argumentNode.parent);
                    return;
                }
            }
            let parent = nodeToEvaluate.parent;
            if (!parent) {
                break;
            }
            // If this is the target of an assignment expression, evaluate the
            // assignment expression node instead.
            if (parent.nodeType === 4 /* ParseNodeType.AssignmentExpression */ && nodeToEvaluate === parent.name) {
                nodeToEvaluate = parent;
                continue;
            }
            // The left expression of a call or member access expression is not generally contextual.
            if (parent.nodeType === 9 /* ParseNodeType.Call */ || parent.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                if (nodeToEvaluate === parent.leftExpression) {
                    // Handle the special case where the LHS is a call to super().
                    if (nodeToEvaluate.nodeType === 9 /* ParseNodeType.Call */ &&
                        nodeToEvaluate.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                        nodeToEvaluate.leftExpression.value === 'super') {
                        nodeToEvaluate = parent;
                        continue;
                    }
                    // Handle the special case where the LHS is a call to a lambda.
                    if (parent.nodeType === 9 /* ParseNodeType.Call */ && nodeToEvaluate.nodeType === 30 /* ParseNodeType.Lambda */) {
                        nodeToEvaluate = parent;
                        continue;
                    }
                    flags = 2 /* EvaluatorFlags.CallBaseDefaults */;
                    break;
                }
            }
            else if (parent.nodeType === 24 /* ParseNodeType.Index */) {
                // The base expression of an index expression is not contextual.
                if (nodeToEvaluate === parent.baseExpression) {
                    flags = 2 /* EvaluatorFlags.IndexBaseDefaults */;
                    break;
                }
            }
            else if (parent.nodeType === 48 /* ParseNodeType.StringList */ && nodeToEvaluate === parent.typeAnnotation) {
                // Forward-declared type annotation expressions need to be be evaluated
                // in context so they have the appropriate flags set. Most of these cases
                // will have been detected above when calling getParentAnnotationNode,
                // but TypeAlias expressions are not handled there.
                nodeToEvaluate = parent;
                continue;
            }
            if (!(0, parseNodes_1.isExpressionNode)(parent)) {
                // If we've hit a non-expression node, we generally want to
                // stop. However, there are a few special "pass through"
                // node types that we can skip over to get to a known
                // expression node.
                if (parent.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */ ||
                    parent.nodeType === 16 /* ParseNodeType.DictionaryExpandEntry */ ||
                    parent.nodeType === 33 /* ParseNodeType.ListComprehensionFor */ ||
                    parent.nodeType === 34 /* ParseNodeType.ListComprehensionIf */) {
                    (0, debug_1.assert)(parent.parent !== undefined && (0, parseNodes_1.isExpressionNode)(parent.parent));
                    parent = parent.parent;
                }
                else if (parent.nodeType === 41 /* ParseNodeType.Parameter */) {
                    (0, debug_1.assert)(parent.parent !== undefined);
                    // Parameters are contextual for lambdas.
                    if (parent.parent.nodeType === 30 /* ParseNodeType.Lambda */) {
                        parent = parent.parent;
                    }
                    else {
                        break;
                    }
                }
                else if (parent.nodeType === 75 /* ParseNodeType.TypeParameter */) {
                    // If this is a bound or default expression in a type parameter list,
                    // we need to evaluate it in the context of the type parameter.
                    if (node === parent.boundExpression || node === parent.defaultExpression) {
                        getTypeOfTypeParameter(parent);
                        return;
                    }
                    break;
                }
                else {
                    break;
                }
            }
            nodeToEvaluate = parent;
        }
        const parent = nodeToEvaluate.parent;
        (0, debug_1.assert)(parent !== undefined);
        switch (parent.nodeType) {
            case 14 /* ParseNodeType.Del */: {
                verifyDeleteExpression(nodeToEvaluate);
                return;
            }
            case 75 /* ParseNodeType.TypeParameter */: {
                // If this is the name node within a type parameter list, see if it's a type alias
                // definition. If so, we need to evaluate the type alias contextually.
                if (nodeToEvaluate === parent.name &&
                    ((_b = parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 76 /* ParseNodeType.TypeParameterList */ &&
                    ((_c = parent.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 77 /* ParseNodeType.TypeAlias */) {
                    getTypeOfTypeAlias(parent.parent.parent);
                    return;
                }
                break;
            }
            case 77 /* ParseNodeType.TypeAlias */: {
                getTypeOfTypeAlias(parent);
                return;
            }
            case 13 /* ParseNodeType.Decorator */: {
                if (((_d = parent.parent) === null || _d === void 0 ? void 0 : _d.nodeType) === 10 /* ParseNodeType.Class */) {
                    getTypeOfClass(parent.parent);
                }
                else if (((_e = parent.parent) === null || _e === void 0 ? void 0 : _e.nodeType) === 28 /* ParseNodeType.Function */) {
                    getTypeOfFunction(parent.parent);
                }
                return;
            }
            case 41 /* ParseNodeType.Parameter */: {
                if (nodeToEvaluate !== parent.defaultValue) {
                    evaluateTypeOfParameter(parent);
                    return;
                }
                break;
            }
            case 1 /* ParseNodeType.Argument */: {
                if (nodeToEvaluate === parent.name) {
                    // A name used to specify a named parameter in an argument isn't an
                    // expression, so there's nothing we can evaluate here.
                    return;
                }
                if (((_f = parent.parent) === null || _f === void 0 ? void 0 : _f.nodeType) === 10 /* ParseNodeType.Class */) {
                    // A class argument must be evaluated in the context of the class declaration.
                    getTypeOfClass(parent.parent);
                    return;
                }
                break;
            }
            case 44 /* ParseNodeType.Return */: {
                // Return expressions must be evaluated in the context of the expected return type.
                if (parent.returnExpression) {
                    const enclosingFunctionNode = ParseTreeUtils.getEnclosingFunction(node);
                    const declaredReturnType = enclosingFunctionNode
                        ? getFunctionDeclaredReturnType(enclosingFunctionNode)
                        : undefined;
                    getTypeOfExpression(parent.returnExpression, 0 /* EvaluatorFlags.None */, (0, typeUtils_1.makeInferenceContext)(declaredReturnType));
                    return;
                }
                break;
            }
            case 54 /* ParseNodeType.TypeAnnotation */: {
                evaluateTypesForTypeAnnotationNode(parent);
                return;
            }
            case 3 /* ParseNodeType.Assignment */: {
                evaluateTypesForAssignmentStatement(parent);
                return;
            }
        }
        if (nodeToEvaluate.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            evaluateTypesForTypeAnnotationNode(nodeToEvaluate);
            return;
        }
        getTypeOfExpression(nodeToEvaluate, flags);
    }
    function evaluateTypeOfParameter(node) {
        // If this parameter has no name, we have nothing to do.
        if (!node.name) {
            return;
        }
        // We need to handle lambdas differently from functions because
        // the former never have parameter type annotations but can
        // be inferred, whereas the latter sometimes have type annotations
        // but cannot be inferred.
        const parent = node.parent;
        if (parent.nodeType === 30 /* ParseNodeType.Lambda */) {
            evaluateTypesForExpressionInContext(parent);
            return;
        }
        (0, debug_1.assert)(parent.nodeType === 28 /* ParseNodeType.Function */);
        const functionNode = parent;
        const paramIndex = functionNode.parameters.findIndex((param) => param === node);
        const typeAnnotation = ParseTreeUtils.getTypeAnnotationForParameter(functionNode, paramIndex);
        if (typeAnnotation) {
            const param = functionNode.parameters[paramIndex];
            const annotatedType = getTypeOfParameterAnnotation(typeAnnotation, functionNode.parameters[paramIndex].category);
            const adjType = transformVariadicParamType(node, node.category, adjustParameterAnnotatedType(param, annotatedType));
            writeTypeCache(node.name, { type: adjType }, 0 /* EvaluatorFlags.None */);
            return;
        }
        const containingClassNode = ParseTreeUtils.getEnclosingClass(functionNode, /* stopAtFunction */ true);
        const classInfo = containingClassNode ? getTypeOfClass(containingClassNode) : undefined;
        if (classInfo &&
            types_1.ClassType.isPseudoGenericClass(classInfo === null || classInfo === void 0 ? void 0 : classInfo.classType) &&
            functionNode.name.value === '__init__') {
            const typeParamName = getPseudoGenericTypeVarName(node.name.value);
            const paramType = classInfo.classType.details.typeParameters.find((param) => param.details.name === typeParamName);
            if (paramType) {
                writeTypeCache(node.name, { type: paramType }, 0 /* EvaluatorFlags.None */);
                return;
            }
        }
        // See if the function is a method in a child class. We may be able to
        // infer the type of the parameter from a method of the same name in
        // a parent class if it has an annotated type.
        const functionFlags = (0, decorators_1.getFunctionInfoFromDecorators)(evaluatorInterface, functionNode, 
        /* isInClass */ true).flags;
        const inferredParamType = inferParameterType(functionNode, functionFlags, paramIndex, classInfo === null || classInfo === void 0 ? void 0 : classInfo.classType);
        writeTypeCache(node.name, { type: transformVariadicParamType(node, node.category, inferredParamType !== null && inferredParamType !== void 0 ? inferredParamType : types_1.UnknownType.create()) }, 0 /* EvaluatorFlags.None */);
    }
    // Evaluates the types that are assigned within the statement that contains
    // the specified parse node. In some cases, a broader statement may need to
    // be evaluated to provide sufficient context for the type. Evaluated types
    // are written back to the type cache for later retrieval.
    function evaluateTypesForStatement(node) {
        initializedBasicTypes(node);
        let curNode = node;
        while (curNode) {
            switch (curNode.nodeType) {
                case 3 /* ParseNodeType.Assignment */: {
                    // See if the assignment is part of a chain of assignments. If so,
                    // evaluate the entire chain.
                    const isInAssignmentChain = curNode.parent &&
                        (curNode.parent.nodeType === 3 /* ParseNodeType.Assignment */ ||
                            curNode.parent.nodeType === 4 /* ParseNodeType.AssignmentExpression */ ||
                            curNode.parent.nodeType === 5 /* ParseNodeType.AugmentedAssignment */) &&
                        curNode.parent.rightExpression === curNode;
                    if (!isInAssignmentChain) {
                        evaluateTypesForAssignmentStatement(curNode);
                        return;
                    }
                    break;
                }
                case 77 /* ParseNodeType.TypeAlias */: {
                    getTypeOfTypeAlias(curNode);
                    return;
                }
                case 4 /* ParseNodeType.AssignmentExpression */: {
                    getTypeOfExpression(curNode);
                    return;
                }
                case 5 /* ParseNodeType.AugmentedAssignment */: {
                    evaluateTypesForAugmentedAssignment(curNode);
                    return;
                }
                case 10 /* ParseNodeType.Class */: {
                    getTypeOfClass(curNode);
                    return;
                }
                case 41 /* ParseNodeType.Parameter */: {
                    evaluateTypeOfParameter(curNode);
                    return;
                }
                case 30 /* ParseNodeType.Lambda */: {
                    evaluateTypesForExpressionInContext(curNode);
                    return;
                }
                case 28 /* ParseNodeType.Function */: {
                    getTypeOfFunction(curNode);
                    return;
                }
                case 26 /* ParseNodeType.For */: {
                    evaluateTypesForForStatement(curNode);
                    return;
                }
                case 25 /* ParseNodeType.Except */: {
                    evaluateTypesForExceptStatement(curNode);
                    return;
                }
                case 59 /* ParseNodeType.WithItem */: {
                    evaluateTypesForWithStatement(curNode);
                    return;
                }
                case 33 /* ParseNodeType.ListComprehensionFor */: {
                    const listComprehension = curNode.parent;
                    (0, debug_1.assert)(listComprehension.nodeType === 32 /* ParseNodeType.ListComprehension */);
                    if (curNode === listComprehension.expression) {
                        evaluateTypesForExpressionInContext(listComprehension);
                    }
                    else {
                        // Evaluate the individual iterations starting with the first
                        // up to the curNode.
                        for (const forIfNode of listComprehension.forIfNodes) {
                            evaluateListComprehensionForIf(forIfNode);
                            if (forIfNode === curNode) {
                                break;
                            }
                        }
                    }
                    return;
                }
                case 21 /* ParseNodeType.ImportAs */: {
                    evaluateTypesForImportAs(curNode);
                    return;
                }
                case 23 /* ParseNodeType.ImportFromAs */: {
                    evaluateTypesForImportFromAs(curNode);
                    return;
                }
                case 22 /* ParseNodeType.ImportFrom */: {
                    evaluateTypesForImportFrom(curNode);
                    return;
                }
                case 64 /* ParseNodeType.Case */: {
                    evaluateTypesForCaseStatement(curNode);
                    return;
                }
            }
            curNode = curNode.parent;
        }
        (0, debug_1.fail)('Unexpected statement');
        return undefined;
    }
    // Helper function for cases where we need to evaluate the types
    // for a subtree so we can determine the type of one of the subnodes
    // within that tree. If the type cannot be determined (because it's part
    // of a cyclical dependency), the function returns undefined.
    function evaluateTypeForSubnode(subnode, callback) {
        // If the type cache is already populated with a complete type,
        // don't bother doing additional work.
        let cacheEntry = readTypeCacheEntry(subnode);
        if (cacheEntry && !cacheEntry.typeResult.isIncomplete) {
            return cacheEntry.typeResult;
        }
        callback();
        cacheEntry = readTypeCacheEntry(subnode);
        if (cacheEntry) {
            return cacheEntry.typeResult;
        }
        return undefined;
    }
    function getCodeFlowAnalyzerForNode(nodeId, typeAtStart) {
        let entries = codeFlowAnalyzerCache.get(nodeId);
        if (entries) {
            const cachedEntry = entries.find((entry) => {
                if (!typeAtStart || !entry.typeAtStart) {
                    return !typeAtStart && !entry.typeAtStart;
                }
                if (!typeAtStart.isIncomplete !== !entry.typeAtStart.isIncomplete) {
                    return false;
                }
                return (0, types_1.isTypeSame)(typeAtStart.type, entry.typeAtStart.type);
            });
            if (cachedEntry) {
                return cachedEntry.codeFlowAnalyzer;
            }
        }
        // Allocate a new code flow analyzer.
        const analyzer = codeFlowEngine.createCodeFlowAnalyzer(typeAtStart);
        if (entries) {
            entries.push({ typeAtStart, codeFlowAnalyzer: analyzer });
        }
        else {
            entries = [{ typeAtStart, codeFlowAnalyzer: analyzer }];
            codeFlowAnalyzerCache.set(nodeId, entries);
        }
        return analyzer;
    }
    // Attempts to determine the type of the reference expression at the
    // point in the code. If the code flow analysis has nothing to say
    // about that expression, it returns un undefined type. Normally
    // flow analysis starts from the reference node, but startNode can be
    // specified to override this in a few special cases (functions and
    // lambdas) to support analysis of captured variables.
    function getFlowTypeOfReference(reference, startNode, options) {
        var _a;
        // See if this execution scope requires code flow for this reference expression.
        const referenceKey = (0, codeFlowTypes_1.createKeyForReference)(reference);
        const executionNode = ParseTreeUtils.getExecutionScopeNode((_a = startNode === null || startNode === void 0 ? void 0 : startNode.parent) !== null && _a !== void 0 ? _a : reference);
        const codeFlowExpressions = AnalyzerNodeInfo.getCodeFlowExpressions(executionNode);
        if (!codeFlowExpressions ||
            (!codeFlowExpressions.has(referenceKey) && !codeFlowExpressions.has(codeFlowTypes_1.wildcardImportReferenceKey))) {
            return { type: undefined, isIncomplete: false };
        }
        if (checkCodeFlowTooComplex(reference)) {
            return { type: undefined, isIncomplete: true };
        }
        // Is there an code flow analyzer cached for this execution scope?
        let analyzer;
        if (isNodeInReturnTypeInferenceContext(executionNode)) {
            // If we're performing the analysis within a temporary
            // context of a function for purposes of inferring its
            // return type for a specified set of arguments, use
            // a temporary analyzer that we'll use only for this context.
            analyzer = getCodeFlowAnalyzerForReturnTypeInferenceContext();
        }
        else {
            analyzer = getCodeFlowAnalyzerForNode(executionNode.id, options === null || options === void 0 ? void 0 : options.typeAtStart);
        }
        const flowNode = AnalyzerNodeInfo.getFlowNode(startNode !== null && startNode !== void 0 ? startNode : reference);
        if (flowNode === undefined) {
            return { type: undefined, isIncomplete: false };
        }
        return analyzer.getTypeFromCodeFlow(flowNode, reference, options);
    }
    // Specializes the specified (potentially generic) class type using
    // the specified type arguments, reporting errors as appropriate.
    // Returns the specialized type and a boolean indicating whether
    // the type indicates a class type (true) or an object type (false).
    function createSpecializedClassType(classType, typeArgs, flags, errorNode) {
        // Handle the special-case classes that are not defined
        // in the type stubs.
        if (types_1.ClassType.isSpecialBuiltIn(classType)) {
            const aliasedName = classType.aliasName || classType.details.name;
            switch (aliasedName) {
                case 'Callable': {
                    return { type: createCallableType(classType, typeArgs, errorNode) };
                }
                case 'Never': {
                    if (typeArgs && typeArgs.length > 0) {
                        addError(localize_1.LocMessage.typeArgsExpectingNone().format({ name: 'Never' }), typeArgs[0].node);
                    }
                    return { type: types_1.NeverType.createNever() };
                }
                case 'NoReturn': {
                    if (typeArgs && typeArgs.length > 0) {
                        addError(localize_1.LocMessage.typeArgsExpectingNone().format({ name: 'NoReturn' }), typeArgs[0].node);
                    }
                    return { type: types_1.NeverType.createNoReturn() };
                }
                case 'Optional': {
                    return { type: createOptionalType(classType, errorNode, typeArgs, flags) };
                }
                case 'Type': {
                    let typeType = createSpecialType(classType, typeArgs, 1, 
                    /* allowParamSpec */ undefined, 
                    /* isSpecialForm */ false);
                    if ((0, types_1.isInstantiableClass)(typeType)) {
                        typeType = (0, typeUtils_1.explodeGenericClass)(typeType);
                    }
                    return { type: typeType };
                }
                case 'ClassVar': {
                    return { type: createClassVarType(classType, errorNode, typeArgs, flags) };
                }
                case 'Protocol': {
                    if ((flags &
                        (67108864 /* EvaluatorFlags.DisallowNonTypeSpecialForms */ | 256 /* EvaluatorFlags.ExpectingTypeAnnotation */)) !==
                        0) {
                        addError(localize_1.LocMessage.protocolNotAllowed(), errorNode);
                    }
                    return {
                        type: createSpecialType(classType, typeArgs, 
                        /* paramLimit */ undefined, 
                        /* allowParamSpec */ true),
                    };
                }
                case 'TypedDict': {
                    if ((flags &
                        (67108864 /* EvaluatorFlags.DisallowNonTypeSpecialForms */ | 256 /* EvaluatorFlags.ExpectingTypeAnnotation */)) !==
                        0) {
                        addError(localize_1.LocMessage.typedDictNotAllowed(), errorNode);
                    }
                    break;
                }
                case 'Literal': {
                    if ((flags &
                        (67108864 /* EvaluatorFlags.DisallowNonTypeSpecialForms */ | 256 /* EvaluatorFlags.ExpectingTypeAnnotation */)) !==
                        0) {
                        addError(localize_1.LocMessage.literalNotAllowed(), errorNode);
                    }
                    break;
                }
                case 'Tuple': {
                    return {
                        type: createSpecialType(classType, typeArgs, 
                        /* paramLimit */ undefined, 
                        /* allowParamSpec */ false, 
                        /* isSpecialForm */ false),
                    };
                }
                case 'Union': {
                    return { type: createUnionType(classType, errorNode, typeArgs, flags) };
                }
                case 'Generic': {
                    return { type: createGenericType(classType, errorNode, typeArgs, flags) };
                }
                case 'Final': {
                    return { type: createFinalType(classType, errorNode, typeArgs, flags) };
                }
                case 'Annotated': {
                    return createAnnotatedType(classType, errorNode, typeArgs);
                }
                case 'Concatenate': {
                    return { type: createConcatenateType(classType, errorNode, typeArgs, flags) };
                }
                case 'TypeGuard':
                case 'TypeIs': {
                    return { type: createTypeGuardType(classType, errorNode, typeArgs, flags) };
                }
                case 'Unpack': {
                    return { type: createUnpackType(classType, errorNode, typeArgs, flags) };
                }
                case 'Required':
                case 'NotRequired': {
                    return createRequiredOrReadOnlyType(classType, errorNode, typeArgs, flags);
                }
                case 'ReadOnly': {
                    return createRequiredOrReadOnlyType(classType, errorNode, typeArgs, flags);
                }
                case 'Self': {
                    return { type: createSelfType(classType, errorNode, typeArgs, flags) };
                }
                case 'LiteralString': {
                    return { type: createSpecialType(classType, typeArgs, 0) };
                }
            }
        }
        const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
        if (fileInfo.isStubFile ||
            fileInfo.executionEnvironment.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_9) ||
            (0, analyzerFileInfo_1.isAnnotationEvaluationPostponed)(AnalyzerNodeInfo.getFileInfo(errorNode)) ||
            (flags & 4 /* EvaluatorFlags.AllowForwardReferences */) !== 0) {
            // Handle "type" specially, since it needs to act like "Type"
            // in Python 3.9 and newer.
            if (types_1.ClassType.isBuiltIn(classType, 'type') && typeArgs) {
                if (typeArgs.length >= 1) {
                    // Treat type[function] as illegal.
                    if ((0, types_1.isFunction)(typeArgs[0].type) || (0, types_1.isOverloadedFunction)(typeArgs[0].type)) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm, localize_1.LocMessage.typeAnnotationWithCallable(), typeArgs[0].node);
                        return { type: types_1.UnknownType.create() };
                    }
                }
                if (typeClassType && (0, types_1.isInstantiableClass)(typeClassType)) {
                    let typeType = createSpecialType(typeClassType, typeArgs, 1, 
                    /* allowParamSpec */ undefined, 
                    /* isSpecialForm */ false);
                    if ((0, types_1.isInstantiableClass)(typeType)) {
                        typeType = (0, typeUtils_1.explodeGenericClass)(typeType);
                    }
                    return { type: typeType };
                }
            }
            // Handle "tuple" specially, since it needs to act like "Tuple"
            // in Python 3.9 and newer.
            if ((0, typeUtils_1.isTupleClass)(classType)) {
                return {
                    type: createSpecialType(classType, typeArgs, 
                    /* paramLimit */ undefined, 
                    /* allowParamSpec */ undefined, 
                    /* isSpecialForm */ false),
                };
            }
        }
        let typeArgCount = typeArgs ? typeArgs.length : 0;
        // Make sure the argument list count is correct.
        const typeParameters = types_1.ClassType.isPseudoGenericClass(classType) ? [] : types_1.ClassType.getTypeParameters(classType);
        // If there are no type parameters or args, the class is already specialized.
        // No need to do any more work.
        if (typeParameters.length === 0 && typeArgCount === 0) {
            return { type: classType };
        }
        const variadicTypeParamIndex = typeParameters.findIndex((param) => (0, types_1.isVariadicTypeVar)(param));
        if (typeArgs) {
            let minTypeArgCount = typeParameters.length;
            const firstDefaultParamIndex = typeParameters.findIndex((param) => !!param.details.isDefaultExplicit);
            if (firstDefaultParamIndex >= 0) {
                minTypeArgCount = firstDefaultParamIndex;
            }
            // Classes that accept inlined type dict type args allow only one.
            if (typeArgs[0].inlinedTypeDict) {
                if (typeArgs.length > 1) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsTooMany().format({
                        name: classType.aliasName || classType.details.name,
                        expected: 1,
                        received: typeArgCount,
                    }), typeArgs[1].node);
                }
                return { type: typeArgs[0].inlinedTypeDict };
            }
            else if (typeArgCount > typeParameters.length) {
                if (!types_1.ClassType.isPartiallyEvaluated(classType) && !types_1.ClassType.isTupleClass(classType)) {
                    if (typeParameters.length === 0) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsExpectingNone().format({
                            name: classType.aliasName || classType.details.name,
                        }), typeArgs[typeParameters.length].node);
                    }
                    else if (typeParameters.length !== 1 || !(0, types_1.isParamSpec)(typeParameters[0])) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsTooMany().format({
                            name: classType.aliasName || classType.details.name,
                            expected: typeParameters.length,
                            received: typeArgCount,
                        }), typeArgs[typeParameters.length].node);
                    }
                    typeArgCount = typeParameters.length;
                }
            }
            else if (typeArgCount < minTypeArgCount) {
                addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeArgsTooFew().format({
                    name: classType.aliasName || classType.details.name,
                    expected: minTypeArgCount,
                    received: typeArgCount,
                }), typeArgs.length > 0 ? typeArgs[0].node.parent : errorNode);
            }
            typeArgs.forEach((typeArg, index) => {
                if (index === variadicTypeParamIndex) {
                    // The types that make up the tuple that maps to the variadic
                    // type variable have already been validated when the tuple
                    // object was created in adjustTypeArgumentsForVariadicTypeVar.
                    if ((0, types_1.isClassInstance)(typeArg.type) && (0, typeUtils_1.isTupleClass)(typeArg.type)) {
                        return;
                    }
                    if ((0, types_1.isVariadicTypeVar)(typeArg.type)) {
                        validateVariadicTypeVarIsUnpacked(typeArg.type, typeArg.node);
                        return;
                    }
                }
                const typeParam = index < typeParameters.length ? typeParameters[index] : undefined;
                const isParamSpecTarget = typeParam === null || typeParam === void 0 ? void 0 : typeParam.details.isParamSpec;
                validateTypeArg(typeArg, {
                    allowParamSpec: true,
                    allowTypeArgList: isParamSpecTarget,
                });
            });
        }
        // Handle ParamSpec arguments and fill in any missing type arguments with Unknown.
        let typeArgTypes = [];
        const fullTypeParams = types_1.ClassType.getTypeParameters(classType);
        // PEP 612 says that if the class has only one type parameter consisting
        // of a ParamSpec, the list of arguments does not need to be enclosed in
        // a list. We'll handle that case specially here.
        if (fullTypeParams.length === 1 && fullTypeParams[0].details.isParamSpec && typeArgs) {
            if (typeArgs.every((typeArg) => !(0, typeUtils_1.isEllipsisType)(typeArg.type) && !typeArg.typeList && !(0, types_1.isParamSpec)(typeArg.type))) {
                if (typeArgs.length !== 1 ||
                    !(0, types_1.isInstantiableClass)(typeArgs[0].type) ||
                    !types_1.ClassType.isBuiltIn(typeArgs[0].type, 'Concatenate')) {
                    // Package up the type arguments into a typeList.
                    typeArgs = [
                        {
                            type: types_1.UnknownType.create(),
                            node: typeArgs[0].node,
                            typeList: typeArgs,
                        },
                    ];
                }
            }
            else if (typeArgs.length > 1) {
                const paramSpecTypeArg = typeArgs.find((typeArg) => (0, types_1.isParamSpec)(typeArg.type));
                if (paramSpecTypeArg) {
                    addError(localize_1.LocMessage.paramSpecContext(), paramSpecTypeArg.node);
                }
                const listTypeArg = typeArgs.find((typeArg) => !!typeArg.typeList);
                if (listTypeArg) {
                    addError(localize_1.LocMessage.typeArgListNotAllowed(), listTypeArg.node);
                }
            }
        }
        const typeVarContext = new typeVarContext_1.TypeVarContext(classType.details.typeVarScopeId);
        fullTypeParams.forEach((typeParam, index) => {
            if (typeArgs && index < typeArgs.length) {
                if (typeParam.details.isParamSpec) {
                    const typeArg = typeArgs[index];
                    const functionType = types_1.FunctionType.createSynthesizedInstance('', 65536 /* FunctionTypeFlags.ParamSpecValue */);
                    if ((0, typeUtils_1.isEllipsisType)(typeArg.type)) {
                        types_1.FunctionType.addDefaultParameters(functionType);
                        functionType.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
                        typeArgTypes.push(functionType);
                        typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(functionType));
                        return;
                    }
                    if (typeArg.typeList) {
                        typeArg.typeList.forEach((paramType, paramIndex) => {
                            types_1.FunctionType.addParameter(functionType, {
                                category: 0 /* ParameterCategory.Simple */,
                                name: `__p${paramIndex}`,
                                isNameSynthesized: true,
                                type: (0, typeUtils_1.convertToInstance)(paramType.type),
                                hasDeclaredType: true,
                            });
                        });
                        if (typeArg.typeList.length > 0) {
                            types_1.FunctionType.addPositionOnlyParameterSeparator(functionType);
                        }
                        typeArgTypes.push(functionType);
                        typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(functionType));
                        return;
                    }
                    if ((0, types_1.isInstantiableClass)(typeArg.type) && types_1.ClassType.isBuiltIn(typeArg.type, 'Concatenate')) {
                        const concatTypeArgs = typeArg.type.typeArguments;
                        if (concatTypeArgs && concatTypeArgs.length > 0) {
                            concatTypeArgs.forEach((typeArg, index) => {
                                if (index === concatTypeArgs.length - 1) {
                                    if ((0, types_1.isParamSpec)(typeArg)) {
                                        functionType.details.paramSpec = typeArg;
                                    }
                                    else if ((0, typeUtils_1.isEllipsisType)(typeArg)) {
                                        types_1.FunctionType.addDefaultParameters(functionType);
                                        functionType.details.flags |=
                                            32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
                                    }
                                }
                                else {
                                    types_1.FunctionType.addParameter(functionType, {
                                        category: 0 /* ParameterCategory.Simple */,
                                        name: `__p${index}`,
                                        isNameSynthesized: true,
                                        hasDeclaredType: true,
                                        type: typeArg,
                                    });
                                }
                            });
                        }
                        typeArgTypes.push(functionType);
                        return;
                    }
                }
                const typeArgType = (0, typeUtils_1.convertToInstance)(typeArgs[index].type);
                typeArgTypes.push(typeArgType);
                typeVarContext.setTypeVarType(typeParam, typeArgType);
                return;
            }
            const solvedDefaultType = (0, typeUtils_1.applySolvedTypeVars)(typeParam, typeVarContext, { unknownIfNotFound: true });
            typeArgTypes.push(solvedDefaultType);
            if ((0, types_1.isParamSpec)(typeParam)) {
                typeVarContext.setTypeVarType(typeParam, (0, typeUtils_1.convertTypeToParamSpecValue)(solvedDefaultType));
            }
            else {
                typeVarContext.setTypeVarType(typeParam, solvedDefaultType);
            }
        });
        typeArgTypes = typeArgTypes.map((typeArgType, index) => {
            if (index < typeArgCount) {
                const diag = new diagnostic_1.DiagnosticAddendum();
                let adjustedTypeArgType = applyTypeArgToTypeVar(typeParameters[index], typeArgType, diag);
                // Determine if the variance must match.
                if (adjustedTypeArgType && (flags & 16384 /* EvaluatorFlags.EnforceTypeVarVarianceConsistency */) !== 0) {
                    const destType = typeParameters[index];
                    const declaredVariance = destType.details.declaredVariance;
                    if (!(0, typeUtils_1.isVarianceOfTypeArgumentCompatible)(adjustedTypeArgType, declaredVariance)) {
                        diag.addMessage(localize_1.LocAddendum.varianceMismatchForClass().format({
                            typeVarName: printType(adjustedTypeArgType),
                            className: classType.details.name,
                        }));
                        adjustedTypeArgType = undefined;
                    }
                }
                if (adjustedTypeArgType) {
                    typeArgType = adjustedTypeArgType;
                }
                else {
                    // Avoid emitting this error for a partially-constructed class.
                    if (!(0, types_1.isClassInstance)(typeArgType) || !types_1.ClassType.isPartiallyEvaluated(typeArgType)) {
                        (0, debug_1.assert)(typeArgs !== undefined);
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments, localize_1.LocMessage.typeVarAssignmentMismatch().format({
                            type: printType(typeArgType),
                            name: types_1.TypeVarType.getReadableName(typeParameters[index]),
                        }) + diag.getString(), typeArgs[index].node);
                    }
                }
            }
            return typeArgType;
        });
        // If the class is partially constructed and doesn't yet have
        // type parameters, assume that the number and types of supplied type
        // arguments are correct.
        if (typeArgs && classType.details.typeParameters.length === 0 && types_1.ClassType.isPartiallyEvaluated(classType)) {
            typeArgTypes = typeArgs.map((t) => (0, typeUtils_1.convertToInstance)(t.type));
        }
        const specializedClass = types_1.ClassType.cloneForSpecialization(classType, typeArgTypes, typeArgs !== undefined);
        return { type: specializedClass };
    }
    function getTypeOfArgument(arg, inferenceContext) {
        if (arg.typeResult) {
            return { type: arg.typeResult.type, isIncomplete: arg.typeResult.isIncomplete };
        }
        if (!arg.valueExpression) {
            // We shouldn't ever get here, but just in case.
            return { type: types_1.UnknownType.create() };
        }
        // If there was no defined type provided, there should always
        // be a value expression from which we can retrieve the type.
        return getTypeOfExpression(arg.valueExpression, /* flags */ undefined, inferenceContext);
    }
    // This function is like getTypeOfArgument except that it is
    // used in cases where the argument is expected to be a type
    // and therefore follows the normal rules of types (e.g. they
    // can be forward-declared in stubs, etc.).
    function getTypeOfArgumentExpectingType(arg, options) {
        if (arg.typeResult) {
            return { type: arg.typeResult.type, isIncomplete: arg.typeResult.isIncomplete };
        }
        // If there was no defined type provided, there should always
        // be a value expression from which we can retrieve the type.
        (0, debug_1.assert)(arg.valueExpression !== undefined);
        return getTypeOfExpressionExpectingType(arg.valueExpression, options);
    }
    function getTypeOfExpressionExpectingType(node, options) {
        let flags = 128 /* EvaluatorFlags.ExpectingInstantiableType */ |
            8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
            131072 /* EvaluatorFlags.DisallowClassVar */;
        if (options === null || options === void 0 ? void 0 : options.allowTypeVarsWithoutScopeId) {
            flags |= 4096 /* EvaluatorFlags.AllowTypeVarsWithoutScopeId */;
        }
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        if (fileInfo.isStubFile || (options === null || options === void 0 ? void 0 : options.allowForwardReference)) {
            flags |= 4 /* EvaluatorFlags.AllowForwardReferences */;
        }
        else {
            flags |= 4194304 /* EvaluatorFlags.InterpreterParsesStringLiteral */;
        }
        if (!options || !options.allowFinal) {
            flags |= 16 /* EvaluatorFlags.DisallowFinal */;
        }
        if (options === null || options === void 0 ? void 0 : options.allowRequired) {
            flags |= 1048576 /* EvaluatorFlags.AllowRequired */ | 256 /* EvaluatorFlags.ExpectingTypeAnnotation */;
        }
        if (options === null || options === void 0 ? void 0 : options.allowUnpackedTuple) {
            flags |= 2097152 /* EvaluatorFlags.AllowUnpackedTupleOrTypeVarTuple */;
        }
        else {
            flags |= 64 /* EvaluatorFlags.DisallowTypeVarTuple */;
        }
        if (!options || !options.allowParamSpec) {
            flags |= 32 /* EvaluatorFlags.DisallowParamSpec */;
        }
        if (options === null || options === void 0 ? void 0 : options.enforceTypeAnnotationRules) {
            flags |= 256 /* EvaluatorFlags.ExpectingTypeAnnotation */;
        }
        if (options === null || options === void 0 ? void 0 : options.disallowProtocolAndTypedDict) {
            flags |= 67108864 /* EvaluatorFlags.DisallowNonTypeSpecialForms */;
        }
        return getTypeOfExpression(node, flags);
    }
    function getBuiltInType(node, name) {
        const scope = ScopeUtils.getScopeForNode(node);
        if (scope) {
            const builtInScope = ScopeUtils.getBuiltInScope(scope);
            const nameType = builtInScope.lookUpSymbol(name);
            if (nameType) {
                return getEffectiveTypeOfSymbol(nameType);
            }
        }
        return types_1.UnknownType.create();
    }
    function getBuiltInObject(node, name, typeArguments) {
        const nameType = getBuiltInType(node, name);
        if ((0, types_1.isInstantiableClass)(nameType)) {
            let classType = nameType;
            if (typeArguments) {
                classType = types_1.ClassType.cloneForSpecialization(classType, typeArguments, 
                /* isTypeArgumentExplicit */ typeArguments !== undefined);
            }
            return types_1.ClassType.cloneAsInstance(classType);
        }
        return nameType;
    }
    function lookUpSymbolRecursive(node, name, honorCodeFlow, preferGlobalScope = false) {
        var _a;
        const scope = ScopeUtils.getScopeForNode(node);
        let symbolWithScope = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbolRecursive(name);
        const scopeType = (_a = scope === null || scope === void 0 ? void 0 : scope.type) !== null && _a !== void 0 ? _a : 3 /* ScopeType.Module */;
        // Functions and list comprehensions don't allow access to implicitly
        // aliased symbols in outer scopes if they haven't yet been assigned
        // within the local scope.
        const scopeTypeHonorsCodeFlow = scopeType !== 1 /* ScopeType.Function */ && scopeType !== 0 /* ScopeType.ListComprehension */;
        if (symbolWithScope && honorCodeFlow && scopeTypeHonorsCodeFlow) {
            // Filter the declarations based on flow reachability.
            const reachableDecl = symbolWithScope.symbol.getDeclarations().find((decl) => {
                if (decl.type !== 8 /* DeclarationType.Alias */ && decl.type !== 0 /* DeclarationType.Intrinsic */) {
                    // Is the declaration in the same execution scope as the "usageNode" node?
                    const usageScope = ParseTreeUtils.getExecutionScopeNode(node);
                    const declNode = decl.type === 6 /* DeclarationType.Class */ ||
                        decl.type === 5 /* DeclarationType.Function */ ||
                        decl.type === 4 /* DeclarationType.TypeAlias */
                        ? decl.node.name
                        : decl.node;
                    const declScope = ParseTreeUtils.getExecutionScopeNode(declNode);
                    if (usageScope === declScope) {
                        if (!isFlowPathBetweenNodes(declNode, node)) {
                            // If there was no control flow path from the usage back
                            // to the source, see if the usage node is reachable by
                            // any path.
                            const flowNode = AnalyzerNodeInfo.getFlowNode(node);
                            const isReachable = flowNode &&
                                codeFlowEngine.isFlowNodeReachable(flowNode, 
                                /* sourceFlowNode */ undefined, 
                                /* ignoreNoReturn */ true);
                            return !isReachable;
                        }
                    }
                }
                return true;
            });
            // If none of the declarations are reachable from the current node,
            // search for the symbol in outer scopes.
            if (!reachableDecl) {
                if (symbolWithScope.scope.type !== 1 /* ScopeType.Function */) {
                    let nextScopeToSearch = symbolWithScope.scope.parent;
                    const isOutsideCallerModule = symbolWithScope.isOutsideCallerModule || symbolWithScope.scope.type === 3 /* ScopeType.Module */;
                    let isBeyondExecutionScope = symbolWithScope.isBeyondExecutionScope || symbolWithScope.scope.isIndependentlyExecutable();
                    if (symbolWithScope.scope.type === 2 /* ScopeType.Class */) {
                        // There is an odd documented behavior for classes in that
                        // symbol resolution skips to the global scope rather than
                        // the next scope in the chain.
                        const globalScopeResult = symbolWithScope.scope.getGlobalScope();
                        nextScopeToSearch = globalScopeResult.scope;
                        if (globalScopeResult.isBeyondExecutionScope) {
                            isBeyondExecutionScope = true;
                        }
                    }
                    if (nextScopeToSearch) {
                        symbolWithScope = nextScopeToSearch.lookUpSymbolRecursive(name, isOutsideCallerModule, isBeyondExecutionScope);
                    }
                    else {
                        symbolWithScope = undefined;
                    }
                }
                else {
                    symbolWithScope = undefined;
                }
            }
        }
        // PEP 563 indicates that if a forward reference can be resolved in the module
        // scope (or, by implication, in the builtins scope), it should prefer that
        // resolution over local resolutions.
        if (symbolWithScope && preferGlobalScope) {
            let curSymbolWithScope = symbolWithScope;
            while (curSymbolWithScope.scope.type !== 3 /* ScopeType.Module */ &&
                curSymbolWithScope.scope.type !== 4 /* ScopeType.Builtin */ &&
                curSymbolWithScope.scope.parent) {
                curSymbolWithScope = curSymbolWithScope.scope.parent.lookUpSymbolRecursive(name, curSymbolWithScope.isOutsideCallerModule, curSymbolWithScope.isBeyondExecutionScope || curSymbolWithScope.scope.isIndependentlyExecutable());
                if (!curSymbolWithScope) {
                    break;
                }
            }
            if ((curSymbolWithScope === null || curSymbolWithScope === void 0 ? void 0 : curSymbolWithScope.scope.type) === 3 /* ScopeType.Module */ ||
                (curSymbolWithScope === null || curSymbolWithScope === void 0 ? void 0 : curSymbolWithScope.scope.type) === 4 /* ScopeType.Builtin */) {
                symbolWithScope = curSymbolWithScope;
            }
        }
        return symbolWithScope;
    }
    // Disables recording of errors and warnings.
    function suppressDiagnostics(node, callback) {
        suppressedNodeStack.push(node);
        try {
            const result = callback();
            suppressedNodeStack.pop();
            return result;
        }
        catch (e) {
            // We don't use finally here because the TypeScript debugger doesn't
            // handle finally well when single stepping.
            suppressedNodeStack.pop();
            throw e;
        }
    }
    // Disables recording of errors and warnings and disables any caching of
    // types, under the assumption that we're performing speculative evaluations.
    // If speculativeNode is undefined, speculative mode is not used. This is
    // useful in cases where we conditionally want to use speculative mode.
    function useSpeculativeMode(speculativeNode, callback, options) {
        if (!speculativeNode) {
            return callback();
        }
        speculativeTypeTracker.enterSpeculativeContext(speculativeNode, options);
        try {
            const result = callback();
            speculativeTypeTracker.leaveSpeculativeContext();
            return result;
        }
        catch (e) {
            // We don't use finally here because the TypeScript debugger doesn't
            // handle finally well when single stepping.
            speculativeTypeTracker.leaveSpeculativeContext();
            throw e;
        }
    }
    function disableSpeculativeMode(callback) {
        const stack = speculativeTypeTracker.disableSpeculativeMode();
        try {
            callback();
            speculativeTypeTracker.enableSpeculativeMode(stack);
        }
        catch (e) {
            // We don't use finally here because the TypeScript debugger doesn't
            // handle finally well when single stepping.
            speculativeTypeTracker.enableSpeculativeMode(stack);
            throw e;
        }
    }
    // Indicates whether the specified node is within a context that
    // is currently being evaluated speculative. If node is undefined,
    // returns true if any node is being evaluated speculatively.
    function isSpeculativeModeInUse(node) {
        return speculativeTypeTracker.isSpeculative(node);
    }
    function getDeclarationFromFunctionNamedParameter(type, paramName) {
        if ((0, types_1.isFunction)(type)) {
            if (type.details.declaration) {
                const functionDecl = type.details.declaration;
                if (functionDecl.type === 5 /* DeclarationType.Function */) {
                    const functionNode = functionDecl.node;
                    const functionScope = AnalyzerNodeInfo.getScope(functionNode);
                    if (functionScope) {
                        const paramSymbol = functionScope.lookUpSymbol(paramName);
                        if (paramSymbol) {
                            return paramSymbol
                                .getDeclarations()
                                .find((decl) => decl.type === 2 /* DeclarationType.Parameter */);
                        }
                        const parameterDetails = (0, parameterUtils_1.getParameterListDetails)(type);
                        if (parameterDetails.unpackedKwargsTypedDictType) {
                            const lookupResults = (0, typeUtils_1.lookUpClassMember)(parameterDetails.unpackedKwargsTypedDictType, paramName);
                            if (lookupResults) {
                                return lookupResults.symbol
                                    .getDeclarations()
                                    .find((decl) => decl.type === 1 /* DeclarationType.Variable */);
                            }
                        }
                    }
                }
            }
        }
        return undefined;
    }
    // In general, string nodes don't have any declarations associated with them, but
    // we need to handle the special case of string literals used as keys within a
    // dictionary expression where those keys are associated with a known TypedDict.
    function getDeclarationsForStringNode(node) {
        var _a;
        const declarations = [];
        const expectedType = (_a = getExpectedType(node)) === null || _a === void 0 ? void 0 : _a.type;
        if (expectedType) {
            (0, typeUtils_1.doForEachSubtype)(expectedType, (subtype) => {
                var _a, _b;
                // If the expected type is a TypedDict then the node is either a key expression
                // or a single entry in a set. We then need to check that the value of the node
                // is a valid entry in the TypedDict to avoid resolving declarations for
                // synthesized symbols such as 'get'.
                if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
                    const entry = (_a = subtype.details.typedDictEntries) === null || _a === void 0 ? void 0 : _a.knownItems.get(node.value);
                    if (entry) {
                        const symbol = (_b = (0, typeUtils_1.lookUpObjectMember)(subtype, node.value)) === null || _b === void 0 ? void 0 : _b.symbol;
                        if (symbol) {
                            (0, collectionUtils_1.appendArray)(declarations, symbol.getDeclarations());
                        }
                    }
                }
            });
        }
        return declarations.length === 0 ? undefined : declarations;
    }
    function getAliasFromImport(node) {
        if (node.parent &&
            node.parent.nodeType === 23 /* ParseNodeType.ImportFromAs */ &&
            node.parent.alias &&
            node === node.parent.name) {
            return node.parent.alias;
        }
        return undefined;
    }
    function getDeclarationsForNameNode(node, skipUnreachableCode = true) {
        var _a, _b, _c;
        if (skipUnreachableCode && AnalyzerNodeInfo.isCodeUnreachable(node)) {
            return undefined;
        }
        const declarations = [];
        // If the node is part of a "from X import Y as Z" statement and the node
        // is the "Y" (non-aliased) name, we need to look up the alias symbol
        // since the non-aliased name is not in the symbol table.
        const alias = getAliasFromImport(node);
        if (alias) {
            const scope = ScopeUtils.getScopeForNode(node);
            if (scope) {
                // Look up the alias symbol.
                const symbolInScope = scope.lookUpSymbolRecursive(alias.value);
                if (symbolInScope) {
                    // The alias could have more decls that don't refer to this import. Filter
                    // out the one(s) that specifically associated with this import statement.
                    const declsForThisImport = symbolInScope.symbol.getDeclarations().filter((decl) => {
                        return decl.type === 8 /* DeclarationType.Alias */ && decl.node === node.parent;
                    });
                    (0, collectionUtils_1.appendArray)(declarations, (0, declarationUtils_1.getDeclarationsWithUsesLocalNameRemoved)(declsForThisImport));
                }
            }
        }
        else if (node.parent &&
            node.parent.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
            node === node.parent.memberName) {
            let baseType = getType(node.parent.leftExpression);
            if (baseType) {
                baseType = makeTopLevelTypeVarsConcrete(baseType);
                const memberName = node.parent.memberName.value;
                (0, typeUtils_1.doForEachSubtype)(baseType, (subtype) => {
                    let symbol;
                    subtype = makeTopLevelTypeVarsConcrete(subtype);
                    if ((0, types_1.isInstantiableClass)(subtype)) {
                        // Try to find a member that has a declared type. If so, that
                        // overrides any inferred types.
                        let member = (0, typeUtils_1.lookUpClassMember)(subtype, memberName, 64 /* MemberAccessFlags.DeclaredTypesOnly */);
                        if (!member) {
                            member = (0, typeUtils_1.lookUpClassMember)(subtype, memberName);
                        }
                        if (!member) {
                            const metaclass = subtype.details.effectiveMetaclass;
                            if (metaclass && (0, types_1.isInstantiableClass)(metaclass)) {
                                member = (0, typeUtils_1.lookUpClassMember)(metaclass, memberName);
                            }
                        }
                        if (member) {
                            symbol = member.symbol;
                        }
                    }
                    else if ((0, types_1.isClassInstance)(subtype)) {
                        // Try to find a member that has a declared type. If so, that
                        // overrides any inferred types.
                        let member = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName, 64 /* MemberAccessFlags.DeclaredTypesOnly */);
                        if (!member) {
                            member = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName);
                        }
                        if (member) {
                            symbol = member.symbol;
                        }
                    }
                    else if ((0, types_1.isModule)(subtype)) {
                        symbol = types_1.ModuleType.getField(subtype, memberName);
                    }
                    if (symbol) {
                        // By default, report only the declarations that have type annotations.
                        // If there are none, then report all of the unannotated declarations,
                        // which includes every assignment of that symbol.
                        const typedDecls = symbol.getTypedDeclarations();
                        if (typedDecls.length > 0) {
                            (0, collectionUtils_1.appendArray)(declarations, typedDecls);
                        }
                        else {
                            (0, collectionUtils_1.appendArray)(declarations, symbol.getDeclarations());
                        }
                    }
                });
            }
        }
        else if (node.parent && node.parent.nodeType === 37 /* ParseNodeType.ModuleName */) {
            const namePartIndex = node.parent.nameParts.findIndex((part) => part === node);
            const importInfo = AnalyzerNodeInfo.getImportInfo(node.parent);
            if (namePartIndex >= 0 &&
                importInfo &&
                !importInfo.isNativeLib &&
                namePartIndex < importInfo.resolvedUris.length) {
                if (importInfo.resolvedUris[namePartIndex]) {
                    evaluateTypesForStatement(node);
                    // Synthesize an alias declaration for this name part. The only
                    // time this case is used is for IDE services such as
                    // the find all references, hover provider and etc.
                    declarations.push((0, declarationUtils_1.createSynthesizedAliasDeclaration)(importInfo.resolvedUris[namePartIndex]));
                }
            }
        }
        else if (node.parent && node.parent.nodeType === 1 /* ParseNodeType.Argument */ && node === node.parent.name) {
            // The target node is the name in a named argument. We need to determine whether
            // the corresponding named parameter can be determined from the context.
            const argNode = node.parent;
            const paramName = node.value;
            if (((_a = argNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 9 /* ParseNodeType.Call */) {
                const baseType = getType(argNode.parent.leftExpression);
                if (baseType) {
                    if ((0, types_1.isFunction)(baseType) && baseType.details.declaration) {
                        const paramDecl = getDeclarationFromFunctionNamedParameter(baseType, paramName);
                        if (paramDecl) {
                            declarations.push(paramDecl);
                        }
                    }
                    else if ((0, types_1.isOverloadedFunction)(baseType)) {
                        baseType.overloads.forEach((f) => {
                            const paramDecl = getDeclarationFromFunctionNamedParameter(f, paramName);
                            if (paramDecl) {
                                declarations.push(paramDecl);
                            }
                        });
                    }
                    else if ((0, types_1.isInstantiableClass)(baseType)) {
                        const initMethodType = (_b = (0, constructors_1.getBoundInitMethod)(evaluatorInterface, argNode.parent.leftExpression, types_1.ClassType.cloneAsInstance(baseType))) === null || _b === void 0 ? void 0 : _b.type;
                        if (initMethodType && (0, types_1.isFunction)(initMethodType)) {
                            const paramDecl = getDeclarationFromFunctionNamedParameter(initMethodType, paramName);
                            if (paramDecl) {
                                declarations.push(paramDecl);
                            }
                            else if (types_1.ClassType.isDataClass(baseType) || types_1.ClassType.isTypedDictClass(baseType)) {
                                const lookupResults = (0, typeUtils_1.lookUpClassMember)(baseType, paramName);
                                if (lookupResults) {
                                    (0, collectionUtils_1.appendArray)(declarations, lookupResults.symbol.getDeclarations());
                                }
                            }
                        }
                    }
                }
            }
            else if (((_c = argNode.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 10 /* ParseNodeType.Class */) {
                const classTypeResult = getTypeOfClass(argNode.parent);
                // Validate the init subclass args for this class so we can properly
                // evaluate its custom keyword parameters.
                if (classTypeResult) {
                    validateInitSubclassArgs(argNode.parent, classTypeResult.classType);
                }
            }
        }
        else {
            const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
            // Determine if this node is within a quoted type annotation.
            const isWithinTypeAnnotation = ParseTreeUtils.isWithinTypeAnnotation(node, !(0, analyzerFileInfo_1.isAnnotationEvaluationPostponed)(AnalyzerNodeInfo.getFileInfo(node)));
            // Determine if this is part of a "type" statement.
            const isWithinTypeAliasStatement = !!ParseTreeUtils.getParentNodeOfType(node, 77 /* ParseNodeType.TypeAlias */);
            const allowForwardReferences = isWithinTypeAnnotation || isWithinTypeAliasStatement || fileInfo.isStubFile;
            let symbol;
            const typeParamSymbol = AnalyzerNodeInfo.getTypeParameterSymbol(node);
            if (typeParamSymbol) {
                symbol = typeParamSymbol;
            }
            else {
                const symbolWithScope = lookUpSymbolRecursive(node, node.value, !allowForwardReferences, isWithinTypeAnnotation);
                symbol = symbolWithScope === null || symbolWithScope === void 0 ? void 0 : symbolWithScope.symbol;
            }
            if (symbol) {
                (0, collectionUtils_1.appendArray)(declarations, symbol.getDeclarations());
            }
        }
        return declarations;
    }
    function getTypeForDeclaration(declaration) {
        var _a, _b, _c, _d;
        switch (declaration.type) {
            case 0 /* DeclarationType.Intrinsic */: {
                if (declaration.intrinsicType === 'Any') {
                    return { type: types_1.AnyType.create() };
                }
                if (declaration.intrinsicType === 'class') {
                    const classNode = ParseTreeUtils.getEnclosingClass(declaration.node);
                    const classTypeInfo = getTypeOfClass(classNode);
                    return { type: classTypeInfo === null || classTypeInfo === void 0 ? void 0 : classTypeInfo.classType };
                }
                const strType = getBuiltInObject(declaration.node, 'str');
                const intType = getBuiltInObject(declaration.node, 'int');
                if ((0, types_1.isClassInstance)(intType) && (0, types_1.isClassInstance)(strType)) {
                    if (declaration.intrinsicType === 'str') {
                        return { type: strType };
                    }
                    if (declaration.intrinsicType === 'str | None') {
                        return { type: (0, types_1.combineTypes)([strType, getNoneType()]) };
                    }
                    if (declaration.intrinsicType === 'int') {
                        return { type: intType };
                    }
                    if (declaration.intrinsicType === 'Iterable[str]') {
                        const iterableType = getBuiltInType(declaration.node, 'Iterable');
                        if ((0, types_1.isInstantiableClass)(iterableType)) {
                            return {
                                type: types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(iterableType, [strType], 
                                /* isTypeArgumentExplicit */ true)),
                            };
                        }
                    }
                    if (declaration.intrinsicType === 'Dict[str, Any]') {
                        const dictType = getBuiltInType(declaration.node, 'dict');
                        if ((0, types_1.isInstantiableClass)(dictType)) {
                            return {
                                type: types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForSpecialization(dictType, [strType, types_1.AnyType.create()], 
                                /* isTypeArgumentExplicit */ true)),
                            };
                        }
                    }
                }
                return { type: types_1.UnknownType.create() };
            }
            case 6 /* DeclarationType.Class */: {
                const classTypeInfo = getTypeOfClass(declaration.node);
                return { type: classTypeInfo === null || classTypeInfo === void 0 ? void 0 : classTypeInfo.decoratedType };
            }
            case 7 /* DeclarationType.SpecialBuiltInClass */: {
                return { type: getTypeOfAnnotation(declaration.node.typeAnnotation) };
            }
            case 5 /* DeclarationType.Function */: {
                const functionTypeInfo = getTypeOfFunction(declaration.node);
                return { type: functionTypeInfo === null || functionTypeInfo === void 0 ? void 0 : functionTypeInfo.decoratedType };
            }
            case 4 /* DeclarationType.TypeAlias */: {
                return { type: getTypeOfTypeAlias(declaration.node) };
            }
            case 2 /* DeclarationType.Parameter */: {
                let typeAnnotationNode = declaration.node.typeAnnotation || declaration.node.typeAnnotationComment;
                // If there wasn't an annotation, see if the parent function
                // has a function-level annotation comment that provides
                // this parameter's annotation type.
                if (!typeAnnotationNode) {
                    if (((_a = declaration.node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 28 /* ParseNodeType.Function */) {
                        const functionNode = declaration.node.parent;
                        if (functionNode.functionAnnotationComment &&
                            !functionNode.functionAnnotationComment.isParamListEllipsis) {
                            const paramIndex = functionNode.parameters.findIndex((param) => param === declaration.node);
                            typeAnnotationNode = ParseTreeUtils.getTypeAnnotationForParameter(functionNode, paramIndex);
                        }
                    }
                }
                if (typeAnnotationNode) {
                    const declaredType = getTypeOfParameterAnnotation(typeAnnotationNode, declaration.node.category);
                    return {
                        type: transformVariadicParamType(declaration.node, declaration.node.category, adjustParameterAnnotatedType(declaration.node, declaredType)),
                    };
                }
                return { type: undefined };
            }
            case 3 /* DeclarationType.TypeParameter */: {
                return { type: getTypeOfTypeParameter(declaration.node) };
            }
            case 1 /* DeclarationType.Variable */: {
                const typeAnnotationNode = declaration.typeAnnotationNode;
                if (typeAnnotationNode) {
                    let declaredType;
                    if (declaration.isRuntimeTypeExpression) {
                        declaredType = (0, typeUtils_1.convertToInstance)(getTypeOfExpressionExpectingType(typeAnnotationNode, {
                            allowFinal: true,
                            allowRequired: true,
                        }).type);
                    }
                    else {
                        const declNode = declaration.isDefinedByMemberAccess &&
                            ((_b = declaration.node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 35 /* ParseNodeType.MemberAccess */
                            ? declaration.node.parent
                            : declaration.node;
                        declaredType = getTypeOfAnnotation(typeAnnotationNode, {
                            isVariableAnnotation: true,
                            allowClassVar: ParseTreeUtils.isClassVarAllowedForAssignmentTarget(declNode),
                            allowFinal: ParseTreeUtils.isFinalAllowedForAssignmentTarget(declNode),
                            allowRequired: ParseTreeUtils.isRequiredAllowedForAssignmentTarget(declNode),
                        });
                    }
                    if (declaredType) {
                        // Apply enum transform if appropriate.
                        if (declaration.node.nodeType === 38 /* ParseNodeType.Name */) {
                            const variableNode = (_c = ParseTreeUtils.getParentNodeOfType(declaration.node, 3 /* ParseNodeType.Assignment */)) !== null && _c !== void 0 ? _c : ParseTreeUtils.getParentNodeOfType(declaration.node, 54 /* ParseNodeType.TypeAnnotation */);
                            if (variableNode) {
                                declaredType =
                                    (_d = (0, enums_1.transformTypeForPossibleEnumClass)(evaluatorInterface, variableNode, declaration.node, () => {
                                        return { declaredType };
                                    })) !== null && _d !== void 0 ? _d : declaredType;
                            }
                        }
                        if ((0, types_1.isClassInstance)(declaredType) && types_1.ClassType.isBuiltIn(declaredType, 'TypeAlias')) {
                            return { type: undefined, isTypeAlias: true };
                        }
                        return { type: declaredType };
                    }
                }
                return { type: undefined };
            }
            case 8 /* DeclarationType.Alias */: {
                return { type: undefined };
            }
        }
    }
    function getTypeOfTypeParameter(node) {
        // Is this type already cached?
        const cachedTypeVarType = readTypeCache(node.name, 0 /* EvaluatorFlags.None */);
        if (cachedTypeVarType && (0, types_1.isTypeVar)(cachedTypeVarType)) {
            return cachedTypeVarType;
        }
        let runtimeClassName = 'TypeVar';
        if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
            runtimeClassName = 'TypeVarTuple';
        }
        else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
            runtimeClassName = 'ParamSpec';
        }
        const runtimeType = getTypingType(node, runtimeClassName);
        const runtimeClass = runtimeType && (0, types_1.isInstantiableClass)(runtimeType) ? runtimeType : undefined;
        let typeVar = types_1.TypeVarType.createInstantiable(node.name.value, node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec);
        if (runtimeClass) {
            typeVar = types_1.TypeBase.cloneAsSpecialForm(typeVar, types_1.ClassType.cloneAsInstance(runtimeClass));
        }
        typeVar.details.isTypeParamSyntax = true;
        if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
            typeVar.details.isVariadic = true;
        }
        // Cache the value before we evaluate the bound or the default type in
        // case it refers to itself in a circular manner.
        writeTypeCache(node, { type: typeVar }, /* flags */ undefined);
        writeTypeCache(node.name, { type: typeVar }, /* flags */ undefined);
        if (node.boundExpression) {
            if (node.boundExpression.nodeType === 52 /* ParseNodeType.Tuple */) {
                const constraints = node.boundExpression.expressions.map((constraint) => {
                    const constraintType = getTypeOfExpressionExpectingType(constraint, {
                        disallowProtocolAndTypedDict: true,
                        allowForwardReference: true,
                    }).type;
                    if ((0, typeUtils_1.requiresSpecialization)(constraintType, {
                        ignorePseudoGeneric: true,
                        ignoreImplicitTypeArgs: true,
                    })) {
                        addError(localize_1.LocMessage.typeVarBoundGeneric(), constraint);
                    }
                    return (0, typeUtils_1.convertToInstance)(constraintType);
                });
                if (constraints.length < 2) {
                    addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeVarSingleConstraint(), node.boundExpression);
                }
                else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
                    typeVar.details.constraints = constraints;
                }
            }
            else {
                const boundType = getTypeOfExpressionExpectingType(node.boundExpression, {
                    disallowProtocolAndTypedDict: true,
                    allowForwardReference: true,
                }).type;
                if ((0, typeUtils_1.requiresSpecialization)(boundType, { ignorePseudoGeneric: true })) {
                    addError(localize_1.LocMessage.typeVarConstraintGeneric(), node.boundExpression);
                }
                if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVar) {
                    typeVar.details.boundType = (0, typeUtils_1.convertToInstance)(boundType);
                }
            }
        }
        if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
            const defaultType = node.defaultExpression
                ? getParamSpecDefaultType(node.defaultExpression, /* isPep695Syntax */ true)
                : undefined;
            if (defaultType) {
                typeVar.details.defaultType = defaultType;
                typeVar.details.isDefaultExplicit = true;
            }
            else {
                typeVar.details.defaultType = (0, typeUtils_1.getUnknownTypeForParamSpec)();
            }
        }
        else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
            const defaultType = node.defaultExpression
                ? getTypeVarTupleDefaultType(node.defaultExpression, /* isPep695Syntax */ true)
                : undefined;
            if (defaultType) {
                typeVar.details.defaultType = defaultType;
                typeVar.details.isDefaultExplicit = true;
            }
            else {
                typeVar.details.defaultType = makeTupleObject([{ type: types_1.UnknownType.create(), isUnbounded: true }]);
            }
        }
        else {
            const defaultType = node.defaultExpression
                ? (0, typeUtils_1.convertToInstance)(getTypeOfExpressionExpectingType(node.defaultExpression, { allowForwardReference: true }).type)
                : undefined;
            if (defaultType) {
                typeVar.details.defaultType = defaultType;
                typeVar.details.isDefaultExplicit = true;
            }
            else {
                typeVar.details.defaultType = types_1.UnknownType.create();
            }
        }
        // If a default is provided, make sure it is compatible with the bound
        // or constraint.
        if (typeVar.details.isDefaultExplicit && node.defaultExpression) {
            verifyTypeVarDefaultIsCompatible(typeVar, node.defaultExpression);
        }
        // Associate the type variable with the owning scope.
        const scopeNode = ParseTreeUtils.getTypeVarScopeNode(node);
        if (scopeNode) {
            let scopeType;
            if (scopeNode.nodeType === 10 /* ParseNodeType.Class */) {
                scopeType = 0 /* TypeVarScopeType.Class */;
                // Set the variance to "auto" for class-scoped TypeVars.
                typeVar.details.declaredVariance = 0 /* Variance.Auto */;
            }
            else if (scopeNode.nodeType === 28 /* ParseNodeType.Function */) {
                scopeType = 1 /* TypeVarScopeType.Function */;
            }
            else {
                (0, debug_1.assert)(scopeNode.nodeType === 77 /* ParseNodeType.TypeAlias */);
                scopeType = 2 /* TypeVarScopeType.TypeAlias */;
            }
            typeVar = types_1.TypeVarType.cloneForScopeId(typeVar, ParseTreeUtils.getScopeIdForNode(scopeNode.nodeType === 77 /* ParseNodeType.TypeAlias */ ? scopeNode.name : scopeNode), scopeNode.name.value, scopeType);
        }
        return typeVar;
    }
    function getInferredTypeOfDeclaration(symbol, decl) {
        var _a, _b, _c, _d;
        const resolvedDecl = resolveAliasDeclaration(decl, /* resolveLocalNames */ true, {
            allowExternallyHiddenAccess: AnalyzerNodeInfo.getFileInfo(decl.node).isStubFile,
        });
        // We couldn't resolve the alias. Substitute an unknown
        // type in this case.
        if (!resolvedDecl) {
            return evaluatorOptions.evaluateUnknownImportsAsAny ? types_1.AnyType.create() : types_1.UnknownType.create();
        }
        function applyLoaderActionsToModuleType(moduleType, loaderActions, importLookup) {
            if (!loaderActions.uri.isEmpty() && loaderActions.loadSymbolsFromPath) {
                const lookupResults = importLookup(loaderActions.uri);
                if (lookupResults) {
                    moduleType.fields = lookupResults.symbolTable;
                    moduleType.docString = lookupResults.docString;
                }
                else {
                    // Note that all module attributes that are not found in the
                    // symbol table should be treated as Any or Unknown rather than
                    // as an error.
                    moduleType.notPresentFieldType = evaluatorOptions.evaluateUnknownImportsAsAny
                        ? types_1.AnyType.create()
                        : types_1.UnknownType.create();
                }
            }
            if (loaderActions.implicitImports) {
                loaderActions.implicitImports.forEach((implicitImport, name) => {
                    // Recursively apply loader actions.
                    let symbolType;
                    if (implicitImport.isUnresolved) {
                        symbolType = types_1.UnknownType.create();
                    }
                    else {
                        const moduleName = moduleType.moduleName ? moduleType.moduleName + '.' + name : '';
                        const importedModuleType = types_1.ModuleType.create(moduleName, implicitImport.uri);
                        symbolType = applyLoaderActionsToModuleType(importedModuleType, implicitImport, importLookup);
                    }
                    const importedModuleSymbol = symbol_1.Symbol.createWithType(0 /* SymbolFlags.None */, symbolType);
                    moduleType.loaderFields.set(name, importedModuleSymbol);
                });
            }
            return moduleType;
        }
        // If the resolved declaration is still an alias, the alias
        // is pointing at a module, and we need to synthesize a
        // module type.
        if (resolvedDecl.type === 8 /* DeclarationType.Alias */) {
            // Build a module type that corresponds to the declaration and
            // its associated loader actions.
            const moduleType = types_1.ModuleType.create(resolvedDecl.moduleName, resolvedDecl.uri);
            if (resolvedDecl.symbolName && resolvedDecl.submoduleFallback) {
                return applyLoaderActionsToModuleType(moduleType, resolvedDecl.submoduleFallback, importLookup);
            }
            else {
                return applyLoaderActionsToModuleType(moduleType, resolvedDecl, importLookup);
            }
        }
        const declaredType = getTypeForDeclaration(resolvedDecl);
        if (declaredType.type) {
            return declaredType.type;
        }
        // If this is part of a "py.typed" package, don't fall back on type inference
        // unless it's marked Final, is a constant, or is a declared type alias.
        const fileInfo = AnalyzerNodeInfo.getFileInfo(resolvedDecl.node);
        let isUnambiguousType = !fileInfo.isInPyTypedPackage || fileInfo.isStubFile;
        // If this is a py.typed package, determine if this is a case where an unannotated
        // variable is considered "unambiguous" because all type checkers are almost
        // guaranteed to infer its type the same.
        if (!isUnambiguousType) {
            if (resolvedDecl.type === 1 /* DeclarationType.Variable */) {
                // Special-case variables within an enum class. These are effectively
                // constants, so we'll treat them as unambiguous.
                const enclosingClass = ParseTreeUtils.getEnclosingClass(resolvedDecl.node, /* stopAtFunction */ true);
                if (enclosingClass) {
                    const classTypeInfo = getTypeOfClass(enclosingClass);
                    if (classTypeInfo && types_1.ClassType.isEnumClass(classTypeInfo.classType)) {
                        isUnambiguousType = true;
                    }
                }
                // Special-case constants, which are treated as unambiguous.
                if (isFinalVariableDeclaration(resolvedDecl) || resolvedDecl.isConstant) {
                    isUnambiguousType = true;
                }
                // Special-case calls to certain built-in type functions.
                if (((_a = resolvedDecl.inferredTypeSource) === null || _a === void 0 ? void 0 : _a.nodeType) === 9 /* ParseNodeType.Call */) {
                    const baseTypeResult = getTypeOfExpression(resolvedDecl.inferredTypeSource.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                    const callType = baseTypeResult.type;
                    const exemptBuiltins = [
                        'TypeVar',
                        'ParamSpec',
                        'TypeVarTuple',
                        'TypedDict',
                        'NamedTuple',
                        'NewType',
                    ];
                    if ((0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, exemptBuiltins)) {
                        isUnambiguousType = true;
                    }
                    else if ((0, types_1.isFunction)(callType) &&
                        exemptBuiltins.some((name) => callType.details.builtInName === name)) {
                        isUnambiguousType = true;
                    }
                }
            }
        }
        // If the resolved declaration had no defined type, use the
        // inferred type for this node.
        if (resolvedDecl.type === 2 /* DeclarationType.Parameter */) {
            (0, debug_1.assert)(resolvedDecl.node.name !== undefined);
            return (_b = evaluateTypeForSubnode(resolvedDecl.node.name, () => {
                evaluateTypeOfParameter(resolvedDecl.node);
            })) === null || _b === void 0 ? void 0 : _b.type;
        }
        if (resolvedDecl.type === 1 /* DeclarationType.Variable */ && resolvedDecl.inferredTypeSource) {
            const isTypeAlias = isExplicitTypeAliasDeclaration(resolvedDecl) || isPossibleTypeAliasOrTypedDict(resolvedDecl);
            // If this is a type alias, evaluate types for the entire assignment
            // statement rather than just the RHS of the assignment.
            const typeSource = isTypeAlias && resolvedDecl.inferredTypeSource.parent
                ? resolvedDecl.inferredTypeSource.parent
                : resolvedDecl.inferredTypeSource;
            let inferredType = (_c = evaluateTypeForSubnode(resolvedDecl.node, () => {
                evaluateTypesForStatement(typeSource);
            })) === null || _c === void 0 ? void 0 : _c.type;
            if (inferredType && resolvedDecl.node.nodeType === 38 /* ParseNodeType.Name */) {
                const variableNode = (_d = ParseTreeUtils.getParentNodeOfType(resolvedDecl.node, 3 /* ParseNodeType.Assignment */)) !== null && _d !== void 0 ? _d : ParseTreeUtils.getParentNodeOfType(resolvedDecl.node, 54 /* ParseNodeType.TypeAnnotation */);
                if (variableNode) {
                    // See if this is an enum member. If so, we need to handle it as a special case.
                    const enumMemberType = (0, enums_1.transformTypeForPossibleEnumClass)(evaluatorInterface, variableNode, resolvedDecl.node, () => {
                        var _a, _b;
                        (0, debug_1.assert)(resolvedDecl.inferredTypeSource !== undefined);
                        const inferredTypeSource = resolvedDecl.inferredTypeSource;
                        return {
                            assignedType: (_b = (_a = evaluateTypeForSubnode(inferredTypeSource, () => {
                                evaluateTypesForStatement(inferredTypeSource);
                            })) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : types_1.UnknownType.create(),
                        };
                    });
                    if (enumMemberType) {
                        inferredType = enumMemberType;
                    }
                }
            }
            if (inferredType && isTypeAlias && resolvedDecl.typeAliasName) {
                // If this was a speculative type alias, it becomes a real type alias only
                // in the event that its inferred type is instantiable or explicitly Any
                // (but not an ellipsis).
                if (isLegalImplicitTypeAliasType(inferredType)) {
                    inferredType = transformTypeForTypeAlias(inferredType, resolvedDecl.typeAliasName, resolvedDecl.node, 
                    /* isPep695Syntax */ false, 
                    /* isPep695TypeVarType */ false);
                    isUnambiguousType = true;
                }
            }
            // Determine whether we need to mark the annotation as ambiguous.
            if (inferredType && fileInfo.isInPyTypedPackage && !fileInfo.isStubFile) {
                if (!isUnambiguousType) {
                    // See if this particular inference can be considered "unambiguous".
                    // Any symbol that is assigned more than once is considered ambiguous.
                    if (isUnambiguousInference(symbol, decl, inferredType)) {
                        isUnambiguousType = true;
                    }
                }
                if (!isUnambiguousType) {
                    inferredType = types_1.TypeBase.cloneForAmbiguousType(inferredType);
                }
            }
            return inferredType;
        }
        return undefined;
    }
    // Applies some heuristics to determine whether it's likely that all Python
    // type checkers will infer the same type.
    function isUnambiguousInference(symbol, decl, inferredType) {
        var _a;
        const nonSlotsDecls = symbol.getDeclarations().filter((decl) => {
            return decl.type !== 1 /* DeclarationType.Variable */ || !decl.isInferenceAllowedInPyTyped;
        });
        // Any symbol with more than one assignment is considered ambiguous.
        if (nonSlotsDecls.length > 1) {
            return false;
        }
        if (decl.type !== 1 /* DeclarationType.Variable */) {
            return false;
        }
        // If there are no non-slots declarations, don't mark the inferred type as ambiguous.
        if (nonSlotsDecls.length === 0) {
            return true;
        }
        // TypeVar definitions don't require a declaration.
        if ((0, types_1.isTypeVar)(inferredType)) {
            return true;
        }
        let assignmentNode;
        const parentNode = decl.node.parent;
        if (parentNode) {
            // Is this a simple assignment (x = y) or an assignment of an instance variable (self.x = y)?
            if (parentNode.nodeType === 3 /* ParseNodeType.Assignment */) {
                assignmentNode = parentNode;
            }
            else if (parentNode.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                ((_a = parentNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 3 /* ParseNodeType.Assignment */) {
                assignmentNode = parentNode.parent;
            }
        }
        if (!assignmentNode) {
            return false;
        }
        const assignedType = getTypeOfExpression(assignmentNode.rightExpression).type;
        // Assume that literal values will always result in the same inferred type.
        if ((0, types_1.isClassInstance)(assignedType) && (0, typeUtils_1.isLiteralType)(assignedType)) {
            return true;
        }
        // If the assignment is a simple name corresponding to an unambiguous
        // type, we'll assume the resulting variable will receive the same
        // unambiguous type.
        if (assignmentNode.rightExpression.nodeType === 38 /* ParseNodeType.Name */ && !types_1.TypeBase.isAmbiguous(assignedType)) {
            return true;
        }
        return false;
    }
    // If the specified declaration is an alias declaration that points to a symbol,
    // it resolves the alias and looks up the symbol, then returns the first declaration
    // associated with that symbol. It does this recursively if necessary. If a symbol
    // lookup fails, undefined is returned. If resolveLocalNames is true, the method
    // resolves aliases through local renames ("as" clauses found in import statements).
    function resolveAliasDeclaration(declaration, resolveLocalNames, options) {
        var _a, _b, _c;
        return (_c = (0, declarationUtils_1.resolveAliasDeclaration)(importLookup, declaration, {
            resolveLocalNames,
            allowExternallyHiddenAccess: (_a = options === null || options === void 0 ? void 0 : options.allowExternallyHiddenAccess) !== null && _a !== void 0 ? _a : false,
            skipFileNeededCheck: (_b = options === null || options === void 0 ? void 0 : options.skipFileNeededCheck) !== null && _b !== void 0 ? _b : false,
        })) === null || _c === void 0 ? void 0 : _c.declaration;
    }
    function resolveAliasDeclarationWithInfo(declaration, resolveLocalNames, options) {
        var _a, _b;
        return (0, declarationUtils_1.resolveAliasDeclaration)(importLookup, declaration, {
            resolveLocalNames,
            allowExternallyHiddenAccess: (_a = options === null || options === void 0 ? void 0 : options.allowExternallyHiddenAccess) !== null && _a !== void 0 ? _a : false,
            skipFileNeededCheck: (_b = options === null || options === void 0 ? void 0 : options.skipFileNeededCheck) !== null && _b !== void 0 ? _b : false,
        });
    }
    // Returns the type of the symbol. If the type is explicitly declared, that type
    // is returned. If not, the type is inferred from assignments to the symbol. All
    // assigned types are evaluated and combined into a union.
    function getEffectiveTypeOfSymbol(symbol) {
        return getEffectiveTypeOfSymbolForUsage(symbol).type;
    }
    // If a "usageNode" node is specified, only declarations that are outside
    // of the current execution scope or that are reachable (as determined by
    // code flow analysis) are considered. This helps in cases where there
    // are cyclical dependencies between symbols.
    function getEffectiveTypeOfSymbolForUsage(symbol, usageNode, useLastDecl = false) {
        let declaredTypeInfo;
        // If there's a declared type, it takes precedence over inferred types.
        if (symbol.hasTypedDeclarations()) {
            declaredTypeInfo = getDeclaredTypeOfSymbol(symbol, usageNode);
            const declaredType = declaredTypeInfo === null || declaredTypeInfo === void 0 ? void 0 : declaredTypeInfo.type;
            let isIncomplete = false;
            if (declaredType) {
                if ((0, types_1.isFunction)(declaredType) && types_1.FunctionType.isPartiallyEvaluated(declaredType)) {
                    isIncomplete = true;
                }
                else if ((0, types_1.isClass)(declaredType) && types_1.ClassType.isPartiallyEvaluated(declaredType)) {
                    isIncomplete = true;
                }
            }
            // If the "declared" type uses a "TypeAlias" type annotation, then
            // we need to use the inferred type path to evaluate its type.
            if (declaredType || !declaredTypeInfo.isTypeAlias) {
                const typedDecls = symbol.getTypedDeclarations();
                const result = {
                    type: declaredType !== null && declaredType !== void 0 ? declaredType : types_1.UnknownType.create(),
                    isIncomplete,
                    includesVariableDecl: typedDecls.some((decl) => decl.type === 1 /* DeclarationType.Variable */),
                    includesIllegalTypeAliasDecl: !typedDecls.every((decl) => isPossibleTypeAliasDeclaration(decl)),
                    includesSpeculativeResult: false,
                    isRecursiveDefinition: !declaredType,
                };
                return result;
            }
        }
        return inferTypeOfSymbolForUsage(symbol, usageNode, useLastDecl);
    }
    function inferTypeOfSymbolForUsage(symbol, usageNode, useLastDecl = false) {
        // Look in the inferred type cache to see if we've computed this already.
        let cacheEntries = effectiveTypeCache.get(symbol.id);
        const usageNodeId = usageNode ? usageNode.id : undefined;
        const effectiveTypeCacheKey = `${usageNodeId === undefined ? '.' : usageNodeId.toString()}${useLastDecl ? '*' : ''}`;
        const cacheEntry = cacheEntries === null || cacheEntries === void 0 ? void 0 : cacheEntries.get(effectiveTypeCacheKey);
        if (cacheEntry && !cacheEntry.isIncomplete) {
            return cacheEntry;
        }
        // Infer the type.
        const decls = symbol.getDeclarations();
        let declIndexToConsider;
        // Limit the number of declarations to explore.
        if (decls.length > maxDeclarationsToUseForInference) {
            const result = {
                type: types_1.UnknownType.create(),
                isIncomplete: false,
                includesVariableDecl: false,
                includesIllegalTypeAliasDecl: !decls.every((decl) => isPossibleTypeAliasDeclaration(decl)),
                includesSpeculativeResult: false,
                isRecursiveDefinition: false,
            };
            addToEffectiveTypeCache(result);
            return result;
        }
        // If the caller has requested that we use only the last decl, we
        // will use only the last one, but we'll ignore decls that are in
        // except clauses.
        if (useLastDecl) {
            decls.forEach((decl, index) => {
                if (!decl.isInExceptSuite) {
                    declIndexToConsider = index;
                }
            });
        }
        else {
            // Handle the case where there are multiple imports — one of them in
            // a try block and one or more in except blocks. In this case, we'll
            // use the one in the try block rather than the excepts.
            if (decls.length > 1 && decls.every((decl) => decl.type === 8 /* DeclarationType.Alias */)) {
                const nonExceptDecls = decls.filter((decl) => decl.type === 8 /* DeclarationType.Alias */ && !decl.isInExceptSuite);
                if (nonExceptDecls.length === 1) {
                    declIndexToConsider = decls.findIndex((decl) => decl === nonExceptDecls[0]);
                }
            }
        }
        // Determine which declarations to use for inference.
        const declsToConsider = [];
        let includesVariableDecl = false;
        let includesIllegalTypeAliasDecl = false;
        let sawExplicitTypeAlias = false;
        decls.forEach((decl, index) => {
            var _a, _b, _c;
            const resolvedDecl = (_a = resolveAliasDeclaration(decl, /* resolveLocalNames */ true, {
                allowExternallyHiddenAccess: AnalyzerNodeInfo.getFileInfo(decl.node).isStubFile,
            })) !== null && _a !== void 0 ? _a : decl;
            if (!isPossibleTypeAliasDeclaration(resolvedDecl) && !isExplicitTypeAliasDeclaration(resolvedDecl)) {
                includesIllegalTypeAliasDecl = true;
            }
            if (resolvedDecl.type === 1 /* DeclarationType.Variable */) {
                // Exempt typing.pyi, which uses variables to define some
                // special forms like Any.
                const fileInfo = AnalyzerNodeInfo.getFileInfo(resolvedDecl.node);
                if (!fileInfo.isTypingStubFile) {
                    includesVariableDecl = true;
                }
            }
            if (declIndexToConsider !== undefined && declIndexToConsider !== index) {
                return;
            }
            // If we have already seen an explicit type alias, do not consider
            // additional decls. This can happen if multiple TypeAlias declarations
            // are provided -- normally an error, but it can happen in stdlib stubs
            // if the user sets the pythonPlatform to "All".
            if (sawExplicitTypeAlias) {
                return;
            }
            // If the symbol is explicitly marked as a ClassVar, consider only the
            // declarations that assign to it from within the class body, not through
            // a member access expression.
            if ((0, symbolUtils_1.isEffectivelyClassVar)(symbol, /* isDataclass */ false) &&
                decl.type === 1 /* DeclarationType.Variable */ &&
                decl.isDefinedByMemberAccess) {
                return;
            }
            if (usageNode !== undefined) {
                if (decl.type !== 8 /* DeclarationType.Alias */) {
                    // Is the declaration in the same execution scope as the "usageNode" node?
                    // If so, we can skip it because code flow analysis will allow us
                    // to determine the type in this context.
                    const usageScope = ParseTreeUtils.getExecutionScopeNode(usageNode);
                    const declScope = ParseTreeUtils.getExecutionScopeNode(decl.node);
                    if (usageScope === declScope) {
                        return;
                    }
                }
            }
            const isExplicitTypeAlias = isExplicitTypeAliasDeclaration(resolvedDecl);
            const isTypeAlias = isExplicitTypeAlias || isPossibleTypeAliasOrTypedDict(resolvedDecl);
            if (isExplicitTypeAlias) {
                sawExplicitTypeAlias = true;
            }
            // If this is a type alias, evaluate it outside of the recursive symbol
            // resolution check so we can evaluate the full assignment statement.
            if (isTypeAlias &&
                resolvedDecl.type === 1 /* DeclarationType.Variable */ &&
                ((_c = (_b = resolvedDecl.inferredTypeSource) === null || _b === void 0 ? void 0 : _b.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 3 /* ParseNodeType.Assignment */) {
                evaluateTypesForAssignmentStatement(resolvedDecl.inferredTypeSource.parent);
            }
            declsToConsider.push(resolvedDecl);
        });
        const result = getTypeOfSymbolForDecls(symbol, declsToConsider, effectiveTypeCacheKey);
        result.includesVariableDecl = includesVariableDecl;
        result.includesIllegalTypeAliasDecl = includesIllegalTypeAliasDecl;
        // Add the result to the effective type cache if it doesn't include speculative results.
        if (!result.includesSpeculativeResult) {
            addToEffectiveTypeCache(result);
        }
        return result;
        function addToEffectiveTypeCache(result) {
            // Add the entry to the cache so we don't need to compute it next time.
            if (!cacheEntries) {
                cacheEntries = new Map();
                effectiveTypeCache.set(symbol.id, cacheEntries);
            }
            cacheEntries.set(effectiveTypeCacheKey, result);
        }
    }
    // Returns the type of a symbol based on a subset of its declarations.
    function getTypeOfSymbolForDecls(symbol, decls, typeCacheKey) {
        var _a, _b;
        const typesToCombine = [];
        let isIncomplete = false;
        let sawPendingEvaluation = false;
        let includesSpeculativeResult = false;
        decls.forEach((decl) => {
            if (pushSymbolResolution(symbol, decl)) {
                try {
                    let type = getInferredTypeOfDeclaration(symbol, decl);
                    if (!popSymbolResolution(symbol)) {
                        isIncomplete = true;
                    }
                    if (type) {
                        if (decl.type === 1 /* DeclarationType.Variable */) {
                            let isConstant = false;
                            if (decl.type === 1 /* DeclarationType.Variable */) {
                                if (decl.isConstant || isFinalVariableDeclaration(decl)) {
                                    isConstant = true;
                                }
                            }
                            // Treat enum values declared within an enum class as though they are const even
                            // though they may not be named as such.
                            if ((0, types_1.isClassInstance)(type) &&
                                types_1.ClassType.isEnumClass(type) &&
                                (0, enums_1.isDeclInEnumClass)(evaluatorInterface, decl)) {
                                isConstant = true;
                            }
                            // If the symbol is constant, we can retain the literal
                            // value. Otherwise, strip literal values to widen the type.
                            if (types_1.TypeBase.isInstance(type) && !isConstant && !isExplicitTypeAliasDeclaration(decl)) {
                                type = stripLiteralValue(type);
                            }
                        }
                        typesToCombine.push(type);
                        if (isSpeculativeModeInUse(decl.node)) {
                            includesSpeculativeResult = true;
                        }
                    }
                    else {
                        isIncomplete = true;
                    }
                }
                catch (e) {
                    // Clean up the stack before rethrowing.
                    popSymbolResolution(symbol);
                    throw e;
                }
            }
            else {
                if (decl.type === 6 /* DeclarationType.Class */) {
                    const classTypeInfo = getTypeOfClass(decl.node);
                    if (classTypeInfo === null || classTypeInfo === void 0 ? void 0 : classTypeInfo.decoratedType) {
                        typesToCombine.push(classTypeInfo.decoratedType);
                    }
                }
                isIncomplete = true;
                // Note that at least one decl could not be evaluated because
                // it was already in the process of being evaluated.
                sawPendingEvaluation = true;
            }
        });
        // How many times have we already attempted to evaluate this declaration already?
        const cacheEntries = effectiveTypeCache.get(symbol.id);
        const evaluationAttempts = ((_b = (_a = cacheEntries === null || cacheEntries === void 0 ? void 0 : cacheEntries.get(typeCacheKey)) === null || _a === void 0 ? void 0 : _a.evaluationAttempts) !== null && _b !== void 0 ? _b : 0) + 1;
        let type;
        if (typesToCombine.length > 0) {
            // Ignore the pending evaluation flag if we've already attempted the
            // type evaluation many times because this probably means there's a
            // cyclical dependency that cannot be broken.
            isIncomplete = sawPendingEvaluation && evaluationAttempts < maxEffectiveTypeEvaluationAttempts;
            type = (0, types_1.combineTypes)(typesToCombine);
        }
        else {
            type = types_1.UnboundType.create();
        }
        return { type, isIncomplete, includesSpeculativeResult, evaluationAttempts };
    }
    // If a declaration has an explicit type (e.g. a variable with an annotation),
    // this function evaluates the type and returns it. If the symbol has no
    // explicit declared type, its type will need to be inferred instead. In some
    // cases, non-type information (such as Final or ClassVar attributes) may be
    // provided, but type inference is still required. In such cases, the attributes
    // are returned as flags.
    function getDeclaredTypeOfSymbol(symbol, usageNode) {
        const synthesizedType = symbol.getSynthesizedType();
        if (synthesizedType) {
            return { type: synthesizedType };
        }
        let typedDecls = symbol.getTypedDeclarations();
        if (typedDecls.length === 0) {
            // If the symbol has no type declaration but is assigned many times,
            // treat it as though it has an explicit type annotation of "Unknown".
            // This will avoid a pathological performance condition for unannotated
            // code that reassigns the same variable hundreds of times. If the symbol
            // effectively has an "Any" annotation, it won't be narrowed.
            if (symbol.getDeclarations().length > maxDeclarationsToUseForInference) {
                return { type: types_1.UnknownType.create() };
            }
            // There was no declaration with a defined type.
            return { type: undefined };
        }
        // If there is more than one typed decl, filter out any that are not
        // reachable from the usage node (if specified). This can happen in
        // cases where a property symbol is redefined to add a setter, deleter,
        // etc.
        if (usageNode && typedDecls.length > 1) {
            const filteredTypedDecls = typedDecls.filter((decl) => {
                if (decl.type !== 8 /* DeclarationType.Alias */) {
                    // Is the declaration in the same execution scope as the "usageNode" node?
                    const usageScope = ParseTreeUtils.getExecutionScopeNode(usageNode);
                    const declScope = ParseTreeUtils.getExecutionScopeNode(decl.node);
                    if (usageScope === declScope) {
                        if (!isFlowPathBetweenNodes(decl.node, usageNode, /* allowSelf */ false)) {
                            return false;
                        }
                    }
                }
                return true;
            });
            if (filteredTypedDecls.length === 0) {
                return { type: types_1.UnboundType.create() };
            }
            typedDecls = filteredTypedDecls;
        }
        // Start with the last decl. If that's already being resolved,
        // use the next-to-last decl, etc. This can happen when resolving
        // property methods. Often the setter method is defined in reference to
        // the initial property, which defines the getter method with the same
        // symbol name.
        let declIndex = typedDecls.length - 1;
        while (declIndex >= 0) {
            const decl = typedDecls[declIndex];
            // If there's a partially-constructed type that is allowed
            // for recursive symbol resolution, return it as the resolved type.
            const partialType = getSymbolResolutionPartialType(symbol, decl);
            if (partialType) {
                return { type: partialType };
            }
            if (getIndexOfSymbolResolution(symbol, decl) < 0) {
                if (pushSymbolResolution(symbol, decl)) {
                    try {
                        const declaredTypeInfo = getTypeForDeclaration(decl);
                        // If there was recursion detected, don't use this declaration.
                        // The exception is it's a class declaration because getTypeOfClass
                        // handles recursion by populating a partially-created class type
                        // in the type cache. This exception is required to handle the
                        // circular dependency between the "type" and "object" classes in
                        // builtins.pyi (since "object" is a "type" and "type" is an "object").
                        if (popSymbolResolution(symbol) || decl.type === 6 /* DeclarationType.Class */) {
                            return declaredTypeInfo;
                        }
                    }
                    catch (e) {
                        // Clean up the stack before rethrowing.
                        popSymbolResolution(symbol);
                        throw e;
                    }
                }
            }
            declIndex--;
        }
        return { type: undefined };
    }
    function inferReturnTypeIfNecessary(type) {
        if ((0, types_1.isFunction)(type)) {
            getFunctionEffectiveReturnType(type);
        }
        else if ((0, types_1.isOverloadedFunction)(type)) {
            type.overloads.forEach((overload) => {
                getFunctionEffectiveReturnType(overload);
            });
        }
    }
    // Returns the return type of the function. If the type is explicitly provided in
    // a type annotation, that type is returned. If not, an attempt is made to infer
    // the return type. If a list of args is provided, the inference logic may take
    // into account argument types to infer the return type.
    function getFunctionEffectiveReturnType(type, args, inferTypeIfNeeded = true) {
        const specializedReturnType = types_1.FunctionType.getSpecializedReturnType(type, /* includeInferred */ false);
        if (specializedReturnType && !(0, types_1.isUnknown)(specializedReturnType)) {
            return adjustCallableReturnType(type, specializedReturnType, /* liveTypeVarScopes */ []);
        }
        if (inferTypeIfNeeded) {
            return getFunctionInferredReturnType(type, args);
        }
        return types_1.UnknownType.create();
    }
    function getFunctionInferredReturnType(type, args) {
        var _a;
        let returnType;
        let isIncomplete = false;
        const analyzeUnannotatedFunctions = true;
        // Don't attempt to infer the return type for a stub file.
        if (types_1.FunctionType.isStubDefinition(type)) {
            return types_1.UnknownType.create();
        }
        // Don't infer the return type for an overloaded function (unless it's synthesized,
        // which is needed for proper operation of the __get__ method in properties).
        if (types_1.FunctionType.isOverloaded(type) && !types_1.FunctionType.isSynthesizedMethod(type)) {
            return types_1.UnknownType.create();
        }
        // If the return type has already been lazily evaluated,
        // don't bother computing it again.
        if (type.inferredReturnType) {
            returnType = type.inferredReturnType;
        }
        else {
            // Don't bother inferring the return type of __init__ because it's
            // always None.
            if (types_1.FunctionType.isInstanceMethod(type) && type.details.name === '__init__') {
                returnType = getNoneType();
            }
            else if (type.details.declaration) {
                const functionNode = type.details.declaration.node;
                const skipUnannotatedFunction = !AnalyzerNodeInfo.getFileInfo(functionNode).diagnosticRuleSet.analyzeUnannotatedFunctions &&
                    ParseTreeUtils.isUnannotatedFunction(functionNode);
                // Skip return type inference if we are in "skip unannotated function" mode.
                if (!skipUnannotatedFunction && !checkCodeFlowTooComplex(functionNode.suite)) {
                    const codeFlowComplexity = AnalyzerNodeInfo.getCodeFlowComplexity(functionNode);
                    // For very complex functions that have no annotated parameter types,
                    // don't attempt to infer the return type because it can be extremely
                    // expensive.
                    const parametersAreAnnotated = type.details.parameters.length <= 1 ||
                        type.details.parameters.some((param) => param.hasDeclaredType);
                    if (parametersAreAnnotated || codeFlowComplexity < maxReturnTypeInferenceCodeFlowComplexity) {
                        // Temporarily disable speculative mode while we
                        // lazily evaluate the return type.
                        let returnTypeResult;
                        disableSpeculativeMode(() => {
                            returnTypeResult = inferFunctionReturnType(functionNode, types_1.FunctionType.isAbstractMethod(type));
                        });
                        returnType = returnTypeResult === null || returnTypeResult === void 0 ? void 0 : returnTypeResult.type;
                        if (returnTypeResult === null || returnTypeResult === void 0 ? void 0 : returnTypeResult.isIncomplete) {
                            isIncomplete = true;
                        }
                    }
                }
            }
            if (!returnType) {
                returnType = types_1.UnknownType.create();
            }
            // Cache the type for next time.
            if (!isIncomplete) {
                type.inferredReturnType = returnType;
            }
        }
        // If the type is partially unknown and the function has one or more unannotated
        // params, try to analyze the function with the provided argument types and
        // attempt to do a better job at inference.
        if (!isIncomplete &&
            analyzeUnannotatedFunctions &&
            (0, typeUtils_1.isPartlyUnknown)(returnType) &&
            types_1.FunctionType.hasUnannotatedParams(type) &&
            !types_1.FunctionType.isStubDefinition(type) &&
            !types_1.FunctionType.isPyTypedDefinition(type) &&
            args) {
            let hasDecorators = false;
            let isAsync = false;
            const declNode = (_a = type.details.declaration) === null || _a === void 0 ? void 0 : _a.node;
            if (declNode) {
                if (declNode.decorators.length > 0) {
                    hasDecorators = true;
                }
                if (declNode.isAsync) {
                    isAsync = true;
                }
            }
            // We can't use this technique if decorators or async are used because they
            // would need to be applied to the inferred return type.
            if (!hasDecorators && !isAsync) {
                const contextualReturnType = getFunctionInferredReturnTypeUsingArguments(type, args);
                if (contextualReturnType) {
                    returnType = contextualReturnType;
                }
            }
        }
        return returnType;
    }
    function getFunctionInferredReturnTypeUsingArguments(type, args) {
        let contextualReturnType;
        if (!type.details.declaration) {
            return undefined;
        }
        const functionNode = type.details.declaration.node;
        const codeFlowComplexity = AnalyzerNodeInfo.getCodeFlowComplexity(functionNode);
        if (codeFlowComplexity >= maxReturnCallSiteTypeInferenceCodeFlowComplexity) {
            return undefined;
        }
        // If an arg hasn't been matched to a specific named parameter,
        // it's an unpacked value that corresponds to multiple parameters.
        // That's an edge case that we don't handle here.
        if (args.some((arg) => !arg.paramName)) {
            return undefined;
        }
        // Detect recurrence. If a function invokes itself either directly
        // or indirectly, we won't attempt to infer contextual return
        // types any further.
        if (returnTypeInferenceContextStack.some((context) => context.functionNode === functionNode)) {
            return undefined;
        }
        const functionType = getTypeOfFunction(functionNode);
        if (!functionType) {
            return undefined;
        }
        // Very complex functions with many arguments can take a long time to analyze,
        // so we'll use a heuristic and avoiding this inference technique for any
        // call site that involves too many arguments.
        if (args.length > maxReturnTypeInferenceArgumentCount) {
            return undefined;
        }
        // Don't explore arbitrarily deep in the call graph.
        if (returnTypeInferenceContextStack.length >= maxReturnTypeInferenceStackSize) {
            return undefined;
        }
        const paramTypes = [];
        let isResultFromCache = false;
        // Suppress diagnostics because we don't want to generate errors.
        suppressDiagnostics(functionNode, () => {
            var _a, _b;
            // Allocate a new temporary type cache for the context of just
            // this function so we can analyze it separately without polluting
            // the main type cache.
            const prevTypeCache = returnTypeInferenceTypeCache;
            returnTypeInferenceContextStack.push({
                functionNode,
                codeFlowAnalyzer: codeFlowEngine.createCodeFlowAnalyzer(/* typeAtStart */ undefined),
            });
            try {
                returnTypeInferenceTypeCache = new Map();
                let allArgTypesAreUnknown = true;
                functionNode.parameters.forEach((param, index) => {
                    if (param.name) {
                        let paramType;
                        const arg = args.find((arg) => param.name.value === arg.paramName);
                        if (arg && arg.argument.valueExpression) {
                            paramType = getTypeOfExpression(arg.argument.valueExpression).type;
                            if (!(0, types_1.isUnknown)(paramType)) {
                                allArgTypesAreUnknown = false;
                            }
                        }
                        else if (param.defaultValue) {
                            paramType = getTypeOfExpression(param.defaultValue).type;
                            if (!(0, types_1.isUnknown)(paramType)) {
                                allArgTypesAreUnknown = false;
                            }
                        }
                        else if (index === 0) {
                            // If this is an instance or class method, use the implied
                            // parameter type for the "self" or "cls" parameter.
                            if (types_1.FunctionType.isInstanceMethod(functionType.functionType) ||
                                types_1.FunctionType.isClassMethod(functionType.functionType)) {
                                if (functionType.functionType.details.parameters.length > 0) {
                                    if (functionNode.parameters[0].name) {
                                        paramType = functionType.functionType.details.parameters[0].type;
                                    }
                                }
                            }
                        }
                        if (!paramType) {
                            paramType = types_1.UnknownType.create();
                        }
                        paramTypes.push(paramType);
                        writeTypeCache(param.name, { type: paramType }, 0 /* EvaluatorFlags.None */);
                    }
                });
                // Don't bother trying to determine the contextual return
                // type if none of the argument types are known.
                if (!allArgTypesAreUnknown) {
                    // See if the return type is already cached. If so, skip the
                    // inference step, which is potentially very expensive.
                    const cacheEntry = (_a = functionType.functionType.callSiteReturnTypeCache) === null || _a === void 0 ? void 0 : _a.find((entry) => {
                        return (entry.paramTypes.length === paramTypes.length &&
                            entry.paramTypes.every((t, i) => (0, types_1.isTypeSame)(t, paramTypes[i])));
                    });
                    if (cacheEntry) {
                        contextualReturnType = cacheEntry.returnType;
                        isResultFromCache = true;
                    }
                    else {
                        contextualReturnType = (_b = inferFunctionReturnType(functionNode, types_1.FunctionType.isAbstractMethod(type))) === null || _b === void 0 ? void 0 : _b.type;
                    }
                }
            }
            finally {
                returnTypeInferenceContextStack.pop();
                returnTypeInferenceTypeCache = prevTypeCache;
            }
        });
        if (contextualReturnType) {
            contextualReturnType = (0, types_1.removeUnbound)(contextualReturnType);
            if (!isResultFromCache) {
                // Cache the resulting type.
                if (!functionType.functionType.callSiteReturnTypeCache) {
                    functionType.functionType.callSiteReturnTypeCache = [];
                }
                if (functionType.functionType.callSiteReturnTypeCache.length >= maxCallSiteReturnTypeCacheSize) {
                    functionType.functionType.callSiteReturnTypeCache =
                        functionType.functionType.callSiteReturnTypeCache.slice(1);
                }
                functionType.functionType.callSiteReturnTypeCache.push({
                    paramTypes,
                    returnType: contextualReturnType,
                });
            }
            return contextualReturnType;
        }
        return undefined;
    }
    function getFunctionDeclaredReturnType(node) {
        const functionTypeInfo = getTypeOfFunction(node);
        if (!functionTypeInfo) {
            // We hit a recursive dependency.
            return types_1.AnyType.create();
        }
        // Ignore this check for abstract methods, which often
        // don't actually return any value.
        if (types_1.FunctionType.isAbstractMethod(functionTypeInfo.functionType)) {
            return types_1.AnyType.create();
        }
        if (types_1.FunctionType.isGenerator(functionTypeInfo.functionType)) {
            return (0, typeUtils_1.getDeclaredGeneratorReturnType)(functionTypeInfo.functionType);
        }
        return functionTypeInfo.functionType.details.declaredReturnType;
    }
    function getTypeOfMember(member) {
        if ((0, types_1.isInstantiableClass)(member.classType)) {
            return (0, typeUtils_1.partiallySpecializeType)(getEffectiveTypeOfSymbol(member.symbol), member.classType, 
            /* selfClass */ undefined, typeClassType !== null && typeClassType !== void 0 ? typeClassType : types_1.UnknownType.create());
        }
        return types_1.UnknownType.create();
    }
    function getTypeOfMemberInternal(errorNode, member, selfClass, flags) {
        if ((0, types_1.isInstantiableClass)(member.classType)) {
            const typeResult = getEffectiveTypeOfSymbolForUsage(member.symbol);
            if (typeResult) {
                // If the type is a function or overloaded function, infer
                // and cache the return type if necessary. This needs to be done
                // prior to specializing.
                inferReturnTypeIfNecessary(typeResult.type);
                if (member.isInstanceMember &&
                    (flags & 1024 /* MemberAccessFlags.DisallowGenericInstanceVariableAccess */) !== 0) {
                    let isGenericNonCallable = false;
                    (0, typeUtils_1.doForEachSubtype)(typeResult.type, (subtype) => {
                        if (!(0, types_1.isAnyOrUnknown)(subtype) && !(0, types_1.isFunction)(subtype) && !(0, types_1.isOverloadedFunction)(subtype)) {
                            if ((0, typeUtils_1.requiresSpecialization)(typeResult.type, {
                                ignoreSelf: true,
                                ignoreImplicitTypeArgs: true,
                            })) {
                                isGenericNonCallable = true;
                            }
                        }
                    });
                    if (isGenericNonCallable && errorNode) {
                        addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.genericInstanceVariableAccess(), errorNode);
                    }
                }
                return {
                    type: (0, typeUtils_1.partiallySpecializeType)(typeResult.type, member.classType, selfClass),
                    isIncomplete: !!typeResult.isIncomplete,
                };
            }
        }
        else if ((0, types_1.isAnyOrUnknown)(member.classType)) {
            return {
                type: member.classType,
                isIncomplete: false,
            };
        }
        return undefined;
    }
    function assignClass(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount, reportErrorsUsingObjType) {
        // If the source or dest types are partially evaluated (i.e. they are in the
        // process of being constructed), assume they are assignable rather than risk
        // emitting false positives.
        if (types_1.ClassType.isHierarchyPartiallyEvaluated(destType) || types_1.ClassType.isHierarchyPartiallyEvaluated(srcType)) {
            return true;
        }
        // Handle typed dicts. They also use a form of structural typing for type
        // checking, as defined in PEP 589.
        if (types_1.ClassType.isTypedDictClass(srcType)) {
            if (types_1.ClassType.isTypedDictClass(destType) && !types_1.ClassType.isSameGenericClass(destType, srcType)) {
                if (!(0, typedDicts_1.assignTypedDictToTypedDict)(evaluatorInterface, destType, srcType, diag, destTypeVarContext, flags, recursionCount)) {
                    return false;
                }
                if (types_1.ClassType.isFinal(destType) !== types_1.ClassType.isFinal(srcType)) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typedDictFinalMismatch().format({
                        sourceType: printType((0, typeUtils_1.convertToInstance)(srcType)),
                        destType: printType((0, typeUtils_1.convertToInstance)(destType)),
                    }));
                    return false;
                }
                // If invariance is being enforced, the two TypedDicts must be assignable to each other.
                if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
                    return (0, typedDicts_1.assignTypedDictToTypedDict)(evaluatorInterface, srcType, destType, 
                    /* diag */ undefined, 
                    /* typeVarContext */ undefined, flags, recursionCount);
                }
                return true;
            }
            // Handle some special cases where a TypedDict can act like
            // a Mapping[str, T] or a dict[str, T].
            if (types_1.ClassType.isBuiltIn(destType, 'Mapping')) {
                const mappingValueType = (0, typedDicts_1.getTypedDictMappingEquivalent)(evaluatorInterface, srcType);
                if (mappingValueType &&
                    mappingType &&
                    (0, types_1.isInstantiableClass)(mappingType) &&
                    strClassType &&
                    (0, types_1.isInstantiableClass)(strClassType)) {
                    srcType = types_1.ClassType.cloneForSpecialization(mappingType, [types_1.ClassType.cloneAsInstance(strClassType), mappingValueType], 
                    /* isTypeArgumentExplicit */ true);
                }
            }
            else if (types_1.ClassType.isBuiltIn(destType, ['dict', 'MutableMapping'])) {
                const dictValueType = (0, typedDicts_1.getTypedDictDictEquivalent)(evaluatorInterface, srcType, recursionCount);
                if (dictValueType &&
                    dictClassType &&
                    (0, types_1.isInstantiableClass)(dictClassType) &&
                    strClassType &&
                    (0, types_1.isInstantiableClass)(strClassType)) {
                    srcType = types_1.ClassType.cloneForSpecialization(dictClassType, [types_1.ClassType.cloneAsInstance(strClassType), dictValueType], 
                    /* isTypeArgumentExplicit */ true);
                }
            }
        }
        // Handle special-case type promotions.
        if (destType.includePromotions) {
            const promotionList = typePromotions.get(destType.details.fullName);
            if (promotionList &&
                promotionList.some((srcName) => srcType.details.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && srcName === mroClass.details.fullName))) {
                if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0) {
                    return true;
                }
            }
        }
        // Is it a structural type (i.e. a protocol)? If so, we need to
        // perform a member-by-member check.
        const inheritanceChain = [];
        const isDerivedFrom = types_1.ClassType.isDerivedFrom(srcType, destType, inheritanceChain);
        // Use the slow path for protocols if the dest doesn't explicitly
        // derive from the source. We also need to use this path if we're
        // testing to see if the metaclass matches the protocol.
        if (types_1.ClassType.isProtocolClass(destType) && !isDerivedFrom) {
            if (!(0, protocols_1.assignClassToProtocol)(evaluatorInterface, destType, types_1.ClassType.cloneAsInstance(srcType), diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.protocolIncompatible().format({
                    sourceType: printType((0, typeUtils_1.convertToInstance)(srcType)),
                    destType: printType((0, typeUtils_1.convertToInstance)(destType)),
                }));
                return false;
            }
            return true;
        }
        if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0 || types_1.ClassType.isSameGenericClass(srcType, destType)) {
            if (isDerivedFrom) {
                (0, debug_1.assert)(inheritanceChain.length > 0);
                if (assignClassWithTypeArgs(destType, srcType, inheritanceChain, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    return true;
                }
            }
        }
        // Everything is assignable to an object.
        if (types_1.ClassType.isBuiltIn(destType, 'object')) {
            if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0) {
                return true;
            }
        }
        const destErrorType = reportErrorsUsingObjType ? types_1.ClassType.cloneAsInstance(destType) : destType;
        const srcErrorType = reportErrorsUsingObjType ? types_1.ClassType.cloneAsInstance(srcType) : srcType;
        let destErrorTypeText = printType(destErrorType);
        let srcErrorTypeText = printType(srcErrorType);
        // If the text is the same, use the fully-qualified name rather than the short name.
        if (destErrorTypeText === srcErrorTypeText && destType.details.fullName && srcType.details.fullName) {
            destErrorTypeText = destType.details.fullName;
            srcErrorTypeText = srcType.details.fullName;
        }
        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeIncompatible().format({
            sourceType: srcErrorTypeText,
            destType: destErrorTypeText,
        }));
        // Tell the user about the disableBytesTypePromotions if that is involved.
        if (types_1.ClassType.isBuiltIn(destType, 'bytes')) {
            const promotions = typePromotions.get(destType.details.fullName);
            if (promotions && promotions.some((name) => name === srcType.details.fullName)) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.bytesTypePromotions());
            }
        }
        return false;
    }
    // This function is used to validate or infer the variance of type
    // parameters within a class. If ignoreBaseClassVariance is set to false,
    // the type parameters for the base class are honored. This is useful for
    // variance inference (PEP 695). For validation of protocol variance, we
    // want to ignore the variance for all base classes in the class hierarchy.
    function assignClassToSelf(destType, srcType, assumedVariance, ignoreBaseClassVariance = true, recursionCount = 0) {
        (0, debug_1.assert)(types_1.ClassType.isSameGenericClass(destType, srcType));
        (0, debug_1.assert)(destType.details.typeParameters.length > 0);
        const typeVarContext = new typeVarContext_1.TypeVarContext();
        let isAssignable = true;
        // Use a try/catch block here to make sure that we reset
        // the assignClassToSelfClass to undefined if an exception occurs.
        try {
            // Stash the current class type so any references to it are treated
            // as though all TypeParameters are invariant.
            assignClassToSelfStack.push({ class: destType, assumedVariance });
            types_1.ClassType.getSymbolTable(destType).forEach((symbol, name) => {
                if (!isAssignable || symbol.isIgnoredForProtocolMatch()) {
                    return;
                }
                // Constructor methods are exempt from variance calculations.
                if (name === '__new__' || name === '__init__') {
                    return;
                }
                const memberInfo = (0, typeUtils_1.lookUpClassMember)(srcType, name);
                (0, debug_1.assert)(memberInfo !== undefined);
                let destMemberType = getEffectiveTypeOfSymbol(symbol);
                const srcMemberType = getTypeOfMember(memberInfo);
                destMemberType = (0, typeUtils_1.partiallySpecializeType)(destMemberType, destType);
                // Properties require special processing.
                if ((0, types_1.isClassInstance)(destMemberType) &&
                    types_1.ClassType.isPropertyClass(destMemberType) &&
                    (0, types_1.isClassInstance)(srcMemberType) &&
                    types_1.ClassType.isPropertyClass(srcMemberType)) {
                    if (!(0, properties_1.assignProperty)(evaluatorInterface, types_1.ClassType.cloneAsInstantiable(destMemberType), types_1.ClassType.cloneAsInstantiable(srcMemberType), destType, srcType, 
                    /* diag */ undefined, typeVarContext, 
                    /* selfTypeVarContext */ undefined, recursionCount)) {
                        isAssignable = false;
                    }
                }
                else {
                    const primaryDecl = symbol.getDeclarations()[0];
                    let flags = 0 /* AssignTypeFlags.Default */;
                    if ((primaryDecl === null || primaryDecl === void 0 ? void 0 : primaryDecl.type) === 1 /* DeclarationType.Variable */ &&
                        !isFinalVariableDeclaration(primaryDecl) &&
                        !types_1.ClassType.isFrozenDataClass(destType)) {
                        // Class and instance variables that are mutable need to
                        // enforce invariance. We will exempt variables that are
                        // private or protected, since these are presumably
                        // not modifiable outside of the class.
                        if (!(0, symbolNameUtils_1.isPrivateOrProtectedName)(name)) {
                            flags |= 1 /* AssignTypeFlags.EnforceInvariance */;
                        }
                    }
                    if (!assignType(destMemberType, srcMemberType, 
                    /* diag */ undefined, typeVarContext, 
                    /* srcTypeVarContext */ undefined, flags | 65536 /* AssignTypeFlags.IgnoreSelfClsParamCompatibility */, recursionCount)) {
                        isAssignable = false;
                    }
                }
            });
            if (!isAssignable) {
                return false;
            }
            // Now handle generic base classes.
            destType.details.baseClasses.forEach((baseClass) => {
                if ((0, types_1.isInstantiableClass)(baseClass) &&
                    !types_1.ClassType.isBuiltIn(baseClass, 'object') &&
                    !types_1.ClassType.isBuiltIn(baseClass, 'Protocol') &&
                    !types_1.ClassType.isBuiltIn(baseClass, 'Generic') &&
                    baseClass.details.typeParameters.length > 0) {
                    const specializedDestBaseClass = (0, typeUtils_1.specializeForBaseClass)(destType, baseClass);
                    const specializedSrcBaseClass = (0, typeUtils_1.specializeForBaseClass)(srcType, baseClass);
                    if (!ignoreBaseClassVariance) {
                        specializedDestBaseClass.details.typeParameters.forEach((param, index) => {
                            if (!param.details.isParamSpec &&
                                !param.details.isVariadic &&
                                !param.details.isSynthesized &&
                                specializedSrcBaseClass.typeArguments &&
                                index < specializedSrcBaseClass.typeArguments.length &&
                                specializedDestBaseClass.typeArguments &&
                                index < specializedDestBaseClass.typeArguments.length) {
                                const paramVariance = param.details.declaredVariance;
                                if ((0, types_1.isTypeVar)(specializedSrcBaseClass.typeArguments[index])) {
                                    if (paramVariance === 2 /* Variance.Invariant */ ||
                                        paramVariance === 4 /* Variance.Contravariant */) {
                                        isAssignable = false;
                                    }
                                }
                                else if ((0, types_1.isTypeVar)(specializedDestBaseClass.typeArguments[index])) {
                                    if (paramVariance === 2 /* Variance.Invariant */ || paramVariance === 3 /* Variance.Covariant */) {
                                        isAssignable = false;
                                    }
                                }
                            }
                        });
                    }
                    if (isAssignable &&
                        !assignClassToSelf(specializedDestBaseClass, specializedSrcBaseClass, assumedVariance, ignoreBaseClassVariance, recursionCount)) {
                        isAssignable = false;
                    }
                }
            });
            return isAssignable;
        }
        finally {
            assignClassToSelfStack.pop();
        }
    }
    // Adjusts the source and/or dest type arguments list to attempt to match
    // the length of the src type arguments list if the dest or source contain
    // entries with indeterminate length or variadic entries. It returns true
    // if the source is potentially compatible with the dest type, false otherwise.
    function adjustTupleTypeArgs(destTypeArgs, srcTypeArgs, flags) {
        const destUnboundedOrVariadicIndex = destTypeArgs.findIndex((t) => t.isUnbounded || (0, types_1.isVariadicTypeVar)(t.type));
        const srcUnboundedIndex = srcTypeArgs.findIndex((t) => t.isUnbounded);
        const srcVariadicIndex = srcTypeArgs.findIndex((t) => (0, types_1.isVariadicTypeVar)(t.type));
        if (srcUnboundedIndex >= 0) {
            if ((0, types_1.isAnyOrUnknown)(srcTypeArgs[srcUnboundedIndex].type)) {
                // If the source contains an unbounded Any, expand it to match the dest length.
                const typeToReplicate = srcTypeArgs.length > 0 ? srcTypeArgs[srcUnboundedIndex].type : types_1.AnyType.create();
                while (srcTypeArgs.length < destTypeArgs.length) {
                    srcTypeArgs.splice(srcUnboundedIndex, 0, { type: typeToReplicate, isUnbounded: true });
                }
                if (srcTypeArgs.length > destTypeArgs.length) {
                    srcTypeArgs.splice(srcUnboundedIndex, 1);
                }
            }
            else if (destUnboundedOrVariadicIndex < 0) {
                // If the source contains an unbounded type but the dest does not, it's incompatible.
                return false;
            }
        }
        // If the dest contains an unbounded Any, expand it to match the source length.
        if (destUnboundedOrVariadicIndex >= 0 &&
            destTypeArgs[destUnboundedOrVariadicIndex].isUnbounded &&
            (0, types_1.isAnyOrUnknown)(destTypeArgs[destUnboundedOrVariadicIndex].type)) {
            while (destTypeArgs.length < srcTypeArgs.length) {
                destTypeArgs.splice(destUnboundedOrVariadicIndex, 0, destTypeArgs[destUnboundedOrVariadicIndex]);
            }
        }
        // Remove any optional parameters from the end of the two lists until the lengths match.
        while (srcTypeArgs.length > destTypeArgs.length && srcTypeArgs[srcTypeArgs.length - 1].isOptional) {
            srcTypeArgs.splice(srcTypeArgs.length - 1, 1);
        }
        while (destTypeArgs.length > srcTypeArgs.length && destTypeArgs[destTypeArgs.length - 1].isOptional) {
            destTypeArgs.splice(destTypeArgs.length - 1, 1);
        }
        // If we're doing reverse type mappings and the source contains a variadic
        // TypeVar, we need to adjust the dest so the reverse type mapping assignment
        // can be performed.
        if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) !== 0) {
            const destArgsToCapture = destTypeArgs.length - srcTypeArgs.length + 1;
            if (srcVariadicIndex >= 0 && destArgsToCapture >= 0) {
                // If the only removed arg from the dest type args is itself a variadic,
                // don't bother adjusting it.
                const skipAdjustment = destArgsToCapture === 1 && (0, types_1.isVariadicTypeVar)(destTypeArgs[srcVariadicIndex].type);
                if (!skipAdjustment && tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                    const removedArgs = destTypeArgs.splice(srcVariadicIndex, destArgsToCapture);
                    // Package up the remaining type arguments into a tuple object.
                    const variadicTuple = makeTupleObject(removedArgs.map((typeArg) => {
                        return {
                            type: typeArg.type,
                            isUnbounded: typeArg.isUnbounded,
                            isOptional: typeArg.isOptional,
                        };
                    }), 
                    /* isUnpackedTuple */ true);
                    destTypeArgs.splice(srcVariadicIndex, 0, {
                        type: variadicTuple,
                        isUnbounded: false,
                    });
                }
            }
        }
        else {
            const srcArgsToCapture = srcTypeArgs.length - destTypeArgs.length + 1;
            if (destUnboundedOrVariadicIndex >= 0 && srcArgsToCapture >= 0) {
                // If the dest contains a variadic element, determine which source
                // args map to this element and package them up into an unpacked tuple.
                if ((0, types_1.isVariadicTypeVar)(destTypeArgs[destUnboundedOrVariadicIndex].type)) {
                    if (tupleClassType && (0, types_1.isInstantiableClass)(tupleClassType)) {
                        const removedArgs = srcTypeArgs.splice(destUnboundedOrVariadicIndex, srcArgsToCapture);
                        let variadicTuple;
                        // If we're left with a single unpacked variadic type var, there's no
                        // need to wrap it in a nested tuple.
                        if (removedArgs.length === 1 && (0, types_1.isUnpackedVariadicTypeVar)(removedArgs[0].type)) {
                            variadicTuple = removedArgs[0].type;
                        }
                        else {
                            // Package up the remaining type arguments into a tuple object.
                            variadicTuple = makeTupleObject(removedArgs.map((typeArg) => {
                                return {
                                    type: typeArg.type,
                                    isUnbounded: typeArg.isUnbounded,
                                    isOptional: typeArg.isOptional,
                                };
                            }), 
                            /* isUnpackedTuple */ true);
                        }
                        srcTypeArgs.splice(destUnboundedOrVariadicIndex, 0, {
                            type: variadicTuple,
                            isUnbounded: false,
                        });
                    }
                }
                else {
                    // If possible, package up the source entries that correspond to
                    // the dest unbounded tuple. This isn't possible if the source contains
                    // an unbounded tuple outside of this range.
                    if (srcUnboundedIndex < 0 ||
                        (srcUnboundedIndex >= destUnboundedOrVariadicIndex &&
                            srcUnboundedIndex < destUnboundedOrVariadicIndex + srcArgsToCapture)) {
                        const removedArgTypes = srcTypeArgs
                            .splice(destUnboundedOrVariadicIndex, srcArgsToCapture)
                            .map((t) => {
                            if ((0, types_1.isTypeVar)(t.type) &&
                                (0, types_1.isUnpackedVariadicTypeVar)(t.type) &&
                                !t.type.isVariadicInUnion) {
                                return types_1.TypeVarType.cloneForUnpacked(t.type, /* isInUnion */ true);
                            }
                            return t.type;
                        });
                        srcTypeArgs.splice(destUnboundedOrVariadicIndex, 0, {
                            type: removedArgTypes.length > 0 ? (0, types_1.combineTypes)(removedArgTypes) : types_1.AnyType.create(),
                            isUnbounded: false,
                        });
                    }
                }
            }
        }
        return destTypeArgs.length === srcTypeArgs.length;
    }
    function assignTupleTypeArguments(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        var _a, _b;
        const destTypeArgs = [...((_a = destType.tupleTypeArguments) !== null && _a !== void 0 ? _a : [])];
        const srcTypeArgs = [...((_b = srcType.tupleTypeArguments) !== null && _b !== void 0 ? _b : [])];
        if (adjustTupleTypeArgs(destTypeArgs, srcTypeArgs, flags)) {
            for (let argIndex = 0; argIndex < srcTypeArgs.length; argIndex++) {
                const entryDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                if (!assignType(destTypeArgs[argIndex].type, srcTypeArgs[argIndex].type, entryDiag === null || entryDiag === void 0 ? void 0 : entryDiag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    if (entryDiag) {
                        entryDiag.addMessage(localize_1.LocAddendum.tupleEntryTypeMismatch().format({
                            entry: argIndex + 1,
                        }));
                    }
                    return false;
                }
            }
        }
        else {
            const isDestIndeterminate = destTypeArgs.some((t) => t.isUnbounded || (0, types_1.isVariadicTypeVar)(t.type));
            if (srcTypeArgs.some((t) => t.isUnbounded || (0, types_1.isVariadicTypeVar)(t.type))) {
                if (isDestIndeterminate) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.tupleSizeIndeterminateSrcDest().format({
                        expected: destTypeArgs.length - 1,
                    }));
                }
                else {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.tupleSizeIndeterminateSrc().format({
                        expected: destTypeArgs.length,
                    }));
                }
            }
            else {
                if (isDestIndeterminate) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.tupleSizeMismatchIndeterminateDest().format({
                        expected: destTypeArgs.length - 1,
                        received: srcTypeArgs.length,
                    }));
                }
                else {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.tupleSizeMismatch().format({
                        expected: destTypeArgs.length,
                        received: srcTypeArgs.length,
                    }));
                }
            }
            return false;
        }
        return true;
    }
    // Determines whether the specified type can be assigned to the
    // specified inheritance chain, taking into account its type arguments.
    function assignClassWithTypeArgs(destType, srcType, inheritanceChain, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        let curSrcType = srcType;
        let prevSrcType;
        inferTypeParameterVarianceForClass(destType);
        // If we're enforcing invariance, literal types must match.
        if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
            const srcIsLiteral = srcType.literalValue !== undefined;
            const destIsLiteral = destType.literalValue !== undefined;
            if (srcIsLiteral !== destIsLiteral) {
                return false;
            }
        }
        else {
            // If the dest is an 'object', it's assignable.
            if (types_1.ClassType.isBuiltIn(destType, 'object')) {
                return true;
            }
        }
        for (let ancestorIndex = inheritanceChain.length - 1; ancestorIndex >= 0; ancestorIndex--) {
            const ancestorType = inheritanceChain[ancestorIndex];
            // If we've hit an "unknown", all bets are off, and we need to assume
            // that the type is assignable. If the destType is marked "@final",
            // we should be able to assume that it's not assignable, but we can't do
            // this in the general case because it breaks assumptions with the
            // NotImplemented symbol exported by typeshed's builtins.pyi. Instead,
            // we'll special-case only None.
            if ((0, types_1.isUnknown)(ancestorType)) {
                return !(0, typeUtils_1.isNoneTypeClass)(destType);
            }
            // If this isn't the first time through the loop, specialize
            // for the next ancestor in the chain.
            if (ancestorIndex < inheritanceChain.length - 1) {
                // If the curSrcType is a NamedTuple and the ancestorType is a tuple,
                // we need to handle this as a special case because the NamedTuple may
                // include typeParams from its parent class.
                let effectiveCurSrcType = curSrcType;
                if (types_1.ClassType.isBuiltIn(curSrcType, 'NamedTuple') &&
                    types_1.ClassType.isBuiltIn(ancestorType, 'tuple') &&
                    prevSrcType) {
                    effectiveCurSrcType = prevSrcType;
                }
                curSrcType = (0, typeUtils_1.specializeForBaseClass)(effectiveCurSrcType, ancestorType);
            }
            // If there are no type parameters on this class, we're done.
            const ancestorTypeParams = types_1.ClassType.getTypeParameters(ancestorType);
            if (ancestorTypeParams.length === 0) {
                continue;
            }
            // If the dest type isn't specialized, there are no type args to validate.
            if (!ancestorType.typeArguments) {
                return true;
            }
            prevSrcType = curSrcType;
        }
        // If we're enforcing invariance, literal types must match as well.
        if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
            const srcIsLiteral = srcType.literalValue !== undefined;
            const destIsLiteral = destType.literalValue !== undefined;
            if (srcIsLiteral !== destIsLiteral) {
                return false;
            }
        }
        // Handle tuple, which supports a variable number of type arguments.
        if (destType.tupleTypeArguments && curSrcType.tupleTypeArguments) {
            return assignTupleTypeArguments(destType, curSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
        }
        if (destType.typeArguments) {
            // If the dest type is specialized, make sure the specialized source
            // type arguments are assignable to the dest type arguments.
            return assignTypeArguments(destType, curSrcType, 
            // Don't emit a diag addendum if we're in an invariant context. It's
            // sufficient to simply indicate that the types are not the same
            // in this case. Adding more information is unnecessary and confusing.
            (flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0 ? diag : undefined, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
        }
        if (destTypeVarContext && curSrcType.typeArguments && !destTypeVarContext.isLocked()) {
            // Populate the typeVar map with type arguments of the source.
            const srcTypeArgs = curSrcType.typeArguments;
            for (let i = 0; i < destType.details.typeParameters.length; i++) {
                const typeArgType = i < srcTypeArgs.length ? srcTypeArgs[i] : types_1.UnknownType.create();
                const typeParam = destType.details.typeParameters[i];
                const variance = types_1.TypeVarType.getVariance(typeParam);
                (0, constraintSolver_1.updateTypeVarType)(evaluatorInterface, destTypeVarContext, typeParam, variance !== 4 /* Variance.Contravariant */ ? typeArgType : undefined, variance !== 3 /* Variance.Covariant */ ? typeArgType : undefined, 
                /* tupleTypes */ curSrcType.tupleTypeArguments, 
                /* forceRetainLiterals */ true);
            }
        }
        return true;
    }
    function getGetterTypeFromProperty(propertyClass, inferTypeIfNeeded) {
        if (!types_1.ClassType.isPropertyClass(propertyClass)) {
            return undefined;
        }
        if (propertyClass.fgetInfo) {
            return getFunctionEffectiveReturnType(propertyClass.fgetInfo.methodType, 
            /* args */ undefined, inferTypeIfNeeded);
        }
        return undefined;
    }
    function assignTypeArguments(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        var _a, _b, _c;
        (0, debug_1.assert)(types_1.ClassType.isSameGenericClass(destType, srcType));
        inferTypeParameterVarianceForClass(destType);
        const destTypeParams = types_1.ClassType.getTypeParameters(destType);
        let destTypeArgs;
        let srcTypeArgs;
        // Are we performing protocol variance validation for this class? If so,
        // treat all of the type parameters as invariant even if they are declared
        // otherwise.
        const assignClassToSelfInfo = assignClassToSelfStack.find((info) => types_1.ClassType.isSameGenericClass(info.class, destType));
        const assumedVariance = assignClassToSelfInfo === null || assignClassToSelfInfo === void 0 ? void 0 : assignClassToSelfInfo.assumedVariance;
        // If either source or dest type arguments are missing, they are
        // treated as "Any", so they are assumed to be assignable.
        if (!destType.typeArguments || !srcType.typeArguments) {
            return true;
        }
        if (types_1.ClassType.isTupleClass(destType)) {
            destTypeArgs = (_b = (_a = destType.tupleTypeArguments) === null || _a === void 0 ? void 0 : _a.map((t) => t.type)) !== null && _b !== void 0 ? _b : [];
            srcTypeArgs = (_c = srcType.tupleTypeArguments) === null || _c === void 0 ? void 0 : _c.map((t) => t.type);
        }
        else {
            destTypeArgs = destType.typeArguments;
            srcTypeArgs = srcType.typeArguments;
        }
        let isCompatible = true;
        srcTypeArgs === null || srcTypeArgs === void 0 ? void 0 : srcTypeArgs.forEach((srcTypeArg, srcArgIndex) => {
            // In most cases, the number of type args should match the number
            // of type arguments, but there are a few special cases where this
            // isn't true (e.g. assigning a Tuple[X, Y, Z] to a tuple[W]).
            const destArgIndex = srcArgIndex >= destTypeArgs.length ? destTypeArgs.length - 1 : srcArgIndex;
            const destTypeArg = destArgIndex >= 0 ? destTypeArgs[destArgIndex] : types_1.UnknownType.create();
            const destTypeParam = destArgIndex < destTypeParams.length ? destTypeParams[destArgIndex] : undefined;
            const assignmentDiag = new diagnostic_1.DiagnosticAddendum();
            const variance = assumedVariance !== null && assumedVariance !== void 0 ? assumedVariance : (destTypeParam ? types_1.TypeVarType.getVariance(destTypeParam) : 3 /* Variance.Covariant */);
            let effectiveFlags;
            let errorSource;
            let includeDiagAddendum = true;
            if (variance === 3 /* Variance.Covariant */) {
                effectiveFlags = flags | 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */;
                errorSource = localize_1.LocAddendum.typeVarIsCovariant;
            }
            else if (variance === 4 /* Variance.Contravariant */) {
                effectiveFlags =
                    (flags ^ 2 /* AssignTypeFlags.ReverseTypeVarMatching */) | 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */;
                errorSource = localize_1.LocAddendum.typeVarIsContravariant;
            }
            else {
                effectiveFlags = flags | 1 /* AssignTypeFlags.EnforceInvariance */ | 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */;
                errorSource = localize_1.LocAddendum.typeVarIsInvariant;
                // Omit the diagnostic addendum for the invariant case because it's obvious
                // why two types are not the same.
                includeDiagAddendum = false;
            }
            if (!assignType(variance === 4 /* Variance.Contravariant */ ? srcTypeArg : destTypeArg, variance === 4 /* Variance.Contravariant */ ? destTypeArg : srcTypeArg, assignmentDiag, variance === 4 /* Variance.Contravariant */ ? srcTypeVarContext : destTypeVarContext, variance === 4 /* Variance.Contravariant */ ? destTypeVarContext : srcTypeVarContext, effectiveFlags, recursionCount)) {
                // Don't report errors with type variables in "pseudo-random"
                // classes since these type variables are not real.
                if (!types_1.ClassType.isPseudoGenericClass(destType)) {
                    if (diag) {
                        if (destTypeParam) {
                            const childDiag = diag.createAddendum();
                            childDiag.addMessage(errorSource().format({
                                name: types_1.TypeVarType.getReadableName(destTypeParam),
                                ...printSrcDestTypes(srcTypeArg, destTypeArg),
                            }));
                            if (includeDiagAddendum) {
                                childDiag.addAddendum(assignmentDiag);
                            }
                            if (isCompatible && types_1.ClassType.isSameGenericClass(destType, srcType)) {
                                // Add additional notes to help the user if this is a common type mismatch.
                                if (types_1.ClassType.isBuiltIn(destType, 'dict') && srcArgIndex === 1) {
                                    childDiag.addMessage(localize_1.LocAddendum.invariantSuggestionDict());
                                }
                                else if (types_1.ClassType.isBuiltIn(destType, 'list')) {
                                    childDiag.addMessage(localize_1.LocAddendum.invariantSuggestionList());
                                }
                                else if (types_1.ClassType.isBuiltIn(destType, 'set')) {
                                    childDiag.addMessage(localize_1.LocAddendum.invariantSuggestionSet());
                                }
                            }
                        }
                        else {
                            diag.addAddendum(assignmentDiag);
                        }
                    }
                    isCompatible = false;
                }
            }
        });
        return isCompatible;
    }
    // Determines if the source type can be assigned to the dest type.
    // If typeVarContext is provided, type variables within the destType are
    // matched against existing type variables in the map. If a type variable
    // in the dest type is not in the type map already, it is assigned a type
    // and added to the map.
    function assignType(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags = 0 /* AssignTypeFlags.Default */, recursionCount = 0) {
        var _a, _b;
        // Handle the case where the dest and src types are the same object.
        // We can normally shortcut this and say that they are compatible,
        // but if the type includes TypeVars, we need to go through
        // the rest of the logic.
        if (destType === srcType && !(0, typeUtils_1.requiresSpecialization)(destType)) {
            return true;
        }
        // If the source type is a special form, use the literal special form
        // class rather than the symbolic form.
        if (srcType.specialForm) {
            let isSpecialFormExempt = false;
            // A few special forms that are normally not compatible with type[T]
            // are compatible specifically in the context of isinstance and issubclass.
            if ((flags & 32768 /* AssignTypeFlags.AllowIsinstanceSpecialForms */) !== 0) {
                if (types_1.ClassType.isBuiltIn(srcType.specialForm, ['Callable', 'UnionType', 'Generic'])) {
                    isSpecialFormExempt = true;
                }
            }
            if (!isSpecialFormExempt) {
                srcType = srcType.specialForm;
            }
        }
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return true;
        }
        recursionCount++;
        // If the source and dest refer to the recursive type aliases, handle
        // the case specially to avoid recursing down both type aliases.
        if ((0, types_1.isTypeVar)(destType) &&
            destType.details.recursiveTypeAliasScopeId &&
            (0, types_1.isTypeVar)(srcType) &&
            srcType.details.recursiveTypeAliasScopeId) {
            // Do the source and dest refer to the same recursive type alias?
            if (((_a = destType.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) &&
                ((_b = srcType.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.typeArguments) &&
                destType.details.recursiveTypeAliasScopeId === srcType.details.recursiveTypeAliasScopeId) {
                let isAssignable = true;
                const srcTypeArgs = srcType.typeAliasInfo.typeArguments;
                destType.typeAliasInfo.typeArguments.forEach((destTypeArg, index) => {
                    const srcTypeArg = index < srcTypeArgs.length ? srcTypeArgs[index] : types_1.UnknownType.create();
                    if (!assignType(destTypeArg, srcTypeArg, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                        isAssignable = false;
                    }
                });
                return isAssignable;
            }
            else {
                // Have we already recursed once?
                if ((flags & 4 /* AssignTypeFlags.SkipRecursiveTypeCheck */) !== 0) {
                    return true;
                }
                // Note that we are comparing two recursive types and do
                // not recursive more than once.
                flags |= 4 /* AssignTypeFlags.SkipRecursiveTypeCheck */;
            }
        }
        // Transform recursive type aliases if necessary.
        const transformedDestType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(destType);
        const transformedSrcType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(srcType);
        // Did either the source or dest include recursive type aliases?
        // If so, we could be dealing with different recursive type aliases
        // or a recursive type alias and a recursive protocol definition.
        if ((transformedDestType !== destType && (0, types_1.isUnion)(transformedDestType)) ||
            (transformedSrcType !== srcType && (0, types_1.isUnion)(transformedSrcType))) {
            // Use a smaller recursive limit in this case to prevent runaway recursion.
            if (recursionCount > maxRecursiveTypeAliasRecursionCount) {
                // Add a special case for when the source is a str, which is itself
                // a recursive type (since it derives from Sequence[str]).
                if ((0, types_1.isClassInstance)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'str') && (0, types_1.isUnion)(transformedDestType)) {
                    return transformedDestType.subtypes.some((subtype) => (0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, ['object', 'str']));
                }
                return true;
            }
        }
        destType = transformedDestType;
        srcType = transformedSrcType;
        // If the source or dest is unbound, allow the assignment. The
        // error will be reported elsewhere.
        if ((0, types_1.isUnbound)(destType) || (0, types_1.isUnbound)(srcType)) {
            return true;
        }
        // If we're in "overload overlap" mode, convert top-level type variables
        // to their concrete forms in the source.
        if ((flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) !== 0) {
            srcType = makeTopLevelTypeVarsConcrete(srcType);
        }
        // Strip flags we don't want to propagate to other calls.
        const originalFlags = flags;
        flags &= ~128 /* AssignTypeFlags.AllowBoolTypeGuard */;
        // Before performing any other checks, see if the dest type is a
        // TypeVar that we are attempting to match.
        if ((0, types_1.isTypeVar)(destType)) {
            if ((0, typeUtils_1.isTypeVarSame)(destType, srcType)) {
                if (destType.scopeId && (destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.hasSolveForScope(destType.scopeId))) {
                    // If the dest TypeVar has no current value bound to it, bind itself.
                    if (!destTypeVarContext.getPrimarySignature().getTypeVar(destType)) {
                        return (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, destType, srcType, diag, destTypeVarContext, flags, recursionCount);
                    }
                }
                return true;
            }
            // If the dest is a constrained or bound type variable and all of the
            // types in the source are conditioned on that same type variable
            // and have compatible types, we'll consider it assignable.
            if (assignConditionalTypeToTypeVar(destType, srcType, recursionCount)) {
                return true;
            }
            // If the source is a conditional type associated with a bound TypeVar
            // and the bound TypeVar matches the condition, the types are compatible.
            const destTypeVar = destType;
            if (types_1.TypeBase.isInstantiable(destType) === types_1.TypeBase.isInstantiable(srcType) &&
                srcType.condition &&
                srcType.condition.some((cond) => {
                    return (cond.typeVar.details.constraints.length === 0 &&
                        cond.typeVar.nameWithScope === destTypeVar.nameWithScope);
                })) {
                return true;
            }
            if ((0, types_1.isUnion)(srcType)) {
                const srcWithoutAny = (0, types_1.removeFromUnion)(srcType, (type) => (0, types_1.isAnyOrUnknown)(type));
                if ((0, types_1.isTypeSame)(destType, srcWithoutAny)) {
                    return true;
                }
            }
            // Handle the special case where both types are Self types. We'll allow
            // them to be treated as equivalent to handle certain common idioms.
            if ((0, types_1.isTypeVar)(srcType) &&
                srcType.details.isSynthesizedSelf &&
                srcType.details.boundType &&
                destType.details.isSynthesizedSelf &&
                destType.details.boundType &&
                types_1.TypeBase.isInstance(srcType) === types_1.TypeBase.isInstance(destType)) {
                if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0 && destTypeVarContext) {
                    (0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, destType, srcType, diag, destTypeVarContext, originalFlags, recursionCount);
                }
                return true;
            }
            // If the dest is a variadic type variable, and the source is a tuple
            // with a single entry that is the same variadic type variable, it's a match.
            if ((0, types_1.isVariadicTypeVar)(destType) &&
                (0, types_1.isClassInstance)(srcType) &&
                (0, typeUtils_1.isTupleClass)(srcType) &&
                srcType.tupleTypeArguments &&
                srcType.tupleTypeArguments.length === 1) {
                if ((0, types_1.isTypeSame)(destType, srcType.tupleTypeArguments[0].type, {}, recursionCount)) {
                    return true;
                }
            }
            if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0 || !(0, types_1.isTypeVar)(srcType)) {
                const targetTypeVarContext = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0 ? destTypeVarContext : srcTypeVarContext;
                if (!(0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, destType, srcType, diag, targetTypeVarContext !== null && targetTypeVarContext !== void 0 ? targetTypeVarContext : new typeVarContext_1.TypeVarContext(), originalFlags, recursionCount)) {
                    return false;
                }
                if ((0, types_1.isAnyOrUnknown)(srcType) && (flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) !== 0) {
                    return false;
                }
                return true;
            }
        }
        if ((0, types_1.isTypeVar)(srcType)) {
            if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) !== 0) {
                // The caller has requested that we solve for source type variables
                // rather than dest. If the type variable is not in the scope of the
                // provided TypeVarContext, simply verify that the concrete types are
                // compatible.
                if (!srcTypeVarContext || !srcTypeVarContext.hasSolveForScope((0, typeUtils_1.getTypeVarScopeId)(srcType))) {
                    return assignType(makeTopLevelTypeVarsConcrete(destType), makeTopLevelTypeVarsConcrete(srcType), diag, 
                    /* destTypeVarContext */ undefined, 
                    /* srcTypeVarContext */ undefined, originalFlags, recursionCount);
                }
                else {
                    if ((0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, srcType, destType, diag, srcTypeVarContext, originalFlags, recursionCount)) {
                        return true;
                    }
                    // If the dest type is a union, only one of the subtypes needs to match.
                    let isAssignable = false;
                    if ((0, types_1.isUnion)(destType)) {
                        (0, typeUtils_1.doForEachSubtype)(destType, (destSubtype) => {
                            if ((0, constraintSolver_1.assignTypeToTypeVar)(evaluatorInterface, srcType, destSubtype, diag, srcTypeVarContext, originalFlags, recursionCount)) {
                                isAssignable = true;
                            }
                        });
                    }
                    return isAssignable;
                }
            }
            if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
                if ((0, types_1.isAnyOrUnknown)(destType)) {
                    return true;
                }
                // If the source is a ParamSpec and the dest is a "...", this is
                // effectively like an "Any" signature, so we'll treat it as though
                // it's Any.
                if ((0, types_1.isParamSpec)(srcType) &&
                    (0, types_1.isFunction)(destType) &&
                    types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType) &&
                    destType.details.parameters.length <= 2) {
                    return true;
                }
                // If the source is an unpacked TypeVarTuple and the dest is a
                // *tuple[Any, ...], we'll treat it as compatible.
                if ((0, types_1.isUnpackedVariadicTypeVar)(srcType) &&
                    (0, types_1.isClassInstance)(destType) &&
                    (0, types_1.isUnpackedClass)(destType) &&
                    destType.tupleTypeArguments &&
                    destType.tupleTypeArguments.length === 1 &&
                    destType.tupleTypeArguments[0].isUnbounded &&
                    (0, types_1.isAnyOrUnknown)(destType.tupleTypeArguments[0].type)) {
                    return true;
                }
                if (!(0, types_1.isUnion)(destType)) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                    return false;
                }
            }
        }
        if ((0, types_1.isAnyOrUnknown)(destType)) {
            return true;
        }
        if ((0, types_1.isAnyOrUnknown)(srcType) && !srcType.specialForm) {
            const targetTypeVarContext = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0 ? destTypeVarContext : srcTypeVarContext;
            if (targetTypeVarContext) {
                // If it's an ellipsis type, convert it to a regular "Any"
                // type. These are functionally equivalent, but "Any" looks
                // better in the text representation.
                const typeVarSubstitution = (0, typeUtils_1.isEllipsisType)(srcType) ? types_1.AnyType.create() : srcType;
                (0, typeUtils_1.setTypeArgumentsRecursive)(destType, typeVarSubstitution, targetTypeVarContext, recursionCount);
            }
            if ((flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) === 0) {
                return true;
            }
        }
        if ((0, types_1.isNever)(srcType)) {
            if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
                if ((0, types_1.isNever)(destType)) {
                    return true;
                }
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                return false;
            }
            const targetTypeVarContext = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0 ? destTypeVarContext : srcTypeVarContext;
            if (targetTypeVarContext) {
                (0, typeUtils_1.setTypeArgumentsRecursive)(destType, types_1.UnknownType.create(), targetTypeVarContext, recursionCount);
            }
            return true;
        }
        if ((0, types_1.isUnion)(destType)) {
            // If both the source and dest are unions, use assignFromUnionType which has
            // special-case logic to handle this case.
            if ((0, types_1.isUnion)(srcType)) {
                return assignFromUnionType(destType, srcType, 
                /* diag */ undefined, destTypeVarContext, srcTypeVarContext, originalFlags, recursionCount);
            }
            const clonedDestTypeVarContext = destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.clone();
            const clonedSrcTypeVarContext = srcTypeVarContext === null || srcTypeVarContext === void 0 ? void 0 : srcTypeVarContext.clone();
            if (assignToUnionType(destType, srcType, 
            /* diag */ undefined, clonedDestTypeVarContext, clonedSrcTypeVarContext, originalFlags, recursionCount)) {
                if (destTypeVarContext && clonedDestTypeVarContext) {
                    destTypeVarContext.copyFromClone(clonedDestTypeVarContext);
                }
                if (srcTypeVarContext && clonedSrcTypeVarContext) {
                    srcTypeVarContext.copyFromClone(clonedSrcTypeVarContext);
                }
                return true;
            }
        }
        const expandedSrcType = makeTopLevelTypeVarsConcrete(srcType);
        if ((0, types_1.isUnion)(expandedSrcType)) {
            return assignFromUnionType(destType, expandedSrcType, diag, destTypeVarContext, srcTypeVarContext, originalFlags, recursionCount);
        }
        if ((0, types_1.isUnion)(destType)) {
            return assignToUnionType(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, originalFlags, recursionCount);
        }
        if ((0, typeUtils_1.isNoneInstance)(destType)) {
            if ((0, typeUtils_1.isNoneInstance)(srcType)) {
                return true;
            }
            if ((0, types_1.isClassInstance)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'NoneType')) {
                return true;
            }
        }
        if ((0, typeUtils_1.isNoneTypeClass)(destType)) {
            if ((0, typeUtils_1.isNoneTypeClass)(srcType)) {
                return true;
            }
            if ((0, types_1.isInstantiableClass)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'NoneType')) {
                return true;
            }
        }
        // Is the src a specialized "type" object?
        if ((0, types_1.isClassInstance)(expandedSrcType) && types_1.ClassType.isBuiltIn(expandedSrcType, 'type')) {
            const srcTypeArgs = expandedSrcType.typeArguments;
            let typeTypeArg;
            if (srcTypeArgs && srcTypeArgs.length >= 1) {
                typeTypeArg = srcTypeArgs[0];
            }
            else {
                typeTypeArg = types_1.UnknownType.create();
            }
            if ((0, types_1.isAnyOrUnknown)(typeTypeArg)) {
                if ((0, typeUtils_1.isEffectivelyInstantiable)(destType)) {
                    return true;
                }
            }
            else if ((0, types_1.isClassInstance)(typeTypeArg) || (0, types_1.isTypeVar)(typeTypeArg)) {
                if (assignType(destType, (0, typeUtils_1.convertToInstantiable)(typeTypeArg), diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    return true;
                }
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                return false;
            }
        }
        if ((0, types_1.isInstantiableClass)(destType)) {
            if ((0, types_1.isInstantiableClass)(expandedSrcType)) {
                // PEP 544 says that if the dest type is a type[Proto] class,
                // the source must be a "concrete" (non-protocol) class.
                if (types_1.ClassType.isProtocolClass(destType) &&
                    (flags & 16384 /* AssignTypeFlags.IgnoreProtocolAssignmentCheck */) === 0) {
                    if (types_1.ClassType.isProtocolClass(expandedSrcType) &&
                        (0, types_1.isInstantiableClass)(srcType) &&
                        !srcType.includeSubclasses) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.protocolSourceIsNotConcrete().format({
                            sourceType: printType((0, typeUtils_1.convertToInstance)(srcType)),
                            destType: printType(destType),
                        }));
                        return false;
                    }
                }
                if (!isSpecialFormClass(expandedSrcType, flags) &&
                    assignClass(destType, expandedSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount, 
                    /* reportErrorsUsingObjType */ false)) {
                    return true;
                }
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                return false;
            }
            else if ((0, types_1.isClassInstance)(expandedSrcType) && (0, typeUtils_1.isMetaclassInstance)(expandedSrcType)) {
                // If the source is a metaclass instance, verify that it's compatible with
                // the metaclass of the instantiable dest type.
                const destMetaclass = destType.details.effectiveMetaclass;
                if (destMetaclass && (0, types_1.isInstantiableClass)(destMetaclass)) {
                    if (assignClass(types_1.ClassType.cloneAsInstance(destMetaclass), expandedSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount, 
                    /* reportErrorsUsingObjType */ false)) {
                        return true;
                    }
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                    return false;
                }
            }
        }
        if ((0, types_1.isClassInstance)(destType)) {
            if (types_1.ClassType.isBuiltIn(destType, 'type')) {
                if ((0, types_1.isInstantiableClass)(srcType) && isSpecialFormClass(srcType, flags)) {
                    return false;
                }
                if ((0, types_1.isAnyOrUnknown)(srcType) && (flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) !== 0) {
                    return false;
                }
                const destTypeArgs = destType.typeArguments;
                if (destTypeArgs && destTypeArgs.length >= 1) {
                    if (types_1.TypeBase.isInstance(destTypeArgs[0]) && types_1.TypeBase.isInstantiable(srcType)) {
                        return assignType(destTypeArgs[0], (0, typeUtils_1.convertToInstance)(srcType), diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                    }
                }
                // Is the dest a "type" object? Assume that all instantiable
                // types are assignable to "type".
                if (types_1.TypeBase.isInstantiable(srcType)) {
                    const isLiteral = (0, types_1.isClass)(srcType) && srcType.literalValue !== undefined;
                    return !isLiteral;
                }
            }
            else if (types_1.ClassType.isBuiltIn(destType, ['TypeGuard', 'TypeIs'])) {
                // Allow the source to be a "bool".
                if ((originalFlags & 128 /* AssignTypeFlags.AllowBoolTypeGuard */) !== 0) {
                    if ((0, types_1.isClassInstance)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'bool')) {
                        return true;
                    }
                }
            }
            let concreteSrcType = makeTopLevelTypeVarsConcrete(srcType);
            if ((0, types_1.isClass)(concreteSrcType) && types_1.TypeBase.isInstance(concreteSrcType)) {
                if (destType.literalValue !== undefined) {
                    const srcLiteral = concreteSrcType.literalValue;
                    if (srcLiteral === undefined || !types_1.ClassType.isLiteralValueSame(concreteSrcType, destType)) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.literalAssignmentMismatch().format({
                            sourceType: printType(srcType),
                            destType: printType(destType),
                        }));
                        return false;
                    }
                }
                // Handle LiteralString special form.
                if (types_1.ClassType.isBuiltIn(destType, 'LiteralString')) {
                    if (types_1.ClassType.isBuiltIn(concreteSrcType, 'str') && concreteSrcType.literalValue !== undefined) {
                        return (flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0;
                    }
                    else if (types_1.ClassType.isBuiltIn(concreteSrcType, 'LiteralString')) {
                        return true;
                    }
                }
                else if (types_1.ClassType.isBuiltIn(concreteSrcType, 'LiteralString') &&
                    strClassType &&
                    (0, types_1.isInstantiableClass)(strClassType) &&
                    (flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0) {
                    concreteSrcType = types_1.ClassType.cloneAsInstance(strClassType);
                }
                if (!assignClass(types_1.ClassType.cloneAsInstantiable(destType), types_1.ClassType.cloneAsInstantiable(concreteSrcType), diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount, 
                /* reportErrorsUsingObjType */ true)) {
                    return false;
                }
                return true;
            }
            else if ((0, types_1.isFunction)(concreteSrcType) || (0, types_1.isOverloadedFunction)(concreteSrcType)) {
                // Is the destination a callback protocol (defined in PEP 544)?
                const destCallbackType = getCallbackProtocolType(destType, recursionCount);
                if (destCallbackType) {
                    return assignType(destCallbackType, concreteSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                }
                // All functions are considered instances of "builtins.function".
                if (functionObj && (0, types_1.isClassInstance)(functionObj)) {
                    return assignType(destType, functionObj, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                }
            }
            else if ((0, types_1.isModule)(concreteSrcType)) {
                // Is the destination the built-in "ModuleType"?
                if (types_1.ClassType.isBuiltIn(destType, 'ModuleType')) {
                    return true;
                }
                if (types_1.ClassType.isProtocolClass(destType)) {
                    return (0, protocols_1.assignModuleToProtocol)(evaluatorInterface, types_1.ClassType.cloneAsInstantiable(destType), concreteSrcType, diag, destTypeVarContext, flags, recursionCount);
                }
            }
            else if ((0, types_1.isInstantiableClass)(concreteSrcType)) {
                // See if the destType is an instantiation of a Protocol
                // class that is effectively a function.
                const callbackType = getCallbackProtocolType(destType, recursionCount);
                if (callbackType) {
                    return assignType(callbackType, concreteSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                }
                // If the destType is an instantiation of a Protocol,
                // see if the class type itself satisfies the protocol.
                if (types_1.ClassType.isProtocolClass(destType)) {
                    return (0, protocols_1.assignClassToProtocol)(evaluatorInterface, types_1.ClassType.cloneAsInstantiable(destType), concreteSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                }
                // Determine if the metaclass can be assigned to the object.
                const metaclass = concreteSrcType.details.effectiveMetaclass;
                if (metaclass) {
                    if ((0, types_1.isAnyOrUnknown)(metaclass)) {
                        return true;
                    }
                    else {
                        return assignClass(types_1.ClassType.cloneAsInstantiable(destType), metaclass, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount, 
                        /* reportErrorsUsingObjType */ false);
                    }
                }
            }
            else if ((0, types_1.isAnyOrUnknown)(concreteSrcType) && !concreteSrcType.specialForm) {
                return (flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) === 0;
            }
            else if ((0, types_1.isUnion)(concreteSrcType)) {
                return assignType(destType, concreteSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
            }
        }
        if ((0, types_1.isFunction)(destType)) {
            let concreteSrcType = makeTopLevelTypeVarsConcrete(srcType);
            if ((0, types_1.isClassInstance)(concreteSrcType)) {
                const boundMethod = getBoundMagicMethod(concreteSrcType, '__call__', 
                /* selfType */ undefined, 
                /* diag */ undefined, recursionCount);
                if (boundMethod) {
                    concreteSrcType = (0, typeUtils_1.removeParamSpecVariadicsFromSignature)(boundMethod);
                }
            }
            // If it's a class, use the constructor for type compatibility checking.
            if ((0, types_1.isInstantiableClass)(concreteSrcType) && concreteSrcType.literalValue === undefined) {
                const constructor = (0, constructors_1.createFunctionFromConstructor)(evaluatorInterface, concreteSrcType, (0, types_1.isTypeVar)(srcType) ? (0, typeUtils_1.convertToInstance)(srcType) : undefined, recursionCount);
                if (constructor) {
                    concreteSrcType = constructor;
                    // The constructor conversion may result in a union of the
                    // __init__ and __new__ callables.
                    if ((0, types_1.isUnion)(concreteSrcType)) {
                        return assignType(destType, concreteSrcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                    }
                }
            }
            if ((0, types_1.isAnyOrUnknown)(concreteSrcType)) {
                return (flags & 16 /* AssignTypeFlags.OverloadOverlapCheck */) === 0;
            }
            if ((0, types_1.isOverloadedFunction)(concreteSrcType)) {
                // Find all of the overloaded functions that match the parameters.
                const overloads = types_1.OverloadedFunctionType.getOverloads(concreteSrcType);
                const filteredOverloads = [];
                const destTypeVarSignatures = [];
                const srcTypeVarSignatures = [];
                overloads.forEach((overload) => {
                    var _a;
                    const overloadScopeId = (_a = (0, typeUtils_1.getTypeVarScopeId)(overload)) !== null && _a !== void 0 ? _a : '';
                    const destTypeVarContextClone = destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.cloneWithSignatureSource(overloadScopeId);
                    const srcTypeVarContextClone = srcTypeVarContext === null || srcTypeVarContext === void 0 ? void 0 : srcTypeVarContext.cloneWithSignatureSource(overloadScopeId);
                    if (assignType(destType, overload, 
                    /* diag */ undefined, destTypeVarContextClone, srcTypeVarContextClone, flags, recursionCount)) {
                        filteredOverloads.push(overload);
                        if (destTypeVarContextClone) {
                            (0, collectionUtils_1.appendArray)(destTypeVarSignatures, destTypeVarContextClone.getSignatureContexts());
                        }
                        if (srcTypeVarContextClone) {
                            (0, collectionUtils_1.appendArray)(srcTypeVarSignatures, srcTypeVarContextClone.getSignatureContexts());
                        }
                    }
                });
                if (filteredOverloads.length === 0) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.noOverloadAssignable().format({ type: printType(destType) }));
                    return false;
                }
                if (destTypeVarContext) {
                    destTypeVarContext.copySignatureContexts(destTypeVarSignatures);
                }
                if (srcTypeVarContext) {
                    srcTypeVarContext.copySignatureContexts(srcTypeVarSignatures);
                }
                return true;
            }
            if ((0, types_1.isFunction)(concreteSrcType)) {
                if (assignFunction(destType, concreteSrcType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext !== null && destTypeVarContext !== void 0 ? destTypeVarContext : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(destType)), srcTypeVarContext !== null && srcTypeVarContext !== void 0 ? srcTypeVarContext : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeIds)(concreteSrcType)), flags, recursionCount)) {
                    return true;
                }
            }
        }
        if ((0, types_1.isOverloadedFunction)(destType)) {
            const overloadDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
            // All overloads in the dest must be assignable.
            const destOverloads = types_1.OverloadedFunctionType.getOverloads(destType);
            // If the source is also an overload with the same number of overloads,
            // there's a good chance that there's a one-to-one mapping. Try this
            // first before using an n^2 algorithm.
            if ((0, types_1.isOverloadedFunction)(srcType)) {
                const srcOverloads = types_1.OverloadedFunctionType.getOverloads(srcType);
                if (destOverloads.length === srcOverloads.length) {
                    if (destOverloads.every((destOverload, index) => {
                        const srcOverload = srcOverloads[index];
                        return assignType(destOverload, srcOverload, 
                        /* diag */ undefined, destTypeVarContext !== null && destTypeVarContext !== void 0 ? destTypeVarContext : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(destOverload)), srcTypeVarContext, flags, recursionCount);
                    })) {
                        return true;
                    }
                }
            }
            const isAssignable = destOverloads.every((destOverload) => {
                if (destTypeVarContext) {
                    destTypeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(destOverload));
                }
                const result = assignType(destOverload, srcType, overloadDiag === null || overloadDiag === void 0 ? void 0 : overloadDiag.createAddendum(), destTypeVarContext !== null && destTypeVarContext !== void 0 ? destTypeVarContext : new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(destOverload)), srcTypeVarContext, flags, recursionCount);
                return result;
            });
            if (!isAssignable) {
                if (overloadDiag) {
                    overloadDiag.addMessage(localize_1.LocAddendum.overloadNotAssignable().format({
                        name: destType.overloads[0].details.name,
                    }));
                }
                return false;
            }
            return true;
        }
        if ((0, types_1.isClass)(destType) && types_1.ClassType.isBuiltIn(destType, 'object')) {
            if (((0, types_1.isInstantiableClass)(destType) && types_1.TypeBase.isInstantiable(srcType)) || (0, types_1.isClassInstance)(destType)) {
                if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) === 0) {
                    // All types (including None, Module, OverloadedFunction) derive from object.
                    return true;
                }
            }
        }
        // Are we trying to assign None to a protocol?
        if ((0, typeUtils_1.isNoneInstance)(srcType) && (0, types_1.isClassInstance)(destType) && types_1.ClassType.isProtocolClass(destType)) {
            if (noneClassType && (0, types_1.isInstantiableClass)(noneClassType)) {
                return (0, protocols_1.assignClassToProtocol)(evaluatorInterface, types_1.ClassType.cloneAsInstantiable(destType), types_1.ClassType.cloneAsInstance(noneClassType), diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
            }
        }
        if ((0, typeUtils_1.isNoneInstance)(destType)) {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.assignToNone());
            return false;
        }
        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
        return false;
    }
    function assignFromUnionType(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        // Start by checking for an exact match. This is needed to handle unions
        // that contain recursive type aliases.
        if ((0, types_1.isTypeSame)(srcType, destType, {}, recursionCount)) {
            return true;
        }
        // Sort the subtypes so we have a deterministic order for unions.
        let sortedSrcTypes = (0, typeUtils_1.sortTypes)(srcType.subtypes);
        let matchedSomeSubtypes = false;
        // Handle the case where the source and dest are both unions. Try
        // to eliminate as many exact type matches between the src and dest.
        if ((0, types_1.isUnion)(destType)) {
            // Handle the special case where the dest is a union of Any and
            // a type variable. This occurs, for example, with the return type of
            // the getattr function.
            const nonAnySubtypes = destType.subtypes.filter((t) => !(0, types_1.isAnyOrUnknown)(t));
            if (nonAnySubtypes.length === 1 && (0, types_1.isTypeVar)(nonAnySubtypes[0])) {
                assignType(nonAnySubtypes[0], srcType, 
                /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                // This always succeeds because the destination contains Any.
                return true;
            }
            const remainingDestSubtypes = [];
            let remainingSrcSubtypes = sortedSrcTypes;
            let canUseFastPath = true;
            // First attempt to match all of the non-generic types in the dest
            // to non-generic types in the source.
            (0, typeUtils_1.sortTypes)(destType.subtypes).forEach((destSubtype) => {
                if ((0, typeUtils_1.requiresSpecialization)(destSubtype)) {
                    remainingDestSubtypes.push(destSubtype);
                }
                else {
                    const srcTypeIndex = remainingSrcSubtypes.findIndex((srcSubtype) => (0, types_1.isTypeSame)(srcSubtype, destSubtype, {}, recursionCount));
                    if (srcTypeIndex >= 0) {
                        remainingSrcSubtypes.splice(srcTypeIndex, 1);
                        matchedSomeSubtypes = true;
                    }
                    else {
                        remainingDestSubtypes.push(destSubtype);
                    }
                }
            });
            // For all remaining source subtypes, attempt to find a dest subtype
            // whose primary type matches.
            remainingSrcSubtypes.forEach((srcSubtype) => {
                const destTypeIndex = remainingDestSubtypes.findIndex((destSubtype) => {
                    if ((0, types_1.isTypeSame)(destSubtype, srcSubtype)) {
                        return true;
                    }
                    if ((0, types_1.isClass)(srcSubtype) &&
                        (0, types_1.isClass)(destSubtype) &&
                        types_1.TypeBase.isInstance(srcSubtype) === types_1.TypeBase.isInstance(destSubtype)) {
                        if (types_1.ClassType.isSameGenericClass(srcSubtype, destSubtype)) {
                            return true;
                        }
                        // Are they equivalent TypedDicts?
                        if (types_1.ClassType.isTypedDictClass(srcSubtype) && types_1.ClassType.isTypedDictClass(destSubtype)) {
                            if (assignType(srcSubtype, destSubtype, 
                            /* diag */ undefined, 
                            /* destTypeVarContext */ undefined, 
                            /* srcTypeVarContext */ undefined, flags, recursionCount)) {
                                return true;
                            }
                        }
                    }
                    if ((0, types_1.isFunction)(srcSubtype) || (0, types_1.isOverloadedFunction)(srcSubtype)) {
                        if ((0, types_1.isFunction)(destSubtype) || (0, types_1.isOverloadedFunction)(destSubtype)) {
                            return true;
                        }
                    }
                    return false;
                });
                if (destTypeIndex >= 0) {
                    if (assignType(remainingDestSubtypes[destTypeIndex], srcSubtype, 
                    /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                        // Note that we have matched at least one subtype indicating
                        // there is at least some overlap.
                        matchedSomeSubtypes = true;
                    }
                    else {
                        canUseFastPath = false;
                    }
                    remainingDestSubtypes.splice(destTypeIndex, 1);
                    remainingSrcSubtypes = remainingSrcSubtypes.filter((t) => t !== srcSubtype);
                }
            });
            // If there is are remaining dest subtypes and they're all type variables,
            // attempt to assign the remaining source subtypes to them.
            if (canUseFastPath && (remainingDestSubtypes.length !== 0 || remainingSrcSubtypes.length !== 0)) {
                if ((flags & 1 /* AssignTypeFlags.EnforceInvariance */) !== 0) {
                    // If we have no src subtypes remaining but not all dest types have been subsumed
                    // by other dest types, then the types are not compatible if we're enforcing invariance.
                    if (remainingSrcSubtypes.length === 0) {
                        return remainingDestSubtypes.every((destSubtype) => isTypeSubsumedByOtherType(destSubtype, destType, 
                        /* allowAnyToSubsume */ true, recursionCount));
                    }
                }
                const isReversed = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) !== 0;
                const effectiveDestSubtypes = isReversed ? remainingSrcSubtypes : remainingDestSubtypes;
                if (effectiveDestSubtypes.length === 0 || effectiveDestSubtypes.some((t) => !(0, types_1.isTypeVar)(t))) {
                    canUseFastPath = false;
                    // We can avoid checking the source subtypes that have already been checked.
                    sortedSrcTypes = remainingSrcSubtypes;
                }
                else if (remainingDestSubtypes.length === remainingSrcSubtypes.length) {
                    // If the number of remaining source subtypes is the same as the number
                    // of dest TypeVars, try to assign each source subtype to its own dest TypeVar.
                    const reorderedDestSubtypes = [...remainingDestSubtypes];
                    for (let srcIndex = 0; srcIndex < remainingSrcSubtypes.length; srcIndex++) {
                        let foundMatchForSrc = false;
                        for (let destIndex = 0; destIndex < reorderedDestSubtypes.length; destIndex++) {
                            if (assignType(reorderedDestSubtypes[destIndex], remainingSrcSubtypes[srcIndex], diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                                foundMatchForSrc = true;
                                // Move the matched dest TypeVar to the end of the list so the other
                                // dest TypeVars have a better chance of being assigned to.
                                reorderedDestSubtypes.push(...reorderedDestSubtypes.splice(destIndex, 1));
                                break;
                            }
                        }
                        if (!foundMatchForSrc) {
                            canUseFastPath = false;
                            break;
                        }
                    }
                    // We can avoid checking the source subtypes that have already been checked.
                    sortedSrcTypes = remainingSrcSubtypes;
                }
                else if (remainingSrcSubtypes.length === 0) {
                    if ((flags & 2048 /* AssignTypeFlags.PopulatingExpectedType */) !== 0) {
                        // If we're populating an expected type, try not to leave
                        // any TypeVars unsolved. Assign the full type to the remaining
                        // dest TypeVars.
                        remainingDestSubtypes.forEach((destSubtype) => {
                            assignType(destSubtype, srcType, 
                            /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags, recursionCount);
                        });
                    }
                    // If we've assigned all of the source subtypes but one or more dest
                    // TypeVars have gone unmatched, treat this as success.
                }
                else {
                    // Try to assign a union of the remaining source types to
                    // the first destination TypeVar.
                    if (!assignType(isReversed ? (0, types_1.combineTypes)(remainingDestSubtypes) : remainingDestSubtypes[0], isReversed ? remainingSrcSubtypes[0] : (0, types_1.combineTypes)(remainingSrcSubtypes), diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                        canUseFastPath = false;
                    }
                }
            }
            if (canUseFastPath) {
                return true;
            }
            // If we're looking for type overlaps and at least one type was matched,
            // consider it as assignable.
            if ((flags & 32 /* AssignTypeFlags.PartialOverloadOverlapCheck */) !== 0 && matchedSomeSubtypes) {
                return true;
            }
        }
        let isIncompatible = false;
        sortedSrcTypes.forEach((subtype) => {
            if (isIncompatible) {
                return;
            }
            if (!assignType(destType, subtype, 
            /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                // Determine if the current subtype is subsumed by another subtype
                // in the same union. If so, we can ignore this.
                const isSubtypeSubsumed = isTypeSubsumedByOtherType(subtype, srcType, 
                /* allowAnyToSubsume */ false, recursionCount);
                // Try again with a concrete version of the subtype.
                if (!isSubtypeSubsumed &&
                    !assignType(destType, subtype, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    isIncompatible = true;
                }
            }
            else {
                matchedSomeSubtypes = true;
            }
        }, /* sortSubtypes */ true);
        if (isIncompatible) {
            // If we're looking for type overlaps and at least one type was matched,
            // consider it as assignable.
            if ((flags & 32 /* AssignTypeFlags.PartialOverloadOverlapCheck */) !== 0 && matchedSomeSubtypes) {
                return true;
            }
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
            return false;
        }
        return true;
    }
    function isSpecialFormClass(classType, flags) {
        if ((flags & 32768 /* AssignTypeFlags.AllowIsinstanceSpecialForms */) !== 0) {
            return false;
        }
        return types_1.ClassType.isSpecialFormClass(classType);
    }
    // Determines whether a type is "subsumed by" (i.e. is a proper subtype of) one
    // of the other type.
    function isTypeSubsumedByOtherType(type, otherType, allowAnyToSubsume, recursionCount = 0) {
        const concreteType = makeTopLevelTypeVarsConcrete(type);
        const otherTypes = (0, types_1.isUnion)(otherType) ? otherType.subtypes : [otherType];
        for (const otherType of otherTypes) {
            if ((0, types_1.isTypeSame)(otherType, type)) {
                continue;
            }
            if ((0, types_1.isAnyOrUnknown)(otherType)) {
                if (allowAnyToSubsume) {
                    return true;
                }
            }
            else if (isProperSubtype(otherType, concreteType, recursionCount)) {
                return true;
            }
        }
        return false;
    }
    // Determines whether the srcType is a subtype of destType but the converse
    // is not true. It's important that we check both directions to avoid
    // matches for types like `tuple[Any]` and `tuple[int]` from being considered
    // proper subtypes of each other.
    function isProperSubtype(destType, srcType, recursionCount) {
        // If the destType has a condition, don't consider the srcType a proper subtype.
        if (destType.condition) {
            return false;
        }
        // Shortcut the check if either type is Any or Unknown.
        if ((0, types_1.isAnyOrUnknown)(destType) || (0, types_1.isAnyOrUnknown)(srcType)) {
            return true;
        }
        // Shortcut the check if either type is a class whose hierarchy contains an unknown type.
        if ((0, types_1.isClass)(destType) && destType.details.mro.some((mro) => (0, types_1.isAnyOrUnknown)(mro))) {
            return true;
        }
        if ((0, types_1.isClass)(srcType) && srcType.details.mro.some((mro) => (0, types_1.isAnyOrUnknown)(mro))) {
            return true;
        }
        return (assignType(destType, srcType, 
        /* diag */ undefined, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount) &&
            !assignType(srcType, destType, 
            /* diag */ undefined, 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount));
    }
    function assignToUnionType(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        // If we need to enforce invariance, the source needs to be compatible
        // with all subtypes in the dest, unless those subtypes are subclasses
        // of other subtypes.
        if (flags & 1 /* AssignTypeFlags.EnforceInvariance */) {
            let isIncompatible = false;
            (0, typeUtils_1.doForEachSubtype)(destType, (subtype, index) => {
                if (!isIncompatible &&
                    !assignType(subtype, srcType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    // Determine whether this subtype is assignable to
                    // another subtype elsewhere in the union. If so, we can ignore
                    // the incompatibility.
                    let skipSubtype = false;
                    if (!(0, types_1.isAnyOrUnknown)(subtype)) {
                        (0, typeUtils_1.doForEachSubtype)(destType, (otherSubtype, otherIndex) => {
                            if (index !== otherIndex && !skipSubtype) {
                                if (assignType(otherSubtype, subtype, 
                                /* diag */ undefined, 
                                /* destTypeVarContext */ undefined, 
                                /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount)) {
                                    skipSubtype = true;
                                }
                            }
                        });
                    }
                    if (!skipSubtype) {
                        isIncompatible = true;
                    }
                }
            });
            if (isIncompatible) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                return false;
            }
            return true;
        }
        // For union destinations, we just need to match one of the types.
        const diagAddendum = diag ? new diagnostic_1.DiagnosticAddendum() : undefined;
        let foundMatch = false;
        // Does the union contain any type variables that need to be solved?
        // If so, we need to use a slower path.
        if (!(0, typeUtils_1.requiresSpecialization)(destType)) {
            for (const subtype of destType.subtypes) {
                if (assignType(subtype, srcType, diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    foundMatch = true;
                    break;
                }
            }
        }
        else {
            // Run through all subtypes in the union. Don't stop at the first
            // match we find because we may need to match TypeVars in other
            // subtypes. We special-case "None" so we can handle Optional[T]
            // without matching the None to the type var.
            if ((0, typeUtils_1.isNoneInstance)(srcType) && (0, typeUtils_1.isOptionalType)(destType)) {
                foundMatch = true;
            }
            else {
                let bestDestTypeVarContext;
                let bestSrcTypeVarContext;
                let bestTypeVarContextScore;
                // If the srcType is a literal, try to use the fast-path lookup
                // in case the destType is a union with hundreds of literals.
                if ((0, types_1.isClassInstance)(srcType) &&
                    (0, typeUtils_1.isLiteralType)(srcType) &&
                    types_1.UnionType.containsType(destType, srcType, /* exclusionSet */ undefined, recursionCount)) {
                    return true;
                }
                (0, typeUtils_1.doForEachSubtype)(destType, (subtype) => {
                    // Make a temporary clone of the typeVarContext. We don't want to modify
                    // the original typeVarContext until we find the "optimal" typeVar mapping.
                    const destTypeVarContextClone = destTypeVarContext === null || destTypeVarContext === void 0 ? void 0 : destTypeVarContext.clone();
                    const srcTypeVarContextClone = srcTypeVarContext === null || srcTypeVarContext === void 0 ? void 0 : srcTypeVarContext.clone();
                    if (assignType(subtype, srcType, diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum(), destTypeVarContextClone, srcTypeVarContextClone, flags, recursionCount)) {
                        foundMatch = true;
                        if (destTypeVarContextClone) {
                            // Ask the typeVarContext to compute a "score" for the current
                            // contents of the table.
                            let typeVarContextScore = destTypeVarContextClone.getScore();
                            // If the type matches exactly, prefer it over other types.
                            if ((0, types_1.isTypeSame)(subtype, stripLiteralValue(srcType))) {
                                typeVarContextScore = Number.POSITIVE_INFINITY;
                            }
                            if (bestTypeVarContextScore === undefined ||
                                bestTypeVarContextScore <= typeVarContextScore) {
                                // We found a typeVar mapping with a higher score than before.
                                bestTypeVarContextScore = typeVarContextScore;
                                bestDestTypeVarContext = destTypeVarContextClone;
                                bestSrcTypeVarContext = srcTypeVarContextClone;
                            }
                        }
                    }
                });
                // If we found a winning type var mapping, copy it back to typeVarContext.
                if (destTypeVarContext && bestDestTypeVarContext) {
                    destTypeVarContext.copyFromClone(bestDestTypeVarContext);
                }
                if (srcTypeVarContext && bestSrcTypeVarContext) {
                    srcTypeVarContext.copyFromClone(bestSrcTypeVarContext);
                }
            }
        }
        // If the source is a constrained TypeVar, see if we can assign all of the
        // constraints to the union.
        if (!foundMatch) {
            if ((0, types_1.isTypeVar)(srcType) && srcType.details.constraints.length > 0) {
                foundMatch = assignType(destType, makeTopLevelTypeVarsConcrete(srcType), diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount);
            }
        }
        if (!foundMatch) {
            if (diag && diagAddendum) {
                diag.addMessage(localize_1.LocAddendum.typeAssignmentMismatch().format(printSrcDestTypes(srcType, destType)));
                diag.addAddendum(diagAddendum);
            }
            return false;
        }
        return true;
    }
    function assignConditionalTypeToTypeVar(destType, srcType, recursionCount) {
        // The srcType is assignable only if all of its subtypes are assignable.
        return !(0, types_1.findSubtype)(srcType, (srcSubtype) => {
            var _a;
            if ((0, types_1.isTypeSame)(destType, srcSubtype, { ignorePseudoGeneric: true }, recursionCount)) {
                return false;
            }
            if ((0, typeUtils_1.isIncompleteUnknown)(srcSubtype)) {
                return false;
            }
            const destTypeVarName = types_1.TypeVarType.getNameWithScope(destType);
            // Determine which conditions on this type apply to this type variable.
            // There might be more than one of them.
            const applicableConditions = ((_a = (0, typeUtils_1.getTypeCondition)(srcSubtype)) !== null && _a !== void 0 ? _a : []).filter((constraint) => constraint.typeVar.nameWithScope === destTypeVarName);
            // If there are no applicable conditions, it's not assignable.
            if (applicableConditions.length === 0) {
                return true;
            }
            return !applicableConditions.some((condition) => {
                if (condition.typeVar.nameWithScope === types_1.TypeVarType.getNameWithScope(destType)) {
                    if (destType.details.boundType) {
                        (0, debug_1.assert)(condition.constraintIndex === 0, 'Expected constraint for bound TypeVar to have index of 0');
                        return assignType(destType.details.boundType, srcSubtype, 
                        /* diag */ undefined, 
                        /* destTypeVarContext */ undefined, 
                        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount);
                    }
                    if (destType.details.constraints.length > 0) {
                        (0, debug_1.assert)(condition.constraintIndex < destType.details.constraints.length, 'Constraint for constrained TypeVar is out of bounds');
                        return assignType(destType.details.constraints[condition.constraintIndex], srcSubtype, 
                        /* diag */ undefined, 
                        /* destTypeVarContext */ undefined, 
                        /* srcTypeVarContext */ undefined, 0 /* AssignTypeFlags.Default */, recursionCount);
                    }
                    // This is a non-bound and non-constrained type variable with a matching condition.
                    return true;
                }
                return false;
            });
        });
    }
    // If the class is a protocol and it has a `__call__` method but no other methods
    // or attributes that would be incompatible with a function, this method returns
    // the signature of the call implied by the `__call__` method. Otherwise it returns
    // undefined.
    function getCallbackProtocolType(objType, recursionCount = 0) {
        if (!(0, types_1.isClassInstance)(objType) || !types_1.ClassType.isProtocolClass(objType)) {
            return undefined;
        }
        // Make sure that the protocol class doesn't define any fields that
        // a normal function wouldn't be compatible with.
        for (const mroClass of objType.details.mro) {
            if ((0, types_1.isClass)(mroClass) && types_1.ClassType.isProtocolClass(mroClass)) {
                for (const field of types_1.ClassType.getSymbolTable(mroClass)) {
                    if (field[0] !== '__call__' && !field[1].isIgnoredForProtocolMatch()) {
                        let fieldIsPartOfFunction = false;
                        if (functionObj && (0, types_1.isClass)(functionObj)) {
                            if (types_1.ClassType.getSymbolTable(functionObj).has(field[0])) {
                                fieldIsPartOfFunction = true;
                            }
                        }
                        if (!fieldIsPartOfFunction) {
                            return undefined;
                        }
                    }
                }
            }
        }
        const boundMethod = getBoundMagicMethod(objType, '__call__', 
        /* selfType */ undefined, 
        /* diag */ undefined, recursionCount);
        if (boundMethod) {
            return (0, typeUtils_1.removeParamSpecVariadicsFromSignature)(boundMethod);
        }
        return undefined;
    }
    function assignFunctionParameter(destType, srcType, paramIndex, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        // Handle the special case where the dest type is a synthesized
        // "self" for a protocol class.
        if ((0, types_1.isTypeVar)(destType) &&
            destType.details.isSynthesized &&
            destType.details.boundType &&
            (0, types_1.isClassInstance)(destType.details.boundType) &&
            types_1.ClassType.isProtocolClass(destType.details.boundType)) {
            return true;
        }
        if ((0, types_1.isVariadicTypeVar)(destType) && !(0, types_1.isUnpacked)(srcType)) {
            return false;
        }
        let specializedSrcType = srcType;
        let specializedDestType = destType;
        let doSpecializationStep = false;
        if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0) {
            specializedDestType = (0, typeUtils_1.applySolvedTypeVars)(destType, destTypeVarContext, { useNarrowBoundOnly: true });
            doSpecializationStep = (0, typeUtils_1.requiresSpecialization)(specializedDestType);
        }
        else {
            specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(srcType, srcTypeVarContext, { useNarrowBoundOnly: true });
            doSpecializationStep = (0, typeUtils_1.requiresSpecialization)(specializedSrcType);
        }
        // Is an additional specialization step required?
        if (doSpecializationStep) {
            assignType(specializedSrcType, specializedDestType, 
            /* diag */ undefined, srcTypeVarContext, destTypeVarContext, (flags ^ 2 /* AssignTypeFlags.ReverseTypeVarMatching */) | 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */, recursionCount);
            if ((flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) === 0) {
                specializedDestType = (0, typeUtils_1.applySolvedTypeVars)(destType, destTypeVarContext);
            }
            else {
                specializedSrcType = (0, typeUtils_1.applySolvedTypeVars)(srcType, srcTypeVarContext);
            }
        }
        if (!assignType(specializedSrcType, specializedDestType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), srcTypeVarContext, destTypeVarContext, flags, recursionCount)) {
            // There are cases involving lambdas where the parameter types are type
            // variables and match exactly but fail the assignment check because the
            // TypeVars are out of scope. This happens because parameter types assigned
            // to lambdas during bidirectional inference do not match the TypeVar scope
            // of the lambda itself.
            if (!(0, types_1.isTypeSame)(destType, srcType)) {
                if (diag && paramIndex !== undefined) {
                    diag.addMessage(localize_1.LocAddendum.paramAssignment().format({
                        index: paramIndex + 1,
                        sourceType: printType(destType),
                        destType: printType(srcType),
                    }));
                }
                return false;
            }
        }
        return true;
    }
    // Determines whether we need to pack some of the source positionals
    // into a tuple that matches a variadic *args parameter in the destination.
    function adjustSourceParamDetailsForDestVariadic(srcDetails, destDetails) {
        var _a;
        // If there is no *args parameter in the dest, we have nothing to do.
        if (destDetails.argsIndex === undefined) {
            return;
        }
        // If the *args parameter isn't an unpacked TypeVarTuple or tuple,
        // we have nothing to do.
        if (!(0, types_1.isUnpacked)(destDetails.params[destDetails.argsIndex].type)) {
            return;
        }
        // If the source doesn't have enough positional parameters, we have nothing to do.
        if (srcDetails.params.length < destDetails.argsIndex) {
            return;
        }
        let srcLastToPackIndex = srcDetails.params.findIndex((p, i) => {
            (0, debug_1.assert)(destDetails.argsIndex !== undefined);
            return i >= destDetails.argsIndex && p.source === parameterUtils_1.ParameterSource.KeywordOnly;
        });
        if (srcLastToPackIndex < 0) {
            srcLastToPackIndex = srcDetails.params.length;
        }
        const destFirstNonPositional = (_a = destDetails.firstKeywordOnlyIndex) !== null && _a !== void 0 ? _a : destDetails.params.length;
        const suffixLength = destFirstNonPositional - destDetails.argsIndex - 1;
        const srcPositionalsToPack = srcDetails.params.slice(destDetails.argsIndex, srcLastToPackIndex - suffixLength);
        const srcTupleTypes = [];
        srcPositionalsToPack.forEach((entry) => {
            if (entry.param.category === 1 /* ParameterCategory.ArgsList */) {
                if ((0, types_1.isUnpackedVariadicTypeVar)(entry.type)) {
                    srcTupleTypes.push({ type: entry.type, isUnbounded: false });
                }
                else if ((0, types_1.isUnpackedClass)(entry.type) && entry.type.tupleTypeArguments) {
                    (0, collectionUtils_1.appendArray)(srcTupleTypes, entry.type.tupleTypeArguments);
                }
                else {
                    srcTupleTypes.push({ type: entry.type, isUnbounded: true });
                }
            }
            else {
                srcTupleTypes.push({ type: entry.type, isUnbounded: false, isOptional: entry.param.hasDefault });
            }
        });
        if (srcTupleTypes.length !== 1 || !(0, types_1.isVariadicTypeVar)(srcTupleTypes[0].type)) {
            const srcPositionalsType = makeTupleObject(srcTupleTypes, /* isUnpackedTuple */ true);
            // Snip out the portion of the source positionals that map to the variadic
            // dest parameter and replace it with a single parameter that is typed as a
            // tuple containing the individual types of the replaced parameters.
            srcDetails.params = [
                ...srcDetails.params.slice(0, destDetails.argsIndex),
                {
                    param: {
                        category: 1 /* ParameterCategory.ArgsList */,
                        name: '_arg_combined',
                        isNameSynthesized: true,
                        hasDeclaredType: true,
                        type: srcPositionalsType,
                    },
                    type: srcPositionalsType,
                    index: -1,
                    source: parameterUtils_1.ParameterSource.PositionOnly,
                },
                ...srcDetails.params.slice(destDetails.argsIndex + srcPositionalsToPack.length, srcDetails.params.length),
            ];
            const argsIndex = srcDetails.params.findIndex((param) => param.param.category === 1 /* ParameterCategory.ArgsList */);
            srcDetails.argsIndex = argsIndex >= 0 ? argsIndex : undefined;
            const kwargsIndex = srcDetails.params.findIndex((param) => param.param.category === 2 /* ParameterCategory.KwargsDict */);
            srcDetails.kwargsIndex = kwargsIndex >= 0 ? kwargsIndex : undefined;
            const firstKeywordOnlyIndex = srcDetails.params.findIndex((param) => param.source === parameterUtils_1.ParameterSource.KeywordOnly);
            srcDetails.firstKeywordOnlyIndex = firstKeywordOnlyIndex >= 0 ? firstKeywordOnlyIndex : undefined;
            srcDetails.positionOnlyParamCount = Math.max(0, srcDetails.params.findIndex((p) => p.source !== parameterUtils_1.ParameterSource.PositionOnly ||
                p.param.category !== 0 /* ParameterCategory.Simple */ ||
                p.param.hasDefault));
        }
    }
    function assignFunction(destType, srcType, diag, destTypeVarContext, srcTypeVarContext, flags, recursionCount) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        let canAssign = true;
        const checkReturnType = (flags & 64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */) === 0;
        const reverseMatching = (flags & 2 /* AssignTypeFlags.ReverseTypeVarMatching */) !== 0;
        flags &= ~64 /* AssignTypeFlags.SkipFunctionReturnTypeCheck */;
        destType = (0, typeUtils_1.removeParamSpecVariadicsFromFunction)(destType);
        srcType = (0, typeUtils_1.removeParamSpecVariadicsFromFunction)(srcType);
        const destParamDetails = (0, parameterUtils_1.getParameterListDetails)(destType);
        const srcParamDetails = (0, parameterUtils_1.getParameterListDetails)(srcType);
        adjustSourceParamDetailsForDestVariadic(reverseMatching ? destParamDetails : srcParamDetails, reverseMatching ? srcParamDetails : destParamDetails);
        const targetIncludesParamSpec = reverseMatching ? !!srcType.details.paramSpec : !!destType.details.paramSpec;
        const destPositionalCount = (_a = destParamDetails.firstKeywordOnlyIndex) !== null && _a !== void 0 ? _a : destParamDetails.params.length;
        const srcPositionalCount = (_b = srcParamDetails.firstKeywordOnlyIndex) !== null && _b !== void 0 ? _b : srcParamDetails.params.length;
        const positionalsToMatch = Math.min(destPositionalCount, srcPositionalCount);
        // Match positional parameters.
        for (let paramIndex = 0; paramIndex < positionalsToMatch; paramIndex++) {
            if (paramIndex === 0 &&
                destType.details.methodClass &&
                (flags & 65536 /* AssignTypeFlags.IgnoreSelfClsParamCompatibility */) !== 0) {
                if (types_1.FunctionType.isInstanceMethod(destType) || types_1.FunctionType.isClassMethod(destType)) {
                    continue;
                }
            }
            // Skip over the *args parameter since it's handled separately below.
            if (paramIndex === destParamDetails.argsIndex) {
                continue;
            }
            const destParam = destParamDetails.params[paramIndex];
            const srcParam = srcParamDetails.params[paramIndex];
            // Find the original index of this source param. If we synthesized it above (for
            // a variadic parameter), it may not be found.
            const srcParamType = srcParam.type;
            const destParamType = destParam.type;
            const destParamName = (_c = destParam.param.name) !== null && _c !== void 0 ? _c : '';
            const srcParamName = (_d = srcParam.param.name) !== null && _d !== void 0 ? _d : '';
            if (destParamName) {
                const isDestPositionalOnly = destParam.source === parameterUtils_1.ParameterSource.PositionOnly;
                if (!isDestPositionalOnly &&
                    destParam.param.category !== 1 /* ParameterCategory.ArgsList */ &&
                    srcParam.param.category !== 1 /* ParameterCategory.ArgsList */) {
                    if (srcParam.source === parameterUtils_1.ParameterSource.PositionOnly) {
                        diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.functionParamPositionOnly().format({
                            name: destParamName,
                        }));
                        canAssign = false;
                    }
                    else if (destParamName !== srcParamName) {
                        diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.functionParamName().format({
                            srcName: srcParamName,
                            destName: destParamName,
                        }));
                        canAssign = false;
                    }
                }
            }
            if (!!destParam.param.hasDefault &&
                !srcParam.param.hasDefault &&
                paramIndex !== srcParamDetails.argsIndex) {
                diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.functionParamDefaultMissing().format({
                    name: srcParamName,
                }));
                canAssign = false;
            }
            // Handle the special case of an overloaded __init__ method whose self
            // parameter is annotated.
            if (paramIndex === 0 &&
                srcType.details.name === '__init__' &&
                types_1.FunctionType.isInstanceMethod(srcType) &&
                destType.details.name === '__init__' &&
                types_1.FunctionType.isInstanceMethod(destType) &&
                types_1.FunctionType.isOverloaded(destType) &&
                destParam.param.hasDeclaredType) {
                continue;
            }
            if (!assignFunctionParameter(destParamType, srcParamType, paramIndex, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                // Handle the special case where the source parameter is a synthesized
                // TypeVar for "self" or "cls".
                if ((flags & 512 /* AssignTypeFlags.SkipSelfClsTypeCheck */) === 0 ||
                    !(0, types_1.isTypeVar)(srcParamType) ||
                    !srcParamType.details.isSynthesized) {
                    canAssign = false;
                }
            }
        }
        if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType) &&
            destParamDetails.firstPositionOrKeywordIndex < srcParamDetails.positionOnlyParamCount &&
            !targetIncludesParamSpec) {
            diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.argsPositionOnly().format({
                expected: srcParamDetails.positionOnlyParamCount,
                received: destParamDetails.firstPositionOrKeywordIndex,
            }));
            canAssign = false;
        }
        if (destPositionalCount < srcPositionalCount) {
            // If the dest type includes a ParamSpec, the additional parameters
            // can be assigned to it, so no need to report an error here.
            if (!targetIncludesParamSpec) {
                const nonDefaultSrcParamCount = srcParamDetails.params.filter((p) => !!p.param.name && !p.param.hasDefault && p.param.category === 0 /* ParameterCategory.Simple */).length;
                if (destParamDetails.argsIndex === undefined) {
                    if (destPositionalCount < nonDefaultSrcParamCount) {
                        if (destParamDetails.firstPositionOrKeywordIndex > 0 &&
                            destParamDetails.firstPositionOrKeywordIndex < srcPositionalCount) {
                            diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.functionTooFewParams().format({
                                expected: nonDefaultSrcParamCount,
                                received: destPositionalCount,
                            }));
                            canAssign = false;
                        }
                    }
                }
                else {
                    // Make sure the remaining positional arguments are of the
                    // correct type for the *args parameter.
                    const destArgsType = destParamDetails.params[destParamDetails.argsIndex].type;
                    if (!(0, types_1.isAnyOrUnknown)(destArgsType)) {
                        for (let paramIndex = destPositionalCount; paramIndex < srcPositionalCount; paramIndex++) {
                            const srcParamType = srcParamDetails.params[paramIndex].type;
                            if (!assignFunctionParameter(destArgsType, srcParamType, paramIndex, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                                canAssign = false;
                            }
                        }
                    }
                }
            }
        }
        else if (srcPositionalCount < destPositionalCount) {
            if (srcParamDetails.argsIndex !== undefined) {
                // Make sure the remaining dest parameters can be assigned to the source
                // *args parameter type.
                const srcArgsType = srcParamDetails.params[srcParamDetails.argsIndex].type;
                for (let paramIndex = srcPositionalCount; paramIndex < destPositionalCount; paramIndex++) {
                    if (paramIndex === srcParamDetails.argsIndex) {
                        continue;
                    }
                    const destParamType = destParamDetails.params[paramIndex].type;
                    if ((0, types_1.isVariadicTypeVar)(destParamType) && !(0, types_1.isVariadicTypeVar)(srcArgsType)) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.typeVarTupleRequiresKnownLength());
                        canAssign = false;
                    }
                    else {
                        if (!assignFunctionParameter(destParamType, srcArgsType, paramIndex, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                            canAssign = false;
                        }
                        if (destParamDetails.params[paramIndex].source !== parameterUtils_1.ParameterSource.PositionOnly &&
                            srcParamDetails.kwargsIndex === undefined) {
                            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.namedParamMissingInSource().format({
                                name: (_e = destParamDetails.params[paramIndex].param.name) !== null && _e !== void 0 ? _e : '',
                            }));
                            canAssign = false;
                        }
                    }
                }
            }
            else if (!srcParamDetails.paramSpec) {
                // If the dest contains a *args, remove it from the positional count
                // because it's OK for zero source args to match it.
                let adjDestPositionalCount = destPositionalCount;
                if (destParamDetails.argsIndex !== undefined && destParamDetails.argsIndex < destPositionalCount) {
                    adjDestPositionalCount--;
                }
                if (srcPositionalCount < adjDestPositionalCount) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.functionTooManyParams().format({
                        expected: srcPositionalCount,
                        received: destPositionalCount,
                    }));
                    canAssign = false;
                }
            }
        }
        // If both src and dest have an "*args" parameter, make sure
        // their types are compatible.
        if (srcParamDetails.argsIndex !== undefined &&
            destParamDetails.argsIndex !== undefined &&
            !types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType)) {
            let destArgsType = destParamDetails.params[destParamDetails.argsIndex].type;
            let srcArgsType = srcParamDetails.params[srcParamDetails.argsIndex].type;
            if (!(0, types_1.isUnpacked)(destArgsType)) {
                destArgsType = makeTupleObject([{ type: destArgsType, isUnbounded: true }], /* isUnpackedTuple */ true);
            }
            if (!(0, types_1.isUnpacked)(srcArgsType)) {
                srcArgsType = makeTupleObject([{ type: srcArgsType, isUnbounded: true }], /* isUnpackedTuple */ true);
            }
            if (!assignFunctionParameter(destArgsType, srcArgsType, destParamDetails.params[destParamDetails.argsIndex].index, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                canAssign = false;
            }
        }
        // If the dest has an "*args" but the source doesn't, report the incompatibility.
        // The converse situation is OK.
        if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType) &&
            srcParamDetails.argsIndex === undefined &&
            srcType.details.paramSpec === undefined &&
            destParamDetails.argsIndex !== undefined &&
            !destParamDetails.hasUnpackedVariadicTypeVar) {
            diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.argsParamMissing().format({
                paramName: (_f = destParamDetails.params[destParamDetails.argsIndex].param.name) !== null && _f !== void 0 ? _f : '',
            }));
            canAssign = false;
        }
        // Handle matching of named (keyword) parameters.
        if (!targetIncludesParamSpec) {
            // Build a dictionary of named parameters in the dest.
            const destParamMap = new Map();
            if (destParamDetails.firstKeywordOnlyIndex !== undefined) {
                destParamDetails.params.forEach((param, index) => {
                    if (index >= destParamDetails.firstKeywordOnlyIndex) {
                        if (param.param.name && param.param.category === 0 /* ParameterCategory.Simple */) {
                            destParamMap.set(param.param.name, param);
                        }
                    }
                });
            }
            // If the dest has fewer positional arguments than the source, the remaining
            // positional arguments in the source can be treated as named arguments.
            let srcStartOfNamed = srcParamDetails.firstKeywordOnlyIndex !== undefined
                ? srcParamDetails.firstKeywordOnlyIndex
                : srcParamDetails.params.length;
            if (destPositionalCount < srcPositionalCount && destParamDetails.argsIndex === undefined) {
                srcStartOfNamed = destPositionalCount;
            }
            if (srcStartOfNamed >= 0) {
                srcParamDetails.params.forEach((srcParamInfo, index) => {
                    if (index >= srcStartOfNamed) {
                        if (srcParamInfo.param.name &&
                            srcParamInfo.param.category === 0 /* ParameterCategory.Simple */ &&
                            srcParamInfo.source !== parameterUtils_1.ParameterSource.PositionOnly) {
                            const destParamInfo = destParamMap.get(srcParamInfo.param.name);
                            const paramDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                            const srcParamType = srcParamInfo.type;
                            if (!destParamInfo) {
                                if (destParamDetails.kwargsIndex === undefined && !srcParamInfo.param.hasDefault) {
                                    if (paramDiag && srcParamDetails.firstKeywordOnlyIndex !== undefined) {
                                        paramDiag.addMessage(localize_1.LocAddendum.namedParamMissingInDest().format({
                                            name: srcParamInfo.param.name,
                                        }));
                                    }
                                    canAssign = false;
                                }
                                else if (destParamDetails.kwargsIndex !== undefined) {
                                    // Make sure we can assign the type to the Kwargs.
                                    if (!assignFunctionParameter(destParamDetails.params[destParamDetails.kwargsIndex].type, srcParamType, destParamDetails.params[destParamDetails.kwargsIndex].index, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                                        canAssign = false;
                                    }
                                }
                            }
                            else {
                                const destParamType = destParamInfo.type;
                                const specializedDestParamType = destTypeVarContext
                                    ? (0, typeUtils_1.applySolvedTypeVars)(destParamType, destTypeVarContext)
                                    : destParamType;
                                if (!assignFunctionParameter(destParamInfo.type, srcParamType, 
                                /* paramIndex */ undefined, paramDiag === null || paramDiag === void 0 ? void 0 : paramDiag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                                    if (paramDiag) {
                                        paramDiag.addMessage(localize_1.LocAddendum.namedParamTypeMismatch().format({
                                            name: srcParamInfo.param.name,
                                            sourceType: printType(specializedDestParamType),
                                            destType: printType(srcParamType),
                                        }));
                                    }
                                    canAssign = false;
                                }
                                if (!!destParamInfo.param.hasDefault && !srcParamInfo.param.hasDefault) {
                                    diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.functionParamDefaultMissing().format({
                                        name: srcParamInfo.param.name,
                                    }));
                                    canAssign = false;
                                }
                                destParamMap.delete(srcParamInfo.param.name);
                            }
                        }
                    }
                });
            }
            // See if there are any unmatched named parameters.
            destParamMap.forEach((destParamInfo, paramName) => {
                if (srcParamDetails.kwargsIndex !== undefined && destParamInfo.param.name) {
                    // Make sure the src kwargs type is compatible.
                    if (!assignFunctionParameter(destParamInfo.param.type, srcParamDetails.params[srcParamDetails.kwargsIndex].type, destParamInfo.index, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                        canAssign = false;
                    }
                    destParamMap.delete(paramName);
                }
                else {
                    diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.namedParamMissingInSource().format({ name: paramName }));
                    canAssign = false;
                }
            });
            // If both src and dest have a "**kwargs" parameter, make sure their types are compatible.
            if (srcParamDetails.kwargsIndex !== undefined && destParamDetails.kwargsIndex !== undefined) {
                if (!assignFunctionParameter(destParamDetails.params[destParamDetails.kwargsIndex].type, srcParamDetails.params[srcParamDetails.kwargsIndex].type, destParamDetails.params[destParamDetails.kwargsIndex].index, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                    canAssign = false;
                }
            }
            // If the dest has a "**kwargs" but the source doesn't, report the incompatibility.
            // The converse situation is OK.
            if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(destType) &&
                srcParamDetails.kwargsIndex === undefined &&
                srcType.details.paramSpec === undefined &&
                destParamDetails.kwargsIndex !== undefined) {
                diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.kwargsParamMissing().format({
                    paramName: destParamDetails.params[destParamDetails.kwargsIndex].param.name,
                }));
                canAssign = false;
            }
        }
        // If the source and the dest are using the same ParamSpec, any additional
        // concatenated parameters must match.
        if (targetIncludesParamSpec &&
            ((_g = srcType.details.paramSpec) === null || _g === void 0 ? void 0 : _g.nameWithScope) === ((_h = destType.details.paramSpec) === null || _h === void 0 ? void 0 : _h.nameWithScope)) {
            if (srcParamDetails.params.length !== destParamDetails.params.length) {
                canAssign = false;
            }
        }
        const effectiveSrcTypeVarContext = reverseMatching ? destTypeVarContext : srcTypeVarContext;
        // If the target function was generic and we solved some of the type variables
        // in that generic type, assign them back to the destination typeVar.
        const typeVarSignatureContext = effectiveSrcTypeVarContext.getPrimarySignature();
        typeVarSignatureContext.getTypeVars().forEach((typeVarEntry) => {
            assignType(typeVarEntry.typeVar, typeVarSignatureContext.getTypeVarType(typeVarEntry.typeVar), 
            /* diag */ undefined, destTypeVarContext, srcTypeVarContext, 0 /* AssignTypeFlags.Default */, recursionCount);
        });
        // Are we assigning to a function with a ParamSpec?
        if (targetIncludesParamSpec) {
            const effectiveDestType = reverseMatching ? srcType : destType;
            const effectiveSrcType = reverseMatching ? destType : srcType;
            if (effectiveDestType.details.paramSpec) {
                const requiredMatchParamCount = effectiveDestType.details.parameters.filter((p) => {
                    if (!p.name) {
                        return false;
                    }
                    if (p.category === 0 /* ParameterCategory.Simple */ && (0, types_1.isParamSpec)(p.type)) {
                        return false;
                    }
                    return true;
                }).length;
                let matchedParamCount = 0;
                const remainingParams = [];
                // If there are parameters in the source that are not matched
                // to parameters in the dest, assume these are concatenated on
                // to the ParamSpec.
                effectiveSrcType.details.parameters.forEach((p, index) => {
                    if (matchedParamCount < requiredMatchParamCount) {
                        if (p.name) {
                            matchedParamCount++;
                        }
                    }
                    else if ((0, types_1.isPositionOnlySeparator)(p) && remainingParams.length === 0) {
                        // Don't bother pushing a position-only separator if it
                        // is the first remaining param.
                    }
                    else {
                        remainingParams.push({
                            category: p.category,
                            name: p.name,
                            isNameSynthesized: p.isNameSynthesized,
                            hasDefault: p.hasDefault,
                            hasDeclaredType: p.hasDeclaredType,
                            defaultValueExpression: p.defaultValueExpression,
                            type: types_1.FunctionType.getEffectiveParameterType(effectiveSrcType, index),
                        });
                    }
                });
                const srcParamSpec = effectiveSrcType.details.paramSpec;
                const destParamSpec = effectiveDestType.details.paramSpec;
                // If there are remaining parameters and the source and dest do not contain
                // the same ParamSpec, synthesize a function for the remaining parameters.
                if (remainingParams.length > 0 ||
                    !srcParamSpec ||
                    !(0, types_1.isTypeSame)(srcParamSpec, destParamSpec, { ignoreTypeFlags: true })) {
                    const remainingFunction = types_1.FunctionType.createInstance('', '', '', effectiveSrcType.details.flags | 64 /* FunctionTypeFlags.SynthesizedMethod */, effectiveSrcType.details.docString);
                    remainingFunction.details.deprecatedMessage = effectiveSrcType.details.deprecatedMessage;
                    remainingFunction.details.typeVarScopeId = effectiveSrcType.details.typeVarScopeId;
                    remainingFunction.details.constructorTypeVarScopeId =
                        effectiveSrcType.details.constructorTypeVarScopeId;
                    remainingFunction.details.methodClass = effectiveSrcType.details.methodClass;
                    remainingParams.forEach((param) => {
                        types_1.FunctionType.addParameter(remainingFunction, param);
                    });
                    remainingFunction.details.paramSpec = srcParamSpec ? (0, typeUtils_1.convertToInstance)(srcParamSpec) : undefined;
                    types_1.FunctionType.addHigherOrderTypeVarScopeIds(remainingFunction, effectiveSrcType.details.higherOrderTypeVarScopeIds);
                    if (!assignType(destParamSpec, remainingFunction, 
                    /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags)) {
                        // If we couldn't assign the function to the ParamSpec, see if we can
                        // assign only the ParamSpec. This is possible if there were no
                        // remaining parameters.
                        if (remainingParams.length > 0 ||
                            !srcParamSpec ||
                            !assignType((0, typeUtils_1.convertToInstance)(destParamSpec), (0, typeUtils_1.convertToInstance)(srcParamSpec), 
                            /* diag */ undefined, destTypeVarContext, srcTypeVarContext, flags)) {
                            canAssign = false;
                        }
                    }
                }
            }
        }
        // Match the return parameter.
        if (checkReturnType) {
            const destReturnType = getFunctionEffectiveReturnType(destType);
            if (!(0, types_1.isAnyOrUnknown)(destReturnType)) {
                const srcReturnType = (0, typeUtils_1.applySolvedTypeVars)(getFunctionEffectiveReturnType(srcType), srcTypeVarContext);
                const returnDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                let isReturnTypeCompatible = false;
                let effectiveFlags = flags;
                // If the source has a declared return type that includes a literal
                // in its annotation, assume that we will want the constraint
                // solver to retain literals.
                if (srcType.details.declaredReturnType &&
                    (0, typeUtils_1.containsLiteralType)(srcType.details.declaredReturnType, /* includeTypeArgs */ true)) {
                    effectiveFlags |= 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */;
                }
                if (assignType(destReturnType, srcReturnType, returnDiag === null || returnDiag === void 0 ? void 0 : returnDiag.createAddendum(), destTypeVarContext, srcTypeVarContext, effectiveFlags, recursionCount)) {
                    isReturnTypeCompatible = true;
                }
                else {
                    // Handle the special case where the return type is a TypeGuard[T]
                    // or TypeIs[T]. This should also act as a bool, since that's its
                    // type at runtime.
                    if ((0, types_1.isClassInstance)(srcReturnType) &&
                        types_1.ClassType.isBuiltIn(srcReturnType, ['TypeGuard', 'TypeIs']) &&
                        boolClassType &&
                        (0, types_1.isInstantiableClass)(boolClassType)) {
                        if (assignType(destReturnType, types_1.ClassType.cloneAsInstance(boolClassType), returnDiag === null || returnDiag === void 0 ? void 0 : returnDiag.createAddendum(), destTypeVarContext, srcTypeVarContext, flags, recursionCount)) {
                            isReturnTypeCompatible = true;
                        }
                    }
                }
                if (!isReturnTypeCompatible) {
                    if (returnDiag) {
                        returnDiag.addMessage(localize_1.LocAddendum.functionReturnTypeMismatch().format({
                            sourceType: printType(srcReturnType),
                            destType: printType(destReturnType),
                        }));
                    }
                    canAssign = false;
                }
            }
        }
        // Apply any solved source TypeVars to the dest TypeVar solutions. This
        // allows for higher-order functions to accept generic callbacks.
        (0, typeUtils_1.applySourceContextTypeVars)(destTypeVarContext, srcTypeVarContext);
        return canAssign;
    }
    // If the declaredType contains type arguments that are "Any" and
    // the corresponding type argument in the assignedType is not "Any",
    // replace that type argument in the assigned type. This function assumes
    // that the caller has already verified that the assignedType is assignable
    // to the declaredType.
    function replaceTypeArgsWithAny(node, declaredType, assignedType, recursionCount = 0) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return undefined;
        }
        recursionCount++;
        if (assignedType.details.typeParameters.length > 0 &&
            assignedType.typeArguments &&
            assignedType.typeArguments.length <= assignedType.details.typeParameters.length &&
            !assignedType.tupleTypeArguments) {
            const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(assignedType));
            (0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluatorInterface, types_1.ClassType.cloneForSpecialization(assignedType, 
            /* typeArguments */ undefined, 
            /* isTypeArgumentExplicit */ false), declaredType, typeVarContext, ParseTreeUtils.getTypeVarScopesForNode(node), node.start);
            let replacedTypeArg = false;
            const newTypeArgs = assignedType.typeArguments.map((typeArg, index) => {
                const typeParam = assignedType.details.typeParameters[index];
                const expectedTypeArgType = typeVarContext.getPrimarySignature().getTypeVarType(typeParam);
                if (expectedTypeArgType) {
                    if ((0, types_1.isAnyOrUnknown)(expectedTypeArgType) || (0, types_1.isAnyOrUnknown)(typeArg)) {
                        replacedTypeArg = true;
                        return expectedTypeArgType;
                    }
                    else if ((0, types_1.isClassInstance)(expectedTypeArgType) && (0, types_1.isClassInstance)(typeArg)) {
                        // Recursively replace Any in the type argument.
                        const recursiveReplacement = replaceTypeArgsWithAny(node, expectedTypeArgType, typeArg, recursionCount);
                        if (recursiveReplacement) {
                            replacedTypeArg = true;
                            return recursiveReplacement;
                        }
                    }
                    else if ((0, typeUtils_1.containsAnyRecursive)(expectedTypeArgType)) {
                        // If the expected type arg contains an Any, we can replace it with
                        // a version that doesn't contain Any if the replacement doesn't violate
                        // the variance of the type parameter.
                        const variance = types_1.TypeVarType.getVariance(typeParam);
                        const isSubtype = assignType(expectedTypeArgType, typeArg);
                        const isSupertype = assignType(typeArg, expectedTypeArgType);
                        if ((variance === 4 /* Variance.Contravariant */ || isSubtype) &&
                            (variance === 3 /* Variance.Covariant */ || isSupertype)) {
                            replacedTypeArg = true;
                            return expectedTypeArgType;
                        }
                    }
                }
                return typeArg;
            });
            if (replacedTypeArg) {
                return types_1.ClassType.cloneForSpecialization(assignedType, newTypeArgs, /* isTypeArgumentExplicit */ true);
            }
        }
        // If the declared and assigned types are the same generic type but the assigned type
        // contains one or more unknowns, use the declared type instead.
        if (types_1.ClassType.isSameGenericClass(declaredType, assignedType)) {
            if ((0, typeUtils_1.containsAnyRecursive)(assignedType) && !(0, typeUtils_1.containsAnyRecursive)(declaredType)) {
                return declaredType;
            }
        }
        return undefined;
    }
    // When a value is assigned to a variable with a declared type,
    // we may be able to narrow the type based on the assignment.
    function narrowTypeBasedOnAssignment(node, declaredType, assignedType) {
        const narrowedType = (0, typeUtils_1.mapSubtypes)(assignedType, (assignedSubtype) => {
            // Handle the special case where the assigned type is a literal type.
            // Some types include very large unions of literal types, and we don't
            // want to use an n^2 loop to compare them.
            if ((0, types_1.isClass)(assignedSubtype) && (0, typeUtils_1.isLiteralType)(assignedSubtype)) {
                if ((0, types_1.isUnion)(declaredType) && types_1.UnionType.containsType(declaredType, assignedSubtype)) {
                    return assignedSubtype;
                }
            }
            const narrowedSubtype = (0, typeUtils_1.mapSubtypes)(declaredType, (declaredSubtype) => {
                // We can't narrow "Any".
                if ((0, types_1.isAnyOrUnknown)(declaredSubtype)) {
                    return declaredSubtype;
                }
                if (assignType(declaredSubtype, assignedSubtype)) {
                    // If the assigned subtype is Any, stick with the declared type.
                    if ((0, types_1.isAny)(assignedSubtype)) {
                        return declaredSubtype;
                    }
                    if ((0, types_1.isClass)(declaredSubtype) &&
                        (0, types_1.isClass)(assignedSubtype) &&
                        types_1.TypeBase.isInstance(declaredSubtype) === types_1.TypeBase.isInstance(assignedSubtype)) {
                        const result = replaceTypeArgsWithAny(node, declaredSubtype, assignedSubtype);
                        if (result) {
                            assignedSubtype = result;
                        }
                        return assignedSubtype;
                    }
                    if (!(0, types_1.isTypeVar)(declaredSubtype) && (0, types_1.isTypeVar)(assignedSubtype)) {
                        // If the source is an unsolved TypeVar but the declared type is concrete,
                        // use the concrete type.
                        return declaredSubtype;
                    }
                    // If the declared type doesn't contain any `Any` but the assigned
                    // type does, stick with the declared type.
                    if ((0, typeUtils_1.containsAnyRecursive)(assignedSubtype) && !(0, typeUtils_1.containsAnyRecursive)(declaredSubtype)) {
                        return declaredSubtype;
                    }
                    return assignedSubtype;
                }
                return undefined;
            });
            // If we couldn't assign the assigned subtype any of the declared
            // subtypes, the types are incompatible. Return the unnarrowed form.
            if ((0, types_1.isNever)(narrowedSubtype)) {
                return assignedSubtype;
            }
            return narrowedSubtype;
        });
        // If the result of narrowing is an Unknown that is incomplete, propagate the
        // incomplete type for the benefit of code flow analysis.
        // If the result of narrowing is a complete Unknown, combine the Unknown type
        // with the declared type. In strict mode, this will retain the "unknown type"
        // diagnostics while still providing reasonable completion suggestions.
        if ((0, typeUtils_1.isIncompleteUnknown)(narrowedType)) {
            return narrowedType;
        }
        else if ((0, types_1.isUnknown)(narrowedType)) {
            return (0, types_1.combineTypes)([narrowedType, declaredType]);
        }
        return narrowedType;
    }
    function validateOverrideMethod(baseMethod, overrideMethod, baseClass, diag, enforceParamNames = true) {
        // If we're overriding a non-method with a method, report it as an error.
        // This occurs when a non-property overrides a property.
        if (!(0, types_1.isFunction)(baseMethod) && !(0, types_1.isOverloadedFunction)(baseMethod)) {
            diag.addMessage(localize_1.LocAddendum.overrideType().format({ type: printType(baseMethod) }));
            return false;
        }
        if ((0, types_1.isFunction)(baseMethod)) {
            // Handle the easy case - a simple function overriding another simple function.
            if ((0, types_1.isFunction)(overrideMethod)) {
                return validateOverrideMethodInternal(baseMethod, overrideMethod, diag, enforceParamNames);
            }
            // For an overload overriding a base method, at least one overload
            // or the implementation must be compatible with the base method.
            if (overrideMethod.overloads.some((overrideOverload) => {
                return validateOverrideMethodInternal(baseMethod, overrideOverload, 
                /* diag */ undefined, enforceParamNames);
            })) {
                return true;
            }
            diag.addMessage(localize_1.LocAddendum.overrideNoOverloadMatches());
            return false;
        }
        // For a non-overloaded method overriding an overloaded method, the
        // override must match all of the overloads.
        if ((0, types_1.isFunction)(overrideMethod)) {
            return types_1.OverloadedFunctionType.getOverloads(baseMethod).every((overload) => {
                // If the override isn't applicable for this base class, skip the check.
                if (baseClass && !isOverrideMethodApplicable(overload, baseClass)) {
                    return true;
                }
                return validateOverrideMethodInternal(overload, overrideMethod, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), enforceParamNames);
            });
        }
        // For an overloaded method overriding an overloaded method, the overrides
        // must all match and be in the correct order. It is OK if the base method
        // has additional overloads that are not present in the override.
        let previousMatchIndex = -1;
        const baseOverloads = types_1.OverloadedFunctionType.getOverloads(baseMethod);
        for (const overrideOverload of types_1.OverloadedFunctionType.getOverloads(overrideMethod)) {
            let possibleMatchIndex;
            let matchIndex = baseOverloads.findIndex((baseOverload, index) => {
                // If the override isn't applicable for this base class, skip the check.
                if (baseClass && !isOverrideMethodApplicable(baseOverload, baseClass)) {
                    return false;
                }
                const isCompatible = validateOverrideMethodInternal(baseOverload, overrideOverload, 
                /* diag */ undefined, enforceParamNames, 
                /* exemptSelfClsParam */ false);
                // If the override is compatible but the match is one that is below the previous
                // matched index, keep looking for additional matches. Record the fact that
                // we found at least one match.
                if (isCompatible && index <= previousMatchIndex && possibleMatchIndex === undefined) {
                    possibleMatchIndex = index;
                    return false;
                }
                return isCompatible;
            });
            if (matchIndex < 0 && possibleMatchIndex !== undefined) {
                matchIndex = possibleMatchIndex;
            }
            if (matchIndex < 0) {
                break;
            }
            if (matchIndex < previousMatchIndex) {
                diag.addMessage(localize_1.LocAddendum.overrideOverloadOrder());
                return false;
            }
            previousMatchIndex = matchIndex;
        }
        if (previousMatchIndex < baseOverloads.length - 1) {
            const unmatchedOverloads = baseOverloads.slice(previousMatchIndex + 1);
            // See if all of the remaining overrides are nonapplicable.
            if (!baseClass ||
                unmatchedOverloads.some((overload) => {
                    return isOverrideMethodApplicable(overload, baseClass);
                })) {
                // We didn't find matches for all of the base overloads.
                diag.addMessage(localize_1.LocAddendum.overrideOverloadNoMatch());
                return false;
            }
        }
        return true;
    }
    // Determines whether a child class override is applicable to a parent
    // class method signature. This is important in cases where the parent
    // class defines an overload where some of the overload signatures supply
    // explicit type annotations for the "self" or "cls" parameter and some
    // of these do not apply to the child class.
    function isOverrideMethodApplicable(baseMethod, childClass) {
        if (!types_1.FunctionType.isInstanceMethod(baseMethod) &&
            !types_1.FunctionType.isClassMethod(baseMethod) &&
            !types_1.FunctionType.isConstructorMethod(baseMethod)) {
            return true;
        }
        const baseParamDetails = (0, parameterUtils_1.getParameterListDetails)(baseMethod);
        if (baseParamDetails.params.length === 0) {
            return true;
        }
        const baseParamType = baseParamDetails.params[0].param;
        if (baseParamType.category !== 0 /* ParameterCategory.Simple */ || !baseParamType.hasDeclaredType) {
            return true;
        }
        // If this is a self or cls parameter, determine whether the override
        // class can be assigned to the base parameter type. If not, then this
        // override doesn't apply. This is important for overloads where the
        // base class contains some overload signatures that are not applicable
        // to the child class.
        const childSelfOrClsType = types_1.FunctionType.isInstanceMethod(baseMethod)
            ? types_1.ClassType.cloneAsInstance(childClass)
            : childClass;
        return assignType(baseParamType.type, childSelfOrClsType, 
        /* diag */ undefined, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, 8 /* AssignTypeFlags.SkipSolveTypeVars */);
    }
    // Determines whether the override method is compatible with the overridden method.
    // This is used both for parent/child overrides and implicit overrides for peer
    // classes in a multi-inheritance case. If enforceParamNames is true, the parameter
    // names of non-positional-only parameters are enforced. If exemptSelfClsParam
    // is true, the "self" and "cls" parameters are exempted from type checks.
    // This is normally the case except with overloaded method overrides where the
    // "self" or "cls" parameter type must be honored to differentiate between overloads.
    function validateOverrideMethodInternal(baseMethod, overrideMethod, diag, enforceParamNames, exemptSelfClsParam = true) {
        var _a, _b;
        const baseParamDetails = (0, parameterUtils_1.getParameterListDetails)(baseMethod);
        const overrideParamDetails = (0, parameterUtils_1.getParameterListDetails)(overrideMethod);
        let canOverride = true;
        if (!types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(baseMethod) &&
            !types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(overrideMethod)) {
            // Verify that we're not overriding a static, class or instance method with
            // an incompatible type.
            if (types_1.FunctionType.isStaticMethod(baseMethod)) {
                if (!types_1.FunctionType.isStaticMethod(overrideMethod)) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideNotStaticMethod());
                    canOverride = false;
                }
            }
            else if (types_1.FunctionType.isClassMethod(baseMethod)) {
                if (!types_1.FunctionType.isClassMethod(overrideMethod)) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideNotClassMethod());
                    canOverride = false;
                }
            }
            else if (types_1.FunctionType.isInstanceMethod(baseMethod)) {
                if (!types_1.FunctionType.isInstanceMethod(overrideMethod)) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideNotInstanceMethod());
                    canOverride = false;
                }
            }
            // Verify that the positional param count matches exactly or that the override
            // adds only params that preserve the original signature.
            let foundParamCountMismatch = false;
            if (overrideParamDetails.positionParamCount < baseParamDetails.positionParamCount) {
                if (overrideParamDetails.argsIndex === undefined) {
                    foundParamCountMismatch = true;
                }
                else {
                    const overrideArgsType = overrideParamDetails.params[overrideParamDetails.argsIndex].type;
                    for (let i = overrideParamDetails.positionParamCount; i < baseParamDetails.positionParamCount; i++) {
                        if (!assignType(overrideArgsType, baseParamDetails.params[i].type, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(baseMethod)), 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
                            localize_1.LocAddendum.overrideParamType().format({
                                index: i + 1,
                                baseType: printType(baseParamDetails.params[i].type),
                                overrideType: printType(overrideArgsType),
                            });
                            canOverride = false;
                        }
                    }
                }
            }
            else if (overrideParamDetails.positionParamCount > baseParamDetails.positionParamCount) {
                // Verify that all of the override parameters that extend the
                // signature are either *args, **kwargs or parameters with
                // default values.
                for (let i = baseParamDetails.positionParamCount; i < overrideParamDetails.positionParamCount; i++) {
                    const overrideParam = overrideParamDetails.params[i].param;
                    if (overrideParam.category === 0 /* ParameterCategory.Simple */ &&
                        overrideParam.name &&
                        !overrideParam.hasDefault) {
                        foundParamCountMismatch = true;
                    }
                }
            }
            if (foundParamCountMismatch) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overridePositionalParamCount().format({
                    baseCount: baseParamDetails.params.length,
                    overrideCount: overrideParamDetails.params.length,
                }));
                canOverride = false;
            }
            const positionalParamCount = Math.min(baseParamDetails.positionParamCount, overrideParamDetails.positionParamCount);
            for (let i = 0; i < positionalParamCount; i++) {
                // If the first parameter is a "self" or "cls" parameter, skip the
                // test because these are allowed to violate the Liskov substitution
                // principle.
                if (i === 0 && exemptSelfClsParam) {
                    if (types_1.FunctionType.isInstanceMethod(overrideMethod) ||
                        types_1.FunctionType.isClassMethod(overrideMethod) ||
                        types_1.FunctionType.isConstructorMethod(overrideMethod)) {
                        continue;
                    }
                }
                const baseParam = baseParamDetails.params[i].param;
                const overrideParam = overrideParamDetails.params[i].param;
                if (i >= baseParamDetails.positionOnlyParamCount &&
                    !(0, symbolNameUtils_1.isPrivateOrProtectedName)(baseParam.name || '') &&
                    baseParamDetails.params[i].source !== parameterUtils_1.ParameterSource.PositionOnly &&
                    baseParam.category === 0 /* ParameterCategory.Simple */ &&
                    enforceParamNames &&
                    baseParam.name !== overrideParam.name) {
                    if (overrideParam.category === 0 /* ParameterCategory.Simple */) {
                        if (!baseParam.isNameSynthesized) {
                            if (overrideParamDetails.params[i].source === parameterUtils_1.ParameterSource.PositionOnly) {
                                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNamePositionOnly().format({
                                    index: i + 1,
                                    baseName: baseParam.name || '*',
                                }));
                            }
                            else {
                                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamName().format({
                                    index: i + 1,
                                    baseName: baseParam.name || '*',
                                    overrideName: overrideParam.name || '*',
                                }));
                            }
                            canOverride = false;
                        }
                    }
                }
                else if (i < overrideParamDetails.positionOnlyParamCount &&
                    i >= baseParamDetails.positionOnlyParamCount) {
                    if (!baseParam.isNameSynthesized &&
                        baseParamDetails.params[i].source !== parameterUtils_1.ParameterSource.PositionOnly) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNamePositionOnly().format({
                            index: i + 1,
                            baseName: baseParam.name || '*',
                        }));
                        canOverride = false;
                    }
                }
                else {
                    const baseParamType = baseParamDetails.params[i].type;
                    const overrideParamType = overrideParamDetails.params[i].type;
                    const baseIsSynthesizedTypeVar = (0, types_1.isTypeVar)(baseParamType) && baseParamType.details.isSynthesized;
                    const overrideIsSynthesizedTypeVar = (0, types_1.isTypeVar)(overrideParamType) && overrideParamType.details.isSynthesized;
                    if (!exemptSelfClsParam || (!baseIsSynthesizedTypeVar && !overrideIsSynthesizedTypeVar)) {
                        if (baseParam.category !== overrideParam.category ||
                            !assignType(overrideParamType, baseParamType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(baseMethod)), 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
                            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamType().format({
                                index: i + 1,
                                baseType: printType(baseParamType),
                                overrideType: printType(overrideParamType),
                            }));
                            canOverride = false;
                        }
                    }
                    if (baseParamDetails.params[i].param.hasDefault &&
                        !overrideParamDetails.params[i].param.hasDefault) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNoDefault().format({
                            index: i + 1,
                        }));
                        canOverride = false;
                    }
                }
            }
            // Check for positional (named) parameters in the base method that
            // do not exist in the override.
            if (enforceParamNames && overrideParamDetails.kwargsIndex === undefined) {
                for (let i = positionalParamCount; i < baseParamDetails.positionParamCount; i++) {
                    const baseParam = baseParamDetails.params[i];
                    if (baseParam.source === parameterUtils_1.ParameterSource.PositionOrKeyword &&
                        baseParam.param.category === 0 /* ParameterCategory.Simple */) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNamePositionOnly().format({
                            index: i + 1,
                            baseName: baseParam.param.name || '*',
                        }));
                        canOverride = false;
                    }
                }
            }
            // Check for a *args match.
            if (baseParamDetails.argsIndex !== undefined) {
                if (overrideParamDetails.argsIndex === undefined) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNameMissing().format({
                        name: (_a = baseParamDetails.params[baseParamDetails.argsIndex].param.name) !== null && _a !== void 0 ? _a : '?',
                    }));
                    canOverride = false;
                }
                else {
                    const overrideParamType = overrideParamDetails.params[overrideParamDetails.argsIndex].type;
                    const baseParamType = baseParamDetails.params[baseParamDetails.argsIndex].type;
                    if (!assignType(overrideParamType, baseParamType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), 
                    /* srcTypeVarContext */ undefined, 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamKeywordType().format({
                            name: (_b = overrideParamDetails.params[overrideParamDetails.argsIndex].param.name) !== null && _b !== void 0 ? _b : '?',
                            baseType: printType(baseParamType),
                            overrideType: printType(overrideParamType),
                        }));
                        canOverride = false;
                    }
                }
            }
            // Now check any keyword-only parameters.
            const baseKwOnlyParams = baseParamDetails.params.filter((paramInfo) => paramInfo.source === parameterUtils_1.ParameterSource.KeywordOnly &&
                paramInfo.param.category === 0 /* ParameterCategory.Simple */);
            const overrideKwOnlyParams = overrideParamDetails.params.filter((paramInfo) => paramInfo.source === parameterUtils_1.ParameterSource.KeywordOnly &&
                paramInfo.param.category === 0 /* ParameterCategory.Simple */);
            baseKwOnlyParams.forEach((paramInfo) => {
                var _a, _b, _c;
                const overrideParamInfo = overrideKwOnlyParams.find((pi) => paramInfo.param.name === pi.param.name);
                if (!overrideParamInfo && overrideParamDetails.kwargsIndex === undefined) {
                    diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNameMissing().format({
                        name: (_a = paramInfo.param.name) !== null && _a !== void 0 ? _a : '?',
                    }));
                    canOverride = false;
                }
                else {
                    let targetParamType = overrideParamInfo === null || overrideParamInfo === void 0 ? void 0 : overrideParamInfo.type;
                    if (!targetParamType) {
                        targetParamType = overrideParamDetails.params[overrideParamDetails.kwargsIndex].type;
                    }
                    if (!assignType(targetParamType, paramInfo.type, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(baseMethod)), 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
                        diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamKeywordType().format({
                            name: (_b = paramInfo.param.name) !== null && _b !== void 0 ? _b : '?',
                            baseType: printType(paramInfo.type),
                            overrideType: printType(targetParamType),
                        }));
                        canOverride = false;
                    }
                    if (overrideParamInfo) {
                        if (paramInfo.param.hasDefault && !overrideParamInfo.param.hasDefault) {
                            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamKeywordNoDefault().format({
                                name: (_c = overrideParamInfo.param.name) !== null && _c !== void 0 ? _c : '?',
                            }));
                            canOverride = false;
                        }
                    }
                }
            });
            // Verify that any keyword-only parameters added by the overload are compatible
            // with the **kwargs in the base.
            overrideKwOnlyParams.forEach((paramInfo) => {
                var _a;
                const baseParamInfo = baseKwOnlyParams.find((pi) => paramInfo.param.name === pi.param.name);
                if (!baseParamInfo) {
                    if (baseParamDetails.kwargsIndex === undefined) {
                        if (!paramInfo.param.hasDefault) {
                            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideParamNameExtra().format({
                                name: (_a = paramInfo.param.name) !== null && _a !== void 0 ? _a : '?',
                            }));
                            canOverride = false;
                        }
                    }
                }
            });
            // Verify that if the base method has a **kwargs parameter, the override does too.
            if (baseParamDetails.kwargsIndex !== undefined && overrideParamDetails.kwargsIndex === undefined) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.kwargsParamMissing().format({
                    paramName: baseParamDetails.params[baseParamDetails.kwargsIndex].param.name,
                }));
                canOverride = false;
            }
        }
        // Verify that one or the other method doesn't contain a ParamSpec.
        if (baseParamDetails.paramSpec && !overrideParamDetails.paramSpec) {
            // If the override uses an `*args: Any, **kwargs: Any` signature, we
            // will allow this as an acceptable overload for a `*args: P.args, **kwargs: P.kwargs`.
            const overrideHasArgsKwargs = overrideParamDetails.argsIndex !== undefined &&
                (0, types_1.isAnyOrUnknown)(overrideParamDetails.params[overrideParamDetails.argsIndex].type) &&
                overrideParamDetails.kwargsIndex !== undefined &&
                (0, types_1.isAnyOrUnknown)(overrideParamDetails.params[overrideParamDetails.kwargsIndex].type);
            if (!overrideHasArgsKwargs) {
                diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.paramSpecMissingInOverride());
                canOverride = false;
            }
        }
        // Now check the return type.
        const baseReturnType = getFunctionEffectiveReturnType(baseMethod);
        const overrideReturnType = getFunctionEffectiveReturnType(overrideMethod);
        if (!assignType(baseReturnType, overrideReturnType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(baseMethod)), new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(overrideMethod)), 8 /* AssignTypeFlags.SkipSolveTypeVars */)) {
            diag === null || diag === void 0 ? void 0 : diag.addMessage(localize_1.LocAddendum.overrideReturnType().format({
                baseType: printType(baseReturnType),
                overrideType: printType(overrideReturnType),
            }));
            canOverride = false;
        }
        return canOverride;
    }
    // Validates that the specified source type matches the constraints
    // of the type variable. If successful, it returns the constraint
    // type that applies. If unsuccessful, it returns undefined.
    function applyTypeArgToTypeVar(destType, srcType, diag) {
        if ((0, types_1.isAnyOrUnknown)(srcType)) {
            return srcType;
        }
        let effectiveSrcType = (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(srcType);
        if ((0, types_1.isTypeVar)(srcType)) {
            if ((0, types_1.isTypeSame)(srcType, destType)) {
                return srcType;
            }
            effectiveSrcType = makeTopLevelTypeVarsConcrete(srcType);
        }
        // If this is a partially-evaluated class, don't perform any further
        // checks. Assume in this case that the type is compatible with the
        // bound or constraint.
        if ((0, types_1.isClass)(effectiveSrcType) && types_1.ClassType.isPartiallyEvaluated(effectiveSrcType)) {
            return srcType;
        }
        // If there's a bound type, make sure the source is derived from it.
        if (destType.details.boundType && !(0, typeUtils_1.isTypeAliasPlaceholder)(effectiveSrcType)) {
            if (!assignType(destType.details.boundType, effectiveSrcType, diag.createAddendum(), 
            /* destTypeVarContext */ undefined, 
            /* srcTypeVarContext */ undefined)) {
                // Avoid adding a message that will confuse users if the TypeVar was
                // synthesized for internal purposes.
                if (!destType.details.isSynthesized) {
                    diag.addMessage(localize_1.LocAddendum.typeBound().format({
                        sourceType: printType(effectiveSrcType),
                        destType: printType(destType.details.boundType),
                        name: types_1.TypeVarType.getReadableName(destType),
                    }));
                }
                return undefined;
            }
        }
        if (destType.details.isParamSpec) {
            if ((0, types_1.isParamSpec)(srcType)) {
                return srcType;
            }
            if ((0, types_1.isFunction)(srcType) && types_1.FunctionType.isParamSpecValue(srcType)) {
                return srcType;
            }
            if ((0, types_1.isClassInstance)(srcType) && types_1.ClassType.isBuiltIn(srcType, 'Concatenate')) {
                return srcType;
            }
            diag.addMessage(localize_1.LocAddendum.typeParamSpec().format({
                type: printType(srcType),
                name: types_1.TypeVarType.getReadableName(destType),
            }));
            return undefined;
        }
        if ((0, types_1.isTypeVar)(srcType) && srcType.details.isParamSpec) {
            diag.addMessage(localize_1.LocMessage.paramSpecContext());
            return undefined;
        }
        // If there are no constraints, we're done.
        const constraints = destType.details.constraints;
        if (constraints.length === 0) {
            return srcType;
        }
        if ((0, typeUtils_1.isTypeAliasPlaceholder)(srcType)) {
            return srcType;
        }
        if ((0, types_1.isTypeVar)(srcType) && srcType.details.constraints.length > 0) {
            // Make sure all the source constraint types map to constraint types in the dest.
            if (srcType.details.constraints.every((sourceConstraint) => {
                return constraints.some((destConstraint) => assignType(destConstraint, sourceConstraint));
            })) {
                return srcType;
            }
        }
        else {
            let bestConstraintSoFar;
            // Try to find the best (narrowest) match among the constraints.
            for (const constraint of constraints) {
                // Don't allow Never as a type argument.
                if (assignType(constraint, effectiveSrcType) && !(0, types_1.isNever)(effectiveSrcType)) {
                    if (!bestConstraintSoFar || assignType(bestConstraintSoFar, constraint)) {
                        bestConstraintSoFar = constraint;
                    }
                }
            }
            if (bestConstraintSoFar) {
                return bestConstraintSoFar;
            }
        }
        diag.addMessage(localize_1.LocAddendum.typeConstrainedTypeVar().format({
            type: printType(srcType),
            name: types_1.TypeVarType.getReadableName(destType),
        }));
        return undefined;
    }
    // Returns a list of unimplemented abstract symbols (methods or variables) for
    // the specified class.
    function getAbstractSymbols(classType) {
        const symbolTable = new Map();
        types_1.ClassType.getReverseMro(classType).forEach((mroClass) => {
            if ((0, types_1.isInstantiableClass)(mroClass)) {
                // See if this class is introducing a new abstract symbol that has not been
                // introduced previously or if it is overriding an abstract symbol with
                // a non-abstract one.
                types_1.ClassType.getSymbolTable(mroClass).forEach((symbol, symbolName) => {
                    const abstractSymbolInfo = getAbstractSymbolInfo(mroClass, symbolName);
                    if (abstractSymbolInfo) {
                        symbolTable.set(symbolName, abstractSymbolInfo);
                    }
                    else {
                        symbolTable.delete(symbolName);
                    }
                });
            }
        });
        // Create a final list of symbols that are abstract.
        const symbolList = [];
        symbolTable.forEach((method) => {
            symbolList.push(method);
        });
        return symbolList;
    }
    // If the memberType is an instance or class method, creates a new
    // version of the function that has the "self" or "cls" parameter bound
    // to it. If treatConstructorAsClassMethod is true, the function is
    // treated like a class method even if it's not marked as such. That's
    // needed to special-case the __new__ magic method when it's invoked as
    // a constructor (as opposed to by name).
    function bindFunctionToClassOrObject(baseType, memberType, memberClass, treatConstructorAsClassMethod = false, selfType, diag, recursionCount = 0) {
        return (0, typeUtils_1.mapSignatures)(memberType, (functionType) => {
            // If the caller specified no base type, always strip the
            // first parameter. This is used in cases like constructors.
            if (!baseType) {
                return types_1.FunctionType.clone(functionType, /* stripFirstParam */ true);
            }
            if (types_1.FunctionType.isInstanceMethod(functionType)) {
                // If the baseType is a metaclass, don't specialize the function.
                if ((0, typeUtils_1.isInstantiableMetaclass)(baseType)) {
                    return functionType;
                }
                const baseObj = (0, types_1.isClassInstance)(baseType)
                    ? baseType
                    : types_1.ClassType.cloneAsInstance((0, typeUtils_1.specializeClassType)(baseType));
                let stripFirstParam = false;
                if ((0, types_1.isClassInstance)(baseType)) {
                    stripFirstParam = true;
                }
                else if (memberClass && (0, typeUtils_1.isInstantiableMetaclass)(memberClass)) {
                    stripFirstParam = true;
                }
                return partiallySpecializeFunctionForBoundClassOrObject(baseType, functionType, memberClass !== null && memberClass !== void 0 ? memberClass : types_1.ClassType.cloneAsInstantiable(baseObj), diag, recursionCount, selfType !== null && selfType !== void 0 ? selfType : baseObj, stripFirstParam);
            }
            if (types_1.FunctionType.isClassMethod(functionType) ||
                (treatConstructorAsClassMethod && types_1.FunctionType.isConstructorMethod(functionType))) {
                const baseClass = (0, types_1.isInstantiableClass)(baseType) ? baseType : types_1.ClassType.cloneAsInstantiable(baseType);
                const clsType = selfType ? (0, typeUtils_1.convertToInstantiable)(selfType) : undefined;
                return partiallySpecializeFunctionForBoundClassOrObject(baseClass, functionType, memberClass !== null && memberClass !== void 0 ? memberClass : baseClass, diag, recursionCount, clsType !== null && clsType !== void 0 ? clsType : baseClass, 
                /* stripFirstParam */ true);
            }
            if (types_1.FunctionType.isStaticMethod(functionType)) {
                const baseClass = (0, types_1.isInstantiableClass)(baseType) ? baseType : types_1.ClassType.cloneAsInstantiable(baseType);
                return partiallySpecializeFunctionForBoundClassOrObject(baseClass, functionType, memberClass !== null && memberClass !== void 0 ? memberClass : baseClass, diag, recursionCount, 
                /* firstParamType */ undefined, 
                /* stripFirstParam */ false);
            }
            return functionType;
        });
    }
    // Specializes the specified function for the specified class,
    // optionally stripping the first first parameter (the "self" or "cls")
    // off of the specialized function in the process. The baseType
    // is the type used to reference the member, and the memberClass
    // is the class that provided the member (could be an ancestor of
    // the baseType's class).
    function partiallySpecializeFunctionForBoundClassOrObject(baseType, memberType, memberClass, diag, recursionCount, firstParamType, stripFirstParam = true) {
        const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(memberClass));
        if (firstParamType && memberType.details.parameters.length > 0) {
            const memberTypeFirstParam = memberType.details.parameters[0];
            const memberTypeFirstParamType = types_1.FunctionType.getEffectiveParameterType(memberType, 0);
            // Fill out the typeVarContext for the "self" or "cls" parameter.
            typeVarContext.addSolveForScope((0, typeUtils_1.getTypeVarScopeId)(memberType));
            if ((0, types_1.isTypeVar)(memberTypeFirstParamType) &&
                memberTypeFirstParamType.details.boundType &&
                (0, types_1.isClassInstance)(memberTypeFirstParamType.details.boundType) &&
                types_1.ClassType.isProtocolClass(memberTypeFirstParamType.details.boundType)) {
                // Handle the protocol class specially. Some protocol classes
                // contain references to themselves or their subclasses, so if
                // we attempt to call assignType, we'll risk infinite recursion.
                // Instead, we'll assume it's assignable.
                if (!typeVarContext.isLocked()) {
                    typeVarContext.setTypeVarType(memberTypeFirstParamType, types_1.TypeBase.isInstantiable(memberTypeFirstParamType)
                        ? (0, typeUtils_1.convertToInstance)(firstParamType)
                        : firstParamType);
                }
            }
            else if (!assignType(memberTypeFirstParamType, firstParamType, diag === null || diag === void 0 ? void 0 : diag.createAddendum(), typeVarContext, 
            /* srcTypeVarContext */ undefined, 8192 /* AssignTypeFlags.AllowUnspecifiedTypeArguments */, recursionCount)) {
                if (memberTypeFirstParam.name &&
                    !memberTypeFirstParam.isNameSynthesized &&
                    memberTypeFirstParam.hasDeclaredType) {
                    if (diag) {
                        diag.addMessage(localize_1.LocMessage.bindTypeMismatch().format({
                            type: printType(baseType),
                            methodName: memberType.details.name || '<anonymous>',
                            paramName: memberTypeFirstParam.name,
                        }));
                    }
                    return undefined;
                }
            }
        }
        // Get the effective return type, which will have the side effect of lazily
        // evaluating (and caching) the inferred return type if there is no defined return type.
        getFunctionEffectiveReturnType(memberType);
        const specializedFunction = (0, typeUtils_1.applySolvedTypeVars)(memberType, typeVarContext);
        return types_1.FunctionType.clone(specializedFunction, stripFirstParam, baseType, (0, typeUtils_1.getTypeVarScopeId)(baseType));
    }
    function isFinalVariable(symbol) {
        return symbol.getDeclarations().some((decl) => isFinalVariableDeclaration(decl));
    }
    function isFinalVariableDeclaration(decl) {
        return decl.type === 1 /* DeclarationType.Variable */ && !!decl.isFinal;
    }
    function isExplicitTypeAliasDeclaration(decl) {
        if (decl.type !== 1 /* DeclarationType.Variable */ || !decl.typeAnnotationNode) {
            return false;
        }
        if (decl.typeAnnotationNode.nodeType !== 38 /* ParseNodeType.Name */ &&
            decl.typeAnnotationNode.nodeType !== 35 /* ParseNodeType.MemberAccess */ &&
            decl.typeAnnotationNode.nodeType !== 48 /* ParseNodeType.StringList */) {
            return false;
        }
        const type = getTypeOfAnnotation(decl.typeAnnotationNode, { isVariableAnnotation: true, allowClassVar: true });
        return (0, types_1.isClassInstance)(type) && types_1.ClassType.isBuiltIn(type, 'TypeAlias');
    }
    function isPossibleTypeAliasDeclaration(decl) {
        var _a;
        if (decl.type !== 1 /* DeclarationType.Variable */ || !decl.typeAliasName || decl.typeAnnotationNode) {
            return false;
        }
        if (((_a = decl.node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 3 /* ParseNodeType.Assignment */) {
            return false;
        }
        // Perform a sanity check on the RHS expression. Some expression
        // forms should never be considered legitimate for type aliases.
        return isLegalTypeAliasExpressionForm(decl.node.parent.rightExpression);
    }
    function isLegalTypeAliasExpressionForm(node) {
        switch (node.nodeType) {
            case 0 /* ParseNodeType.Error */:
            case 55 /* ParseNodeType.UnaryOperation */:
            case 4 /* ParseNodeType.AssignmentExpression */:
            case 54 /* ParseNodeType.TypeAnnotation */:
            case 6 /* ParseNodeType.Await */:
            case 51 /* ParseNodeType.Ternary */:
            case 56 /* ParseNodeType.Unpack */:
            case 52 /* ParseNodeType.Tuple */:
            case 9 /* ParseNodeType.Call */:
            case 32 /* ParseNodeType.ListComprehension */:
            case 46 /* ParseNodeType.Slice */:
            case 60 /* ParseNodeType.Yield */:
            case 61 /* ParseNodeType.YieldFrom */:
            case 30 /* ParseNodeType.Lambda */:
            case 40 /* ParseNodeType.Number */:
            case 15 /* ParseNodeType.Dictionary */:
            case 31 /* ParseNodeType.List */:
            case 45 /* ParseNodeType.Set */:
                return false;
            case 7 /* ParseNodeType.BinaryOperation */:
                return (node.operator === 6 /* OperatorType.BitwiseOr */ &&
                    isLegalTypeAliasExpressionForm(node.leftExpression) &&
                    isLegalTypeAliasExpressionForm(node.rightExpression));
            case 24 /* ParseNodeType.Index */:
                return isLegalTypeAliasExpressionForm(node.baseExpression);
            case 35 /* ParseNodeType.MemberAccess */:
                return isLegalTypeAliasExpressionForm(node.leftExpression);
        }
        return true;
    }
    function isLegalImplicitTypeAliasType(type) {
        // We explicitly exclude "Unknown" and "...".
        if ((0, types_1.isUnknown)(type) || (0, typeUtils_1.isEllipsisType)(type)) {
            return false;
        }
        // Look at the subtypes within the union. If any of them are not
        // instantiable (other than "None" which is special-cased), it is
        // not a legal type alias type.
        let isLegal = true;
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if (!types_1.TypeBase.isInstantiable(subtype) && !(0, typeUtils_1.isNoneInstance)(subtype)) {
                isLegal = false;
            }
        });
        return isLegal;
    }
    function printObjectTypeForClass(type) {
        return TypePrinter.printObjectTypeForClass(type, evaluatorOptions.printTypeFlags, getFunctionEffectiveReturnType);
    }
    function printFunctionParts(type, extraFlags) {
        const flags = extraFlags ? evaluatorOptions.printTypeFlags | extraFlags : evaluatorOptions.printTypeFlags;
        return TypePrinter.printFunctionParts(type, flags, getFunctionEffectiveReturnType);
    }
    // Prints two types and determines whether they need to be output in
    // fully-qualified form for disambiguation.
    function printSrcDestTypes(srcType, destType, options) {
        const simpleSrcType = printType(srcType, options);
        const simpleDestType = printType(destType, options);
        if (simpleSrcType !== simpleDestType) {
            return { sourceType: simpleSrcType, destType: simpleDestType };
        }
        const fullSrcType = printType(srcType, { ...(options !== null && options !== void 0 ? options : {}), useFullyQualifiedNames: true });
        const fullDestType = printType(destType, { ...(options !== null && options !== void 0 ? options : {}), useFullyQualifiedNames: true });
        if (fullSrcType !== fullDestType) {
            return { sourceType: fullSrcType, destType: fullDestType };
        }
        return { sourceType: simpleSrcType, destType: simpleDestType };
    }
    function printType(type, options) {
        let flags = evaluatorOptions.printTypeFlags;
        if (options === null || options === void 0 ? void 0 : options.expandTypeAlias) {
            flags |= 32 /* TypePrinter.PrintTypeFlags.ExpandTypeAlias */;
        }
        if (options === null || options === void 0 ? void 0 : options.enforcePythonSyntax) {
            flags |= 256 /* TypePrinter.PrintTypeFlags.PythonSyntax */;
        }
        if (options === null || options === void 0 ? void 0 : options.useTypingUnpack) {
            flags |= 512 /* TypePrinter.PrintTypeFlags.UseTypingUnpack */;
        }
        if (options === null || options === void 0 ? void 0 : options.printUnknownWithAny) {
            flags |= 1 /* TypePrinter.PrintTypeFlags.PrintUnknownWithAny */;
        }
        if (options === null || options === void 0 ? void 0 : options.printTypeVarVariance) {
            flags |= 2048 /* TypePrinter.PrintTypeFlags.PrintTypeVarVariance */;
        }
        if (options === null || options === void 0 ? void 0 : options.omitTypeArgumentsIfUnknown) {
            flags |= 2 /* TypePrinter.PrintTypeFlags.OmitTypeArgumentsIfUnknown */;
        }
        if (options === null || options === void 0 ? void 0 : options.useFullyQualifiedNames) {
            flags |= 4096 /* TypePrinter.PrintTypeFlags.UseFullyQualifiedNames */;
        }
        return TypePrinter.printType(type, flags, getFunctionEffectiveReturnType);
    }
    // Calls back into the parser to parse the contents of a string literal.
    // This is unfortunately needed in some cases — specifically where the
    // parser couldn't determine that the string literal would be used in
    // a context where it should be treated as a forward-declared type. This
    // call produces an expression tree that is not attached to the main parse
    // expression tree because we don't want to mutate the latter; the
    // expression tree created by this function is therefore used only temporarily.
    function parseStringAsTypeAnnotation(node) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const parser = new parser_1.Parser();
        const textValue = node.strings[0].value;
        // Determine the offset within the file where the string
        // literal's contents begin.
        let valueOffset = node.strings[0].start;
        if (node.strings[0].nodeType === 49 /* ParseNodeType.String */) {
            valueOffset += node.strings[0].token.prefixLength + node.strings[0].token.quoteMarkLength;
        }
        // Construct a temporary dummy string with the text value at the appropriate
        // offset so as to mimic the original file. This will keep all of the token
        // and diagnostic offsets correct.
        const dummyFileContents = ' '.repeat(valueOffset) + textValue;
        const parseOptions = new parser_1.ParseOptions();
        parseOptions.isStubFile = fileInfo.isStubFile;
        parseOptions.pythonVersion = fileInfo.executionEnvironment.pythonVersion;
        parseOptions.reportErrorsForParsedStringContents = true;
        const parseResults = parser.parseTextExpression(dummyFileContents, valueOffset, textValue.length, parseOptions, 
        /* parseTextMode */ undefined, 
        /* initialParenDepth */ undefined, fileInfo.typingSymbolAliases);
        if (parseResults.parseTree && parseResults.parseTree.nodeType !== 62 /* ParseNodeType.FunctionAnnotation */) {
            parseResults.diagnostics.forEach((diag) => {
                addError(diag.message, node);
            });
            parseResults.parseTree.parent = node;
            return parseResults.parseTree;
        }
        return undefined;
    }
    // Given a code flow node and a constrained TypeVar, determines whether that type
    // var can be "narrowed" to a single one of its constraints based on isinstance
    // checks within the code flow.
    function narrowConstrainedTypeVar(node, typeVar) {
        const flowNode = AnalyzerNodeInfo.getFlowNode(node);
        if (!flowNode) {
            return undefined;
        }
        return codeFlowEngine.narrowConstrainedTypeVar(flowNode, typeVar);
    }
    function getPrintExpressionTypesSpaces() {
        return ' '.repeat(printExpressionSpaceCount);
    }
    function getLineNum(node) {
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const range = (0, positionUtils_1.convertOffsetsToRange)(node.start, node.start + node.length, fileInfo.lines);
        return (range.start.line + 1).toString();
    }
    function printControlFlowGraph(flowNode, reference, callName, logger) {
        return codeFlowEngine.printControlFlowGraph(flowNode, reference, callName, logger);
    }
    function printTypeVarContext(typeVarContext) {
        const contexts = typeVarContext.getSignatureContexts();
        contexts.forEach((context, index) => {
            if (contexts.length > 1) {
                console.log(`Signature context ${index + 1}:`);
            }
            context.getTypeVars().forEach((typeVarEntry) => {
                const type = context.getTypeVarType(typeVarEntry.typeVar);
                console.log(`  ${typeVarEntry.typeVar.details.name}: ${type ? printType(type) : '<none>'}`);
            });
        });
    }
    const evaluatorInterface = {
        runWithCancellationToken,
        getType,
        getTypeResult,
        getTypeResultForDecorator,
        getCachedType,
        getTypeOfExpression,
        getTypeOfAnnotation,
        getTypeOfClass,
        getTypeOfFunction,
        getTypeOfExpressionExpectingType,
        getExpectedType,
        evaluateTypeForSubnode,
        evaluateTypesForStatement,
        evaluateTypesForMatchStatement,
        evaluateTypesForCaseStatement,
        evaluateTypeOfParameter,
        canBeTruthy,
        canBeFalsy,
        stripLiteralValue,
        removeTruthinessFromType,
        removeFalsinessFromType,
        verifyRaiseExceptionType,
        verifyDeleteExpression,
        validateOverloadedFunctionArguments,
        validateInitSubclassArgs,
        isAfterNodeReachable,
        isNodeReachable,
        isAsymmetricAccessorAssignment,
        suppressDiagnostics,
        isSpecialFormClass,
        getDeclarationsForStringNode,
        getDeclarationsForNameNode,
        getTypeForDeclaration,
        resolveAliasDeclaration,
        resolveAliasDeclarationWithInfo,
        getTypeOfIterable,
        getTypeOfIterator,
        getGetterTypeFromProperty,
        getTypeOfArgument,
        markNamesAccessed,
        expandPromotionTypes,
        makeTopLevelTypeVarsConcrete,
        mapSubtypesExpandTypeVars,
        isTypeSubsumedByOtherType,
        lookUpSymbolRecursive,
        getDeclaredTypeOfSymbol,
        getEffectiveTypeOfSymbol,
        getEffectiveTypeOfSymbolForUsage,
        getInferredTypeOfDeclaration,
        getDeclaredTypeForExpression,
        getFunctionDeclaredReturnType,
        getFunctionInferredReturnType,
        getBestOverloadForArguments,
        getBuiltInType,
        getTypeOfMember,
        getTypeOfBoundMember,
        getBoundMagicMethod,
        getTypeOfMagicMethodCall,
        bindFunctionToClassOrObject,
        getCallSignatureInfo,
        matchCallArgsToParams,
        getAbstractSymbols,
        narrowConstrainedTypeVar,
        assignType,
        validateOverrideMethod,
        validateCallArguments,
        validateTypeArg,
        assignTypeToExpression,
        assignClassToSelf,
        getTypedDictClassType,
        getTupleClassType,
        getObjectType,
        getNoneType,
        getUnionClassType,
        getBuiltInObject,
        getTypingType,
        assignTypeArguments,
        reportMissingTypeArguments,
        inferReturnTypeIfNecessary,
        inferTypeParameterVarianceForClass,
        isFinalVariable,
        isFinalVariableDeclaration,
        isExplicitTypeAliasDeclaration,
        addInformation,
        addUnusedCode,
        addUnreachableCode,
        addDeprecated,
        addDiagnostic,
        addDiagnosticForTextRange,
        printType,
        printSrcDestTypes,
        printFunctionParts,
        getTypeCacheEntryCount,
        disposeEvaluator,
        useSpeculativeMode,
        isSpeculativeModeInUse,
        setTypeResultForNode,
        checkForCancellation,
        printControlFlowGraph,
        printTypeVarContext,
        typesOverlap,
    };
    const codeFlowEngine = (0, codeFlowEngine_1.getCodeFlowEngine)(evaluatorInterface, speculativeTypeTracker);
    return evaluatorInterface;
}
exports.createTypeEvaluator = createTypeEvaluator;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeEvaluatorTypes.ts":
/*!**************************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeEvaluatorTypes.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * typeEvaluatorTypes.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Abstract interface and other helper types for type evaluator module.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.maxSubtypesForInferredType = void 0;
// Maximum number of unioned subtypes for an inferred type (e.g.
// a list) before the type is considered an "Any".
exports.maxSubtypesForInferredType = 64;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeEvaluatorWithTracker.ts":
/*!********************************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeEvaluatorWithTracker.ts ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * typeEvaluatorWithTracker.ts
 *
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Wraps type evaluator to track performance of internal calls.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createTypeEvaluatorWithTracker = void 0;
const console_1 = __webpack_require__(/*! ../common/console */ "../pyright-internal/src/common/console.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const typeEvaluator_1 = __webpack_require__(/*! ./typeEvaluator */ "../pyright-internal/src/analyzer/typeEvaluator.ts");
// We don't want to track calls from the type evaluator itself, but only entry points.
function createTypeEvaluatorWithTracker(importLookup, evaluatorOptions, logger, printer) {
    function wrapWithLogger(func) {
        // Wrap the function only if told to do so and the log level is high
        // enough for it to log something.
        if (evaluatorOptions.logCalls && logger.logLevel === console_1.LogLevel.Log) {
            return (...args) => {
                return logger.log(func.name, (s) => {
                    if (func.name === 'importLookup' && args.length > 0) {
                        // This is actually a filename, so special case it.
                        s.add(printer === null || printer === void 0 ? void 0 : printer.printFileOrModuleName(args[0]));
                    }
                    else {
                        // Print all parameters.
                        args.forEach((a) => {
                            s.add(printer === null || printer === void 0 ? void 0 : printer.print(a));
                        });
                    }
                    return timing_1.timingStats.typeEvaluationTime.timeOperation(func, ...args);
                }, evaluatorOptions.minimumLoggingThreshold, 
                /* logParsingPerf */ true);
            };
        }
        else if (!(0, core_1.isDebugMode)()) {
            return timing_1.timingStats.typeEvaluationTime.timeOperation.bind(timing_1.timingStats.typeEvaluationTime, func);
        }
        else {
            return func;
        }
    }
    // Wrap all functions with either a logger or a timer.
    importLookup = wrapWithLogger(importLookup);
    const evaluator = (0, typeEvaluator_1.createTypeEvaluator)(importLookup, evaluatorOptions);
    const keys = Object.keys(evaluator);
    keys.forEach((k) => {
        const entry = evaluator[k];
        if (typeof entry === 'function') {
            evaluator[k] = wrapWithLogger(entry);
        }
    });
    return evaluator;
}
exports.createTypeEvaluatorWithTracker = createTypeEvaluatorWithTracker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeGuards.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeGuards.ts ***!
  \******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typeGuards.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides logic for narrowing types based on conditional
 * expressions. The logic handles both positive ("if") and
 * negative ("else") narrowing cases.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.func1 = exports.Tree = exports.Plant = exports.Dog = exports.Animal = exports.enumerateLiteralsForType = exports.narrowTypeForDiscriminatedLiteralFieldComparison = exports.narrowTypeForDiscriminatedTupleComparison = exports.narrowTypeForDiscriminatedDictEntryComparison = exports.narrowTypeForContainerElementType = exports.getElementTypeForContainerNarrowing = exports.isIsinstanceFilterSubclass = exports.isIsinstanceFilterSuperclass = exports.getTypeNarrowingCallback = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const analyzerNodeInfo_1 = __webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const constraintSolver_1 = __webpack_require__(/*! ./constraintSolver */ "../pyright-internal/src/analyzer/constraintSolver.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const scopeUtils_1 = __webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const typedDicts_1 = __webpack_require__(/*! ./typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
// Given a reference expression and a test expression, returns a callback that
// can be used to narrow the type described by the reference expression.
// If the specified flow node is not associated with the test expression,
// it returns undefined.
function getTypeNarrowingCallback(evaluator, reference, testExpression, isPositiveTest, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return undefined;
    }
    recursionCount++;
    if (testExpression.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
        return getTypeNarrowingCallbackForAssignmentExpression(evaluator, reference, testExpression, isPositiveTest, recursionCount);
    }
    if (testExpression.nodeType === 7 /* ParseNodeType.BinaryOperation */) {
        const isOrIsNotOperator = testExpression.operator === 39 /* OperatorType.Is */ || testExpression.operator === 40 /* OperatorType.IsNot */;
        const equalsOrNotEqualsOperator = testExpression.operator === 12 /* OperatorType.Equals */ || testExpression.operator === 28 /* OperatorType.NotEquals */;
        const comparisonOperator = equalsOrNotEqualsOperator ||
            testExpression.operator === 20 /* OperatorType.LessThan */ ||
            testExpression.operator === 21 /* OperatorType.LessThanOrEqual */ ||
            testExpression.operator === 15 /* OperatorType.GreaterThan */ ||
            testExpression.operator === 16 /* OperatorType.GreaterThanOrEqual */;
        if (isOrIsNotOperator || equalsOrNotEqualsOperator) {
            // Invert the "isPositiveTest" value if this is an "is not" operation.
            const adjIsPositiveTest = testExpression.operator === 39 /* OperatorType.Is */ || testExpression.operator === 12 /* OperatorType.Equals */
                ? isPositiveTest
                : !isPositiveTest;
            // Look for "X is None", "X is not None", "X == None", and "X != None".
            // These are commonly-used patterns used in control flow.
            if (testExpression.rightExpression.nodeType === 11 /* ParseNodeType.Constant */ &&
                testExpression.rightExpression.constType === 26 /* KeywordType.None */) {
                // Allow the LHS to be either a simple expression or an assignment
                // expression that assigns to a simple name.
                let leftExpression = testExpression.leftExpression;
                if (leftExpression.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
                    leftExpression = leftExpression.name;
                }
                if (ParseTreeUtils.isMatchingExpression(reference, leftExpression)) {
                    return (type) => {
                        return { type: narrowTypeForIsNone(evaluator, type, adjIsPositiveTest), isIncomplete: false };
                    };
                }
                if (leftExpression.nodeType === 24 /* ParseNodeType.Index */ &&
                    ParseTreeUtils.isMatchingExpression(reference, leftExpression.baseExpression) &&
                    leftExpression.items.length === 1 &&
                    !leftExpression.trailingComma &&
                    leftExpression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                    !leftExpression.items[0].name &&
                    leftExpression.items[0].valueExpression.nodeType === 40 /* ParseNodeType.Number */ &&
                    leftExpression.items[0].valueExpression.isInteger &&
                    !leftExpression.items[0].valueExpression.isImaginary) {
                    const indexValue = leftExpression.items[0].valueExpression.value;
                    if (typeof indexValue === 'number') {
                        return (type) => {
                            return {
                                type: narrowTupleTypeForIsNone(evaluator, type, adjIsPositiveTest, indexValue),
                                isIncomplete: false,
                            };
                        };
                    }
                }
            }
            // Look for "X is ...", "X is not ...", "X == ...", and "X != ...".
            if (testExpression.rightExpression.nodeType === 18 /* ParseNodeType.Ellipsis */) {
                // Allow the LHS to be either a simple expression or an assignment
                // expression that assigns to a simple name.
                let leftExpression = testExpression.leftExpression;
                if (leftExpression.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
                    leftExpression = leftExpression.name;
                }
                if (ParseTreeUtils.isMatchingExpression(reference, leftExpression)) {
                    return (type) => {
                        return {
                            type: narrowTypeForIsEllipsis(evaluator, type, adjIsPositiveTest),
                            isIncomplete: false,
                        };
                    };
                }
            }
            // Look for "type(X) is Y", "type(X) is not Y", "type(X) == Y" or "type(X) != Y".
            if (testExpression.leftExpression.nodeType === 9 /* ParseNodeType.Call */) {
                if (testExpression.leftExpression.arguments.length === 1 &&
                    testExpression.leftExpression.arguments[0].argumentCategory === 0 /* ArgumentCategory.Simple */) {
                    const arg0Expr = testExpression.leftExpression.arguments[0].valueExpression;
                    if (ParseTreeUtils.isMatchingExpression(reference, arg0Expr)) {
                        const callType = evaluator.getTypeOfExpression(testExpression.leftExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */).type;
                        if ((0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, 'type')) {
                            const classTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                            const classType = evaluator.makeTopLevelTypeVarsConcrete(classTypeResult.type);
                            if ((0, types_1.isInstantiableClass)(classType)) {
                                return (type) => {
                                    return {
                                        type: narrowTypeForTypeIs(evaluator, type, classType, adjIsPositiveTest),
                                        isIncomplete: !!classTypeResult.isIncomplete,
                                    };
                                };
                            }
                        }
                    }
                }
            }
            if (isOrIsNotOperator) {
                if (ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression)) {
                    const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                    const rightType = rightTypeResult.type;
                    // Look for "X is Y" or "X is not Y" where Y is a an enum or bool literal.
                    if ((0, types_1.isClassInstance)(rightType) &&
                        (types_1.ClassType.isEnumClass(rightType) || types_1.ClassType.isBuiltIn(rightType, 'bool')) &&
                        rightType.literalValue !== undefined) {
                        return (type) => {
                            return {
                                type: narrowTypeForLiteralComparison(evaluator, type, rightType, adjIsPositiveTest, 
                                /* isIsOperator */ true),
                                isIncomplete: !!rightTypeResult.isIncomplete,
                            };
                        };
                    }
                    // Look for X is <class> or X is not <class>.
                    if ((0, types_1.isInstantiableClass)(rightType)) {
                        return (type) => {
                            return {
                                type: narrowTypeForClassComparison(evaluator, type, rightType, adjIsPositiveTest),
                                isIncomplete: !!rightTypeResult.isIncomplete,
                            };
                        };
                    }
                }
                // Look for X[<literal>] is <literal> or X[<literal>] is not <literal>.
                if (testExpression.leftExpression.nodeType === 24 /* ParseNodeType.Index */ &&
                    testExpression.leftExpression.items.length === 1 &&
                    !testExpression.leftExpression.trailingComma &&
                    testExpression.leftExpression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                    ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression.baseExpression)) {
                    const indexTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression.items[0].valueExpression);
                    const indexType = indexTypeResult.type;
                    if ((0, types_1.isClassInstance)(indexType) && (0, typeUtils_1.isLiteralType)(indexType)) {
                        if (types_1.ClassType.isBuiltIn(indexType, 'str')) {
                            const rightType = evaluator.getTypeOfExpression(testExpression.rightExpression).type;
                            if ((0, types_1.isClassInstance)(rightType) && rightType.literalValue !== undefined) {
                                return (type) => {
                                    return {
                                        type: narrowTypeForDiscriminatedDictEntryComparison(evaluator, type, indexType, rightType, adjIsPositiveTest),
                                        isIncomplete: !!indexTypeResult.isIncomplete,
                                    };
                                };
                            }
                        }
                        else if (types_1.ClassType.isBuiltIn(indexType, 'int')) {
                            const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                            const rightType = rightTypeResult.type;
                            if ((0, types_1.isClassInstance)(rightType) && rightType.literalValue !== undefined) {
                                let canNarrow = false;
                                // Narrowing can be applied only for bool or enum literals.
                                if (types_1.ClassType.isBuiltIn(rightType, 'bool')) {
                                    canNarrow = true;
                                }
                                else if (rightType.literalValue instanceof types_1.EnumLiteral) {
                                    canNarrow = true;
                                }
                                if (canNarrow) {
                                    return (type) => {
                                        return {
                                            type: narrowTypeForDiscriminatedTupleComparison(evaluator, type, indexType, rightType, adjIsPositiveTest),
                                            isIncomplete: !!rightTypeResult.isIncomplete,
                                        };
                                    };
                                }
                            }
                        }
                    }
                }
            }
            if (equalsOrNotEqualsOperator) {
                // Look for X == <literal> or X != <literal>
                const adjIsPositiveTest = testExpression.operator === 12 /* OperatorType.Equals */ ? isPositiveTest : !isPositiveTest;
                if (ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression)) {
                    // Use speculative mode here to avoid polluting the type cache. This is
                    // important in cases where evaluation of the right expression creates
                    // a false dependency on another variable.
                    const rightTypeResult = evaluator.useSpeculativeMode(testExpression.rightExpression, () => {
                        return evaluator.getTypeOfExpression(testExpression.rightExpression);
                    });
                    const rightType = rightTypeResult.type;
                    if ((0, types_1.isClassInstance)(rightType) && rightType.literalValue !== undefined) {
                        return (type) => {
                            return {
                                type: narrowTypeForLiteralComparison(evaluator, type, rightType, adjIsPositiveTest, 
                                /* isIsOperator */ false),
                                isIncomplete: !!rightTypeResult.isIncomplete,
                            };
                        };
                    }
                }
                // Look for X[<literal>] == <literal> or X[<literal>] != <literal>
                if (testExpression.leftExpression.nodeType === 24 /* ParseNodeType.Index */ &&
                    testExpression.leftExpression.items.length === 1 &&
                    !testExpression.leftExpression.trailingComma &&
                    testExpression.leftExpression.items[0].argumentCategory === 0 /* ArgumentCategory.Simple */ &&
                    ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression.baseExpression)) {
                    const indexTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression.items[0].valueExpression);
                    const indexType = indexTypeResult.type;
                    if ((0, types_1.isClassInstance)(indexType) && (0, typeUtils_1.isLiteralType)(indexType)) {
                        if (types_1.ClassType.isBuiltIn(indexType, ['str', 'int'])) {
                            const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                            const rightType = rightTypeResult.type;
                            if ((0, typeUtils_1.isLiteralTypeOrUnion)(rightType)) {
                                return (type) => {
                                    let narrowedType;
                                    if (types_1.ClassType.isBuiltIn(indexType, 'str')) {
                                        narrowedType = narrowTypeForDiscriminatedDictEntryComparison(evaluator, type, indexType, rightType, adjIsPositiveTest);
                                    }
                                    else {
                                        narrowedType = narrowTypeForDiscriminatedTupleComparison(evaluator, type, indexType, rightType, adjIsPositiveTest);
                                    }
                                    return {
                                        type: narrowedType,
                                        isIncomplete: !!indexTypeResult.isIncomplete || !!rightTypeResult.isIncomplete,
                                    };
                                };
                            }
                        }
                    }
                }
            }
            // Look for X.Y == <literal> or X.Y != <literal>
            if (equalsOrNotEqualsOperator &&
                testExpression.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression.leftExpression)) {
                const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                const rightType = rightTypeResult.type;
                const memberName = testExpression.leftExpression.memberName;
                if ((0, types_1.isClassInstance)(rightType)) {
                    if (rightType.literalValue !== undefined || (0, typeUtils_1.isNoneInstance)(rightType)) {
                        return (type) => {
                            return {
                                type: narrowTypeForDiscriminatedLiteralFieldComparison(evaluator, type, memberName.value, rightType, adjIsPositiveTest),
                                isIncomplete: !!rightTypeResult.isIncomplete,
                            };
                        };
                    }
                }
            }
            // Look for X.Y is <literal> or X.Y is not <literal> where <literal> is
            // an enum or bool literal
            if (testExpression.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression.leftExpression)) {
                const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                const rightType = rightTypeResult.type;
                const memberName = testExpression.leftExpression.memberName;
                if ((0, types_1.isClassInstance)(rightType) &&
                    (types_1.ClassType.isEnumClass(rightType) || types_1.ClassType.isBuiltIn(rightType, 'bool')) &&
                    rightType.literalValue !== undefined) {
                    return (type) => {
                        return {
                            type: narrowTypeForDiscriminatedLiteralFieldComparison(evaluator, type, memberName.value, rightType, adjIsPositiveTest),
                            isIncomplete: !!rightTypeResult.isIncomplete,
                        };
                    };
                }
            }
            // Look for X.Y is None or X.Y is not None
            // These are commonly-used patterns used in control flow.
            if (testExpression.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */ &&
                ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression.leftExpression) &&
                testExpression.rightExpression.nodeType === 11 /* ParseNodeType.Constant */ &&
                testExpression.rightExpression.constType === 26 /* KeywordType.None */) {
                const memberName = testExpression.leftExpression.memberName;
                return (type) => {
                    return {
                        type: narrowTypeForDiscriminatedFieldNoneComparison(evaluator, type, memberName.value, adjIsPositiveTest),
                        isIncomplete: false,
                    };
                };
            }
        }
        // Look for len(x) == <literal>, len(x) != <literal>, len(x) < <literal>, etc.
        if (comparisonOperator &&
            testExpression.leftExpression.nodeType === 9 /* ParseNodeType.Call */ &&
            testExpression.leftExpression.arguments.length === 1) {
            const arg0Expr = testExpression.leftExpression.arguments[0].valueExpression;
            if (ParseTreeUtils.isMatchingExpression(reference, arg0Expr)) {
                const callTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const callType = callTypeResult.type;
                if ((0, types_1.isFunction)(callType) && callType.details.fullName === 'builtins.len') {
                    const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                    const rightType = rightTypeResult.type;
                    if ((0, types_1.isClassInstance)(rightType) &&
                        typeof rightType.literalValue === 'number' &&
                        rightType.literalValue >= 0) {
                        let tupleLength = rightType.literalValue;
                        // We'll treat <, <= and == as positive tests with >=, > and != as
                        // their negative counterparts.
                        const isLessOrEqual = testExpression.operator === 12 /* OperatorType.Equals */ ||
                            testExpression.operator === 20 /* OperatorType.LessThan */ ||
                            testExpression.operator === 21 /* OperatorType.LessThanOrEqual */;
                        const adjIsPositiveTest = isLessOrEqual ? isPositiveTest : !isPositiveTest;
                        // For <= (or its negative counterpart >), adjust the tuple length by 1.
                        if (testExpression.operator === 21 /* OperatorType.LessThanOrEqual */ ||
                            testExpression.operator === 15 /* OperatorType.GreaterThan */) {
                            tupleLength++;
                        }
                        const isEqualityCheck = testExpression.operator === 12 /* OperatorType.Equals */ ||
                            testExpression.operator === 28 /* OperatorType.NotEquals */;
                        return (type) => {
                            return {
                                type: narrowTypeForTupleLength(evaluator, type, tupleLength, adjIsPositiveTest, !isEqualityCheck),
                                isIncomplete: !!callTypeResult.isIncomplete || !!rightTypeResult.isIncomplete,
                            };
                        };
                    }
                }
            }
        }
        if (testExpression.operator === 41 /* OperatorType.In */ || testExpression.operator === 42 /* OperatorType.NotIn */) {
            // Look for "x in y" or "x not in y" where y is one of several built-in types.
            if (ParseTreeUtils.isMatchingExpression(reference, testExpression.leftExpression)) {
                const rightTypeResult = evaluator.getTypeOfExpression(testExpression.rightExpression);
                const rightType = rightTypeResult.type;
                const adjIsPositiveTest = testExpression.operator === 41 /* OperatorType.In */ ? isPositiveTest : !isPositiveTest;
                return (type) => {
                    return {
                        type: narrowTypeForContainerType(evaluator, type, rightType, adjIsPositiveTest),
                        isIncomplete: !!rightTypeResult.isIncomplete,
                    };
                };
            }
            if (ParseTreeUtils.isMatchingExpression(reference, testExpression.rightExpression)) {
                // Look for <string literal> in y where y is a union that contains
                // one or more TypedDicts.
                const leftTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression);
                const leftType = leftTypeResult.type;
                if ((0, types_1.isClassInstance)(leftType) && types_1.ClassType.isBuiltIn(leftType, 'str') && (0, typeUtils_1.isLiteralType)(leftType)) {
                    const adjIsPositiveTest = testExpression.operator === 41 /* OperatorType.In */ ? isPositiveTest : !isPositiveTest;
                    return (type) => {
                        return {
                            type: narrowTypeForTypedDictKey(evaluator, type, types_1.ClassType.cloneAsInstantiable(leftType), adjIsPositiveTest),
                            isIncomplete: !!leftTypeResult.isIncomplete,
                        };
                    };
                }
            }
        }
    }
    if (testExpression.nodeType === 9 /* ParseNodeType.Call */) {
        // Look for "isinstance(X, Y)" or "issubclass(X, Y)".
        if (testExpression.arguments.length === 2) {
            // Make sure the first parameter is a supported expression type
            // and the second parameter is a valid class type or a tuple
            // of valid class types.
            const arg0Expr = testExpression.arguments[0].valueExpression;
            const arg1Expr = testExpression.arguments[1].valueExpression;
            if (ParseTreeUtils.isMatchingExpression(reference, arg0Expr)) {
                const callTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const callType = callTypeResult.type;
                if ((0, types_1.isFunction)(callType) &&
                    (callType.details.builtInName === 'isinstance' || callType.details.builtInName === 'issubclass')) {
                    const isInstanceCheck = callType.details.builtInName === 'isinstance';
                    const arg1TypeResult = evaluator.getTypeOfExpression(arg1Expr, 512 /* EvaluatorFlags.AllowMissingTypeArgs */ |
                        8 /* EvaluatorFlags.EvaluateStringLiteralAsType */ |
                        32 /* EvaluatorFlags.DisallowParamSpec */ |
                        64 /* EvaluatorFlags.DisallowTypeVarTuple */);
                    const arg1Type = arg1TypeResult.type;
                    const classTypeList = getIsInstanceClassTypes(arg1Type);
                    const isIncomplete = !!callTypeResult.isIncomplete || !!arg1TypeResult.isIncomplete;
                    if (classTypeList) {
                        return (type) => {
                            const narrowedType = narrowTypeForIsInstance(evaluator, type, classTypeList, isInstanceCheck, isPositiveTest, 
                            /* allowIntersections */ false, testExpression);
                            if (!(0, types_1.isNever)(narrowedType)) {
                                return {
                                    type: narrowedType,
                                    isIncomplete,
                                };
                            }
                            // Try again with intersection types allowed.
                            return {
                                type: narrowTypeForIsInstance(evaluator, type, classTypeList, isInstanceCheck, isPositiveTest, 
                                /* allowIntersections */ true, testExpression),
                                isIncomplete,
                            };
                        };
                    }
                    else if (isIncomplete) {
                        // If the type is incomplete, it may include unknowns, which will result
                        // in classTypeList being undefined.
                        return (type) => {
                            return {
                                type,
                                isIncomplete: true,
                            };
                        };
                    }
                }
            }
        }
        // Look for "callable(X)"
        if (testExpression.arguments.length === 1) {
            const arg0Expr = testExpression.arguments[0].valueExpression;
            if (ParseTreeUtils.isMatchingExpression(reference, arg0Expr)) {
                const callTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const callType = callTypeResult.type;
                if ((0, types_1.isFunction)(callType) && callType.details.builtInName === 'callable') {
                    return (type) => {
                        let narrowedType = narrowTypeForCallable(evaluator, type, isPositiveTest, testExpression, 
                        /* allowIntersections */ false);
                        if (isPositiveTest && (0, types_1.isNever)(narrowedType)) {
                            // Try again with intersections allowed.
                            narrowedType = narrowTypeForCallable(evaluator, type, isPositiveTest, testExpression, 
                            /* allowIntersections */ true);
                        }
                        return { type: narrowedType, isIncomplete: !!callTypeResult.isIncomplete };
                    };
                }
            }
        }
        // Look for "bool(X)"
        if (testExpression.arguments.length === 1 && !testExpression.arguments[0].name) {
            if (ParseTreeUtils.isMatchingExpression(reference, testExpression.arguments[0].valueExpression)) {
                const callTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const callType = callTypeResult.type;
                if ((0, types_1.isInstantiableClass)(callType) && types_1.ClassType.isBuiltIn(callType, 'bool')) {
                    return (type) => {
                        return {
                            type: narrowTypeForTruthiness(evaluator, type, isPositiveTest),
                            isIncomplete: !!callTypeResult.isIncomplete,
                        };
                    };
                }
            }
        }
        // Look for a TypeGuard function.
        if (testExpression.arguments.length >= 1) {
            const arg0Expr = testExpression.arguments[0].valueExpression;
            if (ParseTreeUtils.isMatchingExpression(reference, arg0Expr)) {
                // Does this look like it's a custom type guard function?
                let isPossiblyTypeGuard = false;
                const isFunctionReturnTypeGuard = (type) => {
                    return (type.details.declaredReturnType &&
                        (0, types_1.isClassInstance)(type.details.declaredReturnType) &&
                        types_1.ClassType.isBuiltIn(type.details.declaredReturnType, ['TypeGuard', 'TypeIs']));
                };
                const callTypeResult = evaluator.getTypeOfExpression(testExpression.leftExpression, 2 /* EvaluatorFlags.CallBaseDefaults */);
                const callType = callTypeResult.type;
                if ((0, types_1.isFunction)(callType) && isFunctionReturnTypeGuard(callType)) {
                    isPossiblyTypeGuard = true;
                }
                else if ((0, types_1.isOverloadedFunction)(callType) &&
                    types_1.OverloadedFunctionType.getOverloads(callType).some((o) => isFunctionReturnTypeGuard(o))) {
                    isPossiblyTypeGuard = true;
                }
                else if ((0, types_1.isClassInstance)(callType)) {
                    isPossiblyTypeGuard = true;
                }
                if (isPossiblyTypeGuard) {
                    // Evaluate the type guard call expression.
                    const functionReturnTypeResult = evaluator.getTypeOfExpression(testExpression);
                    const functionReturnType = functionReturnTypeResult.type;
                    if ((0, types_1.isClassInstance)(functionReturnType) &&
                        types_1.ClassType.isBuiltIn(functionReturnType, 'bool') &&
                        functionReturnType.typeGuardType) {
                        const isStrictTypeGuard = !!functionReturnType.isStrictTypeGuard;
                        const typeGuardType = functionReturnType.typeGuardType;
                        const isIncomplete = !!callTypeResult.isIncomplete || !!functionReturnTypeResult.isIncomplete;
                        return (type) => {
                            return {
                                type: narrowTypeForUserDefinedTypeGuard(evaluator, type, typeGuardType, isPositiveTest, isStrictTypeGuard),
                                isIncomplete,
                            };
                        };
                    }
                }
            }
        }
    }
    if (ParseTreeUtils.isMatchingExpression(reference, testExpression)) {
        return (type) => {
            return {
                type: narrowTypeForTruthiness(evaluator, type, isPositiveTest),
                isIncomplete: false,
            };
        };
    }
    // Is this a reference to an aliased conditional expression (a local variable
    // that was assigned a value that can inform type narrowing of the reference expression)?
    const narrowingCallback = getTypeNarrowingCallbackForAliasedCondition(evaluator, reference, testExpression, isPositiveTest, recursionCount);
    if (narrowingCallback) {
        return narrowingCallback;
    }
    // We normally won't find a "not" operator here because they are stripped out
    // by the binder when it creates condition flow nodes, but we can find this
    // in the case of local variables type narrowing.
    if (reference.nodeType === 38 /* ParseNodeType.Name */) {
        if (testExpression.nodeType === 55 /* ParseNodeType.UnaryOperation */ && testExpression.operator === 38 /* OperatorType.Not */) {
            return getTypeNarrowingCallback(evaluator, reference, testExpression.expression, !isPositiveTest, recursionCount);
        }
    }
    return undefined;
}
exports.getTypeNarrowingCallback = getTypeNarrowingCallback;
function getTypeNarrowingCallbackForAliasedCondition(evaluator, reference, testExpression, isPositiveTest, recursionCount) {
    if (testExpression.nodeType !== 38 /* ParseNodeType.Name */ ||
        reference.nodeType !== 38 /* ParseNodeType.Name */ ||
        testExpression === reference) {
        return undefined;
    }
    // Make sure the reference expression is a constant parameter or variable.
    // If the reference expression is modified within the scope multiple times,
    // we need to validate that it is not modified between the test expression
    // evaluation and the conditional check.
    const testExprDecl = getDeclsForLocalVar(evaluator, testExpression, testExpression, /* requireUnique */ true);
    if (!testExprDecl || testExprDecl.length !== 1 || testExprDecl[0].type !== 1 /* DeclarationType.Variable */) {
        return undefined;
    }
    const referenceDecls = getDeclsForLocalVar(evaluator, reference, testExpression, /* requireUnique */ false);
    if (!referenceDecls) {
        return undefined;
    }
    let modifyingDecls = [];
    if (referenceDecls.length > 1) {
        // If there is more than one assignment to the reference variable within
        // the local scope, make sure that none of these assignments are done
        // after the test expression but before the condition check.
        //
        // This is OK:
        //  val = None
        //  is_none = val is None
        //  if is_none: ...
        //
        // This is not OK:
        //  val = None
        //  is_none = val is None
        //  val = 1
        //  if is_none: ...
        modifyingDecls = referenceDecls.filter((decl) => {
            return (evaluator.isNodeReachable(testExpression, decl.node) &&
                evaluator.isNodeReachable(decl.node, testExprDecl[0].node));
        });
    }
    if (modifyingDecls.length !== 0) {
        return undefined;
    }
    const initNode = testExprDecl[0].inferredTypeSource;
    if (!initNode || ParseTreeUtils.isNodeContainedWithin(testExpression, initNode) || !(0, parseNodes_1.isExpressionNode)(initNode)) {
        return undefined;
    }
    return getTypeNarrowingCallback(evaluator, reference, initNode, isPositiveTest, recursionCount);
}
// Determines whether the symbol is a local variable or parameter within
// the current scope. If requireUnique is true, there can be only one
// declaration (assignment) of the symbol, otherwise it is rejected.
function getDeclsForLocalVar(evaluator, name, reachableFrom, requireUnique) {
    const scope = (0, scopeUtils_1.getScopeForNode)(name);
    if ((scope === null || scope === void 0 ? void 0 : scope.type) !== 1 /* ScopeType.Function */ && (scope === null || scope === void 0 ? void 0 : scope.type) !== 3 /* ScopeType.Module */) {
        return undefined;
    }
    const symbol = scope.lookUpSymbol(name.value);
    if (!symbol) {
        return undefined;
    }
    const decls = symbol.getDeclarations();
    if (requireUnique && decls.length > 1) {
        return undefined;
    }
    if (decls.length === 0 ||
        decls.some((decl) => decl.type !== 1 /* DeclarationType.Variable */ && decl.type !== 2 /* DeclarationType.Parameter */)) {
        return undefined;
    }
    // If there are any assignments within different scopes (e.g. via a "global" or
    // "nonlocal" reference), don't consider it a local variable.
    let prevDeclScope;
    if (decls.some((decl) => {
        const nodeToConsider = decl.type === 2 /* DeclarationType.Parameter */ ? decl.node.name : decl.node;
        const declScopeNode = ParseTreeUtils.getExecutionScopeNode(nodeToConsider);
        if (prevDeclScope && declScopeNode !== prevDeclScope) {
            return true;
        }
        prevDeclScope = declScopeNode;
        return false;
    })) {
        return undefined;
    }
    const reachableDecls = decls.filter((decl) => evaluator.isNodeReachable(reachableFrom, decl.node));
    return reachableDecls.length > 0 ? reachableDecls : undefined;
}
function getTypeNarrowingCallbackForAssignmentExpression(evaluator, reference, testExpression, isPositiveTest, recursionCount) {
    var _a;
    return ((_a = getTypeNarrowingCallback(evaluator, reference, testExpression.rightExpression, isPositiveTest, recursionCount)) !== null && _a !== void 0 ? _a : getTypeNarrowingCallback(evaluator, reference, testExpression.name, isPositiveTest, recursionCount));
}
function narrowTypeForUserDefinedTypeGuard(evaluator, type, typeGuardType, isPositiveTest, isStrictTypeGuard) {
    // For non-strict type guards, always narrow to the typeGuardType
    // in the positive case and don't narrow in the negative case.
    if (!isStrictTypeGuard) {
        return isPositiveTest ? typeGuardType : type;
    }
    // For strict type guards, narrow the type.
    return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
        if (isPositiveTest) {
            // In the positive case, we need to compute the intersection of "type"
            // and "typeGuardType". If we assume "type" is a union of (A1 | A2 | ... | An)
            // and "typeGuardType" is a union of (B1 | B2 | ... | Bn), then the intersection
            // of the two is the union of the intersection of all combinations of A's and B's.
            // For each pair, if A and B are the same type, the intersection is that type.
            // If A is a proper subtype of B or vice versa, the intersection is the narrower of
            // the two. If A and B have no commonality, the intersection is Never.
            // If A and B are not the same type but A and B are mutually "subtypes" of each
            // other, that means they don't follow the normal subtyping rules. In this case,
            // we'll try to pick the one that has the most information (i.e. doesn't contain
            // an Any or Unknown).
            return (0, typeUtils_1.mapSubtypes)(typeGuardType, (typeGuardSubtype) => {
                if ((0, types_1.isTypeSame)(subtype, typeGuardSubtype, { ignorePseudoGeneric: true, treatAnySameAsUnknown: true })) {
                    return subtype;
                }
                const isSubtype = evaluator.assignType(typeGuardSubtype, subtype);
                const isSupertype = evaluator.assignType(subtype, typeGuardSubtype);
                if (isSubtype) {
                    if (!isSupertype) {
                        return subtype;
                    }
                    // It's both a subtype and a supertype and it's not the same type.
                    // That means it's some combination of types that don't follow subtyping
                    // rules. Try to retain as much information as possible. If one of the
                    // two types contains an Any and the other does not, use the one that doesn't.
                    return (0, typeUtils_1.containsAnyOrUnknown)(typeGuardSubtype, /* recurse */ true) ? subtype : typeGuardSubtype;
                }
                if (isSupertype) {
                    return typeGuardSubtype;
                }
                // The types have nothing in common.
                return undefined;
            });
        }
        else {
            // In the negative case, we need to compute the intersection of "type" and
            // the negation of "typeGuardType". The type system doesn't have support for
            // type negations, so the actual result will necessarily be broader than the
            // theoretically-correct result.
            // If "type" is a union of (A1 | A2 | ... | An) and "typeGuardType" is a union
            // of (B1 | B2 | ... | Bn), then the intersection of "type" and !"typeGuardType"
            // is (A1 & !B1 & !B2 & ... & !Bn) | (A2 & !B1 & !B2 & ... & !Bn) | ... |.
            // This means we can eliminate an A only if we can show that it doesn't
            // share any commonality with any of the B's.
            let canBeEliminated = false;
            if (!(0, types_1.isAnyOrUnknown)(subtype)) {
                (0, typeUtils_1.doForEachSubtype)(typeGuardType, (typeGuardSubtype) => {
                    if ((0, types_1.isTypeSame)(subtype, typeGuardSubtype, {
                        ignorePseudoGeneric: true,
                        treatAnySameAsUnknown: true,
                    })) {
                        canBeEliminated = true;
                    }
                    else {
                        const isSubtype = evaluator.assignType(typeGuardSubtype, subtype);
                        const isSupertype = evaluator.assignType(subtype, typeGuardSubtype);
                        if (isSubtype && !(0, types_1.isAnyOrUnknown)(typeGuardSubtype)) {
                            if (!isSupertype) {
                                canBeEliminated = true;
                            }
                            else {
                                // In this case, there is not a clear subtype relationship between
                                // "subtype" and "typeGuardSubtype". We'll use a heuristic to produce
                                // a result that is not unexpected. If the typeGuardSubtype is a gradual
                                // type (contains Any) but the subtype does not, we'll eliminate the
                                // subtype. For example, if the typeGuardSubtype is "list[Any]" and
                                // the subtype is "list[str]", we'll eliminate "list[str]". If the types
                                // are reversed, we don't want to eliminate "list[Any]".
                                const subtypeContainsAny = (0, typeUtils_1.containsAnyOrUnknown)(subtype, /* recurse */ true);
                                const typeGuardSubtypeContainsAny = (0, typeUtils_1.containsAnyOrUnknown)(typeGuardSubtype, 
                                /* recurse */ true);
                                if (!subtypeContainsAny && typeGuardSubtypeContainsAny) {
                                    canBeEliminated = true;
                                }
                            }
                        }
                    }
                });
            }
            return canBeEliminated ? undefined : subtype;
        }
    });
}
// Narrow the type based on whether the subtype can be true or false.
function narrowTypeForTruthiness(evaluator, type, isPositiveTest) {
    return (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
        if (isPositiveTest) {
            if (evaluator.canBeTruthy(subtype)) {
                return evaluator.removeFalsinessFromType(subtype);
            }
        }
        else {
            if (evaluator.canBeFalsy(subtype)) {
                return evaluator.removeTruthinessFromType(subtype);
            }
        }
        return undefined;
    });
}
// Handle type narrowing for expressions of the form "a[I] is None" and "a[I] is not None" where
// I is an integer and a is a union of Tuples (or subtypes thereof) with known lengths and entry types.
function narrowTupleTypeForIsNone(evaluator, type, isPositiveTest, indexValue) {
    return evaluator.mapSubtypesExpandTypeVars(type, /* options */ undefined, (subtype) => {
        const tupleType = (0, typeUtils_1.getSpecializedTupleType)(subtype);
        if (!tupleType || (0, typeUtils_1.isUnboundedTupleClass)(tupleType) || !tupleType.tupleTypeArguments) {
            return subtype;
        }
        const tupleLength = tupleType.tupleTypeArguments.length;
        if (indexValue < 0 || indexValue >= tupleLength) {
            return subtype;
        }
        const typeOfEntry = evaluator.makeTopLevelTypeVarsConcrete(tupleType.tupleTypeArguments[indexValue].type);
        if (isPositiveTest) {
            if (!evaluator.assignType(typeOfEntry, evaluator.getNoneType())) {
                return undefined;
            }
        }
        else {
            if ((0, typeUtils_1.isNoneInstance)(typeOfEntry)) {
                return undefined;
            }
        }
        return subtype;
    });
}
// Handle type narrowing for expressions of the form "x is None" and "x is not None".
function narrowTypeForIsNone(evaluator, type, isPositiveTest) {
    const expandedType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
        return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
    });
    let resultIncludesNoneSubtype = false;
    const result = evaluator.mapSubtypesExpandTypeVars(expandedType, 
    /* options */ undefined, (subtype, unexpandedSubtype) => {
        if ((0, types_1.isAnyOrUnknown)(subtype)) {
            // We need to assume that "Any" is always both None and not None,
            // so it matches regardless of whether the test is positive or negative.
            return subtype;
        }
        // If this is a TypeVar that isn't constrained, use the unexpanded
        // TypeVar. For all other cases (including constrained TypeVars),
        // use the expanded subtype.
        const adjustedSubtype = (0, types_1.isTypeVar)(unexpandedSubtype) && unexpandedSubtype.details.constraints.length === 0
            ? unexpandedSubtype
            : subtype;
        // See if it's a match for object.
        if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'object')) {
            resultIncludesNoneSubtype = true;
            return isPositiveTest
                ? (0, typeUtils_1.addConditionToType)(evaluator.getNoneType(), subtype.condition)
                : adjustedSubtype;
        }
        // See if it's a match for None.
        if ((0, typeUtils_1.isNoneInstance)(subtype) === isPositiveTest) {
            resultIncludesNoneSubtype = true;
            if ((0, types_1.isTypeVar)(adjustedSubtype) && adjustedSubtype.details.isSynthesizedSelf) {
                return adjustedSubtype;
            }
            return subtype;
        }
        return undefined;
    });
    // If this is a positive test and the result is a union that includes None,
    // we can eliminate all the non-None subtypes include Any or Unknown. If some
    // of the subtypes are None types with conditions, retain those.
    if (isPositiveTest && resultIncludesNoneSubtype) {
        return (0, typeUtils_1.mapSubtypes)(result, (subtype) => {
            return (0, typeUtils_1.isNoneInstance)(subtype) ? subtype : undefined;
        });
    }
    return result;
}
// Handle type narrowing for expressions of the form "x is ..." and "x is not ...".
function narrowTypeForIsEllipsis(evaluator, type, isPositiveTest) {
    const expandedType = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
        return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
    });
    return evaluator.mapSubtypesExpandTypeVars(expandedType, /* options */ undefined, (subtype, unexpandedSubtype) => {
        if ((0, types_1.isAnyOrUnknown)(subtype)) {
            // We need to assume that "Any" is always both None and not None,
            // so it matches regardless of whether the test is positive or negative.
            return subtype;
        }
        // If this is a TypeVar that isn't constrained, use the unexpanded
        // TypeVar. For all other cases (including constrained TypeVars),
        // use the expanded subtype.
        const adjustedSubtype = (0, types_1.isTypeVar)(unexpandedSubtype) && unexpandedSubtype.details.constraints.length === 0
            ? unexpandedSubtype
            : subtype;
        // See if it's a match for object.
        if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'object')) {
            return isPositiveTest ? (0, typeUtils_1.addConditionToType)(evaluator.getNoneType(), subtype.condition) : adjustedSubtype;
        }
        const isEllipsis = (0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, ['EllipsisType', 'ellipsis']);
        // See if it's a match for "...".
        if (isEllipsis === isPositiveTest) {
            return subtype;
        }
        return undefined;
    });
}
// The "isinstance" and "issubclass" calls support two forms - a simple form
// that accepts a single class, and a more complex form that accepts a tuple
// of classes (including arbitrarily-nested tuples). This method determines
// which form and returns a list of classes or undefined.
function getIsInstanceClassTypes(argType) {
    let foundNonClassType = false;
    const classTypeList = [];
    // Create a helper function that returns a list of class types or
    // undefined if any of the types are not valid.
    const addClassTypesToList = (types) => {
        types.forEach((subtype) => {
            if ((0, types_1.isInstantiableClass)(subtype) || ((0, types_1.isTypeVar)(subtype) && types_1.TypeBase.isInstantiable(subtype))) {
                classTypeList.push(subtype);
            }
            else if ((0, typeUtils_1.isNoneTypeClass)(subtype)) {
                (0, debug_1.assert)((0, types_1.isInstantiableClass)(subtype));
                classTypeList.push(subtype);
            }
            else if ((0, types_1.isFunction)(subtype) &&
                subtype.details.parameters.length === 2 &&
                subtype.details.parameters[0].category === 1 /* ParameterCategory.ArgsList */ &&
                subtype.details.parameters[1].category === 2 /* ParameterCategory.KwargsDict */) {
                classTypeList.push(subtype);
            }
            else {
                foundNonClassType = true;
            }
        });
    };
    const addClassTypesRecursive = (type, recursionCount = 0) => {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return;
        }
        if ((0, types_1.isClass)(type) && types_1.TypeBase.isInstance(type) && (0, typeUtils_1.isTupleClass)(type)) {
            if (type.tupleTypeArguments) {
                type.tupleTypeArguments.forEach((tupleEntry) => {
                    addClassTypesRecursive(tupleEntry.type, recursionCount + 1);
                });
            }
        }
        else {
            (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                addClassTypesToList([subtype]);
            });
        }
    };
    (0, typeUtils_1.doForEachSubtype)(argType, (subtype) => {
        addClassTypesRecursive(subtype);
    });
    return foundNonClassType ? undefined : classTypeList;
}
function isIsinstanceFilterSuperclass(evaluator, varType, concreteVarType, filterType, concreteFilterType, isInstanceCheck) {
    if ((0, types_1.isTypeVar)(filterType)) {
        return (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(filterType), varType);
    }
    // If the filter type represents all possible subclasses
    // of a type, we can't make any statements about its superclass
    // relationship with concreteVarType.
    if (concreteFilterType.includeSubclasses) {
        return false;
    }
    if (types_1.ClassType.isDerivedFrom(concreteVarType, concreteFilterType)) {
        return true;
    }
    if (isInstanceCheck) {
        if (types_1.ClassType.isProtocolClass(concreteFilterType) &&
            evaluator.assignType(concreteFilterType, concreteVarType)) {
            return true;
        }
    }
    // Handle the special case where the variable type is a TypedDict and
    // we're filtering against 'dict'. TypedDict isn't derived from dict,
    // but at runtime, isinstance returns True.
    if (types_1.ClassType.isBuiltIn(concreteFilterType, 'dict') && types_1.ClassType.isTypedDictClass(concreteVarType)) {
        return true;
    }
    return false;
}
exports.isIsinstanceFilterSuperclass = isIsinstanceFilterSuperclass;
function isIsinstanceFilterSubclass(evaluator, varType, concreteFilterType, isInstanceCheck) {
    if (types_1.ClassType.isDerivedFrom(concreteFilterType, varType)) {
        return true;
    }
    if (isInstanceCheck) {
        if (types_1.ClassType.isProtocolClass(varType) && evaluator.assignType(varType, concreteFilterType)) {
            return true;
        }
    }
    return false;
}
exports.isIsinstanceFilterSubclass = isIsinstanceFilterSubclass;
// Attempts to narrow a type (make it more constrained) based on a
// call to isinstance or issubclass. For example, if the original
// type of expression "x" is "Mammal" and the test expression is
// "isinstance(x, Cow)", (assuming "Cow" is a subclass of "Mammal"),
// we can conclude that x must be constrained to "Cow".
function narrowTypeForIsInstance(evaluator, type, classTypeList, isInstanceCheck, isPositiveTest, allowIntersections, errorNode) {
    let expandedTypes = (0, typeUtils_1.mapSubtypes)(type, (subtype) => {
        return (0, typeUtils_1.transformPossibleRecursiveTypeAlias)(subtype);
    });
    expandedTypes = evaluator.expandPromotionTypes(errorNode, expandedTypes);
    // Filters the varType by the parameters of the isinstance
    // and returns the list of types the varType could be after
    // applying the filter.
    const filterClassType = (varType, concreteVarType, conditions, negativeFallbackType) => {
        const filteredTypes = [];
        let foundSuperclass = false;
        let isClassRelationshipIndeterminate = false;
        for (const filterType of classTypeList) {
            let concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType);
            if ((0, types_1.isInstantiableClass)(concreteFilterType)) {
                // If the class was implicitly specialized (e.g. because its type
                // parameters have default values), replace the default type arguments
                // with Unknown.
                if (concreteFilterType.typeArguments && !concreteFilterType.isTypeArgumentExplicit) {
                    concreteFilterType = (0, typeUtils_1.specializeWithUnknownTypeArgs)(types_1.ClassType.cloneForSpecialization(concreteFilterType, 
                    /* typeArguments */ undefined, 
                    /* isTypeArgumentExplicit */ false));
                }
                const filterIsSuperclass = isIsinstanceFilterSuperclass(evaluator, varType, concreteVarType, filterType, concreteFilterType, isInstanceCheck);
                const filterIsSubclass = isIsinstanceFilterSubclass(evaluator, concreteVarType, concreteFilterType, isInstanceCheck);
                if (filterIsSuperclass) {
                    foundSuperclass = true;
                }
                // Normally, a type should never be both a subclass and a superclass.
                // This can happen if either of the class types derives from a
                // class whose type is unknown (e.g. an import failed). We'll
                // note this case specially so we don't do any narrowing, which
                // will generate false positives.
                if (filterIsSubclass &&
                    filterIsSuperclass &&
                    !types_1.ClassType.isSameGenericClass(concreteVarType, concreteFilterType)) {
                    isClassRelationshipIndeterminate = true;
                }
                // If both the variable type and the filter type ar generics, we can't
                // determine the relationship between the two.
                if ((0, types_1.isTypeVar)(varType) && (0, types_1.isTypeVar)(filterType)) {
                    isClassRelationshipIndeterminate = true;
                }
                if (isPositiveTest) {
                    if (filterIsSuperclass) {
                        // If the variable type is a subclass of the isinstance filter,
                        // we haven't learned anything new about the variable type.
                        // If the varType is a Self or type[Self], retain the unnarrowedType.
                        if ((0, types_1.isTypeVar)(varType) && varType.details.isSynthesizedSelf) {
                            filteredTypes.push((0, typeUtils_1.addConditionToType)(varType, conditions));
                        }
                        else {
                            filteredTypes.push((0, typeUtils_1.addConditionToType)(concreteVarType, conditions));
                        }
                    }
                    else if (filterIsSubclass) {
                        if (evaluator.assignType(concreteVarType, concreteFilterType, 
                        /* diag */ undefined, 
                        /* destTypeVarContext */ undefined, 
                        /* srcTypeVarContext */ undefined, 1024 /* AssignTypeFlags.IgnoreTypeVarScope */ |
                            16384 /* AssignTypeFlags.IgnoreProtocolAssignmentCheck */ |
                            32768 /* AssignTypeFlags.AllowIsinstanceSpecialForms */)) {
                            // If the variable type is a superclass of the isinstance
                            // filter, we can narrow the type to the subclass.
                            let specializedFilterType = filterType;
                            // Try to retain the type arguments for the filter type. This is
                            // important because a specialized version of the filter cannot
                            // be passed to isinstance or issubclass.
                            if ((0, types_1.isClass)(filterType)) {
                                if (types_1.ClassType.isSpecialBuiltIn(filterType) ||
                                    filterType.details.typeParameters.length > 0) {
                                    const typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(filterType));
                                    const unspecializedFilterType = types_1.ClassType.cloneForSpecialization(filterType, 
                                    /* typeArguments */ undefined, 
                                    /* isTypeArgumentExplicit */ false);
                                    if ((0, constraintSolver_1.populateTypeVarContextBasedOnExpectedType)(evaluator, unspecializedFilterType, concreteVarType, typeVarContext, 
                                    /* liveTypeVarScopes */ undefined, errorNode.start)) {
                                        specializedFilterType = (0, typeUtils_1.applySolvedTypeVars)(unspecializedFilterType, typeVarContext, { unknownIfNotFound: true });
                                    }
                                }
                            }
                            filteredTypes.push((0, typeUtils_1.addConditionToType)(specializedFilterType, conditions));
                        }
                    }
                    else if (allowIntersections &&
                        !types_1.ClassType.isFinal(concreteVarType) &&
                        !types_1.ClassType.isFinal(concreteFilterType)) {
                        // The two types appear to have no relation. It's possible that the
                        // two types are protocols or the program is expecting one type to
                        // be a mix-in class used with the other. In this case, we'll
                        // synthesize a new class type that represents an intersection of
                        // the two types.
                        const className = `<subclass of ${concreteVarType.details.name} and ${concreteFilterType.details.name}>`;
                        const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(errorNode);
                        // The effective metaclass of the intersection is the narrower of the two metaclasses.
                        let effectiveMetaclass = concreteVarType.details.effectiveMetaclass;
                        if (concreteFilterType.details.effectiveMetaclass) {
                            if (!effectiveMetaclass ||
                                evaluator.assignType(effectiveMetaclass, concreteFilterType.details.effectiveMetaclass)) {
                                effectiveMetaclass = concreteFilterType.details.effectiveMetaclass;
                            }
                        }
                        let newClassType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 0 /* ClassTypeFlags.None */, ParseTreeUtils.getTypeSourceId(errorNode), 
                        /* declaredMetaclass */ undefined, effectiveMetaclass, concreteVarType.details.docString);
                        newClassType.details.baseClasses = [
                            types_1.ClassType.cloneAsInstantiable(concreteVarType),
                            concreteFilterType,
                        ];
                        (0, typeUtils_1.computeMroLinearization)(newClassType);
                        newClassType = (0, typeUtils_1.addConditionToType)(newClassType, concreteFilterType.condition);
                        if ((0, types_1.isTypeVar)(varType) &&
                            !varType.details.isParamSpec &&
                            varType.details.constraints.length === 0) {
                            newClassType = (0, typeUtils_1.addConditionToType)(newClassType, [
                                { typeVar: varType, constraintIndex: 0 },
                            ]);
                        }
                        let newClassInstanceType = types_1.ClassType.cloneAsInstance(newClassType);
                        if (concreteVarType.condition) {
                            newClassInstanceType = (0, typeUtils_1.addConditionToType)(newClassInstanceType, concreteVarType.condition);
                        }
                        // If this is a issubclass check, we do a double conversion from instantiable
                        // to instance back to instantiable to make sure that the includeSubclasses flag
                        // gets cleared.
                        filteredTypes.push(isInstanceCheck ? newClassInstanceType : types_1.ClassType.cloneAsInstantiable(newClassInstanceType));
                    }
                }
            }
            else if ((0, types_1.isTypeVar)(filterType) && types_1.TypeBase.isInstantiable(filterType)) {
                // Handle the case where the filter type is Type[T] and the unexpanded
                // subtype is some instance type, possibly T.
                if (isInstanceCheck && types_1.TypeBase.isInstance(varType)) {
                    if ((0, types_1.isTypeVar)(varType) && (0, types_1.isTypeSame)((0, typeUtils_1.convertToInstance)(filterType), varType)) {
                        // If the unexpanded subtype is T, we can definitively filter
                        // in both the positive and negative cases.
                        if (isPositiveTest) {
                            filteredTypes.push(varType);
                        }
                        else {
                            foundSuperclass = true;
                        }
                    }
                    else {
                        if (isPositiveTest) {
                            filteredTypes.push((0, typeUtils_1.convertToInstance)(filterType));
                        }
                        else {
                            // If the unexpanded subtype is some other instance, we can't
                            // filter anything because it might be an instance.
                            filteredTypes.push(varType);
                            isClassRelationshipIndeterminate = true;
                        }
                    }
                }
                else if (!isInstanceCheck && types_1.TypeBase.isInstantiable(varType)) {
                    if ((0, types_1.isTypeVar)(varType) && (0, types_1.isTypeSame)(filterType, varType)) {
                        if (isPositiveTest) {
                            filteredTypes.push(varType);
                        }
                    }
                    else {
                        if (isPositiveTest) {
                            filteredTypes.push(filterType);
                        }
                        else {
                            filteredTypes.push(varType);
                            isClassRelationshipIndeterminate = true;
                        }
                    }
                }
            }
            else if ((0, types_1.isFunction)(filterType)) {
                // Handle an isinstance check against Callable.
                if (isInstanceCheck) {
                    let isCallable = false;
                    if ((0, types_1.isClass)(concreteVarType)) {
                        if (types_1.TypeBase.isInstantiable(varType)) {
                            isCallable = true;
                        }
                        else {
                            isCallable = !!(0, typeUtils_1.lookUpClassMember)(concreteVarType, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
                        }
                    }
                    if (isCallable) {
                        if (isPositiveTest) {
                            filteredTypes.push(varType);
                        }
                        else {
                            foundSuperclass = true;
                        }
                    }
                    else if (evaluator.assignType(concreteVarType, filterType, 
                    /* diag */ undefined, 
                    /* destTypeVarContext */ undefined, 
                    /* srcTypeVarContext */ undefined, 32768 /* AssignTypeFlags.AllowIsinstanceSpecialForms */)) {
                        if (isPositiveTest) {
                            filteredTypes.push(filterType);
                        }
                    }
                }
            }
        }
        // In the negative case, if one or more of the filters
        // always match the type (i.e. they are an exact match or
        // a superclass of the type), then there's nothing left after
        // the filter is applied. If we didn't find any superclass
        // match, then the original variable type survives the filter.
        if (!isPositiveTest) {
            if (!foundSuperclass || isClassRelationshipIndeterminate) {
                filteredTypes.push(isInstanceCheck ? (0, typeUtils_1.convertToInstantiable)(negativeFallbackType) : negativeFallbackType);
            }
        }
        if (!isInstanceCheck) {
            // We perform a double conversion from instance to instantiable
            // here to make sure that the includeSubclasses flag is cleared
            // if it's a class.
            return filteredTypes.map((t) => ((0, types_1.isInstantiableClass)(t) ? (0, typeUtils_1.convertToInstantiable)((0, typeUtils_1.convertToInstance)(t)) : t));
        }
        return filteredTypes.map((t) => (0, typeUtils_1.convertToInstance)(t));
    };
    // Filters the metaclassType (which is assumed to be a metaclass instance)
    // by the classTypeList and returns the list of types the varType could be
    // after applying the filter.
    const filterMetaclassType = (metaclassType, negativeFallbackType) => {
        const filteredTypes = [];
        let foundPositiveMatch = false;
        let isMatchIndeterminate = false;
        for (const filterType of classTypeList) {
            const concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType);
            if ((0, types_1.isInstantiableClass)(concreteFilterType)) {
                const filterMetaclass = concreteFilterType.details.effectiveMetaclass;
                if (filterMetaclass && (0, types_1.isInstantiableClass)(filterMetaclass)) {
                    let isMetaclassOverlap = evaluator.assignType(metaclassType, types_1.ClassType.cloneAsInstance(filterMetaclass));
                    // Handle the special case where the metaclass for the filter is type.
                    // This will normally be treated as type[Any], which is compatible with
                    // any metaclass, but we specifically want to treat type as the class
                    // type[object] in this case.
                    if (types_1.ClassType.isBuiltIn(filterMetaclass, 'type') && !filterMetaclass.isTypeArgumentExplicit) {
                        if (!types_1.ClassType.isBuiltIn(metaclassType, 'type')) {
                            isMetaclassOverlap = false;
                        }
                    }
                    if (isMetaclassOverlap) {
                        if (isPositiveTest) {
                            filteredTypes.push(filterType);
                            foundPositiveMatch = true;
                        }
                        else if (!(0, types_1.isTypeSame)(metaclassType, filterMetaclass) || filterMetaclass.includeSubclasses) {
                            filteredTypes.push(metaclassType);
                            isMatchIndeterminate = true;
                        }
                    }
                }
                else {
                    filteredTypes.push(metaclassType);
                    isMatchIndeterminate = true;
                }
            }
            else {
                filteredTypes.push(metaclassType);
                isMatchIndeterminate = true;
            }
        }
        // In the negative case, if one or more of the filters
        // always match the type in the positive case, then there's nothing
        // left after the filter is applied.
        if (!isPositiveTest) {
            if (!foundPositiveMatch || isMatchIndeterminate) {
                filteredTypes.push(negativeFallbackType);
            }
        }
        // We perform a double conversion from instance to instantiable
        // here to make sure that the includeSubclasses flag is cleared
        // if it's a class.
        return filteredTypes.map((t) => ((0, types_1.isInstantiableClass)(t) ? (0, typeUtils_1.convertToInstantiable)((0, typeUtils_1.convertToInstance)(t)) : t));
    };
    const filterFunctionType = (varType, unexpandedType) => {
        const filteredTypes = [];
        if (isPositiveTest) {
            for (const filterType of classTypeList) {
                const concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType);
                if (evaluator.assignType(varType, (0, typeUtils_1.convertToInstance)(concreteFilterType), 
                /* diag */ undefined, 
                /* destTypeVarContext */ undefined, 
                /* srcTypeVarContext */ undefined, 1024 /* AssignTypeFlags.IgnoreTypeVarScope */)) {
                    // If the filter type is a Callable, use the original type. If the
                    // filter type is a callback protocol, use the filter type.
                    if ((0, types_1.isFunction)(filterType)) {
                        filteredTypes.push(unexpandedType);
                    }
                    else {
                        filteredTypes.push((0, typeUtils_1.convertToInstance)(filterType));
                    }
                }
            }
        }
        else if (!classTypeList.some((filterType) => {
            // If the filter type is a runtime checkable protocol class, it can
            // be used in an instance check.
            const concreteFilterType = evaluator.makeTopLevelTypeVarsConcrete(filterType);
            if ((0, types_1.isClass)(concreteFilterType) && !types_1.ClassType.isProtocolClass(concreteFilterType)) {
                return false;
            }
            return evaluator.assignType(varType, (0, typeUtils_1.convertToInstance)(concreteFilterType));
        })) {
            filteredTypes.push(unexpandedType);
        }
        return filteredTypes;
    };
    const classListContainsNoneType = () => classTypeList.some((t) => {
        if ((0, typeUtils_1.isNoneTypeClass)(t)) {
            return true;
        }
        return (0, types_1.isInstantiableClass)(t) && types_1.ClassType.isBuiltIn(t, 'NoneType');
    });
    const anyOrUnknownSubstitutions = [];
    const anyOrUnknown = [];
    const filteredType = evaluator.mapSubtypesExpandTypeVars(expandedTypes, 
    /* options */ undefined, (subtype, unexpandedSubtype) => {
        // If we fail to filter anything in the negative case, we need to decide
        // whether to retain the original TypeVar or replace it with its specialized
        // type(s). We'll assume that if someone is using isinstance or issubclass
        // on a constrained TypeVar that they want to filter based on its constrained
        // parts.
        const negativeFallback = (0, typeUtils_1.getTypeCondition)(subtype) ? subtype : unexpandedSubtype;
        const isSubtypeMetaclass = (0, typeUtils_1.isMetaclassInstance)(subtype);
        if (isPositiveTest && (0, types_1.isAnyOrUnknown)(subtype)) {
            // If this is a positive test and the effective type is Any or
            // Unknown, we can assume that the type matches one of the
            // specified types.
            if (isInstanceCheck) {
                anyOrUnknownSubstitutions.push((0, types_1.combineTypes)(classTypeList.map((classType) => (0, typeUtils_1.convertToInstance)(classType))));
            }
            else {
                // We perform a double conversion from instance to instantiable
                // here to make sure that the includeSubclasses flag is cleared
                // if it's a class.
                anyOrUnknownSubstitutions.push((0, types_1.combineTypes)(classTypeList.map((classType) => (0, typeUtils_1.convertToInstantiable)((0, typeUtils_1.convertToInstance)(classType)))));
            }
            anyOrUnknown.push(subtype);
            return undefined;
        }
        if (isInstanceCheck) {
            if ((0, typeUtils_1.isNoneInstance)(subtype)) {
                return classListContainsNoneType() === isPositiveTest ? subtype : undefined;
            }
            if ((0, types_1.isModule)(subtype) || ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'ModuleType'))) {
                // Handle type narrowing for runtime-checkable protocols
                // when applied to modules.
                if (isPositiveTest) {
                    const filteredTypes = classTypeList.filter((classType) => {
                        const concreteClassType = evaluator.makeTopLevelTypeVarsConcrete(classType);
                        return ((0, types_1.isInstantiableClass)(concreteClassType) && types_1.ClassType.isProtocolClass(concreteClassType));
                    });
                    if (filteredTypes.length > 0) {
                        return (0, typeUtils_1.convertToInstance)((0, types_1.combineTypes)(filteredTypes));
                    }
                }
            }
            if ((0, types_1.isClassInstance)(subtype)) {
                return (0, types_1.combineTypes)(filterClassType((0, typeUtils_1.convertToInstance)(unexpandedSubtype), types_1.ClassType.cloneAsInstantiable(subtype), (0, typeUtils_1.getTypeCondition)(subtype), negativeFallback));
            }
            if (((0, types_1.isFunction)(subtype) || (0, types_1.isOverloadedFunction)(subtype)) && isInstanceCheck) {
                return (0, types_1.combineTypes)(filterFunctionType(subtype, (0, typeUtils_1.convertToInstance)(unexpandedSubtype)));
            }
            if ((0, types_1.isInstantiableClass)(subtype) || isSubtypeMetaclass) {
                // Handle the special case of isinstance(x, metaclass).
                const includesMetaclassType = classTypeList.some((classType) => (0, typeUtils_1.isInstantiableMetaclass)(classType));
                if (isPositiveTest) {
                    return includesMetaclassType ? negativeFallback : undefined;
                }
                else {
                    return includesMetaclassType ? undefined : negativeFallback;
                }
            }
        }
        else {
            if ((0, typeUtils_1.isNoneTypeClass)(subtype)) {
                return classListContainsNoneType() === isPositiveTest ? subtype : undefined;
            }
            if ((0, types_1.isClass)(subtype)) {
                if ((0, types_1.isInstantiableClass)(subtype)) {
                    return (0, types_1.combineTypes)(filterClassType(unexpandedSubtype, subtype, (0, typeUtils_1.getTypeCondition)(subtype), negativeFallback));
                }
                else if ((0, typeUtils_1.isMetaclassInstance)(subtype)) {
                    return (0, types_1.combineTypes)(filterMetaclassType(subtype, negativeFallback));
                }
            }
            if (isSubtypeMetaclass) {
                const objectType = evaluator.getBuiltInObject(errorNode, 'object');
                if (objectType && (0, types_1.isClassInstance)(objectType)) {
                    return (0, types_1.combineTypes)(filterClassType((0, typeUtils_1.convertToInstantiable)(unexpandedSubtype), types_1.ClassType.cloneAsInstantiable(objectType), (0, typeUtils_1.getTypeCondition)(subtype), negativeFallback));
                }
            }
        }
        return isPositiveTest ? undefined : negativeFallback;
    });
    // If the result is Any/Unknown and contains no other subtypes and
    // we have substitutions for Any/Unknown, use those instead. We don't
    // want to apply this if the filtering produced something other than
    // Any/Unknown. For example, if the statement is "isinstance(x, list)"
    // and the type of x is "List[str] | int | Any", the result should be
    // "List[str]", not "List[str] | List[Unknown]".
    if ((0, types_1.isNever)(filteredType) && anyOrUnknownSubstitutions.length > 0) {
        return (0, types_1.combineTypes)(anyOrUnknownSubstitutions);
    }
    if ((0, types_1.isNever)(filteredType) && anyOrUnknown.length > 0) {
        return (0, types_1.combineTypes)(anyOrUnknown);
    }
    return filteredType;
}
// Attempts to narrow a union of tuples based on their known length.
function narrowTypeForTupleLength(evaluator, referenceType, lengthValue, isPositiveTest, isLessThanCheck) {
    return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
        // If it's not a tuple, we can't narrow it.
        if (!(0, types_1.isClassInstance)(concreteSubtype) ||
            !(0, typeUtils_1.isTupleClass)(concreteSubtype) ||
            !concreteSubtype.tupleTypeArguments) {
            return subtype;
        }
        // If the tuple contains a variadic TypeVar, we can't narrow it.
        if (concreteSubtype.tupleTypeArguments.some((typeArg) => (0, types_1.isUnpackedVariadicTypeVar)(typeArg.type))) {
            return subtype;
        }
        // If the tuple contains no unbounded elements, then we know its length exactly.
        if (!concreteSubtype.tupleTypeArguments.some((typeArg) => typeArg.isUnbounded)) {
            const tupleLengthMatches = isLessThanCheck
                ? concreteSubtype.tupleTypeArguments.length < lengthValue
                : concreteSubtype.tupleTypeArguments.length === lengthValue;
            return tupleLengthMatches === isPositiveTest ? subtype : undefined;
        }
        // The tuple contains a "...". We'll expand this into as many elements as
        // necessary to match the lengthValue.
        const elementsToAdd = lengthValue - concreteSubtype.tupleTypeArguments.length + 1;
        if (!isLessThanCheck) {
            // If the specified length is smaller than the minimum length of this tuple,
            // we can rule it out for a positive test and rule it in for a negative test.
            if (elementsToAdd < 0) {
                return isPositiveTest ? undefined : subtype;
            }
            if (!isPositiveTest) {
                return subtype;
            }
            return expandUnboundedTupleElement(concreteSubtype, elementsToAdd, /* keepUnbounded */ false);
        }
        // Place an upper limit on the number of union subtypes we
        // will expand the tuple to.
        const maxTupleUnionExpansion = 32;
        if (elementsToAdd > maxTupleUnionExpansion) {
            return subtype;
        }
        if (isPositiveTest) {
            if (elementsToAdd < 1) {
                return undefined;
            }
            const typesToCombine = [];
            for (let i = 0; i < elementsToAdd; i++) {
                typesToCombine.push(expandUnboundedTupleElement(concreteSubtype, i, /* keepUnbounded */ false));
            }
            return (0, types_1.combineTypes)(typesToCombine);
        }
        return expandUnboundedTupleElement(concreteSubtype, elementsToAdd, /* keepUnbounded */ true);
    });
}
// Expands a tuple type that contains an unbounded element to include
// multiple bounded elements of that same type in place of (or in addition
// to) the unbounded element.
function expandUnboundedTupleElement(tupleType, elementsToAdd, keepUnbounded) {
    const tupleTypeArgs = [];
    tupleType.tupleTypeArguments.forEach((typeArg) => {
        if (!typeArg.isUnbounded) {
            tupleTypeArgs.push(typeArg);
        }
        else {
            for (let i = 0; i < elementsToAdd; i++) {
                tupleTypeArgs.push({ isUnbounded: false, type: typeArg.type });
            }
            if (keepUnbounded) {
                tupleTypeArgs.push(typeArg);
            }
        }
    });
    return (0, typeUtils_1.specializeTupleClass)(tupleType, tupleTypeArgs);
}
// Attempts to narrow a type (make it more constrained) based on an "in" binary operator.
function narrowTypeForContainerType(evaluator, referenceType, containerType, isPositiveTest) {
    if (isPositiveTest) {
        const elementType = getElementTypeForContainerNarrowing(containerType);
        if (!elementType) {
            return referenceType;
        }
        return narrowTypeForContainerElementType(evaluator, referenceType, evaluator.makeTopLevelTypeVarsConcrete(elementType));
    }
    // Narrowing in the negative case is possible only with tuples
    // with a known length.
    if (!(0, types_1.isClassInstance)(containerType) ||
        !types_1.ClassType.isBuiltIn(containerType, 'tuple') ||
        !containerType.tupleTypeArguments) {
        return referenceType;
    }
    // Determine which tuple types can be eliminated. Only "None" and
    // literal types can be handled here.
    const typesToEliminate = [];
    containerType.tupleTypeArguments.forEach((tupleEntry) => {
        if (!tupleEntry.isUnbounded) {
            if ((0, typeUtils_1.isNoneInstance)(tupleEntry.type)) {
                typesToEliminate.push(tupleEntry.type);
            }
            else if ((0, types_1.isClassInstance)(tupleEntry.type) && (0, typeUtils_1.isLiteralType)(tupleEntry.type)) {
                typesToEliminate.push(tupleEntry.type);
            }
        }
    });
    if (typesToEliminate.length === 0) {
        return referenceType;
    }
    return (0, typeUtils_1.mapSubtypes)(referenceType, (referenceSubtype) => {
        referenceSubtype = evaluator.makeTopLevelTypeVarsConcrete(referenceSubtype);
        if ((0, types_1.isClassInstance)(referenceSubtype) && referenceSubtype.literalValue === undefined) {
            // If we're able to enumerate all possible literal values
            // (for bool or enum), we can eliminate all others in a negative test.
            const allLiteralTypes = enumerateLiteralsForType(evaluator, referenceSubtype);
            if (allLiteralTypes && allLiteralTypes.length > 0) {
                return (0, types_1.combineTypes)(allLiteralTypes.filter((type) => !typesToEliminate.some((t) => (0, types_1.isTypeSame)(t, type))));
            }
        }
        if (typesToEliminate.some((t) => (0, types_1.isTypeSame)(t, referenceSubtype))) {
            return undefined;
        }
        return referenceSubtype;
    });
}
function getElementTypeForContainerNarrowing(containerType) {
    // We support contains narrowing only for certain built-in types that have been specialized.
    const supportedContainers = ['list', 'set', 'frozenset', 'deque', 'tuple', 'dict', 'defaultdict', 'OrderedDict'];
    if (!(0, types_1.isClassInstance)(containerType) || !types_1.ClassType.isBuiltIn(containerType, supportedContainers)) {
        return undefined;
    }
    if (!containerType.typeArguments || containerType.typeArguments.length < 1) {
        return undefined;
    }
    let elementType = containerType.typeArguments[0];
    if ((0, typeUtils_1.isTupleClass)(containerType) && containerType.tupleTypeArguments) {
        elementType = (0, types_1.combineTypes)(containerType.tupleTypeArguments.map((t) => t.type));
    }
    return elementType;
}
exports.getElementTypeForContainerNarrowing = getElementTypeForContainerNarrowing;
function narrowTypeForContainerElementType(evaluator, referenceType, elementType) {
    let canNarrow = true;
    const elementTypeWithoutLiteral = evaluator.stripLiteralValue(elementType);
    // Look for cases where one or more of the reference subtypes are
    // supertypes of the element types. For example, if the element type
    // is "int | str" and the reference type is "float | bytes", we can
    // narrow the reference type to "float" because it is a supertype of "int".
    const narrowedSupertypes = evaluator.mapSubtypesExpandTypeVars(referenceType, 
    /* options */ undefined, (referenceSubtype) => {
        if ((0, types_1.isAnyOrUnknown)(referenceSubtype)) {
            canNarrow = false;
            return referenceSubtype;
        }
        // Handle "type" specially.
        if ((0, types_1.isClassInstance)(referenceSubtype) && types_1.ClassType.isBuiltIn(referenceSubtype, 'type')) {
            canNarrow = false;
            return referenceSubtype;
        }
        if (evaluator.assignType(elementType, referenceSubtype)) {
            return referenceSubtype;
        }
        if (evaluator.assignType(elementTypeWithoutLiteral, referenceSubtype)) {
            return (0, typeUtils_1.mapSubtypes)(elementType, (elementSubtype) => {
                if ((0, types_1.isClassInstance)(elementSubtype) &&
                    (0, types_1.isSameWithoutLiteralValue)(referenceSubtype, elementSubtype)) {
                    return elementSubtype;
                }
                return undefined;
            });
        }
        return undefined;
    });
    // Look for cases where one or more of the reference subtypes are
    // subtypes of the element types. For example, if the element type
    // is "int | str" and the reference type is "object", we can
    // narrow the reference type to "int | str" because they are both
    // subtypes of "object".
    const narrowedSubtypes = evaluator.mapSubtypesExpandTypeVars(elementType, 
    /* options */ undefined, (elementSubtype) => {
        if ((0, types_1.isAnyOrUnknown)(elementSubtype)) {
            canNarrow = false;
            return referenceType;
        }
        // Handle the special case where the reference type is a dict or Mapping and
        // the element type is a TypedDict. In this case, we can't say whether there
        // is a type overlap, so don't apply narrowing.
        if ((0, types_1.isClassInstance)(referenceType) && types_1.ClassType.isBuiltIn(referenceType, ['dict', 'Mapping'])) {
            if ((0, types_1.isClassInstance)(elementSubtype) && types_1.ClassType.isTypedDictClass(elementSubtype)) {
                return elementSubtype;
            }
        }
        if (evaluator.assignType(referenceType, elementSubtype)) {
            return elementSubtype;
        }
        return undefined;
    });
    return canNarrow ? (0, types_1.combineTypes)([narrowedSupertypes, narrowedSubtypes]) : referenceType;
}
exports.narrowTypeForContainerElementType = narrowTypeForContainerElementType;
// Attempts to narrow a type based on whether it is a TypedDict with
// a literal key value.
function narrowTypeForTypedDictKey(evaluator, referenceType, literalKey, isPositiveTest) {
    const narrowedType = evaluator.mapSubtypesExpandTypeVars(referenceType, /* options */ undefined, (subtype) => {
        var _a, _b;
        if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
            const entries = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, subtype, /* allowNarrowed */ true);
            const tdEntry = (_a = entries.knownItems.get(literalKey.literalValue)) !== null && _a !== void 0 ? _a : entries.extraItems;
            if (isPositiveTest) {
                if (!tdEntry) {
                    return undefined;
                }
                // If the entry is currently not required and not marked provided, we can mark
                // it as provided after this guard expression confirms it is.
                if (tdEntry.isRequired || tdEntry.isProvided) {
                    return subtype;
                }
                const newNarrowedEntriesMap = new Map((_b = subtype.typedDictNarrowedEntries) !== null && _b !== void 0 ? _b : []);
                // Add the new entry.
                newNarrowedEntriesMap.set(literalKey.literalValue, {
                    valueType: tdEntry.valueType,
                    isReadOnly: tdEntry.isReadOnly,
                    isRequired: false,
                    isProvided: true,
                });
                // Clone the TypedDict object with the new entries.
                return types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForNarrowedTypedDictEntries(types_1.ClassType.cloneAsInstantiable(subtype), newNarrowedEntriesMap));
            }
            else {
                return tdEntry !== undefined && (tdEntry.isRequired || tdEntry.isProvided) ? undefined : subtype;
            }
        }
        return subtype;
    });
    return narrowedType;
}
// Attempts to narrow a TypedDict type based on a comparison (equal or not
// equal) between a discriminating entry type that has a declared literal
// type to a literal value.
function narrowTypeForDiscriminatedDictEntryComparison(evaluator, referenceType, indexLiteralType, literalType, isPositiveTest) {
    let canNarrow = true;
    const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
            const symbolMap = (0, typedDicts_1.getTypedDictMembersForClass)(evaluator, subtype);
            const tdEntry = symbolMap.knownItems.get(indexLiteralType.literalValue);
            if (tdEntry && (0, typeUtils_1.isLiteralTypeOrUnion)(tdEntry.valueType)) {
                if (isPositiveTest) {
                    let foundMatch = false;
                    (0, typeUtils_1.doForEachSubtype)(literalType, (literalSubtype) => {
                        if (evaluator.assignType(tdEntry.valueType, literalSubtype)) {
                            foundMatch = true;
                        }
                    });
                    return foundMatch ? subtype : undefined;
                }
                else {
                    let foundNonMatch = false;
                    (0, typeUtils_1.doForEachSubtype)(literalType, (literalSubtype) => {
                        if (!evaluator.assignType(literalSubtype, tdEntry.valueType)) {
                            foundNonMatch = true;
                        }
                    });
                    return foundNonMatch ? subtype : undefined;
                }
            }
        }
        canNarrow = false;
        return subtype;
    });
    return canNarrow ? narrowedType : referenceType;
}
exports.narrowTypeForDiscriminatedDictEntryComparison = narrowTypeForDiscriminatedDictEntryComparison;
function narrowTypeForDiscriminatedTupleComparison(evaluator, referenceType, indexLiteralType, literalType, isPositiveTest) {
    let canNarrow = true;
    const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        var _a;
        if ((0, types_1.isClassInstance)(subtype) &&
            types_1.ClassType.isTupleClass(subtype) &&
            !(0, typeUtils_1.isUnboundedTupleClass)(subtype) &&
            typeof indexLiteralType.literalValue === 'number' &&
            (0, types_1.isClassInstance)(literalType)) {
            const indexValue = indexLiteralType.literalValue;
            if (subtype.tupleTypeArguments && indexValue >= 0 && indexValue < subtype.tupleTypeArguments.length) {
                const tupleEntryType = (_a = subtype.tupleTypeArguments[indexValue]) === null || _a === void 0 ? void 0 : _a.type;
                if (tupleEntryType && (0, typeUtils_1.isLiteralTypeOrUnion)(tupleEntryType)) {
                    if (isPositiveTest) {
                        return evaluator.assignType(tupleEntryType, literalType) ? subtype : undefined;
                    }
                    else {
                        return evaluator.assignType(literalType, tupleEntryType) ? undefined : subtype;
                    }
                }
            }
        }
        canNarrow = false;
        return subtype;
    });
    return canNarrow ? narrowedType : referenceType;
}
exports.narrowTypeForDiscriminatedTupleComparison = narrowTypeForDiscriminatedTupleComparison;
// Attempts to narrow a type based on a comparison (equal or not equal)
// between a discriminating field that has a declared literal type to a
// literal value.
function narrowTypeForDiscriminatedLiteralFieldComparison(evaluator, referenceType, memberName, literalType, isPositiveTest) {
    const narrowedType = (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        var _a;
        let memberInfo;
        if ((0, types_1.isClassInstance)(subtype)) {
            memberInfo = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName);
        }
        else if ((0, types_1.isInstantiableClass)(subtype)) {
            memberInfo = (0, typeUtils_1.lookUpClassMember)(subtype, memberName);
        }
        if (memberInfo && memberInfo.isTypeDeclared) {
            let memberType = evaluator.getTypeOfMember(memberInfo);
            // Handle the case where the field is a property
            // that has a declared literal return type for its getter.
            if ((0, types_1.isClassInstance)(subtype) && (0, types_1.isClassInstance)(memberType) && (0, typeUtils_1.isProperty)(memberType)) {
                const getterType = (_a = memberType.fgetInfo) === null || _a === void 0 ? void 0 : _a.methodType;
                if (getterType && getterType.details.declaredReturnType) {
                    const getterReturnType = types_1.FunctionType.getSpecializedReturnType(getterType);
                    if (getterReturnType) {
                        memberType = getterReturnType;
                    }
                }
            }
            if ((0, typeUtils_1.isLiteralTypeOrUnion)(memberType, /* allowNone */ true)) {
                if (isPositiveTest) {
                    return evaluator.assignType(memberType, literalType) ? subtype : undefined;
                }
                else {
                    return evaluator.assignType(literalType, memberType) ? undefined : subtype;
                }
            }
        }
        return subtype;
    });
    return narrowedType;
}
exports.narrowTypeForDiscriminatedLiteralFieldComparison = narrowTypeForDiscriminatedLiteralFieldComparison;
// Attempts to narrow a type based on a comparison (equal or not equal)
// between a discriminating field that has a declared None type to a
// None.
function narrowTypeForDiscriminatedFieldNoneComparison(evaluator, referenceType, memberName, isPositiveTest) {
    return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        let memberInfo;
        if ((0, types_1.isClassInstance)(subtype)) {
            memberInfo = (0, typeUtils_1.lookUpObjectMember)(subtype, memberName);
        }
        else if ((0, types_1.isInstantiableClass)(subtype)) {
            memberInfo = (0, typeUtils_1.lookUpClassMember)(subtype, memberName);
        }
        if (memberInfo && memberInfo.isTypeDeclared) {
            const memberType = evaluator.makeTopLevelTypeVarsConcrete(evaluator.getTypeOfMember(memberInfo));
            let canNarrow = true;
            if (isPositiveTest) {
                (0, typeUtils_1.doForEachSubtype)(memberType, (memberSubtype) => {
                    memberSubtype = evaluator.makeTopLevelTypeVarsConcrete(memberSubtype);
                    // Don't attempt to narrow if the member is a descriptor or property.
                    if ((0, typeUtils_1.isProperty)(memberSubtype) || (0, typeUtils_1.isMaybeDescriptorInstance)(memberSubtype)) {
                        canNarrow = false;
                    }
                    if ((0, types_1.isAnyOrUnknown)(memberSubtype) || (0, typeUtils_1.isNoneInstance)(memberSubtype) || (0, types_1.isNever)(memberSubtype)) {
                        canNarrow = false;
                    }
                });
            }
            else {
                canNarrow = (0, typeUtils_1.isNoneInstance)(memberType);
            }
            if (canNarrow) {
                return undefined;
            }
        }
        return subtype;
    });
}
// Attempts to narrow a type based on a "type(x) is y" or "type(x) is not y" check.
function narrowTypeForTypeIs(evaluator, type, classType, isPositiveTest) {
    return evaluator.mapSubtypesExpandTypeVars(type, 
    /* options */ undefined, (subtype, unexpandedSubtype) => {
        if ((0, types_1.isClassInstance)(subtype)) {
            const matches = types_1.ClassType.isDerivedFrom(classType, types_1.ClassType.cloneAsInstantiable(subtype));
            if (isPositiveTest) {
                if (matches) {
                    if (types_1.ClassType.isSameGenericClass(subtype, classType)) {
                        return subtype;
                    }
                    return (0, typeUtils_1.addConditionToType)(types_1.ClassType.cloneAsInstance(classType), subtype.condition);
                }
                if (!classType.includeSubclasses) {
                    return undefined;
                }
            }
            else if (!classType.includeSubclasses) {
                // If the class if marked final and it matches, then
                // we can eliminate it in the negative case.
                if (matches && types_1.ClassType.isFinal(subtype)) {
                    return undefined;
                }
                // We can't eliminate the subtype in the negative
                // case because it could be a subclass of the type,
                // in which case `type(x) is y` would fail.
                return subtype;
            }
        }
        else if ((0, typeUtils_1.isNoneInstance)(subtype)) {
            return isPositiveTest ? undefined : subtype;
        }
        else if ((0, types_1.isAnyOrUnknown)(subtype)) {
            return isPositiveTest ? types_1.ClassType.cloneAsInstance(classType) : subtype;
        }
        return unexpandedSubtype;
    });
}
// Attempts to narrow a type based on a comparison with a class using "is" or
// "is not". This pattern is sometimes used for sentinels.
function narrowTypeForClassComparison(evaluator, referenceType, classType, isPositiveTest) {
    return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
        if (isPositiveTest) {
            if ((0, typeUtils_1.isNoneInstance)(concreteSubtype)) {
                return undefined;
            }
            if ((0, types_1.isClassInstance)(concreteSubtype) && types_1.TypeBase.isInstance(subtype)) {
                if (types_1.ClassType.isBuiltIn(concreteSubtype, 'type')) {
                    return classType;
                }
                return undefined;
            }
            if ((0, types_1.isInstantiableClass)(concreteSubtype) && types_1.ClassType.isFinal(concreteSubtype)) {
                if (!types_1.ClassType.isSameGenericClass(concreteSubtype, classType) &&
                    !isIsinstanceFilterSuperclass(evaluator, subtype, concreteSubtype, classType, classType, 
                    /* isInstanceCheck */ false)) {
                    return undefined;
                }
            }
        }
        else {
            if ((0, types_1.isInstantiableClass)(concreteSubtype) &&
                types_1.ClassType.isSameGenericClass(classType, concreteSubtype) &&
                types_1.ClassType.isFinal(classType)) {
                return undefined;
            }
        }
        return subtype;
    });
}
// Attempts to narrow a type (make it more constrained) based on a comparison
// (equal or not equal) to a literal value. It also handles "is" or "is not"
// operators if isIsOperator is true.
function narrowTypeForLiteralComparison(evaluator, referenceType, literalType, isPositiveTest, isIsOperator) {
    return (0, typeUtils_1.mapSubtypes)(referenceType, (subtype) => {
        subtype = evaluator.makeTopLevelTypeVarsConcrete(subtype);
        if ((0, types_1.isAnyOrUnknown)(subtype)) {
            if (isPositiveTest) {
                return literalType;
            }
            return subtype;
        }
        else if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isSameGenericClass(literalType, subtype)) {
            if (subtype.literalValue !== undefined) {
                const literalValueMatches = types_1.ClassType.isLiteralValueSame(subtype, literalType);
                if ((literalValueMatches && !isPositiveTest) || (!literalValueMatches && isPositiveTest)) {
                    return undefined;
                }
                return subtype;
            }
            else if (isPositiveTest) {
                return literalType;
            }
            else {
                // If we're able to enumerate all possible literal values
                // (for bool or enum), we can eliminate all others in a negative test.
                const allLiteralTypes = enumerateLiteralsForType(evaluator, subtype);
                if (allLiteralTypes && allLiteralTypes.length > 0) {
                    return (0, types_1.combineTypes)(allLiteralTypes.filter((type) => !types_1.ClassType.isLiteralValueSame(type, literalType)));
                }
            }
        }
        else if (isPositiveTest) {
            if (isIsOperator || (0, typeUtils_1.isNoneInstance)(subtype)) {
                return undefined;
            }
        }
        return subtype;
    });
}
function enumerateLiteralsForType(evaluator, type) {
    if (types_1.ClassType.isBuiltIn(type, 'bool')) {
        // Booleans have only two types: True and False.
        return [
            types_1.ClassType.cloneWithLiteral(type, /* value */ true),
            types_1.ClassType.cloneWithLiteral(type, /* value */ false),
        ];
    }
    if (types_1.ClassType.isEnumClass(type)) {
        // Enum expansion doesn't apply to enum classes that derive
        // from enum.Flag.
        if (type.details.baseClasses.some((baseClass) => (0, types_1.isClass)(baseClass) && types_1.ClassType.isBuiltIn(baseClass, 'Flag'))) {
            return undefined;
        }
        // Enumerate all of the values in this enumeration.
        const enumList = [];
        const fields = types_1.ClassType.getSymbolTable(type);
        fields.forEach((symbol) => {
            if (!symbol.isIgnoredForProtocolMatch()) {
                const symbolType = evaluator.getEffectiveTypeOfSymbol(symbol);
                if ((0, types_1.isClassInstance)(symbolType) &&
                    types_1.ClassType.isSameGenericClass(type, symbolType) &&
                    symbolType.literalValue !== undefined) {
                    enumList.push(symbolType);
                }
            }
        });
        return enumList;
    }
    return undefined;
}
exports.enumerateLiteralsForType = enumerateLiteralsForType;
// Attempts to narrow a type (make it more constrained) based on a
// call to "callable". For example, if the original type of expression "x" is
// Union[Callable[..., Any], Type[int], int], it would remove the "int" because
// it's not callable.
function narrowTypeForCallable(evaluator, type, isPositiveTest, errorNode, allowIntersections) {
    return evaluator.mapSubtypesExpandTypeVars(type, /* options */ undefined, (subtype) => {
        switch (subtype.category) {
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */: {
                return isPositiveTest ? subtype : undefined;
            }
            case 7 /* TypeCategory.Module */: {
                return isPositiveTest ? undefined : subtype;
            }
            case 6 /* TypeCategory.Class */: {
                if ((0, typeUtils_1.isNoneInstance)(subtype)) {
                    return isPositiveTest ? undefined : subtype;
                }
                if (types_1.TypeBase.isInstantiable(subtype)) {
                    return isPositiveTest ? subtype : undefined;
                }
                // See if the object is callable.
                const callMemberType = (0, typeUtils_1.lookUpClassMember)(subtype, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
                if (!callMemberType) {
                    if (!isPositiveTest) {
                        return subtype;
                    }
                    if (allowIntersections) {
                        // The type appears to not be callable. It's possible that the
                        // two type is a subclass that is callable. We'll synthesize a
                        // new intersection type.
                        const className = `<callable subtype of ${subtype.details.name}>`;
                        const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(errorNode);
                        let newClassType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 0 /* ClassTypeFlags.None */, ParseTreeUtils.getTypeSourceId(errorNode), 
                        /* declaredMetaclass */ undefined, subtype.details.effectiveMetaclass, subtype.details.docString);
                        newClassType.details.baseClasses = [types_1.ClassType.cloneAsInstantiable(subtype)];
                        (0, typeUtils_1.computeMroLinearization)(newClassType);
                        newClassType = (0, typeUtils_1.addConditionToType)(newClassType, subtype.condition);
                        // Add a __call__ method to the new class.
                        const callMethod = types_1.FunctionType.createSynthesizedInstance('__call__');
                        const selfParam = {
                            category: 0 /* ParameterCategory.Simple */,
                            name: 'self',
                            type: types_1.ClassType.cloneAsInstance(newClassType),
                            hasDeclaredType: true,
                        };
                        types_1.FunctionType.addParameter(callMethod, selfParam);
                        types_1.FunctionType.addDefaultParameters(callMethod);
                        callMethod.details.declaredReturnType = types_1.UnknownType.create();
                        types_1.ClassType.getSymbolTable(newClassType).set('__call__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, callMethod));
                        return types_1.ClassType.cloneAsInstance(newClassType);
                    }
                    return undefined;
                }
                else {
                    return isPositiveTest ? subtype : undefined;
                }
            }
            default: {
                // For all other types, we can't determine whether it's
                // callable or not, so we can't eliminate them.
                return subtype;
            }
        }
    });
}
class Animal {
}
exports.Animal = Animal;
class Dog extends Animal {
}
exports.Dog = Dog;
class Plant {
}
exports.Plant = Plant;
class Tree extends Plant {
}
exports.Tree = Tree;
function func1(val) {
    if (val instanceof Tree) {
        console.log(val);
    }
    else {
        console.log(val);
    }
}
exports.func1 = func1;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeInlayHintsWalker.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeInlayHintsWalker.ts ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeInlayHintsWalker = void 0;
const parseTreeWalker_1 = __webpack_require__(/*! ../analyzer/parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const symbolNameUtils_1 = __webpack_require__(/*! ../analyzer/symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const tooltipUtils_1 = __webpack_require__(/*! ../languageService/tooltipUtils */ "../pyright-internal/src/languageService/tooltipUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
// Don't generate inlay hints for arguments to builtin types and functions
const ignoredBuiltinTypes = new Set([
    'builtins.bool',
    'builtins.bytes',
    'builtins.bytearray',
    'builtins.float',
    'builtins.int',
    'builtins.list',
    'builtins.memoryview',
    'builtins.str',
    'builtins.tuple',
    'builtins.range',
    'builtins.enumerate',
    'builtins.map',
    'builtins.filter',
    'builtins.slice',
    'builtins.type',
    'builtins.reversed',
    'builtins.zip',
].flatMap((v) => [`${v}.__new__`, `${v}.__init__`]));
const ignoredBuiltinFunctions = new Set([
    'builtins.len',
    'builtins.max',
    'builtins.min',
    'builtins.next',
    'builtins.repr',
    'builtins.setattr',
    'builtins.getattr',
    'builtins.hasattr',
    'builtins.sorted',
    'builtins.isinstance',
    'builtins.id',
    'builtins.iter',
]);
function isIgnoredBuiltin(type) {
    if (type.details.moduleName !== 'builtins') {
        return false;
    }
    const funcName = type.details.name;
    if (funcName === '__new__' || funcName === '__init__') {
        return ignoredBuiltinTypes.has(type.details.fullName);
    }
    return ignoredBuiltinFunctions.has(type.details.fullName);
}
function isLeftSideOfAssignment(node) {
    var _a;
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 3 /* ParseNodeType.Assignment */) {
        return false;
    }
    return node.start < node.parent.rightExpression.start;
}
class TypeInlayHintsWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_program, fileUri, range) {
        super();
        this._program = _program;
        this.featureItems = [];
        this._checkInRange = (node) => !this._range || textRange_1.TextRange.overlapsRange(this._range, textRange_1.TextRange.create(node.start, node.length));
        this._printType = (type) => this._program.evaluator.printType(type, { enforcePythonSyntax: true });
        this.parseResults = this._program.getParseResults(fileUri);
        this.lines = this.parseResults.tokenizerOutput.lines;
        if (range) {
            this._range = (0, positionUtils_1.convertRangeToTextRange)(range, this.lines);
        }
    }
    visitName(node) {
        var _a;
        if (this._checkInRange(node) &&
            isLeftSideOfAssignment(node) &&
            !(0, symbolNameUtils_1.isDunderName)(node.value) &&
            !(0, symbolNameUtils_1.isUnderscoreOnlyName)(node.value)) {
            const type = (_a = this._program.evaluator) === null || _a === void 0 ? void 0 : _a.getType(node);
            if (type &&
                !(0, types_1.isAny)(type) &&
                !((0, types_1.isClass)(type) && (0, typeUtils_1.isLiteralType)(type)) &&
                !(0, types_1.isTypeVar)(type) &&
                !(0, types_1.isParamSpec)(type)) {
                this.featureItems.push({
                    inlayHintType: 'variable',
                    position: node.start + node.length,
                    value: `: ${(0, types_1.getTypeAliasInfo)(type) ? 'TypeAlias' : this._printType(type)}`,
                });
            }
        }
        return super.visitName(node);
    }
    visitCall(node) {
        if (this._checkInRange(node)) {
            this._generateHintsForCallNode(node);
        }
        return super.visitCall(node);
    }
    visitFunction(node) {
        var _a;
        if (this._checkInRange(node)) {
            const evaluator = this._program.evaluator;
            const functionType = (_a = evaluator === null || evaluator === void 0 ? void 0 : evaluator.getTypeOfFunction(node)) === null || _a === void 0 ? void 0 : _a.functionType;
            if (functionType !== undefined && !functionType.details.declaredReturnType) {
                const inferredReturnType = evaluator === null || evaluator === void 0 ? void 0 : evaluator.getFunctionInferredReturnType(functionType);
                if (inferredReturnType) {
                    this.featureItems.push({
                        inlayHintType: 'functionReturn',
                        position: node.suite.start,
                        value: `-> ${this._printType(inferredReturnType)}`,
                    });
                }
            }
        }
        return super.visitFunction(node);
    }
    _generateHintsForCallNode(node) {
        var _a, _b;
        const evaluator = this._program.evaluator;
        if (!evaluator) {
            return;
        }
        const functionType = evaluator.getType(node.leftExpression);
        if (!functionType) {
            return;
        }
        // if it's an overload, figure out which one to use based on the arguments:
        const matchedFunctionType = (0, tooltipUtils_1.limitOverloadBasedOnCall)(evaluator, functionType, node.leftExpression);
        const matchedArgs = (_a = this._program.evaluator) === null || _a === void 0 ? void 0 : _a.matchCallArgsToParams(node, matchedFunctionType);
        // if there was no match, or if there were multiple matches, we don't want to show any inlay hints because they'd likely be wrong:
        if ((matchedArgs === null || matchedArgs === void 0 ? void 0 : matchedArgs.length) !== 1) {
            return;
        }
        const result = matchedArgs[0];
        if (result.match.argumentErrors) {
            return;
        }
        if (isIgnoredBuiltin(result.type)) {
            return;
        }
        for (const p of result.match.argParams) {
            // If the argument is specified as a keyword argument, there is no need to generate a hint
            if (p.argument.name) {
                continue;
            }
            const argNode = p.argument.valueExpression;
            if (!argNode) {
                continue;
            }
            const funcParam = result.type.details.parameters.find((a) => a.name && a.name === p.paramName);
            if ((funcParam === null || funcParam === void 0 ? void 0 : funcParam.category) !== 0 /* ParameterCategory.Simple */) {
                continue;
            }
            // Arguments starting with double underscores usually come from type stubs,
            // they're probably not very informative. If necessary, an option can be added
            // whether to hide such names or not.
            if ((_b = p.paramName) === null || _b === void 0 ? void 0 : _b.startsWith('__')) {
                continue;
            }
            if (argNode.nodeType === 38 /* ParseNodeType.Name */ && p.paramName === argNode.value) {
                continue;
            }
            if (p.paramName) {
                this.featureItems.push({
                    inlayHintType: 'parameter',
                    position: argNode.start,
                    value: `${p.paramName}=`,
                });
            }
        }
    }
}
exports.TypeInlayHintsWalker = TypeInlayHintsWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typePrinter.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/analyzer/typePrinter.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typePrinter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Converts a type into a string representation.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.printLiteralValue = exports.printLiteralValueTruncated = exports.isLiteralValueTruncated = exports.printObjectTypeForClass = exports.printFunctionParts = exports.printType = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const parameterUtils_1 = __webpack_require__(/*! ./parameterUtils */ "../pyright-internal/src/analyzer/parameterUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const singleTickRegEx = /'/g;
const escapedDoubleQuoteRegEx = /\\"/g;
function printType(type, printTypeFlags, returnTypeCallback) {
    const uniqueNameMap = new UniqueNameMap(printTypeFlags, returnTypeCallback);
    uniqueNameMap.build(type);
    return printTypeInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, [], 0);
}
exports.printType = printType;
function printFunctionParts(type, printTypeFlags, returnTypeCallback) {
    const uniqueNameMap = new UniqueNameMap(printTypeFlags, returnTypeCallback);
    uniqueNameMap.build(type);
    return printFunctionPartsInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, [], 0);
}
exports.printFunctionParts = printFunctionParts;
function printObjectTypeForClass(type, printTypeFlags, returnTypeCallback) {
    const uniqueNameMap = new UniqueNameMap(printTypeFlags, returnTypeCallback);
    uniqueNameMap.build(type);
    return printObjectTypeForClassInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, [], 0);
}
exports.printObjectTypeForClass = printObjectTypeForClass;
const maxLiteralStringLength = 50;
function isLiteralValueTruncated(type) {
    if (typeof type.literalValue === 'string') {
        if (type.literalValue.length > maxLiteralStringLength) {
            return true;
        }
    }
    return false;
}
exports.isLiteralValueTruncated = isLiteralValueTruncated;
function printLiteralValueTruncated(type) {
    if (type.details.name === 'bytes') {
        return 'bytes';
    }
    (0, debug_1.assert)(type.details.name === 'str');
    return 'LiteralString';
}
exports.printLiteralValueTruncated = printLiteralValueTruncated;
function printLiteralValue(type, quotation = "'") {
    const literalValue = type.literalValue;
    if (literalValue === undefined) {
        return '';
    }
    let literalStr;
    if (typeof literalValue === 'string') {
        let effectiveLiteralValue = literalValue;
        // Limit the length of the string literal.
        if (literalValue.length > maxLiteralStringLength) {
            effectiveLiteralValue = literalValue.substring(0, maxLiteralStringLength) + '…';
        }
        if (type.details.name === 'bytes') {
            let bytesString = '';
            // There's no good built-in conversion routine in javascript to convert
            // bytes strings. Determine on a character-by-character basis whether
            // it can be rendered into an ASCII character. If not, use an escape.
            for (let i = 0; i < effectiveLiteralValue.length; i++) {
                const char = effectiveLiteralValue.substring(i, i + 1);
                const charCode = char.charCodeAt(0);
                if (charCode >= 20 && charCode <= 126) {
                    if (charCode === 34) {
                        bytesString += '\\' + char;
                    }
                    else {
                        bytesString += char;
                    }
                }
                else {
                    bytesString += `\\x${((charCode >> 4) & 0xf).toString(16)}${(charCode & 0xf).toString(16)}`;
                }
            }
            literalStr = `b"${bytesString}"`;
        }
        else {
            // JSON.stringify will perform proper escaping for " case.
            // So, we only need to do our own escaping for ' case.
            literalStr = JSON.stringify(effectiveLiteralValue).toString();
            if (quotation !== '"') {
                literalStr = `'${literalStr
                    .substring(1, literalStr.length - 1)
                    .replace(escapedDoubleQuoteRegEx, '"')
                    .replace(singleTickRegEx, "\\'")}'`; // CodeQL [SM02383] Code ql is just wrong here. We don't need to replace backslashes.
            }
        }
    }
    else if (typeof literalValue === 'boolean') {
        literalStr = literalValue ? 'True' : 'False';
    }
    else if (literalValue instanceof types_1.EnumLiteral) {
        literalStr = `${literalValue.className}.${literalValue.itemName}`;
    }
    else if (typeof literalValue === 'bigint') {
        literalStr = literalValue.toString();
        if (literalStr.endsWith('n')) {
            literalStr = literalStr.substring(0, literalStr.length - 1);
        }
    }
    else {
        literalStr = literalValue.toString();
    }
    return literalStr;
}
exports.printLiteralValue = printLiteralValue;
function printTypeInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount) {
    const originalPrintTypeFlags = printTypeFlags;
    const parenthesizeUnion = (printTypeFlags & 16 /* PrintTypeFlags.ParenthesizeUnion */) !== 0;
    printTypeFlags &= ~(16 /* PrintTypeFlags.ParenthesizeUnion */ | 128 /* PrintTypeFlags.ParenthesizeCallable */);
    if (recursionCount > types_1.maxTypeRecursionCount) {
        if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
            return 'Any';
        }
        return '<Recursive>';
    }
    recursionCount++;
    // If this is a type alias, see if we should use its name rather than
    // the type it represents.
    if (type.typeAliasInfo) {
        let expandTypeAlias = true;
        if ((printTypeFlags & 32 /* PrintTypeFlags.ExpandTypeAlias */) === 0) {
            expandTypeAlias = false;
        }
        else {
            if (recursionTypes.find((t) => t === type)) {
                expandTypeAlias = false;
            }
        }
        if (!expandTypeAlias) {
            try {
                recursionTypes.push(type);
                let aliasName = (printTypeFlags & 4096 /* PrintTypeFlags.UseFullyQualifiedNames */) !== 0
                    ? type.typeAliasInfo.fullName
                    : type.typeAliasInfo.name;
                // Use the fully-qualified name if the name isn't unique.
                if (!uniqueNameMap.isUnique(aliasName)) {
                    aliasName = type.typeAliasInfo.fullName;
                }
                const typeParams = type.typeAliasInfo.typeParameters;
                if (typeParams && typeParams.length > 0) {
                    let argumentStrings;
                    // If there is a type arguments array, it's a specialized type alias.
                    if (type.typeAliasInfo.typeArguments) {
                        if ((printTypeFlags & 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */) === 0 ||
                            type.typeAliasInfo.typeArguments.some((typeArg) => !(0, types_1.isUnknown)(typeArg))) {
                            argumentStrings = [];
                            type.typeAliasInfo.typeArguments.forEach((typeArg, index) => {
                                // Which type parameter does this map to?
                                const typeParam = index < typeParams.length ? typeParams[index] : typeParams[typeParams.length - 1];
                                // If this type argument maps to a variadic type parameter, unpack it.
                                if ((0, types_1.isVariadicTypeVar)(typeParam) &&
                                    (0, types_1.isClassInstance)(typeArg) &&
                                    (0, typeUtils_1.isTupleClass)(typeArg) &&
                                    typeArg.tupleTypeArguments &&
                                    typeArg.tupleTypeArguments.every((typeArg) => !typeArg.isUnbounded)) {
                                    typeArg.tupleTypeArguments.forEach((tupleTypeArg) => {
                                        argumentStrings.push(printTypeInternal(tupleTypeArg.type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                                    });
                                }
                                else {
                                    argumentStrings.push(printTypeInternal(typeArg, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                                }
                            });
                        }
                    }
                    else {
                        if ((printTypeFlags & 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */) === 0 ||
                            typeParams.some((typeParam) => !(0, types_1.isUnknown)(typeParam))) {
                            argumentStrings = [];
                            typeParams.forEach((typeParam) => {
                                argumentStrings.push(printTypeInternal(typeParam, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                            });
                        }
                    }
                    if (argumentStrings) {
                        if (argumentStrings.length === 0) {
                            aliasName += `[()]`;
                        }
                        else {
                            aliasName += `[${argumentStrings.join(', ')}]`;
                        }
                    }
                }
                // If it's a TypeVar, don't use the alias name. Instead, use the full
                // name, which may have a scope associated with it.
                if (type.category !== 9 /* TypeCategory.TypeVar */) {
                    return aliasName;
                }
            }
            finally {
                recursionTypes.pop();
            }
        }
    }
    if (recursionTypes.find((t) => {
        var _a;
        return t === type ||
            (t.typeAliasInfo !== undefined && t.typeAliasInfo.fullName === ((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.fullName));
    }) ||
        recursionTypes.length > types_1.maxTypeRecursionCount) {
        // If this is a recursive TypeVar, we've already expanded it once, so
        // just print its name at this point.
        if ((0, types_1.isTypeVar)(type) && type.details.isSynthesized && type.details.recursiveTypeAliasName) {
            return type.details.recursiveTypeAliasName;
        }
        if (type.typeAliasInfo) {
            if (!type.typeAliasInfo.typeParameters) {
                let name = (printTypeFlags & 4096 /* PrintTypeFlags.UseFullyQualifiedNames */) !== 0
                    ? type.typeAliasInfo.fullName
                    : type.typeAliasInfo.name;
                if (!uniqueNameMap.isUnique(name)) {
                    name = type.typeAliasInfo.fullName;
                }
                return name;
            }
            try {
                recursionTypes.push(type);
                return printTypeInternal(type, printTypeFlags & ~32 /* PrintTypeFlags.ExpandTypeAlias */, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
            }
            finally {
                recursionTypes.pop();
            }
        }
        return '...';
    }
    try {
        recursionTypes.push(type);
        const includeConditionalIndicator = (printTypeFlags & (64 /* PrintTypeFlags.OmitConditionalConstraint */ | 256 /* PrintTypeFlags.PythonSyntax */)) === 0;
        const getConditionalIndicator = (subtype) => {
            return subtype.condition !== undefined && includeConditionalIndicator ? '*' : '';
        };
        switch (type.category) {
            case 0 /* TypeCategory.Unbound */: {
                if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
                    return 'Any';
                }
                return 'Unbound';
            }
            case 1 /* TypeCategory.Unknown */: {
                if (printTypeFlags & (256 /* PrintTypeFlags.PythonSyntax */ | 1 /* PrintTypeFlags.PrintUnknownWithAny */)) {
                    return 'Any';
                }
                return 'Unknown';
            }
            case 7 /* TypeCategory.Module */: {
                if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
                    return 'Any';
                }
                return `Module("${type.moduleName}")`;
            }
            case 6 /* TypeCategory.Class */: {
                if (types_1.TypeBase.isInstance(type)) {
                    if (type.literalValue !== undefined) {
                        if (isLiteralValueTruncated(type) && (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0) {
                            return printLiteralValueTruncated(type);
                        }
                        else {
                            return `Literal[${printLiteralValue(type)}]`;
                        }
                    }
                    return `${printObjectTypeForClassInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount)}${getConditionalIndicator(type)}`;
                }
                else {
                    let typeToWrap;
                    if (type.literalValue !== undefined) {
                        if (isLiteralValueTruncated(type) && (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0) {
                            typeToWrap = printLiteralValueTruncated(type);
                        }
                        else {
                            typeToWrap = `Literal[${printLiteralValue(type)}]`;
                        }
                    }
                    else {
                        typeToWrap = printObjectTypeForClassInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                    }
                    return `${_printNestedInstantiable(type, typeToWrap)}${getConditionalIndicator(type)}`;
                }
            }
            case 4 /* TypeCategory.Function */: {
                if (types_1.TypeBase.isInstantiable(type)) {
                    const typeString = printFunctionType(types_1.FunctionType.cloneAsInstance(type), printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                    return `type[${typeString}]`;
                }
                return printFunctionType(type, originalPrintTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
            }
            case 5 /* TypeCategory.OverloadedFunction */: {
                const overloads = types_1.OverloadedFunctionType.getOverloads(type).map((overload) => printTypeInternal(overload, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
                    return 'Callable[..., Any]';
                }
                if (overloads.length === 1) {
                    return overloads[0];
                }
                return `Overload[${overloads.join(', ')}]`;
            }
            case 8 /* TypeCategory.Union */: {
                // Allocate a set that refers to subtypes in the union by
                // their indices. If the index is within the set, it is already
                // accounted for in the output.
                const subtypeHandledSet = new Set();
                // Allocate another set that represents the textual representations
                // of the subtypes in the union.
                const subtypeStrings = new Set();
                // If we're using "|" notation, enclose callable subtypes in parens.
                const updatedPrintTypeFlags = printTypeFlags & 8 /* PrintTypeFlags.PEP604 */
                    ? printTypeFlags | 128 /* PrintTypeFlags.ParenthesizeCallable */
                    : printTypeFlags;
                // Start by matching possible type aliases to the subtypes.
                if ((printTypeFlags & 32 /* PrintTypeFlags.ExpandTypeAlias */) === 0 && type.typeAliasSources) {
                    for (const typeAliasSource of type.typeAliasSources) {
                        let matchedAllSubtypes = true;
                        let allSubtypesPreviouslyHandled = true;
                        const indicesCoveredByTypeAlias = new Set();
                        for (const sourceSubtype of typeAliasSource.subtypes) {
                            let unionSubtypeIndex = 0;
                            let foundMatch = false;
                            const sourceSubtypeInstance = (0, typeUtils_1.convertToInstance)(sourceSubtype);
                            for (const unionSubtype of type.subtypes) {
                                if ((0, types_1.isTypeSame)(sourceSubtypeInstance, unionSubtype)) {
                                    if (!subtypeHandledSet.has(unionSubtypeIndex)) {
                                        allSubtypesPreviouslyHandled = false;
                                    }
                                    indicesCoveredByTypeAlias.add(unionSubtypeIndex);
                                    foundMatch = true;
                                    break;
                                }
                                unionSubtypeIndex++;
                            }
                            if (!foundMatch) {
                                matchedAllSubtypes = false;
                                break;
                            }
                        }
                        if (matchedAllSubtypes && !allSubtypesPreviouslyHandled) {
                            subtypeStrings.add(printTypeInternal(typeAliasSource, updatedPrintTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                            indicesCoveredByTypeAlias.forEach((index) => subtypeHandledSet.add(index));
                        }
                    }
                }
                const noneIndex = type.subtypes.findIndex((subtype) => (0, typeUtils_1.isNoneInstance)(subtype));
                if (noneIndex >= 0 && !subtypeHandledSet.has(noneIndex)) {
                    const typeWithoutNone = (0, typeUtils_1.removeNoneFromUnion)(type);
                    if ((0, types_1.isNever)(typeWithoutNone)) {
                        return 'None';
                    }
                    const optionalType = printTypeInternal(typeWithoutNone, updatedPrintTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                    if (printTypeFlags & 8 /* PrintTypeFlags.PEP604 */) {
                        const unionString = optionalType + ' | None';
                        if (parenthesizeUnion) {
                            return `(${unionString})`;
                        }
                        return unionString;
                    }
                    return 'Optional[' + optionalType + ']';
                }
                const literalObjectStrings = new Set();
                const literalClassStrings = new Set();
                (0, typeUtils_1.doForEachSubtype)(type, (subtype, index) => {
                    if (!subtypeHandledSet.has(index)) {
                        if ((0, types_1.isClassInstance)(subtype) && subtype.literalValue !== undefined) {
                            if (isLiteralValueTruncated(subtype) &&
                                (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0) {
                                subtypeStrings.add(printLiteralValueTruncated(subtype));
                            }
                            else {
                                literalObjectStrings.add(printLiteralValue(subtype));
                            }
                        }
                        else if ((0, types_1.isInstantiableClass)(subtype) && subtype.literalValue !== undefined) {
                            if (isLiteralValueTruncated(subtype) &&
                                (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0) {
                                subtypeStrings.add(`type[${printLiteralValueTruncated(subtype)}]`);
                            }
                            else {
                                literalClassStrings.add(printLiteralValue(subtype));
                            }
                        }
                        else {
                            subtypeStrings.add(printTypeInternal(subtype, updatedPrintTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                        }
                    }
                });
                const dedupedSubtypeStrings = [];
                subtypeStrings.forEach((s) => dedupedSubtypeStrings.push(s));
                if (literalObjectStrings.size > 0) {
                    const literalStrings = [];
                    literalObjectStrings.forEach((s) => literalStrings.push(s));
                    dedupedSubtypeStrings.push(`Literal[${literalStrings.join(', ')}]`);
                }
                if (literalClassStrings.size > 0) {
                    const literalStrings = [];
                    literalClassStrings.forEach((s) => literalStrings.push(s));
                    dedupedSubtypeStrings.push(`type[Literal[${literalStrings.join(', ')}]]`);
                }
                if (dedupedSubtypeStrings.length === 1) {
                    return dedupedSubtypeStrings[0];
                }
                if (printTypeFlags & 8 /* PrintTypeFlags.PEP604 */) {
                    const unionString = dedupedSubtypeStrings.join(' | ');
                    if (parenthesizeUnion) {
                        return `(${unionString})`;
                    }
                    return unionString;
                }
                return `Union[${dedupedSubtypeStrings.join(', ')}]`;
            }
            case 9 /* TypeCategory.TypeVar */: {
                // If it's synthesized, don't expose the internal name we generated.
                // This will confuse users. The exception is if it's a bound synthesized
                // type, in which case we'll print the bound type. This is used for
                // "self" and "cls" parameters.
                if (type.details.isSynthesized) {
                    // If it's a synthesized type var used to implement recursive type
                    // aliases, return the type alias name.
                    if (type.details.recursiveTypeAliasName) {
                        if ((printTypeFlags & 32 /* PrintTypeFlags.ExpandTypeAlias */) !== 0 && type.details.boundType) {
                            return printTypeInternal(types_1.TypeBase.isInstance(type)
                                ? (0, typeUtils_1.convertToInstance)(type.details.boundType)
                                : type.details.boundType, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                        }
                        return type.details.recursiveTypeAliasName;
                    }
                    // If it's a synthesized type var used to implement `self` or `cls` types,
                    // print the type with a special character that indicates that the type
                    // is internally represented as a TypeVar.
                    if (type.details.isSynthesizedSelf && type.details.boundType) {
                        let boundTypeString = printTypeInternal(type.details.boundType, printTypeFlags & ~32 /* PrintTypeFlags.ExpandTypeAlias */, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                        if (!(0, types_1.isAnyOrUnknown)(type.details.boundType)) {
                            if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
                                boundTypeString = `Self`;
                            }
                            else {
                                boundTypeString = `Self@${boundTypeString}`;
                            }
                        }
                        if (types_1.TypeBase.isInstantiable(type)) {
                            return `${_printNestedInstantiable(type, boundTypeString)}`;
                        }
                        return boundTypeString;
                    }
                    return (printTypeFlags & (1 /* PrintTypeFlags.PrintUnknownWithAny */ | 256 /* PrintTypeFlags.PythonSyntax */)) !== 0
                        ? 'Any'
                        : 'Unknown';
                }
                if (type.details.isParamSpec) {
                    const paramSpecText = _getReadableTypeVarName(type, (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0);
                    if (type.paramSpecAccess) {
                        return `${paramSpecText}.${type.paramSpecAccess}`;
                    }
                    return paramSpecText;
                }
                let typeVarName = _getReadableTypeVarName(type, (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) !== 0);
                if (type.isVariadicUnpacked) {
                    typeVarName = _printUnpack(typeVarName, printTypeFlags);
                }
                if (type.isVariadicInUnion) {
                    typeVarName = `Union[${typeVarName}]`;
                }
                if (types_1.TypeBase.isInstantiable(type)) {
                    typeVarName = `${_printNestedInstantiable(type, typeVarName)}`;
                }
                if (!type.details.isVariadic && (printTypeFlags & 2048 /* PrintTypeFlags.PrintTypeVarVariance */) !== 0) {
                    const varianceText = _getTypeVarVarianceText(type);
                    if (varianceText) {
                        typeVarName = `${typeVarName} (${varianceText})`;
                    }
                }
                return typeVarName;
            }
            case 3 /* TypeCategory.Never */: {
                return type.isNoReturn ? 'NoReturn' : 'Never';
            }
            case 2 /* TypeCategory.Any */: {
                const anyType = type;
                return anyType.isEllipsis ? '...' : 'Any';
            }
        }
        return '';
    }
    finally {
        recursionTypes.pop();
    }
}
function printFunctionType(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount) {
    if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
        // Callable works only in cases where all parameters are positional-only.
        let isPositionalParamsOnly = false;
        if (type.details.parameters.length === 0) {
            isPositionalParamsOnly = true;
        }
        else {
            if (type.details.parameters.every((param) => param.category === 0 /* ParameterCategory.Simple */)) {
                const lastParam = type.details.parameters[type.details.parameters.length - 1];
                if (!lastParam.name) {
                    isPositionalParamsOnly = true;
                }
            }
        }
        const returnType = returnTypeCallback(type);
        let returnTypeString = 'Any';
        if (returnType) {
            returnTypeString = printTypeInternal(returnType, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
        }
        if (isPositionalParamsOnly) {
            const paramTypes = [];
            type.details.parameters.forEach((param, index) => {
                if (param.name) {
                    const paramType = types_1.FunctionType.getEffectiveParameterType(type, index);
                    if (recursionTypes.length < types_1.maxTypeRecursionCount) {
                        paramTypes.push(printTypeInternal(paramType, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount));
                    }
                    else {
                        paramTypes.push('Any');
                    }
                }
            });
            if (type.details.paramSpec) {
                if (paramTypes.length > 0) {
                    return `Callable[Concatenate[${paramTypes.join(', ')}, ${type.details.paramSpec.details.name}], ${returnTypeString}]`;
                }
                return `Callable[${type.details.paramSpec.details.name}, ${returnTypeString}]`;
            }
            return `Callable[[${paramTypes.join(', ')}], ${returnTypeString}]`;
        }
        else {
            // We can't represent this type using a Callable so default to
            // a "catch all" Callable.
            return `Callable[..., ${returnTypeString}]`;
        }
    }
    else {
        const parts = printFunctionPartsInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
        const paramSignature = `(${parts[0].join(', ')})`;
        if (types_1.FunctionType.isParamSpecValue(type)) {
            if (parts[0].length === 1 && parts[0][0] === '...') {
                return parts[0][0];
            }
            return paramSignature;
        }
        const fullSignature = `${paramSignature} -> ${parts[1]}`;
        const parenthesizeCallable = (printTypeFlags & 128 /* PrintTypeFlags.ParenthesizeCallable */) !== 0;
        if (parenthesizeCallable) {
            return `(${fullSignature})`;
        }
        return fullSignature;
    }
}
function printObjectTypeForClassInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount) {
    var _a, _b;
    let objName = type.aliasName;
    if (!objName) {
        objName =
            (printTypeFlags & 4096 /* PrintTypeFlags.UseFullyQualifiedNames */) !== 0 ? type.details.fullName : type.details.name;
    }
    // Special-case NoneType to convert it to None.
    if (types_1.ClassType.isBuiltIn(type, 'NoneType')) {
        objName = 'None';
    }
    // Use the fully-qualified name if the name isn't unique.
    if (!uniqueNameMap.isUnique(objName)) {
        objName = type.details.fullName;
    }
    // If this is a pseudo-generic class, don't display the type arguments
    // or type parameters because it will confuse users.
    if (!types_1.ClassType.isPseudoGenericClass(type)) {
        const typeParams = types_1.ClassType.getTypeParameters(type);
        const lastTypeParam = typeParams.length > 0 ? typeParams[typeParams.length - 1] : undefined;
        const isVariadic = lastTypeParam ? lastTypeParam.details.isVariadic : false;
        // If there is a type arguments array, it's a specialized class.
        const typeArgs = (_a = type.tupleTypeArguments) !== null && _a !== void 0 ? _a : (_b = type.typeArguments) === null || _b === void 0 ? void 0 : _b.map((t) => {
            return { type: t, isUnbounded: false };
        });
        if (typeArgs) {
            // Handle Tuple[()] as a special case.
            if (typeArgs.length > 0) {
                const typeArgStrings = [];
                let isAllUnknown = true;
                typeArgs.forEach((typeArg, index) => {
                    const typeParam = index < typeParams.length ? typeParams[index] : undefined;
                    if (typeParam &&
                        typeParam.details.isVariadic &&
                        (0, types_1.isClassInstance)(typeArg.type) &&
                        types_1.ClassType.isBuiltIn(typeArg.type, 'tuple') &&
                        typeArg.type.tupleTypeArguments) {
                        // Expand the tuple type that maps to the variadic type parameter.
                        if (typeArg.type.tupleTypeArguments.length === 0) {
                            if (!(0, types_1.isUnknown)(typeArg.type)) {
                                isAllUnknown = false;
                            }
                            if (index === 0) {
                                typeArgStrings.push(_printUnpack('tuple[()]', printTypeFlags));
                            }
                        }
                        else {
                            (0, collectionUtils_1.appendArray)(typeArgStrings, typeArg.type.tupleTypeArguments.map((typeArg) => {
                                if (!(0, types_1.isUnknown)(typeArg.type)) {
                                    isAllUnknown = false;
                                }
                                const typeArgText = printTypeInternal(typeArg.type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                                if (typeArg.isUnbounded) {
                                    return _printUnpack(`tuple[${typeArgText}, ...]`, printTypeFlags);
                                }
                                return typeArgText;
                            }));
                        }
                    }
                    else {
                        if (!(0, types_1.isUnknown)(typeArg.type)) {
                            isAllUnknown = false;
                        }
                        const typeArgTypeText = printTypeInternal(typeArg.type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                        if (typeArg.isUnbounded) {
                            if (typeArgs.length === 1) {
                                typeArgStrings.push(typeArgTypeText, '...');
                            }
                            else {
                                typeArgStrings.push(_printUnpack(`tuple[${typeArgTypeText}, ...]`, printTypeFlags));
                            }
                        }
                        else {
                            typeArgStrings.push(typeArgTypeText);
                        }
                    }
                });
                if (type.isUnpacked) {
                    objName = _printUnpack(objName, printTypeFlags);
                }
                if ((printTypeFlags & 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */) === 0 || !isAllUnknown) {
                    objName += '[' + typeArgStrings.join(', ') + ']';
                }
            }
            else {
                if (type.isUnpacked) {
                    objName = _printUnpack(objName, printTypeFlags);
                }
                if (types_1.ClassType.isTupleClass(type) || isVariadic) {
                    objName += '[()]';
                }
            }
        }
        else {
            if (type.isUnpacked) {
                objName = _printUnpack(objName, printTypeFlags);
            }
            if (typeParams.length > 0) {
                if ((printTypeFlags & 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */) === 0 ||
                    typeParams.some((typeParam) => !(0, types_1.isUnknown)(typeParam))) {
                    objName +=
                        '[' +
                            typeParams
                                .map((typeParam) => {
                                return printTypeInternal(typeParam, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                            })
                                .join(', ') +
                            ']';
                }
            }
        }
    }
    // Wrap in a "Partial" for TypedDict that has been synthesized as partial.
    if (type.isTypedDictPartial) {
        if ((printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) === 0) {
            objName = `Partial[${objName}]`;
        }
    }
    return objName;
}
function printFunctionPartsInternal(type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount) {
    const paramTypeStrings = [];
    let sawDefinedName = false;
    type.details.parameters.forEach((param, index) => {
        // Handle specialized variadic type parameters specially.
        if (index === type.details.parameters.length - 1 &&
            param.category === 1 /* ParameterCategory.ArgsList */ &&
            (0, types_1.isVariadicTypeVar)(param.type)) {
            const specializedParamType = types_1.FunctionType.getEffectiveParameterType(type, index);
            if ((0, types_1.isClassInstance)(specializedParamType) &&
                types_1.ClassType.isBuiltIn(specializedParamType, 'tuple') &&
                specializedParamType.tupleTypeArguments) {
                specializedParamType.tupleTypeArguments.forEach((paramType) => {
                    const paramString = printTypeInternal(paramType.type, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                    paramTypeStrings.push(paramString);
                });
                return;
            }
        }
        // Handle expanding TypedDict kwargs specially.
        if ((0, parameterUtils_1.isTypedKwargs)(param) &&
            printTypeFlags & 1024 /* PrintTypeFlags.ExpandTypedDictArgs */ &&
            param.type.category === 6 /* TypeCategory.Class */) {
            param.type.details.typedDictEntries.knownItems.forEach((v, k) => {
                const valueTypeString = printTypeInternal(v.valueType, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount);
                paramTypeStrings.push(`${k}: ${valueTypeString}`);
            });
            return;
        }
        let paramString = '';
        if (param.category === 1 /* ParameterCategory.ArgsList */) {
            if (!param.name || !param.isNameSynthesized) {
                paramString += '*';
            }
        }
        else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
            paramString += '**';
        }
        let emittedParamName = false;
        if (param.name && !param.isNameSynthesized) {
            paramString += param.name;
            sawDefinedName = true;
            emittedParamName = true;
        }
        else if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
            paramString += `__p${index}`;
            sawDefinedName = true;
            emittedParamName = true;
        }
        let defaultValueAssignment = '=';
        let isParamSpecArgsKwargsParam = false;
        if (param.name) {
            // Avoid printing type types if parameter have unknown type.
            if (param.hasDeclaredType || param.isTypeInferred) {
                const paramType = types_1.FunctionType.getEffectiveParameterType(type, index);
                let paramTypeString = recursionTypes.length < types_1.maxTypeRecursionCount
                    ? printTypeInternal(paramType, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount)
                    : '';
                if (emittedParamName) {
                    paramString += ': ';
                }
                else if (param.category === 1 /* ParameterCategory.ArgsList */ && !(0, types_1.isUnpacked)(paramType)) {
                    paramString += '*';
                }
                if (param.category === 2 /* ParameterCategory.KwargsDict */ && (0, types_1.isUnpacked)(paramType)) {
                    if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
                        // Use "Unpack" because ** isn't legal syntax prior to Python 3.12.
                        paramTypeString = `Unpack[${paramTypeString.substring(1)}]`;
                    }
                    else {
                        // If this is an unpacked TypeDict for a **kwargs parameter, add another star.
                        paramTypeString = '*' + paramTypeString;
                    }
                }
                paramString += paramTypeString;
                if ((0, types_1.isParamSpec)(paramType)) {
                    if (param.category === 1 /* ParameterCategory.ArgsList */ ||
                        param.category === 2 /* ParameterCategory.KwargsDict */) {
                        isParamSpecArgsKwargsParam = true;
                    }
                }
                // PEP8 indicates that the "=" for the default value should have surrounding
                // spaces when used with a type annotation.
                defaultValueAssignment = ' = ';
            }
            else if ((printTypeFlags & 2 /* PrintTypeFlags.OmitTypeArgumentsIfUnknown */) === 0) {
                if (!param.isNameSynthesized) {
                    paramString += ': ';
                }
                if (printTypeFlags & (1 /* PrintTypeFlags.PrintUnknownWithAny */ | 256 /* PrintTypeFlags.PythonSyntax */)) {
                    paramString += 'Any';
                }
                else {
                    paramString += 'Unknown';
                }
                defaultValueAssignment = ' = ';
            }
        }
        else if (param.category === 0 /* ParameterCategory.Simple */) {
            if (sawDefinedName) {
                paramString += '/';
            }
            else {
                return;
            }
        }
        if (param.hasDefault) {
            if (param.defaultValueExpression) {
                paramString += defaultValueAssignment + ParseTreeUtils.printExpression(param.defaultValueExpression);
            }
            else {
                // If the function doesn't originate from a function declaration (e.g. it is
                // synthesized), we can't get to the default declaration, but we can still indicate
                // that there is a default value provided.
                paramString += defaultValueAssignment + '...';
            }
        }
        // If this is a (...) signature, replace the *args, **kwargs with "...".
        if (types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(type) && !isParamSpecArgsKwargsParam) {
            if (param.category === 1 /* ParameterCategory.ArgsList */) {
                paramString = '...';
            }
            else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                return;
            }
        }
        paramTypeStrings.push(paramString);
    });
    if (type.details.paramSpec) {
        if (printTypeFlags & 256 /* PrintTypeFlags.PythonSyntax */) {
            paramTypeStrings.push(`*args: ${type.details.paramSpec}.args`);
            paramTypeStrings.push(`**kwargs: ${type.details.paramSpec}.kwargs`);
        }
        else {
            paramTypeStrings.push(`**${printTypeInternal(type.details.paramSpec, printTypeFlags, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount)}`);
        }
    }
    const returnType = returnTypeCallback(type);
    const returnTypeString = recursionTypes.length < types_1.maxTypeRecursionCount
        ? printTypeInternal(returnType, printTypeFlags | 16 /* PrintTypeFlags.ParenthesizeUnion */ | 128 /* PrintTypeFlags.ParenthesizeCallable */, returnTypeCallback, uniqueNameMap, recursionTypes, recursionCount)
        : '';
    return [paramTypeStrings, returnTypeString];
}
function _printUnpack(textToWrap, flags) {
    return flags & 512 /* PrintTypeFlags.UseTypingUnpack */ ? `Unpack[${textToWrap}]` : `*${textToWrap}`;
}
// Surrounds a printed type with Type[...] as many times as needed
// for the nested instantiable count.
function _printNestedInstantiable(type, textToWrap) {
    var _a;
    const nestedTypes = ((_a = type.instantiableNestingLevel) !== null && _a !== void 0 ? _a : 0) + 1;
    for (let nestLevel = 0; nestLevel < nestedTypes; nestLevel++) {
        textToWrap = `type[${textToWrap}]`;
    }
    return textToWrap;
}
function _getReadableTypeVarName(type, usePythonSyntax) {
    if (usePythonSyntax) {
        return type.details.name;
    }
    return types_1.TypeVarType.getReadableName(type);
}
function _getTypeVarVarianceText(type) {
    var _a;
    const computedVariance = (_a = type.computedVariance) !== null && _a !== void 0 ? _a : type.details.declaredVariance;
    if (computedVariance === 2 /* Variance.Invariant */) {
        return 'invariant';
    }
    if (computedVariance === 3 /* Variance.Covariant */) {
        return 'covariant';
    }
    if (computedVariance === 4 /* Variance.Contravariant */) {
        return 'contravariant';
    }
    return '';
}
// Represents a map of named types (classes and type aliases) that appear within
// a specified type to determine whether any of the names require disambiguation
// (i.e. their fully-qualified name is required).
class UniqueNameMap {
    constructor(_printTypeFlags, _returnTypeCallback) {
        this._printTypeFlags = _printTypeFlags;
        this._returnTypeCallback = _returnTypeCallback;
        this._map = new Map();
    }
    build(type, recursionTypes = [], recursionCount = 0) {
        var _a;
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return;
        }
        recursionCount++;
        if (type.typeAliasInfo) {
            let expandTypeAlias = true;
            if ((this._printTypeFlags & 32 /* PrintTypeFlags.ExpandTypeAlias */) === 0) {
                expandTypeAlias = false;
            }
            else {
                if (recursionTypes.find((t) => t === type)) {
                    expandTypeAlias = false;
                }
            }
            if (!expandTypeAlias) {
                const typeAliasName = (this._printTypeFlags & 4096 /* PrintTypeFlags.UseFullyQualifiedNames */) !== 0
                    ? type.typeAliasInfo.fullName
                    : type.typeAliasInfo.name;
                this._addIfUnique(typeAliasName, type, /* useTypeAliasName */ true);
                // Recursively add the type arguments if present.
                if (type.typeAliasInfo.typeArguments) {
                    recursionTypes.push(type);
                    try {
                        type.typeAliasInfo.typeArguments.forEach((typeArg) => {
                            this.build(typeArg, recursionTypes, recursionCount);
                        });
                    }
                    finally {
                        recursionTypes.pop();
                    }
                }
                return;
            }
        }
        try {
            recursionTypes.push(type);
            switch (type.category) {
                case 4 /* TypeCategory.Function */: {
                    type.details.parameters.forEach((_, index) => {
                        const paramType = types_1.FunctionType.getEffectiveParameterType(type, index);
                        this.build(paramType, recursionTypes, recursionCount);
                    });
                    const returnType = this._returnTypeCallback(type);
                    this.build(returnType, recursionTypes, recursionCount);
                    break;
                }
                case 5 /* TypeCategory.OverloadedFunction */: {
                    type.overloads.forEach((overload) => {
                        this.build(overload, recursionTypes, recursionCount);
                    });
                    break;
                }
                case 6 /* TypeCategory.Class */: {
                    if (type.literalValue !== undefined) {
                        break;
                    }
                    let className = type.aliasName;
                    if (!className) {
                        className =
                            (this._printTypeFlags & 4096 /* PrintTypeFlags.UseFullyQualifiedNames */) !== 0
                                ? type.details.fullName
                                : type.details.name;
                    }
                    this._addIfUnique(className, type);
                    if (!types_1.ClassType.isPseudoGenericClass(type)) {
                        if (type.tupleTypeArguments) {
                            type.tupleTypeArguments.forEach((typeArg) => {
                                this.build(typeArg.type, recursionTypes, recursionCount);
                            });
                        }
                        else if (type.typeArguments) {
                            type.typeArguments.forEach((typeArg) => {
                                this.build(typeArg, recursionTypes, recursionCount);
                            });
                        }
                    }
                    break;
                }
                case 8 /* TypeCategory.Union */: {
                    (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                        this.build(subtype, recursionTypes, recursionCount);
                    });
                    (_a = type.typeAliasSources) === null || _a === void 0 ? void 0 : _a.forEach((typeAliasSource) => {
                        this.build(typeAliasSource, recursionTypes, recursionCount);
                    });
                    break;
                }
            }
        }
        finally {
            recursionTypes.pop();
        }
    }
    isUnique(name) {
        const entry = this._map.get(name);
        return !entry || entry.length === 1;
    }
    _addIfUnique(name, type, useTypeAliasName = false) {
        const existingEntry = this._map.get(name);
        if (!existingEntry) {
            this._map.set(name, [type]);
        }
        else {
            if (!existingEntry.some((t) => this._isSameTypeName(t, type, useTypeAliasName))) {
                existingEntry.push(type);
            }
        }
    }
    _isSameTypeName(type1, type2, useTypeAliasName) {
        var _a, _b;
        if (useTypeAliasName) {
            return ((_a = type1.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.fullName) === ((_b = type2.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.fullName);
        }
        if ((0, types_1.isClass)(type1) && (0, types_1.isClass)(type2)) {
            return types_1.ClassType.isSameGenericClass(type1, type2);
        }
        return false;
    }
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeStubWriter.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeStubWriter.ts ***!
  \**********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typeStubWriter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic to emit a type stub file for a corresponding parsed
 * and analyzed python source file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeStubWriter = void 0;
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeWalker_1 = __webpack_require__(/*! ./parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const scopeUtils_1 = __webpack_require__(/*! ./scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const SymbolNameUtils = __importStar(__webpack_require__(/*! ./symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
class TrackedImport {
    constructor(importName) {
        this.importName = importName;
        this.isAccessed = false;
    }
}
class TrackedImportAs extends TrackedImport {
    constructor(importName, alias, symbol) {
        super(importName);
        this.alias = alias;
        this.symbol = symbol;
    }
}
class TrackedImportFrom extends TrackedImport {
    constructor(importName, isWildcardImport, node) {
        super(importName);
        this.isWildcardImport = isWildcardImport;
        this.node = node;
        this.symbols = [];
    }
    addSymbol(symbol, name, alias, isAccessed = false) {
        if (!this.symbols.find((s) => s.name === name)) {
            this.symbols.push({
                symbol,
                name,
                alias,
                isAccessed,
            });
        }
    }
}
class ImportSymbolWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_accessedImportedSymbols, _treatStringsAsSymbols) {
        super();
        this._accessedImportedSymbols = _accessedImportedSymbols;
        this._treatStringsAsSymbols = _treatStringsAsSymbols;
    }
    analyze(node) {
        this.walk(node);
    }
    walk(node) {
        if (!AnalyzerNodeInfo.isCodeUnreachable(node)) {
            super.walk(node);
        }
    }
    visitName(node) {
        this._accessedImportedSymbols.add(node.value);
        return true;
    }
    visitMemberAccess(node) {
        const baseExpression = this._getRecursiveModuleAccessExpression(node.leftExpression);
        if (baseExpression) {
            this._accessedImportedSymbols.add(`${baseExpression}.${node.memberName.value}`);
        }
        return true;
    }
    visitString(node) {
        if (this._treatStringsAsSymbols) {
            this._accessedImportedSymbols.add(node.value);
        }
        return true;
    }
    _getRecursiveModuleAccessExpression(node) {
        if (node.nodeType === 38 /* ParseNodeType.Name */) {
            return node.value;
        }
        if (node.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            const baseExpression = this._getRecursiveModuleAccessExpression(node.leftExpression);
            if (!baseExpression) {
                return undefined;
            }
            return `${baseExpression}.${node.memberName.value}`;
        }
        return undefined;
    }
}
class TypeStubWriter extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_stubPath, _sourceFile, _evaluator) {
        super();
        this._stubPath = _stubPath;
        this._sourceFile = _sourceFile;
        this._evaluator = _evaluator;
        this._indentAmount = 0;
        this._includeAllImports = false;
        this._typeStubText = '';
        this._lineEnd = '\n';
        this._tab = '    ';
        this._classNestCount = 0;
        this._functionNestCount = 0;
        this._ifNestCount = 0;
        this._emittedSuite = false;
        this._emitDocString = true;
        this._trackedImportAs = new Map();
        this._trackedImportFrom = new Map();
        this._accessedImportedSymbols = new Set();
        // As a heuristic, we'll include all of the import statements
        // in "__init__.pyi" files even if they're not locally referenced
        // because these are often used as ways to re-export symbols.
        if (this._stubPath.fileName === '__init__.pyi') {
            this._includeAllImports = true;
        }
    }
    write() {
        const parseResults = this._sourceFile.getParseResults();
        this._lineEnd = parseResults.tokenizerOutput.predominantEndOfLineSequence;
        this._tab = parseResults.tokenizerOutput.predominantTabSequence;
        this.walk(parseResults.parserOutput.parseTree);
        this._writeFile();
    }
    walk(node) {
        if (!AnalyzerNodeInfo.isCodeUnreachable(node)) {
            super.walk(node);
        }
    }
    visitClass(node) {
        const className = node.name.value;
        this._emittedSuite = true;
        this._emitDocString = true;
        this._emitDecorators(node.decorators);
        let line = `class ${className}`;
        if (node.typeParameters) {
            line += this._printTypeParameters(node.typeParameters);
        }
        // Remove "object" from the list, since it's implied
        const args = node.arguments.filter((arg) => arg.name !== undefined ||
            arg.argumentCategory !== 0 /* ArgumentCategory.Simple */ ||
            arg.valueExpression.nodeType !== 38 /* ParseNodeType.Name */ ||
            arg.valueExpression.value !== 'object');
        if (args.length > 0) {
            line += `(${args
                .map((arg) => {
                let argString = '';
                if (arg.name) {
                    argString = arg.name.value + '=';
                }
                argString += this._printExpression(arg.valueExpression);
                return argString;
            })
                .join(', ')})`;
        }
        line += ':';
        this._emitLine(line);
        this._emitSuite(() => {
            this._classNestCount++;
            this.walk(node.suite);
            this._classNestCount--;
        });
        this._emitLine('');
        this._emitLine('');
        return false;
    }
    visitFunction(node) {
        const functionName = node.name.value;
        // Skip if we're already within a function or if the name is private/protected.
        if (this._functionNestCount === 0 && !SymbolNameUtils.isPrivateOrProtectedName(functionName)) {
            this._emittedSuite = true;
            this._emitDocString = true;
            this._emitDecorators(node.decorators);
            let line = node.isAsync ? 'async ' : '';
            line += `def ${functionName}`;
            if (node.typeParameters) {
                line += this._printTypeParameters(node.typeParameters);
            }
            line += `(${node.parameters.map((param, index) => this._printParameter(param, node, index)).join(', ')})`;
            let returnAnnotation;
            if (node.returnTypeAnnotation) {
                returnAnnotation = this._printExpression(node.returnTypeAnnotation, /* treatStringsAsSymbols */ true);
            }
            else if (node.functionAnnotationComment) {
                returnAnnotation = this._printExpression(node.functionAnnotationComment.returnTypeAnnotation, 
                /* treatStringsAsSymbols */ true);
            }
            else {
                // Handle a few common cases where we always know the answer.
                if (node.name.value === '__init__') {
                    returnAnnotation = 'None';
                }
                else if (node.name.value === '__str__') {
                    returnAnnotation = 'str';
                }
                else if (['__int__', '__hash__'].some((name) => name === node.name.value)) {
                    returnAnnotation = 'int';
                }
                else if (['__eq__', '__ne__', '__gt__', '__lt__', '__ge__', '__le__'].some((name) => name === node.name.value)) {
                    returnAnnotation = 'bool';
                }
            }
            if (returnAnnotation) {
                line += ' -> ' + returnAnnotation;
            }
            line += ':';
            // If there was not return type annotation, see if we can infer
            // a type that is not unknown and add it as a comment.
            if (!returnAnnotation) {
                const functionType = this._evaluator.getTypeOfFunction(node);
                if (functionType && (0, types_1.isFunction)(functionType.functionType)) {
                    let returnType = this._evaluator.getFunctionInferredReturnType(functionType.functionType);
                    returnType = (0, types_1.removeUnknownFromUnion)(returnType);
                    if (!(0, types_1.isNever)(returnType) && !(0, types_1.isUnknown)(returnType)) {
                        line += ` # -> ${this._evaluator.printType(returnType, { enforcePythonSyntax: true })}:`;
                    }
                }
            }
            this._emitLine(line);
            this._emitSuite(() => {
                // Don't emit any nested functions.
                this._functionNestCount++;
                this.walk(node.suite);
                this._functionNestCount--;
            });
            this._emitLine('');
        }
        return false;
    }
    visitWhile(node) {
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        return false;
    }
    visitFor(node) {
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        return false;
    }
    visitTry(node) {
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        // Only walk a single branch of the try/catch to for imports.
        this.walk(node.trySuite);
        return false;
    }
    visitWith(node) {
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        return false;
    }
    visitIf(node) {
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        // Include if statements if they are located
        // at the global scope.
        if (this._functionNestCount === 0 && this._ifNestCount === 0) {
            this._ifNestCount++;
            this._emittedSuite = true;
            this._emitLine('if ' + this._printExpression(node.testExpression) + ':');
            this._emitSuite(() => {
                this.walkMultiple(node.ifSuite.statements);
            });
            const elseSuite = node.elseSuite;
            if (elseSuite) {
                this._emitLine('else:');
                this._emitSuite(() => {
                    if (elseSuite.nodeType === 19 /* ParseNodeType.If */) {
                        this.walkMultiple([elseSuite.testExpression, elseSuite.ifSuite, elseSuite.elseSuite]);
                    }
                    else {
                        this.walkMultiple(elseSuite.statements);
                    }
                });
            }
            this._ifNestCount--;
        }
        return false;
    }
    visitTypeAlias(node) {
        let line = '';
        line = this._printExpression(node.name);
        if (node.typeParameters) {
            line += this._printTypeParameters(node.typeParameters);
        }
        line += ' = ';
        line += this._printExpression(node.expression);
        this._emitLine(line);
        return false;
    }
    visitAssignment(node) {
        let isTypeAlias = false;
        let line = '';
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
            // Handle "__all__" as a special case.
            if (node.leftExpression.value === '__all__') {
                if (this._functionNestCount === 0 && this._ifNestCount === 0) {
                    this._emittedSuite = true;
                    line = this._printExpression(node.leftExpression);
                    line += ' = ';
                    line += this._printExpression(node.rightExpression);
                    this._emitLine(line);
                }
                return false;
            }
            if (this._functionNestCount === 0) {
                line = this._printExpression(node.leftExpression);
                if (node.typeAnnotationComment) {
                    line += ': ' + this._printExpression(node.typeAnnotationComment, /* treatStringsAsSymbols */ true);
                }
                const valueType = this._evaluator.getType(node.leftExpression);
                if (valueType === null || valueType === void 0 ? void 0 : valueType.typeAliasInfo) {
                    isTypeAlias = true;
                }
                else if (node.rightExpression.nodeType === 9 /* ParseNodeType.Call */) {
                    // Special-case TypeVar, TypeVarTuple, ParamSpec and NewType calls. Treat
                    // them like type aliases.
                    const callBaseType = this._evaluator.getType(node.rightExpression.leftExpression);
                    if (callBaseType &&
                        (0, types_1.isInstantiableClass)(callBaseType) &&
                        types_1.ClassType.isBuiltIn(callBaseType, ['TypeVar', 'TypeVarTuple', 'ParamSpec', 'NewType'])) {
                        isTypeAlias = true;
                    }
                }
            }
        }
        else if (node.leftExpression.nodeType === 54 /* ParseNodeType.TypeAnnotation */) {
            const valueExpr = node.leftExpression.valueExpression;
            if (valueExpr.nodeType === 38 /* ParseNodeType.Name */) {
                if (this._functionNestCount === 0) {
                    line = `${this._printExpression(valueExpr)}: ${this._printExpression(node.leftExpression.typeAnnotation, 
                    /* treatStringsAsSymbols */ true)}`;
                }
            }
        }
        if (line) {
            this._emittedSuite = true;
            line += ' = ';
            if (isTypeAlias) {
                line += this._printExpression(node.rightExpression);
            }
            else {
                line += '...';
            }
            this._emitLine(line);
        }
        return false;
    }
    visitAugmentedAssignment(node) {
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
            // Handle "__all__ +=" as a special case.
            if (node.leftExpression.value === '__all__' && node.operator === 1 /* OperatorType.AddEqual */) {
                if (this._functionNestCount === 0 && this._ifNestCount === 0) {
                    let line = this._printExpression(node.leftExpression);
                    line += ' += ';
                    line += this._printExpression(node.rightExpression);
                    this._emitLine(line);
                }
            }
        }
        return false;
    }
    visitTypeAnnotation(node) {
        if (this._functionNestCount === 0) {
            let line = '';
            if (node.valueExpression.nodeType === 38 /* ParseNodeType.Name */) {
                line = this._printExpression(node.valueExpression);
            }
            else if (node.valueExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                const baseExpression = node.valueExpression.leftExpression;
                if (baseExpression.nodeType === 38 /* ParseNodeType.Name */) {
                    if (baseExpression.value === 'self') {
                        const memberName = node.valueExpression.memberName.value;
                        if (!SymbolNameUtils.isPrivateOrProtectedName(memberName)) {
                            line = this._printExpression(node.valueExpression);
                        }
                    }
                }
            }
            if (line) {
                line += ': ' + this._printExpression(node.typeAnnotation, /* treatStringsAsSymbols */ true);
                this._emitLine(line);
            }
        }
        return false;
    }
    visitImport(node) {
        if (this._functionNestCount > 0 || this._classNestCount > 0) {
            return false;
        }
        const currentScope = (0, scopeUtils_1.getScopeForNode)(node);
        if (currentScope) {
            // Record the input for later.
            node.list.forEach((imp) => {
                const moduleName = this._printModuleName(imp.module);
                if (!this._trackedImportAs.has(moduleName)) {
                    const symbolName = imp.alias
                        ? imp.alias.value
                        : imp.module.nameParts.length > 0
                            ? imp.module.nameParts[0].value
                            : '';
                    const symbolInfo = currentScope.lookUpSymbolRecursive(symbolName);
                    if (symbolInfo) {
                        const trackedImportAs = new TrackedImportAs(moduleName, imp.alias ? imp.alias.value : undefined, symbolInfo.symbol);
                        this._trackedImportAs.set(moduleName, trackedImportAs);
                    }
                }
            });
        }
        return false;
    }
    visitImportFrom(node) {
        if (this._functionNestCount > 0 || this._classNestCount > 0) {
            return false;
        }
        const currentScope = (0, scopeUtils_1.getScopeForNode)(node);
        if (currentScope) {
            // Record the input for later.
            const moduleName = this._printModuleName(node.module);
            let trackedImportFrom = this._trackedImportFrom.get(moduleName);
            if (!trackedImportFrom) {
                trackedImportFrom = new TrackedImportFrom(moduleName, node.isWildcardImport, node);
                this._trackedImportFrom.set(moduleName, trackedImportFrom);
            }
            node.imports.forEach((imp) => {
                const symbolName = imp.alias ? imp.alias.value : imp.name.value;
                const symbolInfo = currentScope.lookUpSymbolRecursive(symbolName);
                if (symbolInfo) {
                    trackedImportFrom.addSymbol(symbolInfo.symbol, imp.name.value, imp.alias ? imp.alias.value : undefined, false);
                }
            });
        }
        return false;
    }
    visitStatementList(node) {
        if (node.statements.length > 0 && node.statements[0].nodeType === 48 /* ParseNodeType.StringList */) {
            // Is this the first statement in a suite? If it's a string
            // literal, assume it's a doc string and emit it.
            if (!this._emittedSuite && this._emitDocString) {
                this._emitLine(this._printExpression(node.statements[0]));
            }
        }
        // Don't emit a doc string after the first statement.
        this._emitDocString = false;
        this.walkMultiple(node.statements);
        return false;
    }
    _emitSuite(callback) {
        this._increaseIndent(() => {
            const prevEmittedSuite = this._emittedSuite;
            this._emittedSuite = false;
            callback();
            if (!this._emittedSuite) {
                this._emitLine('...');
            }
            this._emittedSuite = prevEmittedSuite;
        });
    }
    _increaseIndent(callback) {
        this._indentAmount++;
        callback();
        this._indentAmount--;
    }
    _emitDecorators(decorators) {
        decorators.forEach((decorator) => {
            this._emitLine('@' + this._printExpression(decorator.expression));
        });
    }
    _printHeaderDocString() {
        return ('"""' +
            this._lineEnd +
            'This type stub file was generated by pyright.' +
            this._lineEnd +
            '"""' +
            this._lineEnd +
            this._lineEnd);
    }
    _emitLine(line) {
        for (let i = 0; i < this._indentAmount; i++) {
            this._typeStubText += this._tab;
        }
        this._typeStubText += line + this._lineEnd;
    }
    _printTypeParameters(node) {
        return `[${node.parameters.map((typeParam) => this._printTypeParameter(typeParam)).join(',')}]`;
    }
    _printTypeParameter(node) {
        let line = '';
        if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple) {
            line += '*';
        }
        else if (node.typeParamCategory === parseNodes_1.TypeParameterCategory.ParamSpec) {
            line += '**';
        }
        line += node.name.value;
        if (node.boundExpression) {
            line += ': ';
            line += this._printExpression(node.boundExpression);
        }
        if (node.defaultExpression) {
            line += ' = ';
            line += this._printExpression(node.defaultExpression);
        }
        return line;
    }
    _printModuleName(node) {
        let line = '';
        for (let i = 0; i < node.leadingDots; i++) {
            line += '.';
        }
        line += node.nameParts.map((part) => part.value).join('.');
        return line;
    }
    _printParameter(paramNode, functionNode, paramIndex) {
        let line = '';
        if (paramNode.category === 1 /* ParameterCategory.ArgsList */) {
            line += '*';
        }
        else if (paramNode.category === 2 /* ParameterCategory.KwargsDict */) {
            line += '**';
        }
        if (paramNode.name) {
            line += paramNode.name.value;
        }
        else if (paramNode.category === 0 /* ParameterCategory.Simple */) {
            line += '/';
        }
        const paramTypeAnnotation = ParseTreeUtils.getTypeAnnotationForParameter(functionNode, paramIndex);
        let paramType = '';
        if (paramTypeAnnotation) {
            paramType = this._printExpression(paramTypeAnnotation, /* treatStringsAsSymbols */ true);
        }
        if (paramType) {
            line += ': ' + paramType;
        }
        if (paramNode.defaultValue) {
            // Follow PEP8 spacing rules. Include spaces if type
            // annotation is present, no space otherwise.
            if (paramType) {
                line += ' = ...';
            }
            else {
                line += '=...';
            }
        }
        return line;
    }
    _printExpression(node, isType = false, treatStringsAsSymbols = false) {
        const importSymbolWalker = new ImportSymbolWalker(this._accessedImportedSymbols, treatStringsAsSymbols);
        importSymbolWalker.analyze(node);
        let expressionFlags = isType
            ? 1 /* ParseTreeUtils.PrintExpressionFlags.ForwardDeclarations */
            : 0 /* ParseTreeUtils.PrintExpressionFlags.None */;
        expressionFlags |= 2 /* ParseTreeUtils.PrintExpressionFlags.DoNotLimitStringLength */;
        return ParseTreeUtils.printExpression(node, expressionFlags);
    }
    _printTrackedImports() {
        let importStr = '';
        let lineEmitted = false;
        // Emit the "import" statements.
        this._trackedImportAs.forEach((imp) => {
            if (this._accessedImportedSymbols.has(imp.alias || imp.importName)) {
                imp.isAccessed = true;
            }
            if (imp.isAccessed || this._includeAllImports) {
                importStr += `import ${imp.importName}`;
                if (imp.alias) {
                    importStr += ` as ${imp.alias}`;
                }
                importStr += this._lineEnd;
                lineEmitted = true;
            }
        });
        // Emit the "import from" statements.
        this._trackedImportFrom.forEach((imp) => {
            imp.symbols.forEach((s) => {
                if (this._accessedImportedSymbols.has(s.alias || s.name)) {
                    s.isAccessed = true;
                }
            });
            if (imp.isWildcardImport) {
                importStr += `from ${imp.importName} import *` + this._lineEnd;
                lineEmitted = true;
            }
            const sortedSymbols = imp.symbols
                .filter((s) => s.isAccessed || this._includeAllImports)
                .sort((a, b) => {
                if (a.name < b.name) {
                    return -1;
                }
                else if (a.name > b.name) {
                    return 1;
                }
                return 0;
            });
            if (sortedSymbols.length > 0) {
                importStr += `from ${imp.importName} import `;
                importStr += sortedSymbols
                    .map((symbol) => {
                    let symStr = symbol.name;
                    if (symbol.alias) {
                        symStr += ' as ' + symbol.alias;
                    }
                    return symStr;
                })
                    .join(', ');
                importStr += this._lineEnd;
                lineEmitted = true;
            }
        });
        if (lineEmitted) {
            importStr += this._lineEnd;
        }
        return importStr;
    }
    _writeFile() {
        let finalText = this._printHeaderDocString();
        finalText += this._printTrackedImports();
        finalText += this._typeStubText;
        this._sourceFile.fileSystem.writeFileSync(this._stubPath, finalText, 'utf8');
    }
}
exports.TypeStubWriter = TypeStubWriter;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeUtils.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeUtils.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * typeUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Functions that operate on Type objects.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.partiallySpecializeType = exports.isTupleIndexUnambiguous = exports.isUnboundedTupleClass = exports.isTupleClass = exports.isMaybeDescriptorInstance = exports.isDescriptorInstance = exports.isCallableType = exports.isProperty = exports.isEllipsisType = exports.getUnionSubtypeCount = exports.getLiteralTypeClassName = exports.containsLiteralType = exports.isLiteralTypeOrUnion = exports.isLiteralType = exports.getSpecializedTupleType = exports.selfSpecializeClass = exports.getUnknownTypeForCallable = exports.getUnknownTypeForParamSpec = exports.getUnknownTypeForTypeVar = exports.specializeWithUnknownTypeArgs = exports.specializeWithDefaultTypeArgs = exports.getTypeVarScopeIds = exports.getTypeVarScopeId = exports.transformPossibleRecursiveTypeAlias = exports.isTypeAliasRecursive = exports.isTypeAliasPlaceholder = exports.getTypeCondition = exports.addConditionToType = exports.getFullNameOfType = exports.derivesFromAnyOrUnknown = exports.isUnionableType = exports.preserveUnknown = exports.areTypesSame = exports.doForEachSignature = exports.allSubtypes = exports.someSubtypes = exports.doForEachSubtype = exports.sortTypes = exports.cleanIncompleteUnknown = exports.mapSignatures = exports.mapSubtypes = exports.makeInferenceContext = exports.isBuiltInDeprecatedType = exports.isTypeVarSame = exports.isIncompleteUnknown = exports.removeNoneFromUnion = exports.isNoneTypeClass = exports.isNoneInstance = exports.isOptionalType = exports.UniqueSignatureTracker = void 0;
exports.isVarianceOfTypeArgumentCompatible = exports.combineVariances = exports.requiresSpecialization = exports.requiresTypeArguments = exports.getGeneratorTypeArgs = exports.removeParamSpecVariadicsFromFunction = exports.removeParamSpecVariadicsFromSignature = exports.specializeTupleClass = exports.combineSameSizedTuples = exports.explodeGenericClass = exports.isPartlyUnknown = exports.containsAnyOrUnknown = exports.containsAnyRecursive = exports.getMembersForModule = exports.getMembersForClass = exports.convertToInstantiable = exports.convertToInstance = exports.isEffectivelyInstantiable = exports.isMetaclassInstance = exports.isInstantiableMetaclass = exports.getGeneratorYieldType = exports.getDeclaredGeneratorReturnType = exports.synthesizeTypeVarForSelfCls = exports.derivesFromClassRecursive = exports.derivesFromStdlibClass = exports.specializeForBaseClass = exports.buildTypeVarContext = exports.buildTypeVarContextFromSpecializedClass = exports.setTypeArgumentsRecursive = exports.specializeClassType = exports.isTypeVarLimitedToCallable = exports.getTypeVarArgumentsRecursive = exports.addTypeVarsToListIfUnique = exports.getClassFieldsRecursive = exports.getClassIterator = exports.getClassMemberIterator = exports.lookUpClassMember = exports.lookUpObjectMember = exports.getContainerDepth = exports.getProtocolSymbolsRecursive = exports.getProtocolSymbols = exports.transformExpectedType = exports.replaceTypeVarsWithAny = exports.validateTypeVarDefault = exports.applyInScopePlaceholders = exports.applySourceContextTypeVarsToSignature = exports.applySourceContextTypeVars = exports.applySolvedTypeVars = exports.ensureFunctionSignaturesAreUnique = exports.populateTypeVarContextForSelfType = void 0;
exports.convertParamSpecValueToType = exports.convertTypeToParamSpecValue = exports.getDeclaringModulesForType = exports.computeMroLinearization = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolUtils_1 = __webpack_require__(/*! ./symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
const typeWalker_1 = __webpack_require__(/*! ./typeWalker */ "../pyright-internal/src/analyzer/typeWalker.ts");
// Tracks whether a function signature has been seen before within
// an expression. For example, in the expression "foo(foo, foo)", the
// signature for "foo" will be seen three times at three different
// file offsets. If the signature is generic, we need to create unique
// type variables for each instance because they are independent of
// each other.
class UniqueSignatureTracker {
    constructor() {
        this._trackedSignatures = [];
    }
    getTrackedSignatures() {
        return this._trackedSignatures;
    }
    addTrackedSignatures(signatures) {
        signatures.forEach((s) => {
            s.expressionOffsets.forEach((offset) => {
                this.addSignature(s.type, offset);
            });
        });
    }
    findSignature(signature) {
        // Use the associated overload type if this is a function associated with an overload.
        let effectiveSignature = signature;
        if ((0, types_1.isFunction)(signature) && signature.overloaded) {
            effectiveSignature = signature.overloaded;
        }
        return this._trackedSignatures.find((s) => {
            return (0, types_1.isTypeSame)(effectiveSignature, s.type);
        });
    }
    addSignature(signature, offset) {
        var _a;
        // If this function is part of a broader overload, use the overload instead.
        const effectiveSignature = (0, types_1.isFunction)(signature) ? (_a = signature.overloaded) !== null && _a !== void 0 ? _a : signature : signature;
        const existingSignature = this.findSignature(effectiveSignature);
        if (existingSignature) {
            if (!existingSignature.expressionOffsets.some((o) => o === offset)) {
                existingSignature.expressionOffsets.push(offset);
            }
        }
        else {
            this._trackedSignatures.push({ type: effectiveSignature, expressionOffsets: [offset] });
        }
    }
}
exports.UniqueSignatureTracker = UniqueSignatureTracker;
function isOptionalType(type) {
    if ((0, types_1.isUnion)(type)) {
        return (0, types_1.findSubtype)(type, (subtype) => isNoneInstance(subtype)) !== undefined;
    }
    return false;
}
exports.isOptionalType = isOptionalType;
function isNoneInstance(type) {
    return (0, types_1.isClassInstance)(type) && types_1.ClassType.isBuiltIn(type, 'NoneType');
}
exports.isNoneInstance = isNoneInstance;
function isNoneTypeClass(type) {
    return (0, types_1.isInstantiableClass)(type) && types_1.ClassType.isBuiltIn(type, 'NoneType');
}
exports.isNoneTypeClass = isNoneTypeClass;
// If the type is a union, remove an "None" type from the union,
// returning only the known types.
function removeNoneFromUnion(type) {
    return (0, types_1.removeFromUnion)(type, (t) => isNoneInstance(t));
}
exports.removeNoneFromUnion = removeNoneFromUnion;
function isIncompleteUnknown(type) {
    return (0, types_1.isUnknown)(type) && type.isIncomplete;
}
exports.isIncompleteUnknown = isIncompleteUnknown;
// Similar to isTypeSame except that type1 is a TypeVar and type2
// can be either a TypeVar of the same type or a union that includes
// conditional types associated with that bound TypeVar.
function isTypeVarSame(type1, type2) {
    if ((0, types_1.isTypeSame)(type1, type2)) {
        return true;
    }
    // If this isn't a bound TypeVar, return false.
    if (type1.details.isParamSpec || type1.details.isVariadic || !type1.details.boundType) {
        return false;
    }
    // If the second type isn't a union, return false.
    if (!(0, types_1.isUnion)(type2)) {
        return false;
    }
    let isCompatible = true;
    doForEachSubtype(type2, (subtype) => {
        if (!isCompatible) {
            return;
        }
        if (!(0, types_1.isTypeSame)(type1, subtype)) {
            const conditions = getTypeCondition(subtype);
            if (!conditions ||
                !conditions.some((condition) => condition.typeVar.nameWithScope === type1.nameWithScope)) {
                isCompatible = false;
            }
        }
    });
    return isCompatible;
}
exports.isTypeVarSame = isTypeVarSame;
// The `deprecated` type has been defined as a function, an overloaded function,
// and a class in various versions of typeshed. This function checks for all of
// these variants to determine whether the type is the built-in `deprecated` type.
function isBuiltInDeprecatedType(type) {
    if ((0, types_1.isFunction)(type)) {
        return type.details.builtInName === 'deprecated';
    }
    if ((0, types_1.isOverloadedFunction)(type)) {
        return type.overloads.length > 0 && type.overloads[0].details.builtInName === 'deprecated';
    }
    if ((0, types_1.isInstantiableClass)(type)) {
        return types_1.ClassType.isBuiltIn(type, 'deprecated');
    }
    return false;
}
exports.isBuiltInDeprecatedType = isBuiltInDeprecatedType;
function makeInferenceContext(expectedType, isTypeIncomplete, signatureTracker) {
    if (!expectedType) {
        return undefined;
    }
    return { expectedType, isTypeIncomplete, signatureTracker };
}
exports.makeInferenceContext = makeInferenceContext;
// Calls a callback for each subtype and combines the results
// into a final type. It performs no memory allocations if the
// transformed type is the same as the original.
function mapSubtypes(type, callback, sortSubtypes = false) {
    if ((0, types_1.isUnion)(type)) {
        const subtypes = sortSubtypes ? sortTypes(type.subtypes) : type.subtypes;
        for (let i = 0; i < subtypes.length; i++) {
            const subtype = subtypes[i];
            const transformedType = callback(subtype);
            // Avoid doing any memory allocations until a change is detected.
            if (subtype !== transformedType) {
                const typesToCombine = subtypes.slice(0, i);
                // Create a helper lambda that accumulates transformed subtypes.
                const accumulateSubtype = (newSubtype) => {
                    if (newSubtype) {
                        typesToCombine.push(addConditionToType(newSubtype, getTypeCondition(type)));
                    }
                };
                accumulateSubtype(transformedType);
                for (i++; i < subtypes.length; i++) {
                    accumulateSubtype(callback(subtypes[i]));
                }
                const newType = (0, types_1.combineTypes)(typesToCombine);
                // Do our best to retain type aliases.
                if (newType.category === 8 /* TypeCategory.Union */) {
                    types_1.UnionType.addTypeAliasSource(newType, type);
                }
                return newType;
            }
        }
        return type;
    }
    const transformedSubtype = callback(type);
    if (!transformedSubtype) {
        return types_1.NeverType.createNever();
    }
    return transformedSubtype;
}
exports.mapSubtypes = mapSubtypes;
// Iterates over each signature in a function or overload, allowing the
// caller to replace one or more signatures with new ones.
function mapSignatures(type, callback) {
    if ((0, types_1.isFunction)(type)) {
        return callback(type, 0);
    }
    const newSignatures = [];
    let changeMade = false;
    types_1.OverloadedFunctionType.getOverloads(type).forEach((overload, index) => {
        const newOverload = callback(overload, index);
        if (newOverload !== overload) {
            changeMade = true;
        }
        if (newOverload) {
            newSignatures.push(newOverload);
        }
    });
    // Add the unmodified implementation if it's present.
    const implementation = types_1.OverloadedFunctionType.getImplementation(type);
    if (implementation) {
        newSignatures.push(implementation);
    }
    if (!changeMade) {
        return type;
    }
    if (newSignatures.length === 0) {
        return undefined;
    }
    if (newSignatures.length === 1) {
        return newSignatures[0];
    }
    return types_1.OverloadedFunctionType.create(newSignatures);
}
exports.mapSignatures = mapSignatures;
// The code flow engine uses a special form of the UnknownType (with the
// isIncomplete flag set) to distinguish between an unknown that was generated
// in a loop because it was temporarily incomplete versus an unknown that is
// permanently incomplete. Once an unknown appears within a loop, it is often
// propagated to other types during code flow analysis. We want to remove these
// incomplete unknowns if we find that they are union'ed with other types.
function cleanIncompleteUnknown(type, recursionCount = 0) {
    if (recursionCount >= types_1.maxTypeRecursionCount) {
        return type;
    }
    recursionCount++;
    const result = mapSubtypes(type, (subtype) => {
        // If it's an incomplete unknown, eliminate it.
        if ((0, types_1.isUnknown)(subtype) && subtype.isIncomplete) {
            return undefined;
        }
        if ((0, types_1.isClass)(subtype) && subtype.typeArguments) {
            let typeChanged = false;
            if (subtype.tupleTypeArguments) {
                const updatedTupleTypeArgs = subtype.tupleTypeArguments.map((tupleTypeArg) => {
                    const newTypeArg = cleanIncompleteUnknown(tupleTypeArg.type, recursionCount);
                    if (newTypeArg !== tupleTypeArg.type) {
                        typeChanged = true;
                    }
                    return {
                        type: newTypeArg,
                        isUnbounded: tupleTypeArg.isUnbounded,
                        isOptional: tupleTypeArg.isOptional,
                    };
                });
                if (typeChanged) {
                    return specializeTupleClass(subtype, updatedTupleTypeArgs, !!subtype.isTypeArgumentExplicit, !!subtype.isUnpacked);
                }
            }
            else {
                const updatedTypeArgs = subtype.typeArguments.map((typeArg) => {
                    const newTypeArg = cleanIncompleteUnknown(typeArg, recursionCount);
                    if (newTypeArg !== typeArg) {
                        typeChanged = true;
                    }
                    return newTypeArg;
                });
                if (typeChanged) {
                    return types_1.ClassType.cloneForSpecialization(subtype, updatedTypeArgs, !!subtype.isTypeArgumentExplicit);
                }
            }
        }
        // TODO - this doesn't currently handle function types.
        return subtype;
    });
    // If we eliminated everything, don't return a Never.
    return (0, types_1.isNever)(result) ? type : result;
}
exports.cleanIncompleteUnknown = cleanIncompleteUnknown;
// Sorts types into a deterministic order.
function sortTypes(types) {
    return types.slice(0).sort((a, b) => {
        return compareTypes(a, b);
    });
}
exports.sortTypes = sortTypes;
function compareTypes(a, b, recursionCount = 0) {
    var _a, _b;
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return 0;
    }
    recursionCount++;
    if (a.category !== b.category) {
        return b.category - a.category;
    }
    switch (a.category) {
        case 0 /* TypeCategory.Unbound */:
        case 1 /* TypeCategory.Unknown */:
        case 2 /* TypeCategory.Any */:
        case 3 /* TypeCategory.Never */:
        case 8 /* TypeCategory.Union */: {
            return 0;
        }
        case 4 /* TypeCategory.Function */: {
            const bFunc = b;
            const aParamCount = a.details.parameters.length;
            const bParamCount = bFunc.details.parameters.length;
            if (aParamCount !== bParamCount) {
                return bParamCount - aParamCount;
            }
            for (let i = 0; i < aParamCount; i++) {
                const aParam = a.details.parameters[i];
                const bParam = bFunc.details.parameters[i];
                if (aParam.category !== bParam.category) {
                    return bParam.category - aParam.category;
                }
                const typeComparison = compareTypes(types_1.FunctionType.getEffectiveParameterType(a, i), types_1.FunctionType.getEffectiveParameterType(bFunc, i));
                if (typeComparison !== 0) {
                    return typeComparison;
                }
            }
            const returnTypeComparison = compareTypes((_a = types_1.FunctionType.getSpecializedReturnType(a)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create(), (_b = types_1.FunctionType.getSpecializedReturnType(bFunc)) !== null && _b !== void 0 ? _b : types_1.UnknownType.create());
            if (returnTypeComparison !== 0) {
                return returnTypeComparison;
            }
            const aName = a.details.name;
            const bName = bFunc.details.name;
            if (aName < bName) {
                return -1;
            }
            else if (aName > bName) {
                return 1;
            }
            return 0;
        }
        case 5 /* TypeCategory.OverloadedFunction */: {
            const bOver = b;
            const aOverloadCount = a.overloads.length;
            const bOverloadCount = bOver.overloads.length;
            if (aOverloadCount !== bOverloadCount) {
                return bOverloadCount - aOverloadCount;
            }
            for (let i = 0; i < aOverloadCount; i++) {
                const typeComparison = compareTypes(a.overloads[i], bOver.overloads[i]);
                if (typeComparison !== 0) {
                    return typeComparison;
                }
            }
            return 0;
        }
        case 6 /* TypeCategory.Class */: {
            const bClass = b;
            // Sort instances before instantiables.
            if ((0, types_1.isClassInstance)(a) && (0, types_1.isInstantiableClass)(bClass)) {
                return -1;
            }
            else if ((0, types_1.isInstantiableClass)(a) && (0, types_1.isClassInstance)(bClass)) {
                return 1;
            }
            // Sort literals before non-literals.
            if (isLiteralType(a)) {
                if (!isLiteralType(bClass)) {
                    return -1;
                }
            }
            else if (isLiteralType(bClass)) {
                return 1;
            }
            // Always sort NoneType at the end.
            if (types_1.ClassType.isBuiltIn(a, 'NoneType')) {
                return 1;
            }
            else if (types_1.ClassType.isBuiltIn(bClass, 'NoneType')) {
                return -1;
            }
            // Sort non-generics before generics.
            if (a.details.typeParameters.length > 0 || isTupleClass(a)) {
                if (bClass.details.typeParameters.length === 0) {
                    return 1;
                }
            }
            else if (bClass.details.typeParameters.length > 0 || isTupleClass(bClass)) {
                return -1;
            }
            // Sort by class name.
            const aName = a.details.name;
            const bName = b.details.name;
            if (aName < bName) {
                return -1;
            }
            else if (aName > bName) {
                return 1;
            }
            // Sort by type argument count.
            const aTypeArgCount = a.typeArguments ? a.typeArguments.length : 0;
            const bTypeArgCount = bClass.typeArguments ? bClass.typeArguments.length : 0;
            if (aTypeArgCount < bTypeArgCount) {
                return -1;
            }
            else if (aTypeArgCount > bTypeArgCount) {
                return 1;
            }
            // Sort by type argument.
            for (let i = 0; i < aTypeArgCount; i++) {
                const typeComparison = compareTypes(a.typeArguments[i], bClass.typeArguments[i], recursionCount);
                if (typeComparison !== 0) {
                    return typeComparison;
                }
            }
            return 0;
        }
        case 7 /* TypeCategory.Module */: {
            const aName = a.moduleName;
            const bName = b.moduleName;
            return aName < bName ? -1 : aName === bName ? 0 : 1;
        }
        case 9 /* TypeCategory.TypeVar */: {
            const aName = a.details.name;
            const bName = b.details.name;
            return aName < bName ? -1 : aName === bName ? 0 : 1;
        }
    }
    return 1;
}
function doForEachSubtype(type, callback, sortSubtypes = false) {
    if ((0, types_1.isUnion)(type)) {
        const subtypes = sortSubtypes ? sortTypes(type.subtypes) : type.subtypes;
        subtypes.forEach((subtype, index) => {
            callback(subtype, index, subtypes);
        });
    }
    else {
        callback(type, 0, [type]);
    }
}
exports.doForEachSubtype = doForEachSubtype;
function someSubtypes(type, callback) {
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.some((subtype) => {
            return callback(subtype);
        });
    }
    else {
        return callback(type);
    }
}
exports.someSubtypes = someSubtypes;
function allSubtypes(type, callback) {
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.every((subtype) => {
            callback(subtype);
        });
    }
    else {
        return callback(type);
    }
}
exports.allSubtypes = allSubtypes;
function doForEachSignature(type, callback) {
    if ((0, types_1.isFunction)(type)) {
        callback(type, 0);
    }
    else {
        types_1.OverloadedFunctionType.getOverloads(type).forEach((overload, index) => {
            callback(overload, index);
        });
    }
}
exports.doForEachSignature = doForEachSignature;
// Determines if all of the types in the array are the same.
function areTypesSame(types, options) {
    if (types.length < 2) {
        return true;
    }
    for (let i = 1; i < types.length; i++) {
        if (!(0, types_1.isTypeSame)(types[0], types[i], options)) {
            return false;
        }
    }
    return true;
}
exports.areTypesSame = areTypesSame;
// If either type is "Unknown" (versus Any), propagate the Unknown. Preserve
// the incomplete flag on the unknown if present. The caller should verify that
// one or the other type is Unknown or Any.
function preserveUnknown(type1, type2) {
    if ((0, types_1.isUnknown)(type1) && type1.isIncomplete) {
        return type1;
    }
    else if ((0, types_1.isUnknown)(type2) && type2.isIncomplete) {
        return type2;
    }
    else if ((0, types_1.isUnknown)(type1) || (0, types_1.isUnknown)(type2)) {
        return types_1.UnknownType.create();
    }
    else {
        return types_1.AnyType.create();
    }
}
exports.preserveUnknown = preserveUnknown;
// Determines whether the specified type is a type that can be
// combined with other types for a union.
function isUnionableType(subtypes) {
    let typeFlags = 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */;
    for (const subtype of subtypes) {
        typeFlags &= subtype.flags;
    }
    // All subtypes need to be instantiable. Some types (like Any
    // and None) are both instances and instantiable. It's OK to
    // include some of these, but at least one subtype needs to
    // be definitively instantiable (not an instance).
    return (typeFlags & 1 /* TypeFlags.Instantiable */) !== 0 && (typeFlags & 2 /* TypeFlags.Instance */) === 0;
}
exports.isUnionableType = isUnionableType;
function derivesFromAnyOrUnknown(type) {
    let anyOrUnknown = false;
    doForEachSubtype(type, (subtype) => {
        if ((0, types_1.isAnyOrUnknown)(type)) {
            anyOrUnknown = true;
        }
        else if ((0, types_1.isInstantiableClass)(subtype)) {
            if (types_1.ClassType.hasUnknownBaseClass(subtype)) {
                anyOrUnknown = true;
            }
        }
        else if ((0, types_1.isClassInstance)(subtype)) {
            if (types_1.ClassType.hasUnknownBaseClass(subtype)) {
                anyOrUnknown = true;
            }
        }
    });
    return anyOrUnknown;
}
exports.derivesFromAnyOrUnknown = derivesFromAnyOrUnknown;
function getFullNameOfType(type) {
    var _a;
    if ((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.fullName) {
        return type.typeAliasInfo.fullName;
    }
    switch (type.category) {
        case 2 /* TypeCategory.Any */:
        case 1 /* TypeCategory.Unknown */:
            return 'typing.Any';
        case 6 /* TypeCategory.Class */:
            return type.details.fullName;
        case 4 /* TypeCategory.Function */:
            return type.details.fullName;
        case 7 /* TypeCategory.Module */:
            return type.moduleName;
        case 5 /* TypeCategory.OverloadedFunction */:
            return type.overloads[0].details.fullName;
    }
    return undefined;
}
exports.getFullNameOfType = getFullNameOfType;
function addConditionToType(type, condition, skipSelfCondition = false) {
    if (!condition) {
        return type;
    }
    if (skipSelfCondition) {
        condition = condition.filter((c) => !c.typeVar.details.isSynthesizedSelf);
        if (condition.length === 0) {
            return type;
        }
    }
    switch (type.category) {
        case 0 /* TypeCategory.Unbound */:
        case 1 /* TypeCategory.Unknown */:
        case 2 /* TypeCategory.Any */:
        case 3 /* TypeCategory.Never */:
        case 7 /* TypeCategory.Module */:
        case 9 /* TypeCategory.TypeVar */:
            return type;
        case 4 /* TypeCategory.Function */:
            return types_1.TypeBase.cloneForCondition(type, types_1.TypeCondition.combine(type.condition, condition));
        case 5 /* TypeCategory.OverloadedFunction */:
            return types_1.OverloadedFunctionType.create(type.overloads.map((t) => addConditionToType(t, condition)));
        case 6 /* TypeCategory.Class */:
            return types_1.TypeBase.cloneForCondition(type, types_1.TypeCondition.combine(type.condition, condition));
        case 8 /* TypeCategory.Union */:
            return (0, types_1.combineTypes)(type.subtypes.map((t) => addConditionToType(t, condition)));
    }
}
exports.addConditionToType = addConditionToType;
function getTypeCondition(type) {
    switch (type.category) {
        case 0 /* TypeCategory.Unbound */:
        case 1 /* TypeCategory.Unknown */:
        case 2 /* TypeCategory.Any */:
        case 3 /* TypeCategory.Never */:
        case 7 /* TypeCategory.Module */:
        case 9 /* TypeCategory.TypeVar */:
        case 5 /* TypeCategory.OverloadedFunction */:
        case 8 /* TypeCategory.Union */:
            return undefined;
        case 6 /* TypeCategory.Class */:
        case 4 /* TypeCategory.Function */:
            return type.condition;
    }
}
exports.getTypeCondition = getTypeCondition;
// Indicates whether the specified type is a recursive type alias
// placeholder that has not yet been resolved.
function isTypeAliasPlaceholder(type) {
    return (0, types_1.isTypeVar)(type) && types_1.TypeVarType.isTypeAliasPlaceholder(type);
}
exports.isTypeAliasPlaceholder = isTypeAliasPlaceholder;
// Determines whether the type alias placeholder is used directly
// within the specified type. It's OK if it's used indirectly as
// a type argument.
function isTypeAliasRecursive(typeAliasPlaceholder, type) {
    if (type.category !== 8 /* TypeCategory.Union */) {
        if (type === typeAliasPlaceholder) {
            return true;
        }
        // Handle the specific case where the type alias directly refers to itself.
        // In this case, the type will be unbound because it could not be resolved.
        return ((0, types_1.isUnbound)(type) &&
            type.typeAliasInfo &&
            type.typeAliasInfo.name === typeAliasPlaceholder.details.recursiveTypeAliasName);
    }
    return ((0, types_1.findSubtype)(type, (subtype) => (0, types_1.isTypeVar)(subtype) && subtype.details === typeAliasPlaceholder.details) !==
        undefined);
}
exports.isTypeAliasRecursive = isTypeAliasRecursive;
function transformPossibleRecursiveTypeAlias(type) {
    var _a;
    if (type) {
        if ((0, types_1.isTypeVar)(type) && type.details.recursiveTypeAliasName && type.details.boundType) {
            const unspecializedType = types_1.TypeBase.isInstance(type)
                ? convertToInstance(type.details.boundType)
                : type.details.boundType;
            if (!((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) || !type.details.recursiveTypeParameters) {
                return unspecializedType;
            }
            const typeVarContext = buildTypeVarContext(type.details.recursiveTypeParameters, type.typeAliasInfo.typeArguments, getTypeVarScopeId(type));
            return applySolvedTypeVars(unspecializedType, typeVarContext);
        }
        if ((0, types_1.isUnion)(type) && type.includesRecursiveTypeAlias) {
            let newType = mapSubtypes(type, (subtype) => transformPossibleRecursiveTypeAlias(subtype));
            if (newType !== type && type.typeAliasInfo) {
                // Copy the type alias information if present.
                newType = types_1.TypeBase.cloneForTypeAlias(newType, type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, type.typeAliasInfo.typeArguments);
            }
            return newType;
        }
    }
    return type;
}
exports.transformPossibleRecursiveTypeAlias = transformPossibleRecursiveTypeAlias;
function getTypeVarScopeId(type) {
    if ((0, types_1.isClass)(type)) {
        return type.details.typeVarScopeId;
    }
    if ((0, types_1.isFunction)(type)) {
        return type.details.typeVarScopeId;
    }
    if ((0, types_1.isTypeVar)(type)) {
        return type.scopeId;
    }
    return undefined;
}
exports.getTypeVarScopeId = getTypeVarScopeId;
// This is similar to getTypeVarScopeId except that it includes
// the secondary scope IDs for functions.
function getTypeVarScopeIds(type) {
    const scopeIds = [];
    const scopeId = getTypeVarScopeId(type);
    if (scopeId) {
        scopeIds.push(scopeId);
    }
    if ((0, types_1.isFunction)(type)) {
        if (type.details.constructorTypeVarScopeId) {
            scopeIds.push(type.details.constructorTypeVarScopeId);
        }
        if (type.details.higherOrderTypeVarScopeIds) {
            scopeIds.push(...type.details.higherOrderTypeVarScopeIds);
        }
    }
    return scopeIds;
}
exports.getTypeVarScopeIds = getTypeVarScopeIds;
// If the class type is generic and does not already have type arguments
// specified, specialize it with default type arguments (Unknown or the
// default type if provided).
function specializeWithDefaultTypeArgs(type) {
    if (type.details.typeParameters.length === 0 || type.typeArguments) {
        return type;
    }
    return types_1.ClassType.cloneForSpecialization(type, type.details.typeParameters.map((param) => param.details.defaultType), 
    /* isTypeArgumentExplicit */ false, 
    /* includeSubclasses */ type.includeSubclasses);
}
exports.specializeWithDefaultTypeArgs = specializeWithDefaultTypeArgs;
// Specializes the class with "Unknown" type args (or the equivalent for ParamSpecs
// or TypeVarTuples).
function specializeWithUnknownTypeArgs(type) {
    if (type.details.typeParameters.length === 0) {
        return type;
    }
    return types_1.ClassType.cloneForSpecialization(type, type.details.typeParameters.map((param) => getUnknownTypeForTypeVar(param)), 
    /* isTypeArgumentExplicit */ false, 
    /* includeSubclasses */ type.includeSubclasses);
}
exports.specializeWithUnknownTypeArgs = specializeWithUnknownTypeArgs;
// Returns "Unknown" for simple TypeVars or the equivalent for a ParamSpec.
function getUnknownTypeForTypeVar(typeVar) {
    if (typeVar.details.isParamSpec) {
        return getUnknownTypeForParamSpec();
    }
    return types_1.UnknownType.create();
}
exports.getUnknownTypeForTypeVar = getUnknownTypeForTypeVar;
// Returns the "Unknown" equivalent for a ParamSpec.
function getUnknownTypeForParamSpec() {
    const newFunction = types_1.FunctionType.createInstance('', '', '', 65536 /* FunctionTypeFlags.ParamSpecValue */ | 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */);
    types_1.FunctionType.addDefaultParameters(newFunction);
    return newFunction;
}
exports.getUnknownTypeForParamSpec = getUnknownTypeForParamSpec;
// Returns the equivalent of "Callable[..., Unknown]".
function getUnknownTypeForCallable() {
    const newFunction = types_1.FunctionType.createSynthesizedInstance('', 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */);
    types_1.FunctionType.addDefaultParameters(newFunction);
    newFunction.details.declaredReturnType = types_1.UnknownType.create();
    return newFunction;
}
exports.getUnknownTypeForCallable = getUnknownTypeForCallable;
// If the class is generic and not already specialized, this function
// "self specializes" the class, filling in its own type parameters
// as type arguments.
function selfSpecializeClass(type) {
    if (type.details.typeParameters.length === 0 || type.typeArguments) {
        return type;
    }
    return types_1.ClassType.cloneForSpecialization(type, type.details.typeParameters, /* isTypeArgumentExplicit */ true);
}
exports.selfSpecializeClass = selfSpecializeClass;
// Determines whether the type derives from tuple. If so, it returns
// the specialized tuple type.
function getSpecializedTupleType(type) {
    let classType;
    if ((0, types_1.isInstantiableClass)(type)) {
        classType = type;
    }
    else if ((0, types_1.isClassInstance)(type)) {
        classType = types_1.ClassType.cloneAsInstantiable(type);
    }
    if (!classType) {
        return undefined;
    }
    // See if this class derives from Tuple or tuple. If it does, we'll assume that it
    // hasn't been overridden in a way that changes the behavior of the tuple class.
    const tupleClass = classType.details.mro.find((mroClass) => (0, types_1.isInstantiableClass)(mroClass) && isTupleClass(mroClass));
    if (!tupleClass || !(0, types_1.isInstantiableClass)(tupleClass)) {
        return undefined;
    }
    if (types_1.ClassType.isSameGenericClass(classType, tupleClass)) {
        return classType;
    }
    const typeVarContext = buildTypeVarContextFromSpecializedClass(classType);
    return applySolvedTypeVars(tupleClass, typeVarContext);
}
exports.getSpecializedTupleType = getSpecializedTupleType;
function isLiteralType(type) {
    return types_1.TypeBase.isInstance(type) && type.literalValue !== undefined;
}
exports.isLiteralType = isLiteralType;
function isLiteralTypeOrUnion(type, allowNone = false) {
    if ((0, types_1.isClassInstance)(type)) {
        if (allowNone && isNoneInstance(type)) {
            return true;
        }
        return type.literalValue !== undefined;
    }
    if ((0, types_1.isUnion)(type)) {
        return !(0, types_1.findSubtype)(type, (subtype) => {
            if (!(0, types_1.isClassInstance)(subtype)) {
                return true;
            }
            if (isNoneInstance(subtype)) {
                return !allowNone;
            }
            return subtype.literalValue === undefined;
        });
    }
    return false;
}
exports.isLiteralTypeOrUnion = isLiteralTypeOrUnion;
function containsLiteralType(type, includeTypeArgs = false) {
    class ContainsLiteralTypeWalker extends typeWalker_1.TypeWalker {
        constructor(_includeTypeArgs) {
            super();
            this._includeTypeArgs = _includeTypeArgs;
            this.foundLiteral = false;
        }
        visitClass(classType) {
            if ((0, types_1.isClassInstance)(classType)) {
                if (isLiteralType(classType) || types_1.ClassType.isBuiltIn(classType, 'LiteralString')) {
                    this.foundLiteral = true;
                    this.cancelWalk();
                }
            }
            if (this._includeTypeArgs) {
                super.visitClass(classType);
            }
        }
    }
    const walker = new ContainsLiteralTypeWalker(includeTypeArgs);
    walker.walk(type);
    return walker.foundLiteral;
}
exports.containsLiteralType = containsLiteralType;
// If all of the subtypes are literals with the same built-in class (e.g.
// all 'int' or all 'str'), this function returns the name of that type. If
// some of the subtypes are not literals or the literal classes don't match,
// it returns undefined.
function getLiteralTypeClassName(type) {
    if ((0, types_1.isClassInstance)(type)) {
        if (type.literalValue !== undefined && types_1.ClassType.isBuiltIn(type)) {
            return type.details.name;
        }
        return undefined;
    }
    if ((0, types_1.isUnion)(type)) {
        let className;
        let foundMismatch = false;
        doForEachSubtype(type, (subtype) => {
            const subtypeLiteralTypeName = getLiteralTypeClassName(subtype);
            if (!subtypeLiteralTypeName) {
                foundMismatch = true;
            }
            else if (!className) {
                className = subtypeLiteralTypeName;
            }
        });
        return foundMismatch ? undefined : className;
    }
    return undefined;
}
exports.getLiteralTypeClassName = getLiteralTypeClassName;
function getUnionSubtypeCount(type) {
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.length;
    }
    return 1;
}
exports.getUnionSubtypeCount = getUnionSubtypeCount;
function isEllipsisType(type) {
    return (0, types_1.isAny)(type) && type.isEllipsis;
}
exports.isEllipsisType = isEllipsisType;
function isProperty(type) {
    return (0, types_1.isClassInstance)(type) && types_1.ClassType.isPropertyClass(type);
}
exports.isProperty = isProperty;
function isCallableType(type) {
    if ((0, types_1.isFunction)(type) || (0, types_1.isOverloadedFunction)(type) || (0, types_1.isAnyOrUnknown)(type)) {
        return true;
    }
    if (isEffectivelyInstantiable(type)) {
        return true;
    }
    if ((0, types_1.isClass)(type)) {
        if (types_1.TypeBase.isInstantiable(type)) {
            return true;
        }
        const callMember = lookUpObjectMember(type, '__call__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
        return !!callMember;
    }
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.every((subtype) => isCallableType(subtype));
    }
    return false;
}
exports.isCallableType = isCallableType;
function isDescriptorInstance(type, requireSetter = false) {
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.every((subtype) => isMaybeDescriptorInstance(subtype, requireSetter));
    }
    return isMaybeDescriptorInstance(type, requireSetter);
}
exports.isDescriptorInstance = isDescriptorInstance;
function isMaybeDescriptorInstance(type, requireSetter = false) {
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.some((subtype) => isMaybeDescriptorInstance(subtype, requireSetter));
    }
    if (!(0, types_1.isClassInstance)(type)) {
        return false;
    }
    if (!types_1.ClassType.getSymbolTable(type).has('__get__')) {
        return false;
    }
    if (requireSetter && !types_1.ClassType.getSymbolTable(type).has('__set__')) {
        return false;
    }
    return true;
}
exports.isMaybeDescriptorInstance = isMaybeDescriptorInstance;
function isTupleClass(type) {
    return types_1.ClassType.isBuiltIn(type, 'tuple');
}
exports.isTupleClass = isTupleClass;
// Indicates whether the type is a tuple class of
// the form tuple[x, ...] where the number of elements
// in the tuple is unknown.
function isUnboundedTupleClass(type) {
    return (type.tupleTypeArguments &&
        type.tupleTypeArguments.some((t) => t.isUnbounded || (0, types_1.isUnpackedVariadicTypeVar)(t.type)));
}
exports.isUnboundedTupleClass = isUnboundedTupleClass;
// Indicates whether the specified index is within range and its type is unambiguous
// in that it doesn't involve any element ranges that are of indeterminate length.
function isTupleIndexUnambiguous(type, index) {
    if (!type.tupleTypeArguments) {
        return false;
    }
    if (index < 0) {
        if (isUnboundedTupleClass(type) || type.tupleTypeArguments.length + index < 0) {
            return false;
        }
    }
    let unambiguousIndexLimit = type.tupleTypeArguments.findIndex((t) => t.isUnbounded || (0, types_1.isUnpackedVariadicTypeVar)(t.type));
    if (unambiguousIndexLimit < 0) {
        unambiguousIndexLimit = type.tupleTypeArguments.length;
    }
    return index < unambiguousIndexLimit;
}
exports.isTupleIndexUnambiguous = isTupleIndexUnambiguous;
// Partially specializes a type within the context of a specified
// (presumably specialized) class. Optionally specializes the `Self`
// type variables, replacing them with selfClass.
function partiallySpecializeType(type, contextClassType, selfClass, typeClassType) {
    // If the context class is not specialized (or doesn't need specialization),
    // then there's no need to do any more work.
    if (types_1.ClassType.isUnspecialized(contextClassType) && !selfClass) {
        return type;
    }
    // Partially specialize the type using the specialized class type vars.
    const typeVarContext = buildTypeVarContextFromSpecializedClass(contextClassType);
    if (selfClass) {
        populateTypeVarContextForSelfType(typeVarContext, contextClassType, selfClass);
    }
    let result = applySolvedTypeVars(type, typeVarContext, { typeClassType });
    // If this is a property, we may need to partially specialize the
    // access methods associated with it.
    if ((0, types_1.isClass)(result)) {
        if (result.fgetInfo || result.fsetInfo || result.fdelInfo) {
            function updatePropertyMethodInfo(methodInfo) {
                if (!methodInfo) {
                    return undefined;
                }
                return {
                    methodType: partiallySpecializeType(methodInfo.methodType, contextClassType, selfClass, typeClassType),
                    classType: methodInfo.classType,
                };
            }
            result = types_1.TypeBase.cloneType(result);
            result.fgetInfo = updatePropertyMethodInfo(result.fgetInfo);
            result.fsetInfo = updatePropertyMethodInfo(result.fsetInfo);
            result.fdelInfo = updatePropertyMethodInfo(result.fdelInfo);
        }
    }
    return result;
}
exports.partiallySpecializeType = partiallySpecializeType;
function populateTypeVarContextForSelfType(typeVarContext, contextClassType, selfClass) {
    const synthesizedSelfTypeVar = synthesizeTypeVarForSelfCls(contextClassType, /* isClsParam */ false);
    const selfInstance = convertToInstance(selfClass);
    // We can't call stripLiteralValue here because that method requires the type evaluator.
    // Instead, we'll do a simplified version of it here.
    const selfWithoutLiteral = mapSubtypes(selfInstance, (subtype) => {
        if ((0, types_1.isClass)(subtype)) {
            if (subtype.literalValue !== undefined) {
                return types_1.ClassType.cloneWithLiteral(subtype, /* value */ undefined);
            }
        }
        return subtype;
    });
    if (!(0, types_1.isTypeSame)(synthesizedSelfTypeVar, selfWithoutLiteral)) {
        typeVarContext.setTypeVarType(synthesizedSelfTypeVar, selfInstance, selfWithoutLiteral);
    }
}
exports.populateTypeVarContextForSelfType = populateTypeVarContextForSelfType;
// Looks for duplicate function types within the type and ensures that
// if they are generic, they have unique type variables.
function ensureFunctionSignaturesAreUnique(type, signatureTracker, expressionOffset) {
    const transformer = new UniqueFunctionSignatureTransformer(signatureTracker, expressionOffset);
    return transformer.apply(type, 0);
}
exports.ensureFunctionSignaturesAreUnique = ensureFunctionSignaturesAreUnique;
// Specializes a (potentially generic) type by substituting
// type variables from a type var map.
function applySolvedTypeVars(type, typeVarContext, options = {}) {
    // Use a shortcut if the typeVarContext is empty and no transform is necessary.
    if (typeVarContext.isEmpty() &&
        !options.unknownIfNotFound &&
        !options.eliminateUnsolvedInUnions &&
        !options.applyInScopePlaceholders) {
        return type;
    }
    if (options.applyInScopePlaceholders) {
        applyInScopePlaceholders(typeVarContext);
    }
    const transformer = new ApplySolvedTypeVarsTransformer(typeVarContext, options);
    return transformer.apply(type, 0);
}
exports.applySolvedTypeVars = applySolvedTypeVars;
// Applies solved TypeVars from one context to this context.
function applySourceContextTypeVars(destContext, srcContext) {
    if (srcContext.isEmpty()) {
        return;
    }
    destContext.doForEachSignatureContext((destSignature) => {
        applySourceContextTypeVarsToSignature(destSignature, srcContext);
    });
}
exports.applySourceContextTypeVars = applySourceContextTypeVars;
function applySourceContextTypeVarsToSignature(destSignature, srcContext) {
    destSignature.getTypeVars().forEach((entry) => {
        const newNarrowTypeBound = entry.narrowBound ? applySolvedTypeVars(entry.narrowBound, srcContext) : undefined;
        const newNarrowTypeBoundNoLiterals = entry.narrowBoundNoLiterals
            ? applySolvedTypeVars(entry.narrowBoundNoLiterals, srcContext)
            : undefined;
        const newWideTypeBound = entry.wideBound ? applySolvedTypeVars(entry.wideBound, srcContext) : undefined;
        destSignature.setTypeVarType(entry.typeVar, newNarrowTypeBound, newNarrowTypeBoundNoLiterals, newWideTypeBound);
        if (entry.tupleTypes) {
            destSignature.setTupleTypeVar(entry.typeVar, entry.tupleTypes.map((arg) => {
                return {
                    type: applySolvedTypeVars(arg.type, srcContext),
                    isUnbounded: arg.isUnbounded,
                    isOptional: arg.isOptional,
                };
            }));
        }
    });
}
exports.applySourceContextTypeVarsToSignature = applySourceContextTypeVarsToSignature;
// If the TypeVarContext contains any type variables whose types depend on
// in-scope placeholders used for bidirectional type inference, replace those
// with the solved type associated with those in-scope placeholders.
function applyInScopePlaceholders(typeVarContext) {
    typeVarContext.doForEachSignatureContext((signature) => {
        signature.getTypeVars().forEach((entry) => {
            const typeVar = entry.typeVar;
            if (!typeVar.isInScopePlaceholder) {
                const newNarrowTypeBound = entry.narrowBound
                    ? applyInScopePlaceholdersToType(entry.narrowBound, signature)
                    : undefined;
                const newNarrowTypeBoundNoLiterals = entry.narrowBoundNoLiterals
                    ? applyInScopePlaceholdersToType(entry.narrowBoundNoLiterals, signature)
                    : undefined;
                const newWideTypeBound = entry.wideBound
                    ? applyInScopePlaceholdersToType(entry.wideBound, signature)
                    : undefined;
                signature.setTypeVarType(entry.typeVar, newNarrowTypeBound, newNarrowTypeBoundNoLiterals, newWideTypeBound);
                if (entry.tupleTypes) {
                    signature.setTupleTypeVar(entry.typeVar, entry.tupleTypes.map((arg) => {
                        return {
                            type: applyInScopePlaceholdersToType(arg.type, signature),
                            isUnbounded: arg.isUnbounded,
                            isOptional: arg.isOptional,
                        };
                    }));
                }
            }
        });
    });
}
exports.applyInScopePlaceholders = applyInScopePlaceholders;
// Validates that a default type associated with a TypeVar does not refer to
// other TypeVars or ParamSpecs that are out of scope.
function validateTypeVarDefault(typeVar, liveTypeParams, invalidTypeVars) {
    // If there is no default type or the default type is concrete, there's
    // no need to do any more work here.
    if (typeVar.details.isDefaultExplicit && requiresSpecialization(typeVar.details.defaultType)) {
        const validator = new TypeVarDefaultValidator(liveTypeParams, invalidTypeVars);
        validator.apply(typeVar.details.defaultType, 0);
    }
}
exports.validateTypeVarDefault = validateTypeVarDefault;
function replaceTypeVarsWithAny(type) {
    const transformer = new TypeVarAnyReplacer();
    return transformer.apply(type, 0);
}
exports.replaceTypeVarsWithAny = replaceTypeVarsWithAny;
// During bidirectional type inference for constructors, an "expected type"
// is used to prepopulate the type var map. This is problematic when the
// expected type uses TypeVars that are not part of the context of the
// class we are constructing. We'll replace these type variables with dummy
// type variables.
function transformExpectedType(expectedType, liveTypeVarScopes, usageOffset) {
    const transformer = new ExpectedTypeTransformer(liveTypeVarScopes, usageOffset);
    return transformer.apply(expectedType, 0);
}
exports.transformExpectedType = transformExpectedType;
// Given a protocol class (or abstract class), this function returns
// a set of all the symbols (indexed by symbol name) that are part of
// that protocol and its protocol parent classes. If a same-named symbol
// appears in a parent and a child, the child overrides the parent.
function getProtocolSymbols(classType) {
    const symbolMap = new Map();
    if ((classType.details.flags & 16384 /* ClassTypeFlags.ProtocolClass */) !== 0) {
        getProtocolSymbolsRecursive(classType, symbolMap, 16384 /* ClassTypeFlags.ProtocolClass */);
    }
    return symbolMap;
}
exports.getProtocolSymbols = getProtocolSymbols;
function getProtocolSymbolsRecursive(classType, symbolMap, classFlags = 16384 /* ClassTypeFlags.ProtocolClass */, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return;
    }
    classType.details.baseClasses.forEach((baseClass) => {
        if ((0, types_1.isClass)(baseClass) && (baseClass.details.flags & classFlags) !== 0) {
            getProtocolSymbolsRecursive(baseClass, symbolMap, classFlags, recursionCount + 1);
        }
    });
    types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
        if (!symbol.isIgnoredForProtocolMatch()) {
            symbolMap.set(name, {
                symbol,
                classType,
                isInstanceMember: symbol.isInstanceMember(),
                isClassMember: symbol.isClassMember(),
                isClassVar: (0, symbolUtils_1.isEffectivelyClassVar)(symbol, /* isDataclass */ false),
                isTypeDeclared: symbol.hasTypedDeclarations(),
                skippedUndeclaredType: false,
            });
        }
    });
}
exports.getProtocolSymbolsRecursive = getProtocolSymbolsRecursive;
// Determines the maximum depth of a tuple, list, set or dictionary.
// For example, if the type is tuple[tuple[tuple[int]]], its depth would be 3.
function getContainerDepth(type, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return 1;
    }
    recursionCount++;
    if (!(0, types_1.isClassInstance)(type)) {
        return 0;
    }
    let maxChildDepth = 0;
    if (type.tupleTypeArguments) {
        type.tupleTypeArguments.forEach((typeArgInfo) => {
            doForEachSubtype(typeArgInfo.type, (subtype) => {
                const childDepth = getContainerDepth(subtype, recursionCount);
                maxChildDepth = Math.max(childDepth, maxChildDepth);
            });
        });
    }
    else if (type.typeArguments) {
        type.typeArguments.forEach((typeArg) => {
            doForEachSubtype(typeArg, (subtype) => {
                const childDepth = getContainerDepth(subtype, recursionCount);
                maxChildDepth = Math.max(childDepth, maxChildDepth);
            });
        });
    }
    else {
        return 0;
    }
    return 1 + maxChildDepth;
}
exports.getContainerDepth = getContainerDepth;
function lookUpObjectMember(objectType, memberName, flags = 0 /* MemberAccessFlags.Default */, skipMroClass) {
    if ((0, types_1.isClassInstance)(objectType)) {
        return lookUpClassMember(objectType, memberName, flags, skipMroClass);
    }
    return undefined;
}
exports.lookUpObjectMember = lookUpObjectMember;
// Looks up a member in a class using the multiple-inheritance rules
// defined by Python.
function lookUpClassMember(classType, memberName, flags = 0 /* MemberAccessFlags.Default */, skipMroClass) {
    var _a, _b;
    // Look in the metaclass first.
    const metaclass = classType.details.effectiveMetaclass;
    // Skip the "type" class as an optimization because it is known to not
    // define any instance variables, and it's by far the most common metaclass.
    if (metaclass && (0, types_1.isClass)(metaclass) && !types_1.ClassType.isBuiltIn(metaclass, 'type')) {
        const metaMemberItr = getClassMemberIterator(metaclass, memberName, 32 /* MemberAccessFlags.SkipClassMembers */);
        const metaMember = (_a = metaMemberItr.next()) === null || _a === void 0 ? void 0 : _a.value;
        // If the metaclass defines the member and we didn't hit an Unknown
        // class in the metaclass MRO, use the metaclass member.
        if (metaMember && !(0, types_1.isAnyOrUnknown)(metaMember.classType)) {
            // Set the isClassMember to true because it's a class member from the
            // perspective of the classType.
            metaMember.isClassMember = true;
            return metaMember;
        }
    }
    const memberItr = getClassMemberIterator(classType, memberName, flags, skipMroClass);
    return (_b = memberItr.next()) === null || _b === void 0 ? void 0 : _b.value;
}
exports.lookUpClassMember = lookUpClassMember;
// Iterates members in a class matching memberName using the multiple-inheritance rules.
// For more details, see this note on method resolution
// order: https://www.python.org/download/releases/2.3/mro/.
// As it traverses the inheritance tree, it applies partial specialization
// to the the base class and member. For example, if ClassA inherits from
// ClassB[str] which inherits from Dict[_T1, int], a search for '__iter__'
// would return a class type of Dict[str, int] and a symbolType of
// (self) -> Iterator[str].
// If skipMroClass is defined, all MRO classes up to and including that class
// are skipped.
function* getClassMemberIterator(classType, memberName, flags = 0 /* MemberAccessFlags.Default */, skipMroClass) {
    const declaredTypesOnly = (flags & 64 /* MemberAccessFlags.DeclaredTypesOnly */) !== 0;
    let skippedUndeclaredType = false;
    if ((0, types_1.isClass)(classType)) {
        let classFlags = 0 /* ClassIteratorFlags.Default */;
        if (flags & 1 /* MemberAccessFlags.SkipOriginalClass */) {
            if ((0, types_1.isClass)(classType)) {
                skipMroClass = classType;
            }
        }
        if (flags & 2 /* MemberAccessFlags.SkipBaseClasses */) {
            classFlags = classFlags | 1 /* ClassIteratorFlags.SkipBaseClasses */;
        }
        if (flags & 4 /* MemberAccessFlags.SkipObjectBaseClass */) {
            classFlags = classFlags | 2 /* ClassIteratorFlags.SkipObjectBaseClass */;
        }
        if (flags & 8 /* MemberAccessFlags.SkipTypeBaseClass */) {
            classFlags = classFlags | 4 /* ClassIteratorFlags.SkipTypeBaseClass */;
        }
        const classItr = getClassIterator(classType, classFlags, skipMroClass);
        for (const [mroClass, specializedMroClass] of classItr) {
            if (!(0, types_1.isInstantiableClass)(mroClass)) {
                if (!declaredTypesOnly) {
                    // The class derives from an unknown type, so all bets are off
                    // when trying to find a member. Return an unknown symbol.
                    const cm = {
                        symbol: symbol_1.Symbol.createWithType(0 /* SymbolFlags.None */, mroClass),
                        isInstanceMember: false,
                        isClassMember: true,
                        isClassVar: false,
                        classType: (0, types_1.isAnyOrUnknown)(mroClass) ? mroClass : types_1.UnknownType.create(),
                        isTypeDeclared: false,
                        skippedUndeclaredType: false,
                    };
                    yield cm;
                }
                continue;
            }
            if (!(0, types_1.isInstantiableClass)(specializedMroClass)) {
                continue;
            }
            const memberFields = types_1.ClassType.getSymbolTable(specializedMroClass);
            // Look at instance members first if requested.
            if ((flags & 16 /* MemberAccessFlags.SkipInstanceMembers */) === 0) {
                const symbol = memberFields.get(memberName);
                if (symbol && symbol.isInstanceMember()) {
                    const hasDeclaredType = symbol.hasTypedDeclarations();
                    if (!declaredTypesOnly || hasDeclaredType) {
                        const cm = {
                            symbol,
                            isInstanceMember: true,
                            isClassMember: symbol.isClassMember(),
                            isClassVar: (0, symbolUtils_1.isEffectivelyClassVar)(symbol, types_1.ClassType.isDataClass(specializedMroClass)),
                            classType: specializedMroClass,
                            isTypeDeclared: hasDeclaredType,
                            skippedUndeclaredType,
                        };
                        yield cm;
                    }
                    else {
                        skippedUndeclaredType = true;
                    }
                }
            }
            // Next look at class members.
            if ((flags & 32 /* MemberAccessFlags.SkipClassMembers */) === 0) {
                const symbol = memberFields.get(memberName);
                if (symbol && symbol.isClassMember()) {
                    const hasDeclaredType = symbol.hasTypedDeclarations();
                    if (!declaredTypesOnly || hasDeclaredType) {
                        let isInstanceMember = symbol.isInstanceMember();
                        let isClassMember = true;
                        // For data classes and typed dicts, variables that are declared
                        // within the class are treated as instance variables. This distinction
                        // is important in cases where a variable is a callable type because
                        // we don't want to bind it to the instance like we would for a
                        // class member.
                        const isDataclass = types_1.ClassType.isDataClass(specializedMroClass);
                        const isTypedDict = types_1.ClassType.isTypedDictClass(specializedMroClass);
                        if (hasDeclaredType && (isDataclass || isTypedDict)) {
                            const decls = symbol.getDeclarations();
                            if (decls.length > 0 && decls[0].type === 1 /* DeclarationType.Variable */) {
                                isInstanceMember = true;
                                isClassMember = isDataclass;
                            }
                        }
                        const cm = {
                            symbol,
                            isInstanceMember,
                            isClassMember,
                            isClassVar: (0, symbolUtils_1.isEffectivelyClassVar)(symbol, isDataclass),
                            classType: specializedMroClass,
                            isTypeDeclared: hasDeclaredType,
                            skippedUndeclaredType,
                        };
                        yield cm;
                    }
                    else {
                        skippedUndeclaredType = true;
                    }
                }
            }
        }
    }
    else if ((0, types_1.isAnyOrUnknown)(classType)) {
        // The class derives from an unknown type, so all bets are off
        // when trying to find a member. Return an Any or Unknown symbol.
        const cm = {
            symbol: symbol_1.Symbol.createWithType(0 /* SymbolFlags.None */, classType),
            isInstanceMember: false,
            isClassMember: true,
            isClassVar: false,
            classType,
            isTypeDeclared: false,
            skippedUndeclaredType: false,
        };
        yield cm;
    }
    return undefined;
}
exports.getClassMemberIterator = getClassMemberIterator;
function* getClassIterator(classType, flags = 0 /* ClassIteratorFlags.Default */, skipMroClass) {
    if ((0, types_1.isClass)(classType)) {
        let foundSkipMroClass = skipMroClass === undefined;
        for (const mroClass of classType.details.mro) {
            // Are we still searching for the skipMroClass?
            if (!foundSkipMroClass && skipMroClass) {
                if (!(0, types_1.isClass)(mroClass)) {
                    foundSkipMroClass = true;
                }
                else if (types_1.ClassType.isSameGenericClass(mroClass, skipMroClass)) {
                    foundSkipMroClass = true;
                    continue;
                }
                else {
                    continue;
                }
            }
            // If mroClass is an ancestor of classType, partially specialize
            // it in the context of classType.
            const specializedMroClass = partiallySpecializeType(mroClass, classType);
            // Should we ignore members on the 'object' base class?
            if (flags & 2 /* ClassIteratorFlags.SkipObjectBaseClass */) {
                if ((0, types_1.isInstantiableClass)(specializedMroClass)) {
                    if (types_1.ClassType.isBuiltIn(specializedMroClass, 'object')) {
                        break;
                    }
                }
            }
            // Should we ignore members on the 'type' base class?
            if (flags & 4 /* ClassIteratorFlags.SkipTypeBaseClass */) {
                if ((0, types_1.isInstantiableClass)(specializedMroClass)) {
                    if (types_1.ClassType.isBuiltIn(specializedMroClass, 'type')) {
                        break;
                    }
                }
            }
            yield [mroClass, specializedMroClass];
            if ((flags & 1 /* ClassIteratorFlags.SkipBaseClasses */) !== 0) {
                break;
            }
        }
    }
    return undefined;
}
exports.getClassIterator = getClassIterator;
function getClassFieldsRecursive(classType) {
    const memberMap = new Map();
    // Evaluate the types of members from the end of the MRO to the beginning.
    types_1.ClassType.getReverseMro(classType).forEach((mroClass) => {
        const specializedMroClass = partiallySpecializeType(mroClass, classType);
        if ((0, types_1.isClass)(specializedMroClass)) {
            types_1.ClassType.getSymbolTable(specializedMroClass).forEach((symbol, name) => {
                if (!symbol.isIgnoredForProtocolMatch() && symbol.hasTypedDeclarations()) {
                    memberMap.set(name, {
                        classType: specializedMroClass,
                        symbol,
                        isInstanceMember: symbol.isInstanceMember(),
                        isClassMember: symbol.isClassMember(),
                        isClassVar: (0, symbolUtils_1.isEffectivelyClassVar)(symbol, types_1.ClassType.isDataClass(specializedMroClass)),
                        isTypeDeclared: true,
                        skippedUndeclaredType: false,
                    });
                }
            });
        }
        else {
            // If this ancestor class is unknown, throw away all symbols
            // found so far because they could be overridden by the unknown class.
            memberMap.clear();
        }
    });
    return memberMap;
}
exports.getClassFieldsRecursive = getClassFieldsRecursive;
// Combines two lists of type var types, maintaining the combined order
// but removing any duplicates.
function addTypeVarsToListIfUnique(list1, list2, typeVarScopeId) {
    for (const type2 of list2) {
        if (typeVarScopeId && type2.scopeId !== typeVarScopeId) {
            continue;
        }
        if (!list1.find((type1) => (0, types_1.isTypeSame)(convertToInstance(type1), convertToInstance(type2)))) {
            list1.push(type2);
        }
    }
}
exports.addTypeVarsToListIfUnique = addTypeVarsToListIfUnique;
// Walks the type recursively (in a depth-first manner), finds all
// type variables that are referenced, and returns an ordered list
// of unique type variables. For example, if the type is
// Union[List[Dict[_T1, _T2]], _T1, _T3], the result would be
// [_T1, _T2, _T3].
function getTypeVarArgumentsRecursive(type, recursionCount = 0) {
    var _a, _b;
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return [];
    }
    recursionCount++;
    if ((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) {
        const combinedList = [];
        (_b = type.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.typeArguments.forEach((typeArg) => {
            addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(typeArg, recursionCount));
        });
        return combinedList;
    }
    if ((0, types_1.isTypeVar)(type)) {
        // Don't return any recursive type alias placeholders.
        if (type.details.recursiveTypeAliasName) {
            return [];
        }
        // Don't return any P.args or P.kwargs types.
        if ((0, types_1.isParamSpec)(type) && type.paramSpecAccess) {
            return [];
        }
        return [types_1.TypeBase.isInstantiable(type) ? types_1.TypeVarType.cloneAsInstance(type) : type];
    }
    if ((0, types_1.isClass)(type)) {
        const combinedList = [];
        const typeArgs = type.tupleTypeArguments ? type.tupleTypeArguments.map((e) => e.type) : type.typeArguments;
        if (typeArgs) {
            typeArgs.forEach((typeArg) => {
                addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(typeArg, recursionCount));
            });
        }
        return combinedList;
    }
    if ((0, types_1.isUnion)(type)) {
        const combinedList = [];
        doForEachSubtype(type, (subtype) => {
            addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(subtype, recursionCount));
        });
        return combinedList;
    }
    if ((0, types_1.isFunction)(type)) {
        const combinedList = [];
        for (let i = 0; i < type.details.parameters.length; i++) {
            addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(types_1.FunctionType.getEffectiveParameterType(type, i), recursionCount));
        }
        if (type.details.paramSpec) {
            addTypeVarsToListIfUnique(combinedList, [type.details.paramSpec]);
        }
        const returnType = types_1.FunctionType.getSpecializedReturnType(type);
        if (returnType) {
            addTypeVarsToListIfUnique(combinedList, getTypeVarArgumentsRecursive(returnType, recursionCount));
        }
        return combinedList;
    }
    return [];
}
exports.getTypeVarArgumentsRecursive = getTypeVarArgumentsRecursive;
// Determines if the type variable appears within the type and only within
// a particular Callable within that type.
function isTypeVarLimitedToCallable(type, typeVar) {
    const info = getTypeVarWithinTypeInfoRecursive(type, typeVar);
    return info.isTypeVarUsed && info.isUsedInCallable;
}
exports.isTypeVarLimitedToCallable = isTypeVarLimitedToCallable;
function getTypeVarWithinTypeInfoRecursive(type, typeVar, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return { isTypeVarUsed: false, isUsedInCallable: false };
    }
    recursionCount++;
    let typeVarUsedCount = 0;
    let usedInCallableCount = 0;
    if ((0, types_1.isTypeVar)(type)) {
        // Ignore P.args or P.kwargs types.
        if (!(0, types_1.isParamSpec)(type) || !type.paramSpecAccess) {
            if ((0, types_1.isTypeSame)(typeVar, convertToInstance(type))) {
                typeVarUsedCount++;
            }
        }
    }
    else if ((0, types_1.isClass)(type)) {
        if (type.typeArguments) {
            type.typeArguments.forEach((typeArg) => {
                const subResult = getTypeVarWithinTypeInfoRecursive(typeArg, typeVar, recursionCount);
                if (subResult.isTypeVarUsed) {
                    typeVarUsedCount++;
                }
                if (subResult.isUsedInCallable) {
                    usedInCallableCount++;
                }
            });
        }
    }
    else if ((0, types_1.isUnion)(type)) {
        doForEachSubtype(type, (subtype) => {
            const subResult = getTypeVarWithinTypeInfoRecursive(subtype, typeVar, recursionCount);
            if (subResult.isTypeVarUsed) {
                typeVarUsedCount++;
            }
            if (subResult.isUsedInCallable) {
                usedInCallableCount++;
            }
        });
    }
    else if ((0, types_1.isFunction)(type)) {
        for (let i = 0; i < type.details.parameters.length; i++) {
            if (getTypeVarWithinTypeInfoRecursive(types_1.FunctionType.getEffectiveParameterType(type, i), typeVar, recursionCount).isTypeVarUsed) {
                typeVarUsedCount++;
            }
        }
        if (type.details.paramSpec) {
            if ((0, types_1.isTypeSame)(typeVar, convertToInstance(type.details.paramSpec))) {
                typeVarUsedCount++;
            }
        }
        const returnType = types_1.FunctionType.getSpecializedReturnType(type);
        if (returnType) {
            if (getTypeVarWithinTypeInfoRecursive(returnType, typeVar, recursionCount).isTypeVarUsed) {
                typeVarUsedCount++;
            }
        }
        if (typeVarUsedCount > 0) {
            typeVarUsedCount = 1;
            usedInCallableCount = 1;
        }
    }
    return {
        isTypeVarUsed: typeVarUsedCount > 0,
        isUsedInCallable: usedInCallableCount === 1 && typeVarUsedCount === 1,
    };
}
// Creates a specialized version of the class, filling in any unspecified
// type arguments with Unknown.
function specializeClassType(type) {
    const typeVarContext = new typeVarContext_1.TypeVarContext(getTypeVarScopeId(type));
    const typeParams = types_1.ClassType.getTypeParameters(type);
    typeParams.forEach((typeParam) => {
        typeVarContext.setTypeVarType(typeParam, applySolvedTypeVars(typeParam.details.defaultType, typeVarContext));
    });
    return applySolvedTypeVars(type, typeVarContext);
}
exports.specializeClassType = specializeClassType;
// Recursively finds all of the type arguments and sets them
// to the specified srcType.
function setTypeArgumentsRecursive(destType, srcType, typeVarContext, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return;
    }
    recursionCount++;
    if (typeVarContext.isLocked()) {
        return;
    }
    switch (destType.category) {
        case 8 /* TypeCategory.Union */:
            doForEachSubtype(destType, (subtype) => {
                setTypeArgumentsRecursive(subtype, srcType, typeVarContext, recursionCount);
            });
            break;
        case 6 /* TypeCategory.Class */:
            if (destType.typeArguments) {
                destType.typeArguments.forEach((typeArg) => {
                    setTypeArgumentsRecursive(typeArg, srcType, typeVarContext, recursionCount);
                });
            }
            if (destType.tupleTypeArguments) {
                destType.tupleTypeArguments.forEach((typeArg) => {
                    setTypeArgumentsRecursive(typeArg.type, srcType, typeVarContext, recursionCount);
                });
            }
            break;
        case 4 /* TypeCategory.Function */:
            if (destType.specializedTypes) {
                destType.specializedTypes.parameterTypes.forEach((paramType) => {
                    setTypeArgumentsRecursive(paramType, srcType, typeVarContext, recursionCount);
                });
                if (destType.specializedTypes.returnType) {
                    setTypeArgumentsRecursive(destType.specializedTypes.returnType, srcType, typeVarContext, recursionCount);
                }
            }
            else {
                destType.details.parameters.forEach((param) => {
                    setTypeArgumentsRecursive(param.type, srcType, typeVarContext, recursionCount);
                });
                if (destType.details.declaredReturnType) {
                    setTypeArgumentsRecursive(destType.details.declaredReturnType, srcType, typeVarContext, recursionCount);
                }
            }
            if (destType.details.paramSpec) {
                // Fill in an empty signature for a ParamSpec.
                if (!typeVarContext.getPrimarySignature().getTypeVar(destType.details.paramSpec)) {
                    typeVarContext.setTypeVarType(destType.details.paramSpec, getUnknownTypeForParamSpec());
                }
            }
            break;
        case 5 /* TypeCategory.OverloadedFunction */:
            destType.overloads.forEach((subtype) => {
                setTypeArgumentsRecursive(subtype, srcType, typeVarContext, recursionCount);
            });
            break;
        case 9 /* TypeCategory.TypeVar */:
            if (!typeVarContext.getPrimarySignature().getTypeVar(destType)) {
                typeVarContext.setTypeVarType(destType, srcType);
            }
            break;
    }
}
exports.setTypeArgumentsRecursive = setTypeArgumentsRecursive;
// Builds a mapping between type parameters and their specialized
// types. For example, if the generic type is Dict[_T1, _T2] and the
// specialized type is Dict[str, int], it returns a map that associates
// _T1 with str and _T2 with int.
function buildTypeVarContextFromSpecializedClass(classType) {
    const typeParameters = types_1.ClassType.getTypeParameters(classType);
    const typeVarContext = buildTypeVarContext(typeParameters, classType.typeArguments, getTypeVarScopeId(classType));
    if (types_1.ClassType.isTupleClass(classType) && classType.tupleTypeArguments && typeParameters.length >= 1) {
        typeVarContext.setTupleTypeVar(typeParameters[0], classType.tupleTypeArguments);
    }
    return typeVarContext;
}
exports.buildTypeVarContextFromSpecializedClass = buildTypeVarContextFromSpecializedClass;
function buildTypeVarContext(typeParameters, typeArgs, typeVarScopeId) {
    const typeVarContext = new typeVarContext_1.TypeVarContext(typeVarScopeId);
    typeParameters.forEach((typeParam, index) => {
        let typeArgType;
        if (typeArgs) {
            if (typeParam.details.isParamSpec) {
                if (index < typeArgs.length) {
                    typeArgType = typeArgs[index];
                    if ((0, types_1.isFunction)(typeArgType) && types_1.FunctionType.isParamSpecValue(typeArgType)) {
                        const parameters = [];
                        const typeArgFunctionType = typeArgType;
                        typeArgType.details.parameters.forEach((param, paramIndex) => {
                            parameters.push({
                                category: param.category,
                                name: param.name,
                                hasDefault: !!param.hasDefault,
                                defaultValueExpression: param.defaultValueExpression,
                                isNameSynthesized: param.isNameSynthesized,
                                type: types_1.FunctionType.getEffectiveParameterType(typeArgFunctionType, paramIndex),
                            });
                        });
                        typeVarContext.setTypeVarType(typeParam, convertTypeToParamSpecValue(typeArgType));
                    }
                    else if ((0, types_1.isParamSpec)(typeArgType) || (0, types_1.isAnyOrUnknown)(typeArgType)) {
                        typeVarContext.setTypeVarType(typeParam, convertTypeToParamSpecValue(typeArgType));
                    }
                }
            }
            else {
                if (index >= typeArgs.length) {
                    typeArgType = types_1.AnyType.create();
                }
                else {
                    typeArgType = typeArgs[index];
                }
                typeVarContext.setTypeVarType(typeParam, typeArgType, 
                /* narrowBoundNoLiterals */ undefined, typeArgType);
            }
        }
    });
    return typeVarContext;
}
exports.buildTypeVarContext = buildTypeVarContext;
// Determines the specialized base class type that srcType derives from.
function specializeForBaseClass(srcType, baseClass) {
    const typeParams = types_1.ClassType.getTypeParameters(baseClass);
    // If there are no type parameters for the specified base class,
    // no specialization is required.
    if (typeParams.length === 0) {
        return baseClass;
    }
    const typeVarContext = buildTypeVarContextFromSpecializedClass(srcType);
    const specializedType = applySolvedTypeVars(baseClass, typeVarContext);
    (0, debug_1.assert)((0, types_1.isInstantiableClass)(specializedType));
    return specializedType;
}
exports.specializeForBaseClass = specializeForBaseClass;
function derivesFromStdlibClass(classType, className) {
    return classType.details.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, className));
}
exports.derivesFromStdlibClass = derivesFromStdlibClass;
// If ignoreUnknown is true, an unknown base class is ignored when
// checking for derivation. If ignoreUnknown is false, a return value
// of true is assumed.
function derivesFromClassRecursive(classType, baseClassToFind, ignoreUnknown) {
    if (types_1.ClassType.isSameGenericClass(classType, baseClassToFind)) {
        return true;
    }
    for (const baseClass of classType.details.baseClasses) {
        if ((0, types_1.isInstantiableClass)(baseClass)) {
            if (derivesFromClassRecursive(baseClass, baseClassToFind, ignoreUnknown)) {
                return true;
            }
        }
        else if (!ignoreUnknown && (0, types_1.isAnyOrUnknown)(baseClass)) {
            // If the base class is unknown, we have to make a conservative assumption.
            return true;
        }
    }
    return false;
}
exports.derivesFromClassRecursive = derivesFromClassRecursive;
function synthesizeTypeVarForSelfCls(classType, isClsParam) {
    var _a;
    const selfType = types_1.TypeVarType.createInstance(`__type_of_self__`);
    const scopeId = (_a = getTypeVarScopeId(classType)) !== null && _a !== void 0 ? _a : '';
    selfType.details.isSynthesized = true;
    selfType.details.isSynthesizedSelf = true;
    selfType.nameWithScope = types_1.TypeVarType.makeNameWithScope(selfType.details.name, scopeId);
    selfType.scopeId = scopeId;
    const boundType = types_1.ClassType.cloneForSpecialization(classType, types_1.ClassType.getTypeParameters(classType), 
    /* isTypeArgumentExplicit */ false, 
    /* includeSubclasses */ !!classType.includeSubclasses);
    selfType.details.boundType = types_1.ClassType.cloneAsInstance(boundType);
    return isClsParam ? types_1.TypeVarType.cloneAsInstantiable(selfType) : selfType;
}
exports.synthesizeTypeVarForSelfCls = synthesizeTypeVarForSelfCls;
// Returns the declared "return" type (the type returned from a return statement)
// if it was declared, or undefined otherwise.
function getDeclaredGeneratorReturnType(functionType) {
    const returnType = types_1.FunctionType.getSpecializedReturnType(functionType);
    if (returnType) {
        const generatorTypeArgs = getGeneratorTypeArgs(returnType);
        if (generatorTypeArgs) {
            // The send type is the third type arg.
            return generatorTypeArgs.length >= 3 ? generatorTypeArgs[2] : types_1.UnknownType.create();
        }
    }
    return undefined;
}
exports.getDeclaredGeneratorReturnType = getDeclaredGeneratorReturnType;
// If the declared return type is a Generator, Iterable, Iterator or the async
// counterparts, returns the yield type. If the type is invalid for a generator,
// returns undefined.
function getGeneratorYieldType(declaredReturnType, isAsync) {
    let isLegalGeneratorType = true;
    const yieldType = mapSubtypes(declaredReturnType, (subtype) => {
        if ((0, types_1.isAnyOrUnknown)(subtype)) {
            return subtype;
        }
        if ((0, types_1.isClassInstance)(subtype)) {
            const expectedClasses = [
                ['AsyncIterable', 'Iterable'],
                ['AsyncIterator', 'Iterator'],
                ['AsyncGenerator', 'Generator'],
                ['', 'AwaitableGenerator'],
            ];
            if (expectedClasses.some((classes) => types_1.ClassType.isBuiltIn(subtype, isAsync ? classes[0] : classes[1]))) {
                return subtype.typeArguments && subtype.typeArguments.length >= 1
                    ? subtype.typeArguments[0]
                    : types_1.UnknownType.create();
            }
        }
        isLegalGeneratorType = false;
        return undefined;
    });
    return isLegalGeneratorType ? yieldType : undefined;
}
exports.getGeneratorYieldType = getGeneratorYieldType;
function isInstantiableMetaclass(type) {
    return ((0, types_1.isInstantiableClass)(type) &&
        type.details.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, 'type')));
}
exports.isInstantiableMetaclass = isInstantiableMetaclass;
function isMetaclassInstance(type) {
    return ((0, types_1.isClassInstance)(type) &&
        type.details.mro.some((mroClass) => (0, types_1.isClass)(mroClass) && types_1.ClassType.isBuiltIn(mroClass, 'type')));
}
exports.isMetaclassInstance = isMetaclassInstance;
function isEffectivelyInstantiable(type) {
    if (types_1.TypeBase.isInstantiable(type)) {
        return true;
    }
    // Handle the special case of 'type' (or subclasses thereof),
    // which are instantiable.
    if (isMetaclassInstance(type)) {
        return true;
    }
    if ((0, types_1.isUnion)(type)) {
        return type.subtypes.every((subtype) => isEffectivelyInstantiable(subtype));
    }
    return false;
}
exports.isEffectivelyInstantiable = isEffectivelyInstantiable;
function convertToInstance(type, includeSubclasses = true) {
    var _a;
    // See if we've already performed this conversion and cached it.
    if (((_a = type.cached) === null || _a === void 0 ? void 0 : _a.instanceType) && includeSubclasses) {
        return type.cached.instanceType;
    }
    let result = mapSubtypes(type, (subtype) => {
        switch (subtype.category) {
            case 6 /* TypeCategory.Class */: {
                // Handle type[x] as a special case.
                if (types_1.ClassType.isBuiltIn(subtype, 'type')) {
                    if (types_1.TypeBase.isInstance(subtype)) {
                        if (!subtype.typeArguments || subtype.typeArguments.length < 1) {
                            return types_1.UnknownType.create();
                        }
                        else {
                            return subtype.typeArguments[0];
                        }
                    }
                    else {
                        if (subtype.typeArguments && subtype.typeArguments.length > 0) {
                            if (!(0, types_1.isAnyOrUnknown)(subtype.typeArguments[0])) {
                                return convertToInstantiable(subtype.typeArguments[0]);
                            }
                        }
                    }
                }
                return types_1.ClassType.cloneAsInstance(subtype, includeSubclasses);
            }
            case 4 /* TypeCategory.Function */: {
                if (types_1.TypeBase.isInstantiable(subtype)) {
                    return types_1.FunctionType.cloneAsInstance(subtype);
                }
                break;
            }
            case 9 /* TypeCategory.TypeVar */: {
                if (types_1.TypeBase.isInstantiable(subtype)) {
                    return types_1.TypeVarType.cloneAsInstance(subtype);
                }
                break;
            }
            case 2 /* TypeCategory.Any */: {
                return types_1.AnyType.convertToInstance(subtype);
            }
            case 1 /* TypeCategory.Unknown */: {
                return types_1.UnknownType.convertToInstance(subtype);
            }
            case 3 /* TypeCategory.Never */: {
                return types_1.NeverType.convertToInstance(subtype);
            }
            case 0 /* TypeCategory.Unbound */: {
                return types_1.UnboundType.convertToInstance(subtype);
            }
        }
        return subtype;
    });
    // Copy over any type alias information.
    if (type.typeAliasInfo && type !== result) {
        result = types_1.TypeBase.cloneForTypeAlias(result, type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, type.typeAliasInfo.typeArguments);
    }
    if (type !== result && includeSubclasses) {
        // Cache the converted value for next time.
        if (!type.cached) {
            type.cached = {};
        }
        type.cached.instanceType = result;
    }
    return result;
}
exports.convertToInstance = convertToInstance;
function convertToInstantiable(type, includeSubclasses = true) {
    var _a;
    // See if we've already performed this conversion and cached it.
    if ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.instantiableType) {
        return type.cached.instantiableType;
    }
    let result = mapSubtypes(type, (subtype) => {
        switch (subtype.category) {
            case 6 /* TypeCategory.Class */: {
                return types_1.ClassType.cloneAsInstantiable(subtype, includeSubclasses);
            }
            case 4 /* TypeCategory.Function */: {
                return types_1.FunctionType.cloneAsInstantiable(subtype);
            }
            case 9 /* TypeCategory.TypeVar */: {
                return types_1.TypeVarType.cloneAsInstantiable(subtype);
            }
        }
        return subtype;
    });
    // Copy over any type alias information.
    if (type.typeAliasInfo && type !== result) {
        result = types_1.TypeBase.cloneForTypeAlias(result, type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, type.typeAliasInfo.typeArguments);
    }
    if (type !== result) {
        // Cache the converted value for next time.
        if (!type.cached) {
            type.cached = {};
        }
        type.cached.instantiableType = result;
    }
    return result;
}
exports.convertToInstantiable = convertToInstantiable;
function getMembersForClass(classType, symbolTable, includeInstanceVars) {
    classType.details.mro.forEach((mroClass) => {
        if ((0, types_1.isInstantiableClass)(mroClass)) {
            // Add any new member variables from this class.
            const isClassTypedDict = types_1.ClassType.isTypedDictClass(mroClass);
            types_1.ClassType.getSymbolTable(mroClass).forEach((symbol, name) => {
                if (symbol.isClassMember() || (includeInstanceVars && symbol.isInstanceMember())) {
                    if (!isClassTypedDict || !(0, symbolUtils_1.isTypedDictMemberAccessedThroughIndex)(symbol)) {
                        if (!symbol.isInitVar()) {
                            const existingSymbol = symbolTable.get(name);
                            if (!existingSymbol) {
                                symbolTable.set(name, symbol);
                            }
                            else if (!existingSymbol.hasTypedDeclarations() && symbol.hasTypedDeclarations()) {
                                // If the existing symbol is unannotated but a parent class
                                // has an annotation for the symbol, use the parent type instead.
                                symbolTable.set(name, symbol);
                            }
                        }
                    }
                }
            });
        }
    });
    // Add members of the metaclass as well.
    if (!includeInstanceVars) {
        const metaclass = classType.details.effectiveMetaclass;
        if (metaclass && (0, types_1.isInstantiableClass)(metaclass)) {
            for (const mroClass of metaclass.details.mro) {
                if ((0, types_1.isInstantiableClass)(mroClass)) {
                    types_1.ClassType.getSymbolTable(mroClass).forEach((symbol, name) => {
                        const existingSymbol = symbolTable.get(name);
                        if (!existingSymbol) {
                            symbolTable.set(name, symbol);
                        }
                        else if (!existingSymbol.hasTypedDeclarations() && symbol.hasTypedDeclarations()) {
                            // If the existing symbol is unannotated but a parent class
                            // has an annotation for the symbol, use the parent type instead.
                            symbolTable.set(name, symbol);
                        }
                    });
                }
                else {
                    break;
                }
            }
        }
    }
}
exports.getMembersForClass = getMembersForClass;
function getMembersForModule(moduleType, symbolTable) {
    // Start with the loader fields. If there are any symbols of the
    // same name defined within the module, they will overwrite the
    // loader fields.
    if (moduleType.loaderFields) {
        moduleType.loaderFields.forEach((symbol, name) => {
            symbolTable.set(name, symbol);
        });
    }
    moduleType.fields.forEach((symbol, name) => {
        symbolTable.set(name, symbol);
    });
}
exports.getMembersForModule = getMembersForModule;
// Determines if the type contains an Any recursively.
function containsAnyRecursive(type) {
    class AnyWalker extends typeWalker_1.TypeWalker {
        constructor() {
            super(...arguments);
            this.foundAny = false;
        }
        visitAny(type) {
            this.foundAny = true;
            this.cancelWalk();
        }
    }
    const walker = new AnyWalker();
    walker.walk(type);
    return walker.foundAny;
}
exports.containsAnyRecursive = containsAnyRecursive;
// Determines if the type contains an Any or Unknown type. If so,
// it returns the Any or Unknown type. Unknowns are preferred over
// Any if both are present. If recurse is true, it will recurse
// through type arguments and parameters.
function containsAnyOrUnknown(type, recurse) {
    class AnyOrUnknownWalker extends typeWalker_1.TypeWalker {
        constructor(_recurse) {
            super();
            this._recurse = _recurse;
        }
        visitUnknown(type) {
            this.anyOrUnknownType = this.anyOrUnknownType ? preserveUnknown(this.anyOrUnknownType, type) : type;
        }
        visitAny(type) {
            this.anyOrUnknownType = this.anyOrUnknownType ? preserveUnknown(this.anyOrUnknownType, type) : type;
        }
        visitClass(type) {
            if (this._recurse) {
                super.visitClass(type);
            }
        }
        visitFunction(type) {
            if (this._recurse) {
                // A function with a "..." type is effectively an "Any".
                if (types_1.FunctionType.shouldSkipArgsKwargsCompatibilityCheck(type)) {
                    this.anyOrUnknownType = this.anyOrUnknownType
                        ? preserveUnknown(this.anyOrUnknownType, types_1.AnyType.create())
                        : types_1.AnyType.create();
                }
                super.visitFunction(type);
            }
        }
    }
    const walker = new AnyOrUnknownWalker(recurse);
    walker.walk(type);
    return walker.anyOrUnknownType;
}
exports.containsAnyOrUnknown = containsAnyOrUnknown;
// Determines if any part of the type contains "Unknown", including any type arguments.
// This function does not use the TypeWalker because it is called very frequently,
// and allocating a memory walker object for every call significantly increases
// peak memory usage.
function isPartlyUnknown(type, recursionCount = 0) {
    var _a, _b;
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return false;
    }
    recursionCount++;
    if ((0, types_1.isUnknown)(type)) {
        return true;
    }
    // If this is a generic type alias, see if any of its type arguments
    // are either unspecified or are partially known.
    if ((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) {
        if (type.typeAliasInfo.typeArguments.some((typeArg) => isPartlyUnknown(typeArg, recursionCount))) {
            return true;
        }
    }
    // See if a union contains an unknown type.
    if ((0, types_1.isUnion)(type)) {
        return (0, types_1.findSubtype)(type, (subtype) => isPartlyUnknown(subtype, recursionCount)) !== undefined;
    }
    // See if an object or class has an unknown type argument.
    if ((0, types_1.isClass)(type)) {
        // If this is a reference to the class itself, as opposed to a reference
        // to a type that represents the class and its subclasses, don't flag
        // the type as partially unknown.
        if (!type.includeSubclasses) {
            return false;
        }
        if (!types_1.ClassType.isPseudoGenericClass(type)) {
            const typeArgs = ((_b = type.tupleTypeArguments) === null || _b === void 0 ? void 0 : _b.map((t) => t.type)) || type.typeArguments;
            if (typeArgs) {
                for (const argType of typeArgs) {
                    if (isPartlyUnknown(argType, recursionCount)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    // See if a function has an unknown type.
    if ((0, types_1.isOverloadedFunction)(type)) {
        return types_1.OverloadedFunctionType.getOverloads(type).some((overload) => {
            return isPartlyUnknown(overload, recursionCount);
        });
    }
    if ((0, types_1.isFunction)(type)) {
        for (let i = 0; i < type.details.parameters.length; i++) {
            // Ignore parameters such as "*" that have no name.
            if (type.details.parameters[i].name) {
                const paramType = types_1.FunctionType.getEffectiveParameterType(type, i);
                if (isPartlyUnknown(paramType, recursionCount)) {
                    return true;
                }
            }
        }
        if (type.details.declaredReturnType &&
            !types_1.FunctionType.isParamSpecValue(type) &&
            isPartlyUnknown(type.details.declaredReturnType, recursionCount)) {
            return true;
        }
        return false;
    }
    return false;
}
exports.isPartlyUnknown = isPartlyUnknown;
// If the specified type is a generic class with a single type argument
// that is a union, it "explodes" the class into a union of classes with
// each element of the union - e.g. Foo[A | B] becomes Foo[A] | Foo[B].
function explodeGenericClass(classType) {
    if (!classType.typeArguments || classType.typeArguments.length !== 1 || !(0, types_1.isUnion)(classType.typeArguments[0])) {
        return classType;
    }
    return (0, types_1.combineTypes)(classType.typeArguments[0].subtypes.map((subtype) => {
        return types_1.ClassType.cloneForSpecialization(classType, [subtype], /* isTypeArgumentExplicit */ true);
    }));
}
exports.explodeGenericClass = explodeGenericClass;
// If the type is a union of same-sized tuples, these are combined into
// a single tuple with that size. Otherwise, returns undefined.
function combineSameSizedTuples(type, tupleType) {
    if (!tupleType || !(0, types_1.isInstantiableClass)(tupleType) || isUnboundedTupleClass(tupleType)) {
        return type;
    }
    let tupleEntries;
    let isValid = true;
    doForEachSubtype(type, (subtype) => {
        if ((0, types_1.isClassInstance)(subtype)) {
            let tupleClass;
            if ((0, types_1.isClass)(subtype) && isTupleClass(subtype) && !isUnboundedTupleClass(subtype)) {
                tupleClass = subtype;
            }
            if (!tupleClass) {
                // Look in the mro list to see if this subtype derives from a
                // tuple with a known size. This includes named tuples.
                tupleClass = subtype.details.mro.find((mroClass) => (0, types_1.isClass)(mroClass) && isTupleClass(mroClass) && !isUnboundedTupleClass(mroClass));
            }
            if (tupleClass && (0, types_1.isClass)(tupleClass) && tupleClass.tupleTypeArguments) {
                if (tupleEntries) {
                    if (tupleEntries.length === tupleClass.tupleTypeArguments.length) {
                        tupleClass.tupleTypeArguments.forEach((entry, index) => {
                            tupleEntries[index].push(entry.type);
                        });
                    }
                    else {
                        isValid = false;
                    }
                }
                else {
                    tupleEntries = tupleClass.tupleTypeArguments.map((entry) => [entry.type]);
                }
            }
            else {
                isValid = false;
            }
        }
        else {
            isValid = false;
        }
    });
    if (!isValid || !tupleEntries) {
        return type;
    }
    return convertToInstance(specializeTupleClass(tupleType, tupleEntries.map((entry) => {
        return { type: (0, types_1.combineTypes)(entry), isUnbounded: false };
    })));
}
exports.combineSameSizedTuples = combineSameSizedTuples;
// Tuples require special handling for specialization. This method computes
// the "effective" type argument, which is a union of the variadic type
// arguments.
function specializeTupleClass(classType, typeArgs, isTypeArgumentExplicit = true, isUnpackedTuple = false) {
    const combinedTupleType = (0, types_1.combineTypes)(typeArgs.map((t) => {
        if ((0, types_1.isTypeVar)(t.type) && (0, types_1.isUnpackedVariadicTypeVar)(t.type)) {
            // Treat the unpacked TypeVarTuple as a union.
            return types_1.TypeVarType.cloneForUnpacked(t.type, /* isInUnion */ true);
        }
        return t.type;
    }));
    const clonedClassType = types_1.ClassType.cloneForSpecialization(classType, [combinedTupleType], isTypeArgumentExplicit, 
    /* includeSubclasses */ undefined, typeArgs);
    if (isUnpackedTuple) {
        clonedClassType.isUnpacked = true;
    }
    return clonedClassType;
}
exports.specializeTupleClass = specializeTupleClass;
// If the type is a function or overloaded function that has a paramSpec
// associated with it and P.args and P.kwargs at the end of the signature,
// it removes these parameters from the function.
function removeParamSpecVariadicsFromSignature(type) {
    if ((0, types_1.isFunction)(type)) {
        return removeParamSpecVariadicsFromFunction(type);
    }
    const newOverloads = [];
    let newTypeNeeded = false;
    for (const overload of type.overloads) {
        const newOverload = removeParamSpecVariadicsFromFunction(overload);
        newOverloads.push(newOverload);
        if (newOverload !== overload) {
            newTypeNeeded = true;
        }
    }
    return newTypeNeeded ? types_1.OverloadedFunctionType.create(newOverloads) : type;
}
exports.removeParamSpecVariadicsFromSignature = removeParamSpecVariadicsFromSignature;
function removeParamSpecVariadicsFromFunction(type) {
    const paramCount = type.details.parameters.length;
    if (paramCount < 2) {
        return type;
    }
    const argsParam = type.details.parameters[paramCount - 2];
    const kwargsParam = type.details.parameters[paramCount - 1];
    if (argsParam.category !== 1 /* ParameterCategory.ArgsList */ ||
        kwargsParam.category !== 2 /* ParameterCategory.KwargsDict */ ||
        !(0, types_1.isParamSpec)(argsParam.type) ||
        !(0, types_1.isParamSpec)(kwargsParam.type) ||
        !(0, types_1.isTypeSame)(argsParam.type, kwargsParam.type)) {
        return type;
    }
    return types_1.FunctionType.cloneRemoveParamSpecVariadics(type, types_1.TypeVarType.cloneForParamSpecAccess(argsParam.type, /* access */ undefined));
}
exports.removeParamSpecVariadicsFromFunction = removeParamSpecVariadicsFromFunction;
function _expandVariadicUnpackedUnion(type) {
    if ((0, types_1.isClassInstance)(type) && isTupleClass(type) && type.tupleTypeArguments && type.isUnpacked) {
        return (0, types_1.combineTypes)(type.tupleTypeArguments.map((t) => t.type));
    }
    return type;
}
// If the declared return type for the function is a Generator or AsyncGenerator,
// returns the type arguments for the type.
function getGeneratorTypeArgs(returnType) {
    var _a;
    if ((0, types_1.isClassInstance)(returnType)) {
        if (types_1.ClassType.isBuiltIn(returnType, ['Generator', 'AsyncGenerator'])) {
            return returnType.typeArguments;
        }
        else if (types_1.ClassType.isBuiltIn(returnType, 'AwaitableGenerator')) {
            // AwaitableGenerator has four type arguments, and the first 3
            // correspond to the generator.
            return (_a = returnType.typeArguments) === null || _a === void 0 ? void 0 : _a.slice(0, 3);
        }
    }
    return undefined;
}
exports.getGeneratorTypeArgs = getGeneratorTypeArgs;
function requiresTypeArguments(classType) {
    if (classType.details.typeParameters.length > 0) {
        const firstTypeParam = classType.details.typeParameters[0];
        // If there are type parameters, type arguments are needed.
        // The exception is if type parameters have been synthesized
        // for classes that have untyped constructors.
        if (firstTypeParam.details.isSynthesized) {
            return false;
        }
        // If the first type parameter has a default type, then no
        // type arguments are needed.
        if (firstTypeParam.details.isDefaultExplicit) {
            return false;
        }
        return true;
    }
    // There are a few built-in special classes that require
    // type arguments even though typeParameters is empty.
    if (types_1.ClassType.isSpecialBuiltIn(classType)) {
        const specialClasses = [
            'Tuple',
            'Callable',
            'Generic',
            'Type',
            'Optional',
            'Union',
            'Literal',
            'Annotated',
            'TypeGuard',
            'TypeIs',
        ];
        if (specialClasses.some((t) => t === (classType.aliasName || classType.details.name))) {
            return true;
        }
    }
    return false;
}
exports.requiresTypeArguments = requiresTypeArguments;
function requiresSpecialization(type, options, recursionCount = 0) {
    var _a;
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return false;
    }
    recursionCount++;
    // Is the answer cached?
    const canUseCache = !(options === null || options === void 0 ? void 0 : options.ignorePseudoGeneric) && !(options === null || options === void 0 ? void 0 : options.ignoreSelf);
    if (canUseCache && ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.requiresSpecialization) !== undefined) {
        return type.cached.requiresSpecialization;
    }
    const result = _requiresSpecialization(type, options, recursionCount);
    if (canUseCache) {
        if (type.cached === undefined) {
            type.cached = {};
        }
        type.cached.requiresSpecialization = result;
    }
    return result;
}
exports.requiresSpecialization = requiresSpecialization;
function _requiresSpecialization(type, options, recursionCount = 0) {
    var _a;
    // If the type is conditioned on a TypeVar, it may need to be specialized.
    if (type.condition) {
        return true;
    }
    switch (type.category) {
        case 6 /* TypeCategory.Class */: {
            if (types_1.ClassType.isPseudoGenericClass(type) && (options === null || options === void 0 ? void 0 : options.ignorePseudoGeneric)) {
                return false;
            }
            if (!type.isTypeArgumentExplicit && (options === null || options === void 0 ? void 0 : options.ignoreImplicitTypeArgs)) {
                return false;
            }
            if (type.typeArguments) {
                return type.typeArguments.some((typeArg) => requiresSpecialization(typeArg, options, recursionCount));
            }
            return types_1.ClassType.getTypeParameters(type).length > 0;
        }
        case 4 /* TypeCategory.Function */: {
            if (type.details.paramSpec) {
                return true;
            }
            for (let i = 0; i < type.details.parameters.length; i++) {
                if (requiresSpecialization(types_1.FunctionType.getEffectiveParameterType(type, i), options, recursionCount)) {
                    return true;
                }
            }
            const declaredReturnType = type.specializedTypes && type.specializedTypes.returnType
                ? type.specializedTypes.returnType
                : type.details.declaredReturnType;
            if (declaredReturnType) {
                if (requiresSpecialization(declaredReturnType, options, recursionCount)) {
                    return true;
                }
            }
            else if (type.inferredReturnType) {
                if (requiresSpecialization(type.inferredReturnType, options, recursionCount)) {
                    return true;
                }
            }
            return false;
        }
        case 5 /* TypeCategory.OverloadedFunction */: {
            return type.overloads.some((overload) => requiresSpecialization(overload, options, recursionCount));
        }
        case 8 /* TypeCategory.Union */: {
            return type.subtypes.some((subtype) => requiresSpecialization(subtype, options, recursionCount));
        }
        case 9 /* TypeCategory.TypeVar */: {
            // Most TypeVar types need to be specialized.
            if (!type.details.recursiveTypeAliasName) {
                if (type.details.isSynthesizedSelf && (options === null || options === void 0 ? void 0 : options.ignoreSelf)) {
                    return false;
                }
                return true;
            }
            // If this is a recursive type alias, it may need to be specialized
            // if it has generic type arguments.
            if ((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) {
                return type.typeAliasInfo.typeArguments.some((typeArg) => requiresSpecialization(typeArg, options, recursionCount));
            }
        }
    }
    return false;
}
// Combines two variances to produce a resulting variance.
function combineVariances(variance1, variance2) {
    if (variance1 === 1 /* Variance.Unknown */) {
        return variance2;
    }
    if (variance2 === 2 /* Variance.Invariant */ ||
        (variance2 === 3 /* Variance.Covariant */ && variance1 === 4 /* Variance.Contravariant */) ||
        (variance2 === 4 /* Variance.Contravariant */ && variance1 === 3 /* Variance.Covariant */)) {
        return 2 /* Variance.Invariant */;
    }
    return variance1;
}
exports.combineVariances = combineVariances;
// Determines if the variance of the type argument for a generic class is compatible
// With the declared variance of the corresponding type parameter.
function isVarianceOfTypeArgumentCompatible(type, typeParamVariance) {
    if (typeParamVariance === 1 /* Variance.Unknown */ || typeParamVariance === 0 /* Variance.Auto */) {
        return true;
    }
    if ((0, types_1.isTypeVar)(type) && !type.details.isParamSpec && !type.details.isVariadic) {
        const typeArgVariance = type.details.declaredVariance;
        if (typeArgVariance === 4 /* Variance.Contravariant */ || typeArgVariance === 3 /* Variance.Covariant */) {
            return typeArgVariance === typeParamVariance;
        }
    }
    else if ((0, types_1.isClassInstance)(type)) {
        if (type.details.typeParameters && type.details.typeParameters.length > 0) {
            return type.details.typeParameters.every((typeParam, index) => {
                let typeArgType;
                if (typeParam.details.isParamSpec || typeParam.details.isVariadic) {
                    return true;
                }
                if (type.typeArguments && index < type.typeArguments.length) {
                    typeArgType = type.typeArguments[index];
                }
                const declaredVariance = typeParam.details.declaredVariance;
                if (declaredVariance === 0 /* Variance.Auto */) {
                    return true;
                }
                let effectiveVariance = 2 /* Variance.Invariant */;
                if (declaredVariance === 3 /* Variance.Covariant */) {
                    // If the declared variance is covariant, the effective variance
                    // is simply copied from the type param variance.
                    effectiveVariance = typeParamVariance;
                }
                else if (declaredVariance === 4 /* Variance.Contravariant */) {
                    // If the declared variance is contravariant, it flips the
                    // effective variance from contravariant to covariant or vice versa.
                    if (typeParamVariance === 3 /* Variance.Covariant */) {
                        effectiveVariance = 4 /* Variance.Contravariant */;
                    }
                    else if (typeParamVariance === 4 /* Variance.Contravariant */) {
                        effectiveVariance = 3 /* Variance.Covariant */;
                    }
                }
                return isVarianceOfTypeArgumentCompatible(typeArgType !== null && typeArgType !== void 0 ? typeArgType : types_1.UnknownType.create(), effectiveVariance);
            });
        }
    }
    return true;
}
exports.isVarianceOfTypeArgumentCompatible = isVarianceOfTypeArgumentCompatible;
// Computes the method resolution ordering for a class whose base classes
// have already been filled in. The algorithm for computing MRO is described
// here: https://www.python.org/download/releases/2.3/mro/. It returns true
// if an MRO was possible, false otherwise.
function computeMroLinearization(classType) {
    let isMroFound = true;
    // Clear out any existing MRO information.
    classType.details.mro = [];
    const filteredBaseClasses = classType.details.baseClasses.filter((baseClass, index) => {
        if ((0, types_1.isInstantiableClass)(baseClass)) {
            // Generic has some special-case logic (see description of __mro_entries__
            // in PEP 560) that we need to account for here.
            if (types_1.ClassType.isBuiltIn(baseClass, 'Generic')) {
                // If the class is a Protocol or TypedDict, the generic is ignored for
                // the purposes of computing the MRO.
                if (types_1.ClassType.isProtocolClass(classType) || types_1.ClassType.isTypedDictClass(classType)) {
                    return false;
                }
                // If the class contains any specialized generic classes after
                // the Generic base, the Generic base is ignored for purposes
                // of computing the MRO.
                if (classType.details.baseClasses.some((innerBaseClass, innerIndex) => {
                    return (innerIndex > index &&
                        (0, types_1.isInstantiableClass)(innerBaseClass) &&
                        innerBaseClass.typeArguments &&
                        innerBaseClass.isTypeArgumentExplicit);
                })) {
                    return false;
                }
            }
        }
        return true;
    });
    // Construct the list of class lists that need to be merged.
    const classListsToMerge = [];
    filteredBaseClasses.forEach((baseClass) => {
        if ((0, types_1.isInstantiableClass)(baseClass)) {
            const typeVarContext = buildTypeVarContextFromSpecializedClass(baseClass);
            classListsToMerge.push(baseClass.details.mro.map((mroClass) => {
                return applySolvedTypeVars(mroClass, typeVarContext);
            }));
        }
        else {
            classListsToMerge.push([baseClass]);
        }
    });
    classListsToMerge.push(filteredBaseClasses.map((baseClass) => {
        const typeVarContext = buildTypeVarContextFromSpecializedClass(classType);
        return applySolvedTypeVars(baseClass, typeVarContext);
    }));
    // The first class in the MRO is the class itself.
    const typeVarContext = buildTypeVarContextFromSpecializedClass(classType);
    classType.details.mro.push(applySolvedTypeVars(classType, typeVarContext));
    // Helper function that returns true if the specified searchClass
    // is found in the "tail" (i.e. in elements 1 through n) of any
    // of the class lists.
    function isInTail(searchClass, classLists) {
        return classLists.some((classList) => {
            return (classList.findIndex((value) => (0, types_1.isInstantiableClass)(value) && types_1.ClassType.isSameGenericClass(value, searchClass)) > 0);
        });
    }
    // Helper function that filters the class lists to remove any duplicate
    // entries of the specified class. This is used once the class has been
    // added to the MRO.
    function filterClass(classToFilter, classLists) {
        for (let i = 0; i < classLists.length; i++) {
            classLists[i] = classLists[i].filter((value) => {
                return !(0, types_1.isInstantiableClass)(value) || !types_1.ClassType.isSameGenericClass(value, classToFilter);
            });
        }
    }
    while (true) {
        let foundValidHead = false;
        let nonEmptyList = undefined;
        for (let i = 0; i < classListsToMerge.length; i++) {
            const classList = classListsToMerge[i];
            if (classList.length > 0) {
                if (nonEmptyList === undefined) {
                    nonEmptyList = classList;
                }
                if (!(0, types_1.isInstantiableClass)(classList[0])) {
                    foundValidHead = true;
                    classType.details.mro.push(classList[0]);
                    classList.shift();
                    break;
                }
                else if (!isInTail(classList[0], classListsToMerge)) {
                    foundValidHead = true;
                    classType.details.mro.push(classList[0]);
                    filterClass(classList[0], classListsToMerge);
                    break;
                }
            }
        }
        // If all lists are empty, we are done.
        if (!nonEmptyList) {
            break;
        }
        // We made it all the way through the list of class lists without
        // finding a valid head, but there is at least one list that's not
        // yet empty. This means there's no valid MRO order.
        if (!foundValidHead) {
            isMroFound = false;
            // Handle the situation by pull the head off the first empty list.
            // This allows us to make forward progress.
            if (!(0, types_1.isInstantiableClass)(nonEmptyList[0])) {
                classType.details.mro.push(nonEmptyList[0]);
                nonEmptyList.shift();
            }
            else {
                classType.details.mro.push(nonEmptyList[0]);
                filterClass(nonEmptyList[0], classListsToMerge);
            }
        }
    }
    return isMroFound;
}
exports.computeMroLinearization = computeMroLinearization;
// Returns zero or more unique module names that point to the place(s)
// where the type is declared. Unions, for example, can result in more
// than one result. Type arguments are not included.
function getDeclaringModulesForType(type) {
    const moduleList = [];
    addDeclaringModuleNamesForType(type, moduleList);
    return moduleList;
}
exports.getDeclaringModulesForType = getDeclaringModulesForType;
function addDeclaringModuleNamesForType(type, moduleList, recursionCount = 0) {
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return;
    }
    recursionCount++;
    const addIfUnique = (moduleName) => {
        if (moduleName && !moduleList.some((n) => n === moduleName)) {
            moduleList.push(moduleName);
        }
    };
    switch (type.category) {
        case 6 /* TypeCategory.Class */: {
            addIfUnique(type.details.moduleName);
            break;
        }
        case 4 /* TypeCategory.Function */: {
            addIfUnique(type.details.moduleName);
            break;
        }
        case 5 /* TypeCategory.OverloadedFunction */: {
            type.overloads.forEach((overload) => {
                addDeclaringModuleNamesForType(overload, moduleList, recursionCount);
            });
            break;
        }
        case 8 /* TypeCategory.Union */: {
            doForEachSubtype(type, (subtype) => {
                addDeclaringModuleNamesForType(subtype, moduleList, recursionCount);
            });
            break;
        }
        case 7 /* TypeCategory.Module */: {
            addIfUnique(type.moduleName);
            break;
        }
    }
}
function convertTypeToParamSpecValue(type) {
    if ((0, types_1.isParamSpec)(type)) {
        const newFunction = types_1.FunctionType.createInstance('', '', '', 65536 /* FunctionTypeFlags.ParamSpecValue */);
        newFunction.details.paramSpec = type;
        newFunction.details.typeVarScopeId = getTypeVarScopeId(type);
        return newFunction;
    }
    if ((0, types_1.isFunction)(type)) {
        const newFunction = types_1.FunctionType.createInstance('', '', '', type.details.flags | 65536 /* FunctionTypeFlags.ParamSpecValue */, type.details.docString);
        type.details.parameters.forEach((param, index) => {
            types_1.FunctionType.addParameter(newFunction, {
                category: param.category,
                name: param.name,
                hasDefault: param.hasDefault,
                defaultValueExpression: param.defaultValueExpression,
                isNameSynthesized: param.isNameSynthesized,
                type: types_1.FunctionType.getEffectiveParameterType(type, index),
            });
        });
        if (type.details.higherOrderTypeVarScopeIds) {
            newFunction.details.higherOrderTypeVarScopeIds = [...type.details.higherOrderTypeVarScopeIds];
            newFunction.details.typeVarScopeId = newFunction.details.higherOrderTypeVarScopeIds.pop();
        }
        newFunction.details.paramSpec = type.details.paramSpec;
        return newFunction;
    }
    return getUnknownTypeForParamSpec();
}
exports.convertTypeToParamSpecValue = convertTypeToParamSpecValue;
function convertParamSpecValueToType(paramSpecValue, omitParamSpec = false) {
    let hasParameters = paramSpecValue.details.parameters.length > 0;
    if (paramSpecValue.details.parameters.length === 1) {
        // If the ParamSpec has a position-only separator as its only parameter,
        // treat it as though there are no parameters.
        const onlyParam = paramSpecValue.details.parameters[0];
        if ((0, types_1.isPositionOnlySeparator)(onlyParam)) {
            hasParameters = false;
        }
    }
    if (hasParameters || !paramSpecValue.details.paramSpec || omitParamSpec) {
        // Create a function type from the param spec entries.
        const functionType = types_1.FunctionType.createInstance('', '', '', 65536 /* FunctionTypeFlags.ParamSpecValue */ | paramSpecValue.details.flags);
        types_1.FunctionType.addHigherOrderTypeVarScopeIds(functionType, paramSpecValue.details.typeVarScopeId);
        paramSpecValue.details.parameters.forEach((entry) => {
            types_1.FunctionType.addParameter(functionType, {
                category: entry.category,
                name: entry.name,
                hasDefault: entry.hasDefault,
                defaultValueExpression: entry.defaultValueExpression,
                isNameSynthesized: entry.isNameSynthesized,
                hasDeclaredType: true,
                type: entry.type,
            });
        });
        if (!omitParamSpec) {
            functionType.details.paramSpec = paramSpecValue.details.paramSpec;
        }
        functionType.details.docString = paramSpecValue.details.docString;
        return functionType;
    }
    return paramSpecValue.details.paramSpec;
}
exports.convertParamSpecValueToType = convertParamSpecValueToType;
// Recursively walks a type and calls a callback for each TypeVar, allowing
// it to be replaced with something else.
class TypeVarTransformer {
    constructor() {
        this._isTransformingTypeArg = false;
        this._pendingTypeVarTransformations = new Set();
        this._pendingFunctionTransformations = [];
    }
    apply(type, recursionCount) {
        var _a, _b;
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return type;
        }
        recursionCount++;
        type = this.transformGenericTypeAlias(type, recursionCount);
        // If the type is conditioned on a type variable, see if the condition
        // still applies.
        if (type.condition) {
            type = this.transformConditionalType(type, recursionCount);
        }
        // Shortcut the operation if possible.
        if (!requiresSpecialization(type)) {
            return type;
        }
        if ((0, types_1.isAnyOrUnknown)(type)) {
            return type;
        }
        if (isNoneInstance(type)) {
            return type;
        }
        if ((0, types_1.isTypeVar)(type)) {
            // Handle recursive type aliases specially. In particular,
            // we need to specialize type arguments for generic recursive
            // type aliases.
            if (type.details.recursiveTypeAliasName) {
                if (!((_a = type.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments)) {
                    return type;
                }
                let requiresUpdate = false;
                const typeArgs = type.typeAliasInfo.typeArguments.map((typeArg) => {
                    const replacementType = this.apply(typeArg, recursionCount);
                    if (replacementType !== typeArg) {
                        requiresUpdate = true;
                    }
                    return replacementType;
                });
                if (requiresUpdate) {
                    return types_1.TypeBase.cloneForTypeAlias(type, type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, typeArgs);
                }
                return type;
            }
            let replacementType = type;
            // Recursively transform the results, but ensure that we don't replace any
            // type variables in the same scope recursively by setting it the scope in the
            // _pendingTypeVarTransformations set.
            if (!this._isTypeVarScopePending(type.scopeId)) {
                if (type.details.isParamSpec) {
                    let paramSpecWithoutAccess = type;
                    if (type.paramSpecAccess) {
                        paramSpecWithoutAccess = types_1.TypeVarType.cloneForParamSpecAccess(type, /* access */ undefined);
                    }
                    const paramSpecValue = this.transformParamSpec(paramSpecWithoutAccess, recursionCount);
                    if (paramSpecValue) {
                        const paramSpecType = convertParamSpecValueToType(paramSpecValue);
                        if (type.paramSpecAccess) {
                            if ((0, types_1.isParamSpec)(paramSpecType)) {
                                replacementType = types_1.TypeVarType.cloneForParamSpecAccess(paramSpecType, type.paramSpecAccess);
                            }
                            else {
                                replacementType = types_1.UnknownType.create();
                            }
                        }
                        else {
                            replacementType = paramSpecType;
                        }
                    }
                }
                else {
                    replacementType = (_b = this.transformTypeVar(type, recursionCount)) !== null && _b !== void 0 ? _b : type;
                    if (!this._isTransformingTypeArg) {
                        if (type.scopeId) {
                            this._pendingTypeVarTransformations.add(type.scopeId);
                        }
                        replacementType = this.apply(replacementType, recursionCount);
                        if (type.scopeId) {
                            this._pendingTypeVarTransformations.delete(type.scopeId);
                        }
                    }
                    // If we're transforming a variadic type variable that was in a union,
                    // expand the union types.
                    if ((0, types_1.isVariadicTypeVar)(type) && type.isVariadicInUnion) {
                        replacementType = _expandVariadicUnpackedUnion(replacementType);
                    }
                }
            }
            return replacementType;
        }
        if ((0, types_1.isUnion)(type)) {
            const newUnionType = mapSubtypes(type, (subtype) => {
                let transformedType = this.apply(subtype, recursionCount);
                // If we're transforming a variadic type variable within a union,
                // combine the individual types within the variadic type variable.
                if ((0, types_1.isVariadicTypeVar)(subtype) && !(0, types_1.isVariadicTypeVar)(transformedType)) {
                    const subtypesToCombine = [];
                    doForEachSubtype(transformedType, (transformedSubtype) => {
                        subtypesToCombine.push(_expandVariadicUnpackedUnion(transformedSubtype));
                    });
                    transformedType = (0, types_1.combineTypes)(subtypesToCombine);
                }
                if (this.transformUnionSubtype) {
                    return this.transformUnionSubtype(subtype, transformedType, recursionCount);
                }
                return transformedType;
            });
            return !(0, types_1.isNever)(newUnionType) ? newUnionType : types_1.UnknownType.create();
        }
        if ((0, types_1.isClass)(type)) {
            return this.transformTypeVarsInClassType(type, recursionCount);
        }
        if ((0, types_1.isFunction)(type)) {
            // Prevent recursion.
            if (this._pendingFunctionTransformations.some((t) => t === type)) {
                return type;
            }
            this._pendingFunctionTransformations.push(type);
            const result = this.transformTypeVarsInFunctionType(type, recursionCount);
            this._pendingFunctionTransformations.pop();
            return result;
        }
        if ((0, types_1.isOverloadedFunction)(type)) {
            // Prevent recursion.
            if (this._pendingFunctionTransformations.some((t) => t === type)) {
                return type;
            }
            this._pendingFunctionTransformations.push(type);
            let requiresUpdate = false;
            // Specialize each of the functions in the overload.
            const newOverloads = [];
            type.overloads.forEach((entry) => {
                const replacementType = this.transformTypeVarsInFunctionType(entry, recursionCount);
                if ((0, types_1.isFunction)(replacementType)) {
                    newOverloads.push(replacementType);
                }
                else {
                    (0, collectionUtils_1.appendArray)(newOverloads, replacementType.overloads);
                }
                if (replacementType !== entry) {
                    requiresUpdate = true;
                }
            });
            this._pendingFunctionTransformations.pop();
            // Construct a new overload with the specialized function types.
            return requiresUpdate ? types_1.OverloadedFunctionType.create(newOverloads) : type;
        }
        return type;
    }
    transformTypeVar(typeVar, recursionCount) {
        return undefined;
    }
    transformTupleTypeVar(paramSpec, recursionCount) {
        return undefined;
    }
    transformParamSpec(paramSpec, recursionCount) {
        return undefined;
    }
    transformUnionSubtype(preTransform, postTransform, recursionCount) {
        return postTransform;
    }
    doForEachSignatureContext(callback) {
        // By default, simply return the result of the callback. Subclasses
        // can override this method as they see fit.
        return callback();
    }
    transformGenericTypeAlias(type, recursionCount) {
        if (!type.typeAliasInfo || !type.typeAliasInfo.typeParameters || !type.typeAliasInfo.typeArguments) {
            return type;
        }
        let requiresUpdate = false;
        const newTypeArgs = type.typeAliasInfo.typeArguments.map((typeArg) => {
            const updatedType = this.apply(typeArg, recursionCount);
            if (type !== updatedType) {
                requiresUpdate = true;
            }
            return updatedType;
        });
        return requiresUpdate
            ? types_1.TypeBase.cloneForTypeAlias(type, type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, type.typeAliasInfo.fileUri, type.typeAliasInfo.typeVarScopeId, type.typeAliasInfo.isPep695Syntax, type.typeAliasInfo.typeParameters, newTypeArgs)
            : type;
    }
    transformConditionalType(type, recursionCount) {
        // By default, do not perform any transform.
        return type;
    }
    transformTypeVarsInClassType(classType, recursionCount) {
        const typeParams = types_1.ClassType.getTypeParameters(classType);
        // Handle the common case where the class has no type parameters.
        if (typeParams.length === 0 &&
            !types_1.ClassType.isSpecialBuiltIn(classType) &&
            !types_1.ClassType.isBuiltIn(classType, 'type')) {
            return classType;
        }
        let newTypeArgs;
        let newTupleTypeArgs;
        let specializationNeeded = false;
        const transformParamSpec = (paramSpec) => {
            const paramSpecValue = this.transformParamSpec(paramSpec, recursionCount);
            if (paramSpecValue) {
                specializationNeeded = true;
                return convertParamSpecValueToType(paramSpecValue);
            }
            else {
                return paramSpec;
            }
        };
        const wasTransformingTypeArg = this._isTransformingTypeArg;
        this._isTransformingTypeArg = true;
        // If type args were previously provided, specialize them.
        // Handle tuples specially.
        if (types_1.ClassType.isTupleClass(classType)) {
            if (classType.tupleTypeArguments) {
                newTupleTypeArgs = [];
                classType.tupleTypeArguments.forEach((oldTypeArgType) => {
                    const newTypeArgType = this.apply(oldTypeArgType.type, recursionCount);
                    if (newTypeArgType !== oldTypeArgType.type) {
                        specializationNeeded = true;
                    }
                    if ((0, types_1.isUnpackedVariadicTypeVar)(oldTypeArgType.type) &&
                        (0, types_1.isClassInstance)(newTypeArgType) &&
                        isTupleClass(newTypeArgType) &&
                        newTypeArgType.tupleTypeArguments) {
                        (0, collectionUtils_1.appendArray)(newTupleTypeArgs, newTypeArgType.tupleTypeArguments);
                    }
                    else {
                        newTupleTypeArgs.push({
                            type: newTypeArgType,
                            isUnbounded: oldTypeArgType.isUnbounded,
                            isOptional: oldTypeArgType.isOptional,
                        });
                    }
                });
            }
            else if (typeParams.length > 0) {
                newTupleTypeArgs = this.transformTupleTypeVar(typeParams[0], recursionCount);
                if (newTupleTypeArgs) {
                    specializationNeeded = true;
                }
                else {
                    const newTypeArgType = this.apply(typeParams[0], recursionCount);
                    if (typeParams[0] !== newTypeArgType) {
                        newTupleTypeArgs = [{ type: newTypeArgType, isUnbounded: true }];
                        specializationNeeded = true;
                    }
                }
            }
            // If this is an empty tuple, don't recompute the non-tuple type argument.
            if (newTupleTypeArgs && newTupleTypeArgs.length > 0) {
                // Combine the tuple type args into a single non-tuple type argument.
                newTypeArgs = [
                    (0, types_1.combineTypes)(newTupleTypeArgs.map((t) => {
                        if ((0, types_1.isTypeVar)(t.type) && (0, types_1.isUnpackedVariadicTypeVar)(t.type)) {
                            // Treat the unpacked TypeVarTuple as a union.
                            return types_1.TypeVarType.cloneForUnpacked(t.type, /* isInUnion */ true);
                        }
                        return t.type;
                    })),
                ];
            }
        }
        if (!newTypeArgs) {
            if (classType.typeArguments) {
                newTypeArgs = classType.typeArguments.map((oldTypeArgType) => {
                    if ((0, types_1.isTypeVar)(oldTypeArgType) && oldTypeArgType.details.isParamSpec) {
                        return transformParamSpec(oldTypeArgType);
                    }
                    let newTypeArgType = this.apply(oldTypeArgType, recursionCount);
                    if (newTypeArgType !== oldTypeArgType) {
                        specializationNeeded = true;
                        // If this was a variadic type variable that was part of a union
                        // (e.g. Union[Unpack[Vs]]), expand the subtypes into a union here.
                        if ((0, types_1.isTypeVar)(oldTypeArgType) &&
                            (0, types_1.isVariadicTypeVar)(oldTypeArgType) &&
                            oldTypeArgType.isVariadicInUnion) {
                            newTypeArgType = _expandVariadicUnpackedUnion(newTypeArgType);
                        }
                    }
                    return newTypeArgType;
                });
            }
            else {
                newTypeArgs = [];
                typeParams.forEach((typeParam) => {
                    let replacementType = typeParam;
                    if (typeParam.details.isParamSpec) {
                        replacementType = transformParamSpec(typeParam);
                        if (replacementType !== typeParam) {
                            specializationNeeded = true;
                        }
                    }
                    else {
                        if (!this._isTypeVarScopePending(typeParam.scopeId)) {
                            const transformedType = this.transformTypeVar(typeParam, recursionCount);
                            replacementType = transformedType !== null && transformedType !== void 0 ? transformedType : typeParam;
                            if (replacementType !== typeParam) {
                                specializationNeeded = true;
                            }
                            else if (transformedType !== undefined && !classType.typeArguments) {
                                specializationNeeded = true;
                            }
                        }
                    }
                    newTypeArgs.push(replacementType);
                });
            }
        }
        this._isTransformingTypeArg = wasTransformingTypeArg;
        // If specialization wasn't needed, don't allocate a new class.
        if (!specializationNeeded) {
            return classType;
        }
        return types_1.ClassType.cloneForSpecialization(classType, newTypeArgs, 
        /* isTypeArgumentExplicit */ true, 
        /* includeSubclasses */ undefined, newTupleTypeArgs);
    }
    transformTypeVarsInFunctionType(sourceType, recursionCount) {
        return this.doForEachSignatureContext(() => {
            let functionType = sourceType;
            // Handle functions with a parameter specification in a special manner.
            if (functionType.details.paramSpec) {
                const paramSpec = this.transformParamSpec(functionType.details.paramSpec, recursionCount);
                if (paramSpec) {
                    functionType = types_1.FunctionType.cloneForParamSpec(functionType, paramSpec);
                }
            }
            const declaredReturnType = types_1.FunctionType.getSpecializedReturnType(functionType);
            const specializedReturnType = declaredReturnType
                ? this.apply(declaredReturnType, recursionCount)
                : undefined;
            let typesRequiredSpecialization = declaredReturnType !== specializedReturnType;
            const specializedParameters = {
                parameterTypes: [],
                returnType: specializedReturnType,
            };
            // Does this function end with *args: P.args, **args: P.kwargs? If so, we'll
            // modify the function and replace these parameters with the signature captured
            // by the ParamSpec.
            if (functionType.details.parameters.length >= 2) {
                const argsParam = functionType.details.parameters[functionType.details.parameters.length - 2];
                const kwargsParam = functionType.details.parameters[functionType.details.parameters.length - 1];
                const argsParamType = types_1.FunctionType.getEffectiveParameterType(functionType, functionType.details.parameters.length - 2);
                const kwargsParamType = types_1.FunctionType.getEffectiveParameterType(functionType, functionType.details.parameters.length - 1);
                if (argsParam.category === 1 /* ParameterCategory.ArgsList */ &&
                    kwargsParam.category === 2 /* ParameterCategory.KwargsDict */ &&
                    (0, types_1.isParamSpec)(argsParamType) &&
                    (0, types_1.isParamSpec)(kwargsParamType) &&
                    (0, types_1.isTypeSame)(argsParamType, kwargsParamType)) {
                    const paramSpecType = this.transformParamSpec(argsParamType, recursionCount);
                    if (paramSpecType) {
                        if (paramSpecType.details.parameters.length > 0 ||
                            paramSpecType.details.paramSpec === undefined ||
                            !(0, types_1.isTypeSame)(argsParamType, paramSpecType.details.paramSpec)) {
                            functionType = types_1.FunctionType.cloneForParamSpecApplication(functionType, paramSpecType);
                        }
                    }
                }
            }
            let variadicParamIndex;
            let variadicTypesToUnpack;
            const specializedDefaultArgs = [];
            const wasTransformingTypeArg = this._isTransformingTypeArg;
            this._isTransformingTypeArg = true;
            for (let i = 0; i < functionType.details.parameters.length; i++) {
                const paramType = types_1.FunctionType.getEffectiveParameterType(functionType, i);
                const specializedType = this.apply(paramType, recursionCount);
                specializedParameters.parameterTypes.push(specializedType);
                // Do we need to specialize the default argument type for this parameter?
                let defaultArgType = types_1.FunctionType.getEffectiveParameterDefaultArgType(functionType, i);
                if (defaultArgType) {
                    const specializedArgType = this.apply(defaultArgType, recursionCount);
                    if (specializedArgType !== defaultArgType) {
                        defaultArgType = specializedArgType;
                        typesRequiredSpecialization = true;
                    }
                }
                specializedDefaultArgs.push(defaultArgType);
                if (variadicParamIndex === undefined &&
                    (0, types_1.isVariadicTypeVar)(paramType) &&
                    functionType.details.parameters[i].category === 1 /* ParameterCategory.ArgsList */) {
                    variadicParamIndex = i;
                    if ((0, types_1.isClassInstance)(specializedType) &&
                        isTupleClass(specializedType) &&
                        specializedType.isUnpacked) {
                        variadicTypesToUnpack = specializedType.tupleTypeArguments;
                    }
                }
                if (paramType !== specializedType) {
                    typesRequiredSpecialization = true;
                }
            }
            let specializedInferredReturnType;
            if (functionType.inferredReturnType) {
                specializedInferredReturnType = this.apply(functionType.inferredReturnType, recursionCount);
                if (specializedInferredReturnType !== functionType.inferredReturnType) {
                    typesRequiredSpecialization = true;
                }
            }
            this._isTransformingTypeArg = wasTransformingTypeArg;
            if (!typesRequiredSpecialization) {
                return functionType;
            }
            if (specializedDefaultArgs.some((t) => t !== undefined)) {
                specializedParameters.parameterDefaultArgs = specializedDefaultArgs;
            }
            // If there was no unpacked variadic type variable, we're done.
            if (!variadicTypesToUnpack) {
                return types_1.FunctionType.cloneForSpecialization(functionType, specializedParameters, specializedInferredReturnType);
            }
            // Unpack the tuple and synthesize a new function in the process.
            const newFunctionType = types_1.TypeBase.isInstantiable(functionType)
                ? types_1.FunctionType.createInstantiable(functionType.details.flags | 64 /* FunctionTypeFlags.SynthesizedMethod */)
                : types_1.FunctionType.createSynthesizedInstance('', functionType.details.flags);
            let insertKeywordOnlySeparator = false;
            let swallowPositionOnlySeparator = false;
            specializedParameters.parameterTypes.forEach((paramType, index) => {
                if (index === variadicParamIndex) {
                    let sawUnboundedEntry = false;
                    // Unpack the tuple into individual parameters.
                    variadicTypesToUnpack.forEach((unpackedType) => {
                        types_1.FunctionType.addParameter(newFunctionType, {
                            category: unpackedType.isUnbounded || (0, types_1.isVariadicTypeVar)(unpackedType.type)
                                ? 1 /* ParameterCategory.ArgsList */
                                : 0 /* ParameterCategory.Simple */,
                            name: `__p${newFunctionType.details.parameters.length}`,
                            isNameSynthesized: true,
                            type: unpackedType.type,
                            hasDeclaredType: true,
                        });
                        if (unpackedType.isUnbounded) {
                            sawUnboundedEntry = true;
                        }
                    });
                    if (sawUnboundedEntry) {
                        swallowPositionOnlySeparator = true;
                    }
                    else {
                        insertKeywordOnlySeparator = true;
                    }
                }
                else {
                    const param = { ...functionType.details.parameters[index] };
                    if ((0, types_1.isKeywordOnlySeparator)(param)) {
                        insertKeywordOnlySeparator = false;
                    }
                    else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                        insertKeywordOnlySeparator = false;
                    }
                    // Insert a keyword-only separator parameter if we previously
                    // unpacked a variadic TypeVar.
                    if (param.category === 0 /* ParameterCategory.Simple */ && param.name && insertKeywordOnlySeparator) {
                        types_1.FunctionType.addKeywordOnlyParameterSeparator(newFunctionType);
                        insertKeywordOnlySeparator = false;
                    }
                    param.type = paramType;
                    if (param.name && param.isNameSynthesized) {
                        param.name = `__p${newFunctionType.details.parameters.length}`;
                    }
                    if (param.category !== 0 /* ParameterCategory.Simple */ || param.name || !swallowPositionOnlySeparator) {
                        types_1.FunctionType.addParameter(newFunctionType, param);
                    }
                }
            });
            newFunctionType.details.declaredReturnType = specializedParameters.returnType;
            return newFunctionType;
        });
    }
    _isTypeVarScopePending(typeVarScopeId) {
        return !!typeVarScopeId && this._pendingTypeVarTransformations.has(typeVarScopeId);
    }
}
// Converts all type variables to Any.
class TypeVarAnyReplacer extends TypeVarTransformer {
    constructor() {
        super();
    }
    transformTypeVar(typeVar) {
        return types_1.AnyType.create();
    }
    transformParamSpec(paramSpec) {
        return getUnknownTypeForParamSpec();
    }
}
// For a TypeVar with a default type, validates whether the default type is using
// any other TypeVars that are not currently in scope.
class TypeVarDefaultValidator extends TypeVarTransformer {
    constructor(_liveTypeParams, _invalidTypeVars) {
        super();
        this._liveTypeParams = _liveTypeParams;
        this._invalidTypeVars = _invalidTypeVars;
    }
    transformTypeVar(typeVar) {
        const replacementType = this._liveTypeParams.find((param) => param.details.name === typeVar.details.name);
        if (!replacementType || (0, types_1.isParamSpec)(replacementType)) {
            this._invalidTypeVars.add(typeVar.details.name);
        }
        return types_1.UnknownType.create();
    }
    transformParamSpec(paramSpec) {
        const replacementType = this._liveTypeParams.find((param) => param.details.name === paramSpec.details.name);
        if (!replacementType || !(0, types_1.isParamSpec)(replacementType)) {
            this._invalidTypeVars.add(paramSpec.details.name);
        }
        return undefined;
    }
}
class UniqueFunctionSignatureTransformer extends TypeVarTransformer {
    constructor(_signatureTracker, _expressionOffset) {
        super();
        this._signatureTracker = _signatureTracker;
        this._expressionOffset = _expressionOffset;
    }
    transformGenericTypeAlias(type, recursionCount) {
        // Don't transform type aliases.
        return type;
    }
    transformTypeVarsInClassType(classType, recursionCount) {
        // Don't transform classes.
        return classType;
    }
    transformTypeVarsInFunctionType(sourceType, recursionCount) {
        if (sourceType.trackedSignatures) {
            this._signatureTracker.addTrackedSignatures(sourceType.trackedSignatures);
        }
        // If this function is not generic, there's no need to check for uniqueness.
        if (sourceType.details.typeParameters.length === 0) {
            return super.transformTypeVarsInFunctionType(sourceType, recursionCount);
        }
        let updatedSourceType = sourceType;
        const existingSignature = this._signatureTracker.findSignature(sourceType);
        if (existingSignature) {
            let offsetIndex = existingSignature.expressionOffsets.findIndex((offset) => offset === this._expressionOffset);
            if (offsetIndex < 0) {
                offsetIndex = existingSignature.expressionOffsets.length;
            }
            if (offsetIndex > 0) {
                const typeVarContext = new typeVarContext_1.TypeVarContext(getTypeVarScopeIds(sourceType));
                // Create new type variables with the same scope but with
                // different (unique) names.
                sourceType.details.typeParameters.forEach((typeParam) => {
                    if (typeParam.scopeType === 1 /* TypeVarScopeType.Function */) {
                        let replacement = types_1.TypeVarType.cloneForNewName(typeParam, `${typeParam.details.name}(${offsetIndex})`);
                        if (replacement.details.isParamSpec) {
                            replacement = convertTypeToParamSpecValue(replacement);
                        }
                        typeVarContext.setTypeVarType(typeParam, replacement);
                    }
                });
                updatedSourceType = applySolvedTypeVars(sourceType, typeVarContext);
                (0, debug_1.assert)((0, types_1.isFunction)(updatedSourceType) || (0, types_1.isOverloadedFunction)(updatedSourceType));
            }
        }
        this._signatureTracker.addSignature(sourceType, this._expressionOffset);
        return updatedSourceType;
    }
}
// Specializes a (potentially generic) type by substituting
// type variables from a type var map.
class ApplySolvedTypeVarsTransformer extends TypeVarTransformer {
    constructor(_typeVarContext, _options) {
        super();
        this._typeVarContext = _typeVarContext;
        this._options = _options;
        this._isSolvingDefaultType = false;
    }
    transformTypeVar(typeVar, recursionCount) {
        var _a, _b;
        const signatureContext = this._typeVarContext.getSignatureContext((_a = this._activeTypeVarSignatureContextIndex) !== null && _a !== void 0 ? _a : 0);
        // If the type variable is unrelated to the scopes we're solving,
        // don't transform that type variable.
        if (typeVar.scopeId && this._typeVarContext.hasSolveForScope(typeVar.scopeId)) {
            let replacement = signatureContext.getTypeVarType(typeVar, !!this._options.useNarrowBoundOnly);
            // If there was no narrow bound but there is a wide bound that
            // contains literals or a TypeVar, we'll use the wide bound even if
            // "useNarrowBoundOnly" is specified.
            if (!replacement && this._options.useNarrowBoundOnly) {
                const wideType = signatureContext.getTypeVarType(typeVar);
                if (wideType) {
                    if ((0, types_1.isTypeVar)(wideType) || containsLiteralType(wideType, /* includeTypeArgs */ true)) {
                        replacement = wideType;
                    }
                }
            }
            if (replacement) {
                if (types_1.TypeBase.isInstantiable(typeVar)) {
                    if ((0, types_1.isAnyOrUnknown)(replacement) &&
                        this._options.typeClassType &&
                        (0, types_1.isInstantiableClass)(this._options.typeClassType)) {
                        replacement = types_1.ClassType.cloneForSpecialization(types_1.ClassType.cloneAsInstance(this._options.typeClassType), [replacement], 
                        /* isTypeArgumentExplicit */ true);
                    }
                    else {
                        replacement = convertToInstantiable(replacement, /* includeSubclasses */ false);
                    }
                }
                else {
                    // If the TypeVar is not instantiable (i.e. not a type[T]), then
                    // it represents an instance of a type. If the replacement includes
                    // a generic class that has not been specialized, specialize it
                    // now with default type arguments.
                    replacement = mapSubtypes(replacement, (subtype) => {
                        if ((0, types_1.isClassInstance)(subtype)) {
                            // If the includeSubclasses wasn't set, force it to be set by
                            // converting to/from an instantiable.
                            if (!subtype.includeSubclasses) {
                                subtype = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneAsInstantiable(subtype));
                            }
                            if (this._options.unknownIfNotFound) {
                                return specializeWithDefaultTypeArgs(subtype);
                            }
                        }
                        return subtype;
                    });
                }
                if ((0, types_1.isTypeVar)(replacement) && typeVar.isVariadicUnpacked && replacement.details.isVariadic) {
                    return types_1.TypeVarType.cloneForUnpacked(replacement, typeVar.isVariadicInUnion);
                }
                return replacement;
            }
            // If this typeVar is in scope for what we're solving but the type
            // var map doesn't contain any entry for it, replace with the
            // default or Unknown.
            let useDefaultOrUnknown = false;
            if (this._options.unknownIfNotFound) {
                const exemptTypeVars = (_b = this._options.unknownExemptTypeVars) !== null && _b !== void 0 ? _b : [];
                const typeVarInstance = types_1.TypeBase.isInstance(typeVar) ? typeVar : types_1.TypeVarType.cloneAsInstance(typeVar);
                if (!exemptTypeVars.some((t) => (0, types_1.isTypeSame)(t, typeVarInstance))) {
                    useDefaultOrUnknown = true;
                }
            }
            else if (this._options.applyInScopePlaceholders && typeVar.isInScopePlaceholder) {
                useDefaultOrUnknown = true;
            }
            if (useDefaultOrUnknown) {
                // Use the default value if there is one.
                if (typeVar.details.isDefaultExplicit) {
                    return this._solveDefaultType(typeVar.details.defaultType, recursionCount);
                }
                return types_1.UnknownType.create();
            }
        }
        // If we're solving a default type, handle type variables with no scope ID.
        if (this._isSolvingDefaultType && !typeVar.scopeId) {
            const replacementEntry = signatureContext
                .getTypeVars()
                .find((entry) => entry.typeVar.details.name === typeVar.details.name);
            if (replacementEntry) {
                return signatureContext.getTypeVarType(replacementEntry.typeVar);
            }
            if (typeVar.details.isDefaultExplicit) {
                return this.apply(typeVar.details.defaultType, recursionCount);
            }
            return types_1.UnknownType.create();
        }
        return undefined;
    }
    transformUnionSubtype(preTransform, postTransform) {
        var _a;
        // If a union contains unsolved TypeVars within scope, eliminate them
        // unless this results in an empty union. This elimination is needed
        // in cases where TypeVars can go unsolved due to unions in parameter
        // annotations, like this:
        //   def test(x: Union[str, T]) -> Union[str, T]
        if (this._options.eliminateUnsolvedInUnions) {
            if ((0, types_1.isTypeVar)(preTransform) &&
                preTransform.scopeId !== undefined &&
                this._typeVarContext.hasSolveForScope(preTransform.scopeId)) {
                const signatureContext = this._typeVarContext.getSignatureContext((_a = this._activeTypeVarSignatureContextIndex) !== null && _a !== void 0 ? _a : 0);
                const typeVarType = signatureContext.getTypeVarType(preTransform);
                // Did the TypeVar remain unsolved?
                if (!typeVarType || ((0, types_1.isTypeVar)(typeVarType) && typeVarType.isInScopePlaceholder)) {
                    // If the TypeVar was not transformed, then it was unsolved,
                    // and we'll eliminate it.
                    if (preTransform === postTransform) {
                        return undefined;
                    }
                    // If unknownIfNotFound is true, the postTransform type will
                    // be Unknown, which we want to eliminate.
                    if ((0, types_1.isUnknown)(postTransform) && this._options.unknownIfNotFound) {
                        return undefined;
                    }
                }
            }
        }
        return postTransform;
    }
    transformTupleTypeVar(typeVar) {
        var _a;
        if (!typeVar.scopeId || !this._typeVarContext.hasSolveForScope(typeVar.scopeId)) {
            const defaultType = typeVar.details.defaultType;
            if (typeVar.details.isDefaultExplicit && (0, types_1.isClassInstance)(defaultType) && defaultType.tupleTypeArguments) {
                return defaultType.tupleTypeArguments;
            }
            return undefined;
        }
        const signatureContext = this._typeVarContext.getSignatureContext((_a = this._activeTypeVarSignatureContextIndex) !== null && _a !== void 0 ? _a : 0);
        return signatureContext.getTupleTypeVar(typeVar);
    }
    transformParamSpec(paramSpec, recursionCount) {
        var _a, _b;
        const signatureContext = this._typeVarContext.getSignatureContext((_a = this._activeTypeVarSignatureContextIndex) !== null && _a !== void 0 ? _a : 0);
        // If we're solving a default type, handle param specs with no scope ID.
        if (this._isSolvingDefaultType && !paramSpec.scopeId) {
            const replacementEntry = signatureContext
                .getTypeVars()
                .find((entry) => entry.typeVar.details.name === paramSpec.details.name);
            if (replacementEntry) {
                return signatureContext.getParamSpecType(replacementEntry.typeVar);
            }
            if (paramSpec.details.isDefaultExplicit) {
                return convertTypeToParamSpecValue(this.apply(paramSpec.details.defaultType, recursionCount));
            }
            return getUnknownTypeForParamSpec();
        }
        if (!paramSpec.scopeId || !this._typeVarContext.hasSolveForScope(paramSpec.scopeId)) {
            return undefined;
        }
        const transformedParamSpec = signatureContext.getParamSpecType(paramSpec);
        if (transformedParamSpec) {
            return transformedParamSpec;
        }
        let useDefaultOrUnknown = false;
        if (this._options.unknownIfNotFound) {
            const exemptTypeVars = (_b = this._options.unknownExemptTypeVars) !== null && _b !== void 0 ? _b : [];
            if (!exemptTypeVars.some((t) => (0, types_1.isTypeSame)(t, paramSpec, { ignoreTypeFlags: true }))) {
                useDefaultOrUnknown = true;
            }
        }
        else if (this._options.applyInScopePlaceholders && paramSpec.isInScopePlaceholder) {
            useDefaultOrUnknown = true;
        }
        if (useDefaultOrUnknown) {
            // Use the default value if there is one.
            if (paramSpec.details.isDefaultExplicit) {
                return convertTypeToParamSpecValue(this._solveDefaultType(paramSpec.details.defaultType, recursionCount));
            }
            // Convert to the ParamSpec equivalent of "Unknown".
            return getUnknownTypeForParamSpec();
        }
        return undefined;
    }
    transformConditionalType(type, recursionCount) {
        var _a;
        if (!type.condition) {
            return type;
        }
        const signatureContext = this._typeVarContext.getSignatureContext((_a = this._activeTypeVarSignatureContextIndex) !== null && _a !== void 0 ? _a : 0);
        for (const condition of type.condition) {
            // This doesn't apply to bound type variables.
            if (condition.typeVar.details.constraints.length === 0) {
                continue;
            }
            const typeVarEntry = signatureContext.getTypeVar(condition.typeVar);
            if (!typeVarEntry || condition.constraintIndex >= typeVarEntry.typeVar.details.constraints.length) {
                continue;
            }
            const value = signatureContext.getTypeVarType(typeVarEntry.typeVar);
            if (!value) {
                continue;
            }
            const constraintType = typeVarEntry.typeVar.details.constraints[condition.constraintIndex];
            // If this violates the constraint, substitute a Never type.
            if (!(0, types_1.isTypeSame)(constraintType, value)) {
                return types_1.NeverType.createNever();
            }
        }
        return type;
    }
    doForEachSignatureContext(callback) {
        const signatureContexts = this._typeVarContext.getSignatureContexts();
        // Handle the common case where there are not multiple signature contexts.
        if (signatureContexts.length <= 1) {
            return callback();
        }
        // Loop through all of the signature contexts in the type var context
        // to create an overload type.
        const overloadTypes = signatureContexts.map((_, index) => {
            this._activeTypeVarSignatureContextIndex = index;
            return callback();
        });
        this._activeTypeVarSignatureContextIndex = undefined;
        const filteredOverloads = [];
        doForEachSubtype((0, types_1.combineTypes)(overloadTypes), (subtype) => {
            (0, debug_1.assert)((0, types_1.isFunction)(subtype));
            subtype = types_1.FunctionType.cloneWithNewFlags(subtype, subtype.details.flags | 256 /* FunctionTypeFlags.Overloaded */);
            filteredOverloads.push(subtype);
        });
        if (filteredOverloads.length === 1) {
            return filteredOverloads[0];
        }
        return types_1.OverloadedFunctionType.create(filteredOverloads);
    }
    _solveDefaultType(defaultType, recursionCount) {
        const wasSolvingDefaultType = this._isSolvingDefaultType;
        this._isSolvingDefaultType = true;
        const result = this.apply(defaultType, recursionCount);
        this._isSolvingDefaultType = wasSolvingDefaultType;
        return result;
    }
}
class ExpectedTypeTransformer extends TypeVarTransformer {
    constructor(_liveTypeVarScopes, _usageOffset) {
        super();
        this._liveTypeVarScopes = _liveTypeVarScopes;
        this._usageOffset = _usageOffset;
    }
    transformTypeVar(typeVar) {
        if (!this._isTypeVarLive(typeVar)) {
            return types_1.TypeVarType.cloneAsInScopePlaceholder(typeVar, this._usageOffset);
        }
        return typeVar;
    }
    transformParamSpec(paramSpec) {
        if (!this._isTypeVarLive(paramSpec)) {
            return convertTypeToParamSpecValue(types_1.TypeVarType.cloneAsInScopePlaceholder(paramSpec, this._usageOffset));
        }
        return undefined;
    }
    _isTypeVarLive(typeVar) {
        return this._liveTypeVarScopes.some((scopeId) => typeVar.scopeId === scopeId);
    }
}
class InScopePlaceholderTransformer extends TypeVarTransformer {
    constructor(_signatureContext) {
        super();
        this._signatureContext = _signatureContext;
    }
    transformTypeVar(typeVar) {
        var _a;
        if (typeVar.isInScopePlaceholder) {
            return (_a = this._signatureContext.getTypeVarType(typeVar)) !== null && _a !== void 0 ? _a : typeVar;
        }
        return typeVar;
    }
    transformParamSpec(paramSpec) {
        if (paramSpec.isInScopePlaceholder) {
            return this._signatureContext.getParamSpecType(paramSpec);
        }
        return undefined;
    }
}
function applyInScopePlaceholdersToType(type, signatureContext) {
    // Handle the common case where there are no in-scope placeholders.
    // No more work is required in this case.
    if (!signatureContext.getTypeVars().some((entry) => entry.typeVar.isInScopePlaceholder)) {
        return type;
    }
    const transformer = new InScopePlaceholderTransformer(signatureContext);
    return transformer.apply(type, 0);
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeVarContext.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeVarContext.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * typeVarContext.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Module that records the relationship between type variables (and ParamSpecs)
 * and their types. It is used by the type evaluator to "solve" for the type of
 * each type variable.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeVarContext = exports.TypeVarSignatureContext = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
// The maximum number of signature contexts that can be associated
// with a TypeVarContext. This equates to the number of overloads
// that can be captured by a ParamSpec (or multiple ParamSpecs).
// We should never hit this limit in practice, but there are certain
// pathological cases where we could, and we need to protect against
// this so it doesn't completely exhaust memory. This was previously
// set to 64, but we have seen cases where a library uses in excess
// of 300 overloads on a single function.
const maxSignatureContextCount = 1024;
class TypeVarSignatureContext {
    constructor() {
        this._typeVarMap = new Map();
    }
    clone() {
        const newContext = new TypeVarSignatureContext();
        this._typeVarMap.forEach((value) => {
            newContext.setTypeVarType(value.typeVar, value.narrowBound, value.narrowBoundNoLiterals, value.wideBound);
            if (value.tupleTypes) {
                newContext.setTupleTypeVar(value.typeVar, value.tupleTypes);
            }
        });
        if (this._sourceTypeVarScopeId) {
            this._sourceTypeVarScopeId.forEach((scopeId) => newContext.addSourceTypeVarScopeId(scopeId));
        }
        return newContext;
    }
    isSame(other) {
        if (this._typeVarMap.size !== other._typeVarMap.size) {
            return false;
        }
        function typesMatch(type1, type2) {
            if (!type1 || !type2) {
                return type1 === type2;
            }
            return (0, types_1.isTypeSame)(type1, type2);
        }
        let isSame = true;
        this._typeVarMap.forEach((value, key) => {
            const otherValue = other._typeVarMap.get(key);
            if (!otherValue ||
                !typesMatch(value.narrowBound, otherValue.narrowBound) ||
                !typesMatch(value.wideBound, otherValue.wideBound)) {
                isSame = false;
            }
        });
        return isSame;
    }
    isEmpty() {
        return this._typeVarMap.size === 0;
    }
    // Provides a "score" - a value that values completeness (number
    // of type variables that are assigned) and simplicity.
    getScore() {
        let score = 0;
        // Sum the scores for the defined type vars.
        this._typeVarMap.forEach((value) => {
            // Add 1 to the score for each type variable defined.
            score += 1;
            // Add a fractional amount based on the simplicity of the definition.
            // The more complex, the lower the score. In the spirit of Occam's
            // Razor, we always want to favor simple answers.
            const typeVarType = this.getTypeVarType(value.typeVar);
            score += 1.0 - this._getComplexityScoreForType(typeVarType);
        });
        return score;
    }
    getTypeVarType(reference, useNarrowBoundOnly = false) {
        var _a, _b;
        const entry = this.getTypeVar(reference);
        if (!entry) {
            return undefined;
        }
        if (useNarrowBoundOnly) {
            return entry.narrowBound;
        }
        // Prefer the narrow version with no literals. It will be undefined
        // if the literal type couldn't be widened due to constraints imposed
        // by the wide bound.
        return (_b = (_a = entry.narrowBoundNoLiterals) !== null && _a !== void 0 ? _a : entry.narrowBound) !== null && _b !== void 0 ? _b : entry.wideBound;
    }
    getParamSpecType(reference) {
        const entry = this.getTypeVar(reference);
        if (!(entry === null || entry === void 0 ? void 0 : entry.narrowBound)) {
            return undefined;
        }
        if ((0, types_1.isFunction)(entry.narrowBound)) {
            return entry.narrowBound;
        }
        return undefined;
    }
    setTypeVarType(reference, narrowBound, narrowBoundNoLiterals, wideBound, tupleTypes) {
        const key = types_1.TypeVarType.getNameWithScope(reference);
        this._typeVarMap.set(key, {
            typeVar: reference,
            narrowBound,
            narrowBoundNoLiterals,
            wideBound,
            tupleTypes,
        });
    }
    getTupleTypeVar(reference) {
        var _a;
        return (_a = this.getTypeVar(reference)) === null || _a === void 0 ? void 0 : _a.tupleTypes;
    }
    setTupleTypeVar(reference, types) {
        // Caller should have already assigned a value to this type variable.
        const entry = this.getTypeVar(reference);
        (0, debug_1.assert)(entry);
        entry.tupleTypes = types;
    }
    getTypeVar(reference) {
        const key = types_1.TypeVarType.getNameWithScope(reference);
        return this._typeVarMap.get(key);
    }
    getTypeVars() {
        const entries = [];
        this._typeVarMap.forEach((entry) => {
            entries.push(entry);
        });
        return entries;
    }
    getTypeVarCount() {
        return this._typeVarMap.size;
    }
    getWideTypeBound(reference) {
        const entry = this.getTypeVar(reference);
        if (entry) {
            return entry.wideBound;
        }
        return undefined;
    }
    addSourceTypeVarScopeId(scopeId) {
        if (!this._sourceTypeVarScopeId) {
            this._sourceTypeVarScopeId = new Set();
        }
        this._sourceTypeVarScopeId.add(scopeId);
    }
    hasSourceTypeVarScopeId(scopeId) {
        if (!this._sourceTypeVarScopeId) {
            return false;
        }
        return this._sourceTypeVarScopeId.has(scopeId);
    }
    // Returns a "score" for a type that captures the relative complexity
    // of the type. Scores should all be between 0 and 1 where 0 means
    // very simple and 1 means complex. This is a heuristic, so there's
    // often no objectively correct answer.
    _getComplexityScoreForType(type, recursionCount = 0) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return 1;
        }
        recursionCount++;
        switch (type.category) {
            case 1 /* TypeCategory.Unknown */:
            case 2 /* TypeCategory.Any */:
            case 9 /* TypeCategory.TypeVar */: {
                return 0.5;
            }
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */: {
                // Classes and unions should be preferred over functions,
                // so make this relatively high (more than 0.75).
                return 0.8;
            }
            case 0 /* TypeCategory.Unbound */:
            case 3 /* TypeCategory.Never */:
                return 1.0;
            case 8 /* TypeCategory.Union */: {
                let maxScore = 0;
                // If this union has a very large number of subtypes, don't bother
                // accurately computing the score. Assume a fixed value.
                if (type.subtypes.length < 16) {
                    type.subtypes.forEach((subtype) => {
                        const subtypeScore = this._getComplexityScoreForType(subtype, recursionCount);
                        maxScore = Math.max(maxScore, subtypeScore);
                    });
                }
                else {
                    maxScore = 0.5;
                }
                return maxScore;
            }
            case 6 /* TypeCategory.Class */: {
                return this._getComplexityScoreForClass(type, recursionCount);
            }
        }
        // For all other types, return a score of 0.
        return 0;
    }
    _getComplexityScoreForClass(classType, recursionCount) {
        let typeArgScoreSum = 0;
        let typeArgCount = 0;
        if (classType.tupleTypeArguments) {
            classType.tupleTypeArguments.forEach((typeArg) => {
                typeArgScoreSum += this._getComplexityScoreForType(typeArg.type, recursionCount);
                typeArgCount++;
            });
        }
        else if (classType.typeArguments) {
            classType.typeArguments.forEach((type) => {
                typeArgScoreSum += this._getComplexityScoreForType(type, recursionCount);
                typeArgCount++;
            });
        }
        else if (classType.details.typeParameters) {
            classType.details.typeParameters.forEach((type) => {
                typeArgScoreSum += this._getComplexityScoreForType(types_1.AnyType.create(), recursionCount);
                typeArgCount++;
            });
        }
        const averageTypeArgComplexity = typeArgCount > 0 ? typeArgScoreSum / typeArgCount : 0;
        return 0.5 + averageTypeArgComplexity * 0.25;
    }
}
exports.TypeVarSignatureContext = TypeVarSignatureContext;
class TypeVarContext {
    constructor(solveForScopes) {
        this._isLocked = false;
        this._id = TypeVarContext.nextTypeVarContextId++;
        if (Array.isArray(solveForScopes)) {
            this._solveForScopes = solveForScopes;
        }
        else if (solveForScopes !== undefined) {
            this._solveForScopes = [solveForScopes];
        }
        else {
            this._solveForScopes = undefined;
        }
        this._signatureContexts = [new TypeVarSignatureContext()];
    }
    clone() {
        const newTypeVarMap = new TypeVarContext();
        if (this._solveForScopes) {
            newTypeVarMap._solveForScopes = Array.from(this._solveForScopes);
        }
        newTypeVarMap._signatureContexts = this._signatureContexts.map((context) => context.clone());
        newTypeVarMap._isLocked = this._isLocked;
        return newTypeVarMap;
    }
    cloneWithSignatureSource(typeVarScopeId) {
        const clonedContext = this.clone();
        if (typeVarScopeId) {
            const filteredSignatures = this._signatureContexts.filter((context) => context.hasSourceTypeVarScopeId(typeVarScopeId));
            if (filteredSignatures.length > 0) {
                clonedContext._signatureContexts = filteredSignatures;
            }
            else {
                clonedContext._signatureContexts.forEach((context) => {
                    context.addSourceTypeVarScopeId(typeVarScopeId);
                });
            }
        }
        return clonedContext;
    }
    // Copies a cloned type var context back into this object.
    copyFromClone(clone) {
        this._signatureContexts = clone._signatureContexts.map((context) => context.clone());
        this._isLocked = clone._isLocked;
    }
    // Copy the specified signature contexts into this type var context.
    copySignatureContexts(contexts) {
        (0, debug_1.assert)(contexts.length > 0);
        // Limit the number of signature contexts. There are rare circumstances
        // where this can grow to unbounded numbers and exhaust memory.
        if (contexts.length < maxSignatureContextCount) {
            this._signatureContexts = Array.from(contexts);
        }
    }
    isSame(other) {
        if (other._signatureContexts.length !== this._signatureContexts.length) {
            return false;
        }
        return this._signatureContexts.every((context, index) => context.isSame(other._signatureContexts[index]));
    }
    getId() {
        return this._id;
    }
    // Returns the list of scopes this type var map is "solving".
    getSolveForScopes() {
        return this._solveForScopes;
    }
    hasSolveForScope(scopeId) {
        if (Array.isArray(scopeId)) {
            return scopeId.some((s) => this.hasSolveForScope(s));
        }
        if (scopeId === types_1.InScopePlaceholderScopeId) {
            return true;
        }
        return (scopeId !== undefined &&
            this._solveForScopes !== undefined &&
            this._solveForScopes.some((s) => s === scopeId));
    }
    setSolveForScopes(scopeIds) {
        scopeIds.forEach((scopeId) => {
            this.addSolveForScope(scopeId);
        });
    }
    addSolveForScope(scopeId) {
        if (Array.isArray(scopeId)) {
            scopeId.forEach((s) => this.addSolveForScope(s));
            return;
        }
        if (scopeId !== undefined && !this.hasSolveForScope(scopeId)) {
            if (!this._solveForScopes) {
                this._solveForScopes = [];
            }
            this._solveForScopes.push(scopeId);
        }
    }
    lock() {
        // Locks the type var map, preventing any further changes.
        (0, debug_1.assert)(!this._isLocked);
        this._isLocked = true;
    }
    unlock() {
        // Unlocks the type var map, allowing further changes.
        this._isLocked = false;
    }
    isLocked() {
        return this._isLocked;
    }
    isEmpty() {
        return this._signatureContexts.every((context) => context.isEmpty());
    }
    setTypeVarType(reference, narrowBound, narrowBoundNoLiterals, wideBound, tupleTypes) {
        (0, debug_1.assert)(!this._isLocked);
        return this._signatureContexts.forEach((context) => {
            context.setTypeVarType(reference, narrowBound, narrowBoundNoLiterals, wideBound, tupleTypes);
        });
    }
    setTupleTypeVar(reference, tupleTypes) {
        (0, debug_1.assert)(!this._isLocked);
        return this._signatureContexts.forEach((context) => {
            context.setTupleTypeVar(reference, tupleTypes);
        });
    }
    getScore() {
        let total = 0;
        this._signatureContexts.forEach((context) => {
            total += context.getScore();
        });
        // Return the average score among all signature contexts.
        return total / this._signatureContexts.length;
    }
    getPrimarySignature() {
        return this._signatureContexts[0];
    }
    getSignatureContexts() {
        return this._signatureContexts;
    }
    doForEachSignatureContext(callback) {
        const wasLocked = this.isLocked();
        this.unlock();
        this.getSignatureContexts().forEach((signature, signatureIndex) => {
            callback(signature, signatureIndex);
        });
        if (wasLocked) {
            this.lock();
        }
    }
    getSignatureContext(index) {
        (0, debug_1.assert)(index >= 0 && index < this._signatureContexts.length);
        return this._signatureContexts[index];
    }
    doForEachSignature(callback) {
        this._signatureContexts.forEach((context) => {
            callback(context);
        });
    }
}
exports.TypeVarContext = TypeVarContext;
TypeVarContext.nextTypeVarContextId = 1;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typeWalker.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/typeWalker.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * typeWalker.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A class that walks the parts of a type (e.g. the parameters of a function
 * or the type arguments of a class). It detects and prevents infinite recursion.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeWalker = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
class TypeWalker {
    constructor() {
        this._recursionCount = 0;
        this._isWalkCanceled = false;
        this._hitRecursionLimit = false;
    }
    get isRecursionLimitHit() {
        return this._hitRecursionLimit;
    }
    get isWalkCanceled() {
        return this._isWalkCanceled;
    }
    walk(type) {
        if (this._recursionCount > types_1.maxTypeRecursionCount) {
            this._hitRecursionLimit = true;
            return;
        }
        if (this._isWalkCanceled) {
            return;
        }
        this._recursionCount++;
        if (type.typeAliasInfo) {
            this.visitTypeAlias(type);
        }
        switch (type.category) {
            case 0 /* TypeCategory.Unbound */:
                this.visitUnbound(type);
                break;
            case 2 /* TypeCategory.Any */:
                this.visitAny(type);
                break;
            case 1 /* TypeCategory.Unknown */:
                this.visitUnknown(type);
                break;
            case 3 /* TypeCategory.Never */:
                this.visitNever(type);
                break;
            case 4 /* TypeCategory.Function */:
                this.visitFunction(type);
                break;
            case 5 /* TypeCategory.OverloadedFunction */:
                this.visitOverloadedFunction(type);
                break;
            case 6 /* TypeCategory.Class */:
                this.visitClass(type);
                break;
            case 7 /* TypeCategory.Module */:
                this.visitModule(type);
                break;
            case 8 /* TypeCategory.Union */:
                this.visitUnion(type);
                break;
            case 9 /* TypeCategory.TypeVar */:
                this.visitTypeVar(type);
                break;
            default:
                (0, debug_1.assertNever)(type);
        }
        this._recursionCount--;
    }
    cancelWalk() {
        this._isWalkCanceled = true;
    }
    visitTypeAlias(type) {
        (0, debug_1.assert)(type.typeAliasInfo);
        if (type.typeAliasInfo.typeArguments) {
            for (const typeArg of type.typeAliasInfo.typeArguments) {
                this.walk(typeArg);
                if (this._isWalkCanceled) {
                    break;
                }
            }
        }
    }
    visitUnbound(type) {
        // Nothing to do.
    }
    visitAny(type) {
        // Nothing to do.
    }
    visitUnknown(type) {
        // Nothing to do.
    }
    visitNever(type) {
        // Nothing to do.
    }
    visitFunction(type) {
        var _a;
        for (let i = 0; i < type.details.parameters.length; i++) {
            // Ignore parameters such as "*" that have no name.
            if (type.details.parameters[i].name) {
                const paramType = types_1.FunctionType.getEffectiveParameterType(type, i);
                this.walk(paramType);
                if (this._isWalkCanceled) {
                    break;
                }
            }
        }
        if (!this._isWalkCanceled && !types_1.FunctionType.isParamSpecValue(type) && !types_1.FunctionType.isParamSpecValue(type)) {
            const returnType = (_a = type.details.declaredReturnType) !== null && _a !== void 0 ? _a : type.inferredReturnType;
            if (returnType) {
                this.walk(returnType);
            }
        }
    }
    visitOverloadedFunction(type) {
        for (const overload of type.overloads) {
            this.walk(overload);
            if (this._isWalkCanceled) {
                break;
            }
        }
    }
    visitClass(type) {
        var _a;
        if (!types_1.ClassType.isPseudoGenericClass(type)) {
            const typeArgs = ((_a = type.tupleTypeArguments) === null || _a === void 0 ? void 0 : _a.map((t) => t.type)) || type.typeArguments;
            if (typeArgs) {
                for (const argType of typeArgs) {
                    this.walk(argType);
                    if (this._isWalkCanceled) {
                        break;
                    }
                }
            }
        }
    }
    visitModule(type) {
        // Nothing to do.
    }
    visitUnion(type) {
        for (const subtype of type.subtypes) {
            this.walk(subtype);
            if (this._isWalkCanceled) {
                break;
            }
        }
    }
    visitTypeVar(type) {
        // Nothing to do.
    }
}
exports.TypeWalker = TypeWalker;


/***/ }),

/***/ "../pyright-internal/src/analyzer/typedDicts.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/analyzer/typedDicts.ts ***!
  \******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * typedDicts.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides special-case logic for the construction of TypedDict
 * classes.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.narrowForKeyAssignment = exports.getTypeOfIndexedTypedDict = exports.assignToTypedDict = exports.assignTypedDictToTypedDict = exports.getEffectiveExtraItemsEntryType = exports.getTypedDictDictEquivalent = exports.getTypedDictMappingEquivalent = exports.getTypedDictMembersForClass = exports.synthesizeTypedDictClassMethods = exports.createTypedDictTypeInlined = exports.createTypedDictType = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticRules_1 = __webpack_require__(/*! ../common/diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ./analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const ParseTreeUtils = __importStar(__webpack_require__(/*! ./parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const symbol_1 = __webpack_require__(/*! ./symbol */ "../pyright-internal/src/analyzer/symbol.ts");
const symbolUtils_1 = __webpack_require__(/*! ./symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const types_1 = __webpack_require__(/*! ./types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ./typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const typeVarContext_1 = __webpack_require__(/*! ./typeVarContext */ "../pyright-internal/src/analyzer/typeVarContext.ts");
// Creates a new custom TypedDict "alternate syntax" factory class.
function createTypedDictType(evaluator, errorNode, typedDictClass, argList) {
    var _a, _b, _c;
    const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode);
    // TypedDict supports two different syntaxes:
    // Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
    // Point2D = TypedDict('Point2D', x=int, y=int, label=str)
    let className;
    if (argList.length === 0) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.typedDictFirstArg(), errorNode);
    }
    else {
        const nameArg = argList[0];
        if (nameArg.argumentCategory !== 0 /* ArgumentCategory.Simple */ ||
            !nameArg.valueExpression ||
            nameArg.valueExpression.nodeType !== 48 /* ParseNodeType.StringList */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.typedDictFirstArg(), argList[0].valueExpression || errorNode);
        }
        else {
            className = nameArg.valueExpression.strings.map((s) => s.value).join('');
        }
    }
    const effectiveClassName = className || 'TypedDict';
    const classType = types_1.ClassType.createInstantiable(effectiveClassName, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, effectiveClassName), fileInfo.moduleName, fileInfo.fileUri, 128 /* ClassTypeFlags.TypedDictClass */ | 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */, ParseTreeUtils.getTypeSourceId(errorNode), 
    /* declaredMetaclass */ undefined, typedDictClass.details.effectiveMetaclass);
    classType.details.baseClasses.push(typedDictClass);
    (0, typeUtils_1.computeMroLinearization)(classType);
    const classFields = types_1.ClassType.getSymbolTable(classType);
    classFields.set('__class__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */ | 64 /* SymbolFlags.IgnoredForProtocolMatch */, classType));
    let usingDictSyntax = false;
    if (argList.length < 2) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.typedDictSecondArgDict(), errorNode);
    }
    else {
        const entriesArg = argList[1];
        if (entriesArg.argumentCategory === 0 /* ArgumentCategory.Simple */ &&
            entriesArg.valueExpression &&
            entriesArg.valueExpression.nodeType === 15 /* ParseNodeType.Dictionary */) {
            usingDictSyntax = true;
            getTypedDictFieldsFromDictSyntax(evaluator, entriesArg.valueExpression, classFields, /* isInline */ false);
        }
        else if (entriesArg.name) {
            const entrySet = new Set();
            for (let i = 1; i < argList.length; i++) {
                const entry = argList[i];
                if (!entry.name || !entry.valueExpression) {
                    continue;
                }
                if (entrySet.has(entry.name.value)) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictEntryUnique(), entry.valueExpression);
                    continue;
                }
                // Record names in a map to detect duplicates.
                entrySet.add(entry.name.value);
                const newSymbol = new symbol_1.Symbol(8 /* SymbolFlags.InstanceMember */);
                const declaration = {
                    type: 1 /* DeclarationType.Variable */,
                    node: entry.name,
                    uri: fileInfo.fileUri,
                    typeAnnotationNode: entry.valueExpression,
                    isRuntimeTypeExpression: true,
                    range: (0, positionUtils_1.convertOffsetsToRange)(entry.name.start, textRange_1.TextRange.getEnd(entry.valueExpression), fileInfo.lines),
                    moduleName: fileInfo.moduleName,
                    isInExceptSuite: false,
                };
                newSymbol.addDeclaration(declaration);
                classFields.set(entry.name.value, newSymbol);
            }
        }
        else {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportArgumentType, localize_1.LocMessage.typedDictSecondArgDict(), errorNode);
        }
    }
    if (usingDictSyntax) {
        for (const arg of argList.slice(2)) {
            if (((_a = arg.name) === null || _a === void 0 ? void 0 : _a.value) === 'total' || ((_b = arg.name) === null || _b === void 0 ? void 0 : _b.value) === 'closed') {
                if (!arg.valueExpression ||
                    arg.valueExpression.nodeType !== 11 /* ParseNodeType.Constant */ ||
                    !(arg.valueExpression.constType === 15 /* KeywordType.False */ ||
                        arg.valueExpression.constType === 33 /* KeywordType.True */)) {
                    evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictBoolParam().format({ name: arg.name.value }), arg.valueExpression || errorNode);
                }
                else if (arg.name.value === 'total' && arg.valueExpression.constType === 15 /* KeywordType.False */) {
                    classType.details.flags |= 1024 /* ClassTypeFlags.CanOmitDictValues */;
                }
                else if (arg.name.value === 'closed' && arg.valueExpression.constType === 33 /* KeywordType.True */) {
                    if (AnalyzerNodeInfo.getFileInfo(errorNode).diagnosticRuleSet.enableExperimentalFeatures) {
                        classType.details.flags |=
                            256 /* ClassTypeFlags.TypedDictMarkedClosed */ | 512 /* ClassTypeFlags.TypedDictEffectivelyClosed */;
                    }
                }
            }
            else {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportCallIssue, localize_1.LocMessage.typedDictExtraArgs(), arg.valueExpression || errorNode);
            }
        }
    }
    synthesizeTypedDictClassMethods(evaluator, errorNode, classType);
    // Validate that the assigned variable name is consistent with the provided name.
    if (((_c = errorNode.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 3 /* ParseNodeType.Assignment */ && className) {
        const target = errorNode.parent.leftExpression;
        const typedDictTarget = target.nodeType === 54 /* ParseNodeType.TypeAnnotation */ ? target.valueExpression : target;
        if (typedDictTarget.nodeType === 38 /* ParseNodeType.Name */) {
            if (typedDictTarget.value !== className) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictAssignedName().format({
                    name: className,
                }), typedDictTarget);
            }
        }
    }
    return classType;
}
exports.createTypedDictType = createTypedDictType;
// Creates a new anonymous TypedDict class from an inlined dict[{}] type annotation.
function createTypedDictTypeInlined(evaluator, dictNode, typedDictClass) {
    const fileInfo = AnalyzerNodeInfo.getFileInfo(dictNode);
    const className = '<TypedDict>';
    const classType = types_1.ClassType.createInstantiable(className, ParseTreeUtils.getClassFullName(dictNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, 128 /* ClassTypeFlags.TypedDictClass */, ParseTreeUtils.getTypeSourceId(dictNode), 
    /* declaredMetaclass */ undefined, typedDictClass.details.effectiveMetaclass);
    classType.details.baseClasses.push(typedDictClass);
    (0, typeUtils_1.computeMroLinearization)(classType);
    getTypedDictFieldsFromDictSyntax(evaluator, dictNode, types_1.ClassType.getSymbolTable(classType), /* isInline */ true);
    synthesizeTypedDictClassMethods(evaluator, dictNode, classType);
    return classType;
}
exports.createTypedDictTypeInlined = createTypedDictTypeInlined;
function synthesizeTypedDictClassMethods(evaluator, node, classType) {
    var _a;
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    // Synthesize a __new__ method.
    const newType = types_1.FunctionType.createSynthesizedInstance('__new__', 1 /* FunctionTypeFlags.ConstructorMethod */);
    types_1.FunctionType.addParameter(newType, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'cls',
        type: classType,
        hasDeclaredType: true,
    });
    types_1.FunctionType.addDefaultParameters(newType);
    newType.details.declaredReturnType = types_1.ClassType.cloneAsInstance(classType);
    newType.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    // Synthesize an __init__ method with two overrides.
    const initOverride1 = types_1.FunctionType.createSynthesizedInstance('__init__', 256 /* FunctionTypeFlags.Overloaded */);
    types_1.FunctionType.addParameter(initOverride1, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.ClassType.cloneAsInstance(classType),
        hasDeclaredType: true,
    });
    initOverride1.details.declaredReturnType = evaluator.getNoneType();
    initOverride1.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    // The first parameter must be positional-only.
    types_1.FunctionType.addParameter(initOverride1, {
        category: 0 /* ParameterCategory.Simple */,
        name: '__map',
        type: types_1.ClassType.cloneAsInstance(classType),
        hasDeclaredType: true,
    });
    types_1.FunctionType.addPositionOnlyParameterSeparator(initOverride1);
    // All subsequent parameters must be named, so insert an empty "*".
    types_1.FunctionType.addKeywordOnlyParameterSeparator(initOverride1);
    const initOverride2 = types_1.FunctionType.createSynthesizedInstance('__init__', 256 /* FunctionTypeFlags.Overloaded */);
    types_1.FunctionType.addParameter(initOverride2, {
        category: 0 /* ParameterCategory.Simple */,
        name: 'self',
        type: types_1.ClassType.cloneAsInstance(classType),
        hasDeclaredType: true,
    });
    initOverride2.details.declaredReturnType = evaluator.getNoneType();
    initOverride2.details.constructorTypeVarScopeId = classType.details.typeVarScopeId;
    // All parameters must be named, so insert an empty "*".
    types_1.FunctionType.addKeywordOnlyParameterSeparator(initOverride2);
    const entries = getTypedDictMembersForClass(evaluator, classType);
    const extraEntriesInfo = (_a = entries.extraItems) !== null && _a !== void 0 ? _a : getEffectiveExtraItemsEntryType(evaluator, classType);
    let allEntriesAreReadOnly = entries.knownItems.size > 0;
    entries.knownItems.forEach((entry, name) => {
        types_1.FunctionType.addParameter(initOverride1, {
            category: 0 /* ParameterCategory.Simple */,
            name,
            hasDefault: true,
            type: entry.valueType,
            hasDeclaredType: true,
        });
        types_1.FunctionType.addParameter(initOverride2, {
            category: 0 /* ParameterCategory.Simple */,
            name,
            hasDefault: !entry.isRequired,
            type: entry.valueType,
            hasDeclaredType: true,
        });
        if (!entry.isReadOnly) {
            allEntriesAreReadOnly = false;
        }
    });
    if (entries.extraItems && !(0, types_1.isNever)(entries.extraItems.valueType)) {
        types_1.FunctionType.addParameter(initOverride1, {
            category: 2 /* ParameterCategory.KwargsDict */,
            name: 'kwargs',
            hasDefault: false,
            type: entries.extraItems.valueType,
            hasDeclaredType: true,
        });
        types_1.FunctionType.addParameter(initOverride2, {
            category: 2 /* ParameterCategory.KwargsDict */,
            name: 'kwargs',
            hasDefault: false,
            type: entries.extraItems.valueType,
            hasDeclaredType: true,
        });
    }
    const symbolTable = types_1.ClassType.getSymbolTable(classType);
    const initType = types_1.OverloadedFunctionType.create([initOverride1, initOverride2]);
    symbolTable.set('__init__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, initType));
    symbolTable.set('__new__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, newType));
    const strClass = evaluator.getBuiltInType(node, 'str');
    // Synthesize a "get", pop, and setdefault method for each named entry.
    if ((0, types_1.isInstantiableClass)(strClass)) {
        const selfParam = {
            category: 0 /* ParameterCategory.Simple */,
            name: 'self',
            type: types_1.ClassType.cloneAsInstance(classType),
            hasDeclaredType: true,
        };
        function createDefaultTypeVar(func) {
            let defaultTypeVar = types_1.TypeVarType.createInstance(`__TDefault`);
            defaultTypeVar = types_1.TypeVarType.cloneForScopeId(defaultTypeVar, func.details.typeVarScopeId, classType.details.name, 1 /* TypeVarScopeType.Function */);
            return defaultTypeVar;
        }
        function createGetMethod(keyType, valueType, includeDefault, isEntryRequired = false, defaultTypeMatchesField = false) {
            const getOverload = types_1.FunctionType.createSynthesizedInstance('get', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(getOverload, selfParam);
            getOverload.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node);
            types_1.FunctionType.addParameter(getOverload, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'k',
                type: keyType,
                hasDeclaredType: true,
            });
            if (includeDefault) {
                const defaultTypeVar = createDefaultTypeVar(getOverload);
                let defaultParamType;
                let returnType;
                if (isEntryRequired) {
                    // If the entry is required, the type of the default param doesn't matter
                    // because the type will always come from the value.
                    defaultParamType = types_1.AnyType.create();
                    returnType = valueType;
                }
                else {
                    if (defaultTypeMatchesField) {
                        defaultParamType = valueType;
                    }
                    else {
                        defaultParamType = (0, types_1.combineTypes)([valueType, defaultTypeVar]);
                    }
                    returnType = defaultParamType;
                }
                types_1.FunctionType.addParameter(getOverload, {
                    category: 0 /* ParameterCategory.Simple */,
                    name: 'default',
                    type: defaultParamType,
                    hasDeclaredType: true,
                });
                getOverload.details.declaredReturnType = returnType;
            }
            else {
                getOverload.details.declaredReturnType = isEntryRequired
                    ? valueType
                    : (0, types_1.combineTypes)([valueType, evaluator.getNoneType()]);
            }
            return getOverload;
        }
        function createPopMethods(keyType, valueType, isEntryRequired) {
            const keyParam = {
                category: 0 /* ParameterCategory.Simple */,
                name: 'k',
                type: keyType,
                hasDeclaredType: true,
            };
            const popOverload1 = types_1.FunctionType.createSynthesizedInstance('pop', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(popOverload1, selfParam);
            types_1.FunctionType.addParameter(popOverload1, keyParam);
            popOverload1.details.declaredReturnType = valueType;
            const popOverload2 = types_1.FunctionType.createSynthesizedInstance('pop', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(popOverload2, selfParam);
            types_1.FunctionType.addParameter(popOverload2, keyParam);
            popOverload2.details.typeVarScopeId = ParseTreeUtils.getScopeIdForNode(node);
            const defaultTypeVar = createDefaultTypeVar(popOverload2);
            let defaultParamType;
            let returnType;
            if (isEntryRequired) {
                // If the entry is required, the type of the default param doesn't matter
                // because the type will always come from the value.
                defaultParamType = types_1.AnyType.create();
                returnType = valueType;
            }
            else {
                defaultParamType = (0, types_1.combineTypes)([valueType, defaultTypeVar]);
                returnType = defaultParamType;
            }
            types_1.FunctionType.addParameter(popOverload2, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'default',
                hasDeclaredType: true,
                type: defaultParamType,
                hasDefault: true,
            });
            popOverload2.details.declaredReturnType = returnType;
            return [popOverload1, popOverload2];
        }
        function createSetDefaultMethod(keyType, valueType) {
            const setDefaultOverload = types_1.FunctionType.createSynthesizedInstance('setdefault', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(setDefaultOverload, selfParam);
            types_1.FunctionType.addParameter(setDefaultOverload, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'k',
                hasDeclaredType: true,
                type: keyType,
            });
            types_1.FunctionType.addParameter(setDefaultOverload, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'default',
                hasDeclaredType: true,
                type: valueType,
            });
            setDefaultOverload.details.declaredReturnType = valueType;
            return setDefaultOverload;
        }
        function createDelItemMethod(keyType) {
            const delItemOverload = types_1.FunctionType.createSynthesizedInstance('delitem', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(delItemOverload, selfParam);
            types_1.FunctionType.addParameter(delItemOverload, {
                category: 0 /* ParameterCategory.Simple */,
                name: 'k',
                hasDeclaredType: true,
                type: keyType,
            });
            delItemOverload.details.declaredReturnType = evaluator.getNoneType();
            return delItemOverload;
        }
        function createUpdateMethod() {
            // Overload 1: update(__m: Partial[<writable fields>], /)
            const updateMethod1 = types_1.FunctionType.createSynthesizedInstance('update', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(updateMethod1, selfParam);
            // Overload 2: update(__m: Iterable[tuple[<name>, <type>]], /)
            const updateMethod2 = types_1.FunctionType.createSynthesizedInstance('update', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(updateMethod2, selfParam);
            // Overload 3: update(*, <name>: <type>, ...)
            const updateMethod3 = types_1.FunctionType.createSynthesizedInstance('update', 256 /* FunctionTypeFlags.Overloaded */);
            types_1.FunctionType.addParameter(updateMethod3, selfParam);
            // If all entries are read-only, don't allow updates.
            types_1.FunctionType.addParameter(updateMethod1, {
                category: 0 /* ParameterCategory.Simple */,
                name: '__m',
                hasDeclaredType: true,
                type: allEntriesAreReadOnly
                    ? types_1.NeverType.createNever()
                    : types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneForPartialTypedDict(classType)),
            });
            types_1.FunctionType.addPositionOnlyParameterSeparator(updateMethod1);
            types_1.FunctionType.addKeywordOnlyParameterSeparator(updateMethod3);
            updateMethod1.details.declaredReturnType = evaluator.getNoneType();
            updateMethod2.details.declaredReturnType = evaluator.getNoneType();
            updateMethod3.details.declaredReturnType = evaluator.getNoneType();
            const tuplesToCombine = [];
            const tupleClass = evaluator.getBuiltInType(node, 'tuple');
            entries.knownItems.forEach((entry, name) => {
                if (!entry.isReadOnly) {
                    // For writable entries, add a tuple entry.
                    if (tupleClass && (0, types_1.isInstantiableClass)(tupleClass) && strClass && (0, types_1.isInstantiableClass)(strClass)) {
                        const tupleType = (0, typeUtils_1.specializeTupleClass)(types_1.ClassType.cloneAsInstance(tupleClass), [
                            {
                                type: types_1.ClassType.cloneWithLiteral(types_1.ClassType.cloneAsInstance(strClass), name),
                                isUnbounded: false,
                            },
                            { type: entry.valueType, isUnbounded: false },
                        ]);
                        tuplesToCombine.push(tupleType);
                    }
                    // For writable entries, add a keyword argument.
                    types_1.FunctionType.addParameter(updateMethod3, {
                        category: 0 /* ParameterCategory.Simple */,
                        name,
                        hasDeclaredType: true,
                        hasDefault: true,
                        defaultType: types_1.AnyType.create(/* isEllipsis */ true),
                        type: entry.valueType,
                    });
                }
            });
            const iterableClass = evaluator.getTypingType(node, 'Iterable');
            if (iterableClass && (0, types_1.isInstantiableClass)(iterableClass)) {
                const iterableType = types_1.ClassType.cloneAsInstance(iterableClass);
                types_1.FunctionType.addParameter(updateMethod2, {
                    category: 0 /* ParameterCategory.Simple */,
                    name: '__m',
                    hasDeclaredType: true,
                    type: types_1.ClassType.cloneForSpecialization(iterableType, [(0, types_1.combineTypes)(tuplesToCombine)], 
                    /* isTypeArgumentExplicit */ true),
                });
            }
            types_1.FunctionType.addPositionOnlyParameterSeparator(updateMethod2);
            // Note that the order of method1 and method2 is swapped. This is done so
            // the method1 signature is used in the error message when neither method2
            // or method1 match.
            return types_1.OverloadedFunctionType.create([updateMethod2, updateMethod1, updateMethod3]);
        }
        const getOverloads = [];
        const popOverloads = [];
        const setDefaultOverloads = [];
        entries.knownItems.forEach((entry, name) => {
            const nameLiteralType = types_1.ClassType.cloneAsInstance(types_1.ClassType.cloneWithLiteral(strClass, name));
            getOverloads.push(createGetMethod(nameLiteralType, entry.valueType, /* includeDefault */ false, entry.isRequired));
            getOverloads.push(createGetMethod(nameLiteralType, entry.valueType, 
            /* includeDefault */ true, 
            /* isEntryRequired */ entry.isRequired, 
            /* defaultTypeMatchesField */ entry.isRequired));
            // Add a pop method if the entry is not required.
            if (!entry.isRequired && !entry.isReadOnly) {
                (0, collectionUtils_1.appendArray)(popOverloads, createPopMethods(nameLiteralType, entry.valueType, entry.isRequired));
            }
            if (!entry.isReadOnly) {
                setDefaultOverloads.push(createSetDefaultMethod(nameLiteralType, entry.valueType));
            }
        });
        const strType = types_1.ClassType.cloneAsInstance(strClass);
        // If the class is closed, we can assume that any other keys that
        // are present will return the default parameter value or the extra
        // entries value type.
        if (types_1.ClassType.isTypedDictEffectivelyClosed(classType)) {
            getOverloads.push(createGetMethod(strType, (0, types_1.combineTypes)([extraEntriesInfo.valueType, evaluator.getNoneType()]), 
            /* includeDefault */ false, 
            /* isEntryRequired */ true));
            getOverloads.push(createGetMethod(strType, extraEntriesInfo.valueType, /* includeDefault */ true));
        }
        else {
            // Provide a final `get` overload that handles the general case where
            // the key is a str but the literal value isn't known.
            getOverloads.push(createGetMethod(strType, types_1.AnyType.create(), /* includeDefault */ false));
            getOverloads.push(createGetMethod(strType, types_1.AnyType.create(), /* includeDefault */ true));
        }
        symbolTable.set('get', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.OverloadedFunctionType.create(getOverloads)));
        if (popOverloads.length > 0) {
            symbolTable.set('pop', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.OverloadedFunctionType.create(popOverloads)));
        }
        if (setDefaultOverloads.length > 0) {
            symbolTable.set('setdefault', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, types_1.OverloadedFunctionType.create(setDefaultOverloads)));
        }
        if (!allEntriesAreReadOnly) {
            symbolTable.set('__delitem__', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, createDelItemMethod(strType)));
        }
        symbolTable.set('update', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, createUpdateMethod()));
        // If the TypedDict is closed and all of its entries are NotRequired and
        // not ReadOnly, add a "clear" and "popitem" method.
        const dictValueType = getTypedDictDictEquivalent(evaluator, classType);
        if (dictValueType) {
            const clearMethod = types_1.FunctionType.createSynthesizedInstance('clear');
            types_1.FunctionType.addParameter(clearMethod, selfParam);
            clearMethod.details.declaredReturnType = evaluator.getNoneType();
            symbolTable.set('clear', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, clearMethod));
            const popItemMethod = types_1.FunctionType.createSynthesizedInstance('popitem');
            types_1.FunctionType.addParameter(popItemMethod, selfParam);
            let tupleType = evaluator.getTupleClassType();
            if (tupleType && (0, types_1.isInstantiableClass)(tupleType)) {
                tupleType = (0, typeUtils_1.specializeTupleClass)(types_1.ClassType.cloneAsInstance(tupleType), [
                    { type: strType, isUnbounded: false },
                    { type: dictValueType, isUnbounded: false },
                ], 
                /* isTypeArgumentExplicit */ true);
            }
            else {
                tupleType = types_1.UnknownType.create();
            }
            popItemMethod.details.declaredReturnType = tupleType;
            symbolTable.set('popitem', symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, popItemMethod));
        }
        // If the TypedDict is closed, we can provide a more accurate value type
        // for the "items", "keys" and "values" methods.
        const mappingValueType = getTypedDictMappingEquivalent(evaluator, classType);
        if (mappingValueType) {
            ['items', 'keys', 'values'].forEach((methodName) => {
                const method = types_1.FunctionType.createSynthesizedInstance(methodName);
                types_1.FunctionType.addParameter(method, selfParam);
                const returnTypeClass = evaluator.getTypingType(node, `dict_${methodName}`);
                if (returnTypeClass &&
                    (0, types_1.isInstantiableClass)(returnTypeClass) &&
                    returnTypeClass.details.typeParameters.length === 2) {
                    method.details.declaredReturnType = types_1.ClassType.cloneForSpecialization(types_1.ClassType.cloneAsInstance(returnTypeClass), [strType, mappingValueType], 
                    /* isTypeArgumentExplicit */ true);
                    symbolTable.set(methodName, symbol_1.Symbol.createWithType(4 /* SymbolFlags.ClassMember */, method));
                }
            });
        }
    }
}
exports.synthesizeTypedDictClassMethods = synthesizeTypedDictClassMethods;
function getTypedDictMembersForClass(evaluator, classType, allowNarrowed = false) {
    var _a;
    // Were the entries already calculated and cached?
    if (!classType.details.typedDictEntries) {
        const entries = {
            knownItems: new Map(),
            extraItems: undefined,
        };
        getTypedDictMembersForClassRecursive(evaluator, classType, entries);
        if (types_1.ClassType.isTypedDictMarkedClosed(classType) && !entries.extraItems) {
            entries.extraItems = {
                valueType: types_1.NeverType.createNever(),
                isReadOnly: false,
                isRequired: false,
                isProvided: false,
            };
        }
        // Cache the entries for next time.
        classType.details.typedDictEntries = entries;
    }
    const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(classType);
    // Create a specialized copy of the entries so the caller can mutate them.
    const entries = new Map();
    classType.details.typedDictEntries.knownItems.forEach((value, key) => {
        const tdEntry = { ...value };
        tdEntry.valueType = (0, typeUtils_1.applySolvedTypeVars)(tdEntry.valueType, typeVarContext);
        // If the class is "Partial", make all entries optional and convert all
        // read-only entries to Never.
        if (classType.isTypedDictPartial) {
            tdEntry.isRequired = false;
            if (tdEntry.isReadOnly) {
                tdEntry.valueType = types_1.NeverType.createNever();
            }
            else {
                tdEntry.isReadOnly = true;
            }
        }
        entries.set(key, tdEntry);
    });
    // Apply narrowed types on top of existing entries if present.
    if (allowNarrowed && classType.typedDictNarrowedEntries) {
        classType.typedDictNarrowedEntries.forEach((value, key) => {
            const tdEntry = { ...value };
            tdEntry.valueType = (0, typeUtils_1.applySolvedTypeVars)(tdEntry.valueType, typeVarContext);
            entries.set(key, tdEntry);
        });
    }
    return {
        knownItems: entries,
        extraItems: (_a = classType.details.typedDictEntries) === null || _a === void 0 ? void 0 : _a.extraItems,
    };
}
exports.getTypedDictMembersForClass = getTypedDictMembersForClass;
// If the TypedDict class is consistent with Mapping[str, T] where T
// is some type other than object, it returns T. Otherwise it returns undefined.
function getTypedDictMappingEquivalent(evaluator, classType) {
    (0, debug_1.assert)((0, types_1.isInstantiableClass)(classType));
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    // If the TypedDict class isn't closed, it's just a normal Mapping[str, object].
    if (!types_1.ClassType.isTypedDictEffectivelyClosed(classType)) {
        return undefined;
    }
    const entries = getTypedDictMembersForClass(evaluator, classType);
    const typesToCombine = [];
    entries.knownItems.forEach((entry) => {
        typesToCombine.push(entry.valueType);
    });
    if (entries.extraItems) {
        typesToCombine.push(entries.extraItems.valueType);
    }
    // Is the final value type 'object'?
    const valueType = (0, types_1.combineTypes)(typesToCombine);
    if ((0, types_1.isClassInstance)(valueType) && types_1.ClassType.isBuiltIn(valueType, 'object')) {
        return undefined;
    }
    return valueType;
}
exports.getTypedDictMappingEquivalent = getTypedDictMappingEquivalent;
// If the TypedDict class is consistent with dict[str, T], it returns T.
// Otherwise it returns undefined.
function getTypedDictDictEquivalent(evaluator, classType, recursionCount = 0) {
    (0, debug_1.assert)((0, types_1.isInstantiableClass)(classType));
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    // If the TypedDict class isn't closed, it's not equivalent to a dict.
    if (!types_1.ClassType.isTypedDictEffectivelyClosed(classType)) {
        return undefined;
    }
    const entries = getTypedDictMembersForClass(evaluator, classType);
    // If there is no "extraItems" defined or it is read-only, it's not
    // equivalent to a dict.
    if (!entries.extraItems || entries.extraItems.isReadOnly) {
        return undefined;
    }
    let dictValueType = entries.extraItems.valueType;
    let isEquivalentToDict = true;
    entries.knownItems.forEach((entry) => {
        if (entry.isReadOnly || entry.isRequired) {
            isEquivalentToDict = false;
        }
        dictValueType = (0, types_1.combineTypes)([dictValueType, entry.valueType]);
        if (!evaluator.assignType(dictValueType, entry.valueType, 
        /* diag */ undefined, 
        /* destTypeVarContext */ undefined, 
        /* srcTypeVarContext */ undefined, 1 /* AssignTypeFlags.EnforceInvariance */, recursionCount + 1)) {
            isEquivalentToDict = false;
        }
    });
    if (!isEquivalentToDict) {
        return undefined;
    }
    return dictValueType;
}
exports.getTypedDictDictEquivalent = getTypedDictDictEquivalent;
function getTypedDictFieldsFromDictSyntax(evaluator, entryDict, classFields, isInline) {
    const entrySet = new Set();
    const fileInfo = AnalyzerNodeInfo.getFileInfo(entryDict);
    entryDict.entries.forEach((entry) => {
        if (entry.nodeType !== 17 /* ParseNodeType.DictionaryKeyEntry */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictSecondArgDictEntry(), entry);
            return;
        }
        if (entry.keyExpression.nodeType !== 48 /* ParseNodeType.StringList */) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictEntryName(), entry.keyExpression);
            return;
        }
        const entryName = entry.keyExpression.strings.map((s) => s.value).join('');
        if (!entryName) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictEmptyName(), entry.keyExpression);
            return;
        }
        if (entrySet.has(entryName)) {
            evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typedDictEntryUnique(), entry.keyExpression);
            return;
        }
        // Record names in a set to detect duplicates.
        entrySet.add(entryName);
        const newSymbol = new symbol_1.Symbol(8 /* SymbolFlags.InstanceMember */);
        const declaration = {
            type: 1 /* DeclarationType.Variable */,
            node: entry.keyExpression,
            uri: fileInfo.fileUri,
            typeAnnotationNode: entry.valueExpression,
            isRuntimeTypeExpression: !isInline,
            range: (0, positionUtils_1.convertOffsetsToRange)(entry.keyExpression.start, textRange_1.TextRange.getEnd(entry.keyExpression), fileInfo.lines),
            moduleName: fileInfo.moduleName,
            isInExceptSuite: false,
        };
        newSymbol.addDeclaration(declaration);
        classFields.set(entryName, newSymbol);
    });
    // Set the type in the type cache for the dict node so it doesn't
    // get evaluated again.
    evaluator.setTypeResultForNode(entryDict, { type: types_1.UnknownType.create() });
}
function getTypedDictMembersForClassRecursive(evaluator, classType, entries, recursionCount = 0) {
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    if (recursionCount > types_1.maxTypeRecursionCount) {
        return;
    }
    recursionCount++;
    classType.details.baseClasses.forEach((baseClassType) => {
        if ((0, types_1.isInstantiableClass)(baseClassType) && types_1.ClassType.isTypedDictClass(baseClassType)) {
            const specializedBaseClassType = (0, typeUtils_1.partiallySpecializeType)(baseClassType, classType);
            (0, debug_1.assert)((0, types_1.isClass)(specializedBaseClassType));
            // Recursively gather keys from parent classes. Don't report any errors
            // in these cases because they will be reported within that class.
            getTypedDictMembersForClassRecursive(evaluator, specializedBaseClassType, entries, recursionCount);
        }
    });
    const typeVarContext = (0, typeUtils_1.buildTypeVarContextFromSpecializedClass)(classType);
    // Add any new typed dict entries from this class.
    types_1.ClassType.getSymbolTable(classType).forEach((symbol, name) => {
        if (!symbol.isIgnoredForProtocolMatch()) {
            // Only variables (not functions, classes, etc.) are considered.
            const lastDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
            if (lastDecl && lastDecl.type === 1 /* DeclarationType.Variable */) {
                let valueType = evaluator.getEffectiveTypeOfSymbol(symbol);
                valueType = (0, typeUtils_1.applySolvedTypeVars)(valueType, typeVarContext);
                const allowRequired = !types_1.ClassType.isTypedDictMarkedClosed(classType) || name !== '__extra_items__';
                let isRequired = !types_1.ClassType.isCanOmitDictValues(classType);
                let isReadOnly = false;
                if (isRequiredTypedDictVariable(evaluator, symbol, allowRequired)) {
                    isRequired = true;
                }
                else if (isNotRequiredTypedDictVariable(evaluator, symbol, allowRequired)) {
                    isRequired = false;
                }
                if (isReadOnlyTypedDictVariable(evaluator, symbol)) {
                    isReadOnly = true;
                }
                const tdEntry = {
                    valueType,
                    isReadOnly,
                    isRequired,
                    isProvided: false,
                };
                if (types_1.ClassType.isTypedDictMarkedClosed(classType) && name === '__extra_items__') {
                    tdEntry.isRequired = false;
                    entries.extraItems = tdEntry;
                }
                else {
                    entries.knownItems.set(name, tdEntry);
                }
            }
        }
    });
}
function getEffectiveExtraItemsEntryType(evaluator, classType) {
    var _a;
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    // Missing entries in a non-closed TypedDict class are implicitly typed as
    // ReadOnly[NotRequired[object]].
    if (!types_1.ClassType.isTypedDictMarkedClosed(classType)) {
        return {
            valueType: evaluator.getObjectType(),
            isReadOnly: true,
            isRequired: false,
            isProvided: false,
        };
    }
    if ((_a = classType.details.typedDictEntries) === null || _a === void 0 ? void 0 : _a.extraItems) {
        return classType.details.typedDictEntries.extraItems;
    }
    return {
        valueType: types_1.NeverType.createNever(),
        isReadOnly: true,
        isRequired: false,
        isProvided: false,
    };
}
exports.getEffectiveExtraItemsEntryType = getEffectiveExtraItemsEntryType;
function assignTypedDictToTypedDict(evaluator, destType, srcType, diag, typeVarContext, flags, recursionCount = 0) {
    var _a, _b;
    let typesAreConsistent = true;
    const destEntries = getTypedDictMembersForClass(evaluator, destType);
    const srcEntries = getTypedDictMembersForClass(evaluator, srcType, /* allowNarrowed */ true);
    const extraSrcEntries = (_a = srcEntries.extraItems) !== null && _a !== void 0 ? _a : getEffectiveExtraItemsEntryType(evaluator, srcType);
    destEntries.knownItems.forEach((destEntry, name) => {
        // If we've already determined that the types are inconsistent and
        // the caller isn't interested in detailed diagnostics, skip the remainder.
        if (!typesAreConsistent && !diag) {
            return;
        }
        const srcEntry = srcEntries.knownItems.get(name);
        if (!srcEntry) {
            if (destEntry.isRequired || !destEntry.isReadOnly) {
                diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.typedDictFieldMissing().format({
                    name,
                    type: evaluator.printType(types_1.ClassType.cloneAsInstance(srcType)),
                }));
                typesAreConsistent = false;
            }
            else {
                if ((0, types_1.isClassInstance)(extraSrcEntries.valueType)) {
                    const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                    if (!evaluator.assignType(destEntry.valueType, extraSrcEntries.valueType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
                    /* srcTypeVarContext */ undefined, flags, recursionCount)) {
                        subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberTypeMismatch().format({ name }));
                        typesAreConsistent = false;
                    }
                }
            }
        }
        else {
            if (destEntry.isRequired !== srcEntry.isRequired && !destEntry.isReadOnly) {
                const message = destEntry.isRequired
                    ? localize_1.LocAddendum.typedDictFieldRequired()
                    : localize_1.LocAddendum.typedDictFieldNotRequired();
                diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(message.format({
                    name,
                    type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
                }));
                typesAreConsistent = false;
            }
            if (!destEntry.isReadOnly && srcEntry.isReadOnly) {
                diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.typedDictFieldNotReadOnly().format({
                    name,
                    type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
                }));
                typesAreConsistent = false;
            }
            const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
            if (!evaluator.assignType(destEntry.valueType, srcEntry.valueType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
            /* srcTypeVarContext */ undefined, destEntry.isReadOnly ? flags : flags | 1 /* AssignTypeFlags.EnforceInvariance */, recursionCount)) {
                subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.memberTypeMismatch().format({ name }));
                typesAreConsistent = false;
            }
        }
    });
    // If the types are not consistent and the caller isn't interested
    // in detailed diagnostics, don't do additional work.
    if (!typesAreConsistent && !diag) {
        return false;
    }
    // If the destination TypedDict is closed, check any extra entries in the source
    // TypedDict to ensure that they don't violate the "extra items" type.
    if (types_1.ClassType.isTypedDictEffectivelyClosed(destType)) {
        const extraDestEntries = (_b = destEntries.extraItems) !== null && _b !== void 0 ? _b : getEffectiveExtraItemsEntryType(evaluator, destType);
        srcEntries.knownItems.forEach((srcEntry, name) => {
            // Have we already checked this item in the loop above?
            if (destEntries.knownItems.has(name)) {
                return;
            }
            if (!destEntries.extraItems) {
                const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.typedDictExtraFieldNotAllowed().format({
                    name,
                    type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
                }));
                typesAreConsistent = false;
            }
            else {
                if (srcEntry.isRequired && !destEntries.extraItems.isReadOnly) {
                    diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.typedDictFieldNotRequired().format({
                        name,
                        type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
                    }));
                    typesAreConsistent = false;
                }
                const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
                if (!evaluator.assignType(destEntries.extraItems.valueType, srcEntry.valueType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
                /* srcTypeVarContext */ undefined, destEntries.extraItems.isReadOnly ? flags : flags | 1 /* AssignTypeFlags.EnforceInvariance */, recursionCount)) {
                    subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.typedDictExtraFieldTypeMismatch().format({
                        name,
                        type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
                    }));
                    typesAreConsistent = false;
                }
                else if (!destEntries.extraItems.isReadOnly && srcEntry.isReadOnly) {
                    diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.typedDictFieldNotReadOnly().format({
                        name,
                        type: evaluator.printType(types_1.ClassType.cloneAsInstance(srcType)),
                    }));
                    typesAreConsistent = false;
                }
            }
        });
        const subDiag = diag === null || diag === void 0 ? void 0 : diag.createAddendum();
        if (!evaluator.assignType(extraDestEntries.valueType, extraSrcEntries.valueType, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
        /* srcTypeVarContext */ undefined, extraDestEntries.isReadOnly ? flags : flags | 1 /* AssignTypeFlags.EnforceInvariance */, recursionCount)) {
            subDiag === null || subDiag === void 0 ? void 0 : subDiag.addMessage(localize_1.LocAddendum.typedDictExtraFieldTypeMismatch().format({
                name: '__extra_items__',
                type: evaluator.printType(types_1.ClassType.cloneAsInstance(srcType)),
            }));
            typesAreConsistent = false;
        }
        else if (!extraDestEntries.isReadOnly && extraSrcEntries.isReadOnly) {
            diag === null || diag === void 0 ? void 0 : diag.createAddendum().addMessage(localize_1.LocAddendum.typedDictFieldNotReadOnly().format({
                name: '__extra_items__',
                type: evaluator.printType(types_1.ClassType.cloneAsInstance(destType)),
            }));
            typesAreConsistent = false;
        }
    }
    return typesAreConsistent;
}
exports.assignTypedDictToTypedDict = assignTypedDictToTypedDict;
// Determines whether the specified keys and values can be assigned to
// a typed dictionary class. The caller should have already validated
// that the class is indeed a typed dict. If the types are compatible,
// the typed dict class or a narrowed form of the class is returned.
// Narrowing is possible when not-required keys are provided. If the
// types are not compatible, the function returns undefined.
function assignToTypedDict(evaluator, classType, keyTypes, valueTypes, diagAddendum) {
    (0, debug_1.assert)((0, types_1.isClassInstance)(classType));
    (0, debug_1.assert)(types_1.ClassType.isTypedDictClass(classType));
    (0, debug_1.assert)(keyTypes.length === valueTypes.length);
    let isMatch = true;
    const narrowedEntries = new Map();
    let typeVarContext;
    let genericClassType = classType;
    if (classType.details.typeParameters.length > 0) {
        typeVarContext = new typeVarContext_1.TypeVarContext((0, typeUtils_1.getTypeVarScopeId)(classType));
        // Create a generic (nonspecialized version) of the class.
        if (classType.typeArguments) {
            genericClassType = types_1.ClassType.cloneForSpecialization(classType, 
            /* typeArguments */ undefined, 
            /* isTypeArgumentExplicit */ false);
        }
    }
    const tdEntries = getTypedDictMembersForClass(evaluator, genericClassType);
    keyTypes.forEach((keyTypeResult, index) => {
        const keyType = keyTypeResult.type;
        if (!(0, types_1.isClassInstance)(keyType) || !types_1.ClassType.isBuiltIn(keyType, 'str') || !(0, typeUtils_1.isLiteralType)(keyType)) {
            isMatch = false;
        }
        else {
            const keyValue = keyType.literalValue;
            const symbolEntry = tdEntries.knownItems.get(keyValue);
            if (!symbolEntry) {
                if (tdEntries.extraItems) {
                    const subDiag = diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum();
                    if (!evaluator.assignType(tdEntries.extraItems.valueType, valueTypes[index].type, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
                    /* srcTypeVarContext */ undefined, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */)) {
                        if (subDiag) {
                            subDiag.addMessage(localize_1.LocAddendum.typedDictFieldTypeMismatch().format({
                                name: '__extra_items__',
                                type: evaluator.printType(valueTypes[index].type),
                            }));
                            subDiag.addTextRange(keyTypeResult.node);
                        }
                        isMatch = false;
                    }
                }
                else {
                    // The provided key name doesn't exist.
                    isMatch = false;
                    if (diagAddendum) {
                        const subDiag = diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum();
                        subDiag.addMessage(localize_1.LocAddendum.typedDictFieldUndefined().format({
                            name: keyType.literalValue,
                            type: evaluator.printType(types_1.ClassType.cloneAsInstance(classType)),
                        }));
                        subDiag.addTextRange(keyTypeResult.node);
                    }
                }
            }
            else {
                // Can we assign the value to the declared type?
                const subDiag = diagAddendum === null || diagAddendum === void 0 ? void 0 : diagAddendum.createAddendum();
                if (!evaluator.assignType(symbolEntry.valueType, valueTypes[index].type, subDiag === null || subDiag === void 0 ? void 0 : subDiag.createAddendum(), typeVarContext, 
                /* srcTypeVarContext */ undefined, 256 /* AssignTypeFlags.RetainLiteralsForTypeVar */)) {
                    if (subDiag) {
                        subDiag.addMessage(localize_1.LocAddendum.typedDictFieldTypeMismatch().format({
                            name: keyType.literalValue,
                            type: evaluator.printType(valueTypes[index].type),
                        }));
                        subDiag.addTextRange(keyTypeResult.node);
                    }
                    isMatch = false;
                }
                if (!symbolEntry.isRequired) {
                    narrowedEntries.set(keyValue, {
                        valueType: valueTypes[index].type,
                        isReadOnly: !!valueTypes[index].isReadOnly,
                        isRequired: false,
                        isProvided: true,
                    });
                }
                symbolEntry.isProvided = true;
            }
        }
    });
    if (!isMatch) {
        return undefined;
    }
    // See if any required keys are missing.
    tdEntries.knownItems.forEach((entry, name) => {
        if (entry.isRequired && !entry.isProvided) {
            if (diagAddendum) {
                diagAddendum.addMessage(localize_1.LocAddendum.typedDictFieldRequired().format({
                    name,
                    type: evaluator.printType(classType),
                }));
            }
            isMatch = false;
        }
    });
    if (!isMatch) {
        return undefined;
    }
    const specializedClassType = typeVarContext
        ? (0, typeUtils_1.applySolvedTypeVars)(genericClassType, typeVarContext)
        : classType;
    return narrowedEntries.size === 0
        ? specializedClassType
        : types_1.ClassType.cloneForNarrowedTypedDictEntries(specializedClassType, narrowedEntries);
}
exports.assignToTypedDict = assignToTypedDict;
function getTypeOfIndexedTypedDict(evaluator, node, baseType, usage) {
    if (node.items.length !== 1) {
        evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.typeArgsMismatchOne().format({ received: node.items.length }), node);
        return { type: types_1.UnknownType.create() };
    }
    // Look for subscript types that are not supported by TypedDict.
    if (node.trailingComma || node.items[0].name || node.items[0].argumentCategory !== 0 /* ArgumentCategory.Simple */) {
        return undefined;
    }
    const entries = getTypedDictMembersForClass(evaluator, baseType, /* allowNarrowed */ usage.method === 'get');
    const indexTypeResult = evaluator.getTypeOfExpression(node.items[0].valueExpression);
    const indexType = indexTypeResult.type;
    let diag = new diagnostic_1.DiagnosticAddendum();
    let allDiagsInvolveNotRequiredKeys = true;
    const resultingType = (0, typeUtils_1.mapSubtypes)(indexType, (subtype) => {
        var _a, _b, _c;
        if ((0, types_1.isAnyOrUnknown)(subtype)) {
            return subtype;
        }
        if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isBuiltIn(subtype, 'str')) {
            if (subtype.literalValue === undefined) {
                // If it's a plain str with no literal value, we can't
                // make any determination about the resulting type.
                return types_1.UnknownType.create();
            }
            // Look up the entry in the typed dict to get its type.
            const entryName = subtype.literalValue;
            const entry = (_a = entries.knownItems.get(entryName)) !== null && _a !== void 0 ? _a : entries.extraItems;
            if (!entry) {
                diag.addMessage(localize_1.LocAddendum.keyUndefined().format({
                    name: entryName,
                    type: evaluator.printType(baseType),
                }));
                allDiagsInvolveNotRequiredKeys = false;
                return types_1.UnknownType.create();
            }
            else if (!(entry.isRequired || entry.isProvided) && usage.method === 'get') {
                if (!ParseTreeUtils.isWithinTryBlock(node, /* treatWithAsTryBlock */ true)) {
                    diag.addMessage(localize_1.LocAddendum.keyNotRequired().format({
                        name: entryName,
                        type: evaluator.printType(baseType),
                    }));
                }
            }
            else if (entry.isReadOnly && usage.method !== 'get') {
                diag.addMessage(localize_1.LocAddendum.keyReadOnly().format({
                    name: entryName,
                    type: evaluator.printType(baseType),
                }));
            }
            if (usage.method === 'set') {
                if (!evaluator.assignType(entry.valueType, (_c = (_b = usage.setType) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : types_1.AnyType.create(), diag)) {
                    allDiagsInvolveNotRequiredKeys = false;
                }
            }
            else if (usage.method === 'del' && entry.isRequired) {
                diag.addMessage(localize_1.LocAddendum.keyRequiredDeleted().format({
                    name: entryName,
                }));
                allDiagsInvolveNotRequiredKeys = false;
            }
            return entry.valueType;
        }
        diag.addMessage(localize_1.LocAddendum.typeNotStringLiteral().format({ type: evaluator.printType(subtype) }));
        allDiagsInvolveNotRequiredKeys = false;
        return types_1.UnknownType.create();
    });
    // If we have an "expected type" diagnostic addendum (used for assignments),
    // use that rather than the local diagnostic information because it will
    // be more informative.
    if (usage.setExpectedTypeDiag && !diag.isEmpty() && !usage.setExpectedTypeDiag.isEmpty()) {
        diag = usage.setExpectedTypeDiag;
    }
    if (!diag.isEmpty()) {
        let typedDictDiag;
        if (usage.method === 'set') {
            typedDictDiag = localize_1.LocMessage.typedDictSet();
        }
        else if (usage.method === 'del') {
            typedDictDiag = localize_1.LocMessage.typedDictDelete();
        }
        else {
            typedDictDiag = localize_1.LocMessage.typedDictAccess();
        }
        evaluator.addDiagnostic(allDiagsInvolveNotRequiredKeys
            ? diagnosticRules_1.DiagnosticRule.reportTypedDictNotRequiredAccess
            : diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, typedDictDiag + diag.getString(), node);
    }
    return { type: resultingType, isIncomplete: !!indexTypeResult.isIncomplete };
}
exports.getTypeOfIndexedTypedDict = getTypeOfIndexedTypedDict;
// If the specified type has a non-required key, this method marks the
// key as present.
function narrowForKeyAssignment(classType, key) {
    var _a;
    // We should never be called if the classType is not a TypedDict or if typedDictEntries
    // is empty, but this can theoretically happen in the presence of certain circular
    // dependencies.
    if (!types_1.ClassType.isTypedDictClass(classType) || !classType.details.typedDictEntries) {
        return classType;
    }
    const tdEntry = classType.details.typedDictEntries.knownItems.get(key);
    if (!tdEntry || tdEntry.isRequired) {
        return classType;
    }
    const narrowedTdEntry = (_a = classType.typedDictNarrowedEntries) === null || _a === void 0 ? void 0 : _a.get(key);
    if (narrowedTdEntry === null || narrowedTdEntry === void 0 ? void 0 : narrowedTdEntry.isProvided) {
        return classType;
    }
    const narrowedEntries = classType.typedDictNarrowedEntries
        ? new Map(classType.typedDictNarrowedEntries)
        : new Map();
    narrowedEntries.set(key, {
        isProvided: true,
        isRequired: false,
        isReadOnly: tdEntry.isReadOnly,
        valueType: tdEntry.valueType,
    });
    return types_1.ClassType.cloneForNarrowedTypedDictEntries(classType, narrowedEntries);
}
exports.narrowForKeyAssignment = narrowForKeyAssignment;
function isRequiredTypedDictVariable(evaluator, symbol, allowRequired) {
    return symbol.getDeclarations().some((decl) => {
        if (decl.type !== 1 /* DeclarationType.Variable */ || !decl.typeAnnotationNode) {
            return false;
        }
        const annotatedType = evaluator.getTypeOfExpressionExpectingType(decl.typeAnnotationNode, {
            allowFinal: true,
            allowRequired: true,
        });
        if (!allowRequired) {
            if (annotatedType.isRequired) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.requiredNotInTypedDict(), decl.typeAnnotationNode);
            }
            return false;
        }
        return !!annotatedType.isRequired;
    });
}
function isNotRequiredTypedDictVariable(evaluator, symbol, allowRequired) {
    return symbol.getDeclarations().some((decl) => {
        if (decl.type !== 1 /* DeclarationType.Variable */ || !decl.typeAnnotationNode) {
            return false;
        }
        const annotatedType = evaluator.getTypeOfExpressionExpectingType(decl.typeAnnotationNode, {
            allowFinal: true,
            allowRequired: true,
        });
        if (!allowRequired) {
            if (annotatedType.isNotRequired) {
                evaluator.addDiagnostic(diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues, localize_1.LocMessage.notRequiredNotInTypedDict(), decl.typeAnnotationNode);
            }
            return false;
        }
        return !!annotatedType.isNotRequired;
    });
}
function isReadOnlyTypedDictVariable(evaluator, symbol) {
    return symbol.getDeclarations().some((decl) => {
        if (decl.type !== 1 /* DeclarationType.Variable */ || !decl.typeAnnotationNode) {
            return false;
        }
        const annotatedType = evaluator.getTypeOfExpressionExpectingType(decl.typeAnnotationNode, {
            allowFinal: true,
            allowRequired: true,
        });
        return !!annotatedType.isReadOnly;
    });
}


/***/ }),

/***/ "../pyright-internal/src/analyzer/types.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/analyzer/types.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * types.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Representation of types used during type analysis within Python.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isSameWithoutLiteralValue = exports.combineTypes = exports.findSubtype = exports.removeFromUnion = exports.removeUnbound = exports.removeUnknownFromUnion = exports.isTypeSame = exports.getTypeAliasInfo = exports.isOverloadedFunction = exports.isFunction = exports.isParamSpec = exports.isUnpacked = exports.isUnpackedClass = exports.isUnpackedVariadicTypeVar = exports.isVariadicTypeVar = exports.isTypeVar = exports.isModule = exports.isClassInstance = exports.isInstantiableClass = exports.isClass = exports.isPossiblyUnbound = exports.isUnion = exports.isUnbound = exports.isAnyOrUnknown = exports.isUnknown = exports.isAny = exports.isNever = exports.TypeVarType = exports.UnionType = exports.TypeCondition = exports.AnyType = exports.NeverType = exports.OverloadedFunctionType = exports.FunctionType = exports.isKeywordOnlySeparator = exports.isPositionOnlySeparator = exports.ClassType = exports.ModuleType = exports.UnknownType = exports.UnboundType = exports.TypeBase = exports.maxTypeRecursionCount = exports.EnumLiteral = exports.InScopePlaceholderScopeId = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
exports.InScopePlaceholderScopeId = '-';
class EnumLiteral {
    constructor(classFullName, className, itemName, itemType) {
        this.classFullName = classFullName;
        this.className = className;
        this.itemName = itemName;
        this.itemType = itemType;
    }
    getName() {
        return `${this.classFullName}.${this.itemName}`;
    }
}
exports.EnumLiteral = EnumLiteral;
// This constant controls the maximum number of nested types (i.e. types
// used as type arguments or parameter types in other types) before we
// give up. This constant was previously set to 32, but there were certain
// pathological recursive types where this resulted in a hang. It was also
// previously lowered to 10, but this caused some legitimate failures in
// code that used numpy. Even at 16, there are some legitimate failures in
// numpy.
exports.maxTypeRecursionCount = 20;
var TypeBase;
(function (TypeBase) {
    function isInstantiable(type) {
        return (type.flags & 1 /* TypeFlags.Instantiable */) !== 0;
    }
    TypeBase.isInstantiable = isInstantiable;
    function isInstance(type) {
        return (type.flags & 2 /* TypeFlags.Instance */) !== 0;
    }
    TypeBase.isInstance = isInstance;
    function isAmbiguous(type) {
        return !!type.isAmbiguous;
    }
    TypeBase.isAmbiguous = isAmbiguous;
    function cloneType(type) {
        const clone = { ...type };
        delete clone.cached;
        return clone;
    }
    TypeBase.cloneType = cloneType;
    function cloneAsSpecialForm(type, specialForm) {
        const clone = { ...type };
        delete clone.cached;
        if (specialForm) {
            clone.specialForm = specialForm;
        }
        else {
            delete clone.specialForm;
        }
        return clone;
    }
    TypeBase.cloneAsSpecialForm = cloneAsSpecialForm;
    function cloneTypeAsInstance(type, cache) {
        (0, debug_1.assert)(TypeBase.isInstantiable(type));
        const newInstance = TypeBase.cloneType(type);
        if (newInstance.instantiableNestingLevel === undefined) {
            newInstance.flags &= ~1 /* TypeFlags.Instantiable */;
            newInstance.flags |= 2 /* TypeFlags.Instance */;
            delete newInstance.instantiableNestingLevel;
        }
        else {
            if (newInstance.instantiableNestingLevel === 1) {
                delete newInstance.instantiableNestingLevel;
            }
            else {
                newInstance.instantiableNestingLevel--;
            }
        }
        // Should we cache it for next time?
        if (cache) {
            if (!type.cached) {
                type.cached = {};
            }
            type.cached.typeBaseInstanceType = newInstance;
        }
        return newInstance;
    }
    TypeBase.cloneTypeAsInstance = cloneTypeAsInstance;
    function cloneTypeAsInstantiable(type, cache) {
        const newInstance = TypeBase.cloneType(type);
        if (TypeBase.isInstance(type)) {
            newInstance.flags &= ~2 /* TypeFlags.Instance */;
            newInstance.flags |= 1 /* TypeFlags.Instantiable */;
        }
        else {
            newInstance.instantiableNestingLevel =
                newInstance.instantiableNestingLevel === undefined ? 1 : newInstance.instantiableNestingLevel;
        }
        // Should we cache it for next time?
        if (cache) {
            if (!type.cached) {
                type.cached = {};
            }
            type.cached.typeBaseInstantiableType = newInstance;
        }
        return newInstance;
    }
    TypeBase.cloneTypeAsInstantiable = cloneTypeAsInstantiable;
    function cloneForTypeAlias(type, name, fullName, moduleName, fileUri, typeVarScopeId, isPep695Syntax, typeParams, typeArgs) {
        const typeClone = cloneType(type);
        typeClone.typeAliasInfo = {
            name,
            fullName,
            moduleName,
            fileUri,
            typeParameters: typeParams,
            typeArguments: typeArgs,
            typeVarScopeId,
            isPep695Syntax,
        };
        return typeClone;
    }
    TypeBase.cloneForTypeAlias = cloneForTypeAlias;
    function cloneForCondition(type, condition) {
        // Handle the common case where there are no conditions. In this case,
        // cloning isn't necessary.
        if (type.condition === undefined && condition === undefined) {
            return type;
        }
        const typeClone = cloneType(type);
        typeClone.condition = condition;
        return typeClone;
    }
    TypeBase.cloneForCondition = cloneForCondition;
    function cloneForAmbiguousType(type) {
        if (type.isAmbiguous) {
            return type;
        }
        const typeClone = cloneType(type);
        typeClone.isAmbiguous = true;
        return typeClone;
    }
    TypeBase.cloneForAmbiguousType = cloneForAmbiguousType;
})(TypeBase || (exports.TypeBase = TypeBase = {}));
var UnboundType;
(function (UnboundType) {
    const _instance = {
        category: 0 /* TypeCategory.Unbound */,
        flags: 1 /* TypeFlags.Instantiable */ | 2 /* TypeFlags.Instance */,
    };
    function create() {
        // All Unbound objects are the same, so use a shared instance.
        return _instance;
    }
    UnboundType.create = create;
    function convertToInstance(type) {
        // Remove the "special form" if present. Otherwise return the existing type.
        return type.specialForm ? UnboundType.create() : type;
    }
    UnboundType.convertToInstance = convertToInstance;
})(UnboundType || (exports.UnboundType = UnboundType = {}));
var UnknownType;
(function (UnknownType) {
    const _instance = {
        category: 1 /* TypeCategory.Unknown */,
        flags: 1 /* TypeFlags.Instantiable */ | 2 /* TypeFlags.Instance */,
        isIncomplete: false,
    };
    const _incompleteInstance = {
        category: 1 /* TypeCategory.Unknown */,
        flags: 1 /* TypeFlags.Instantiable */ | 2 /* TypeFlags.Instance */,
        isIncomplete: true,
    };
    function create(isIncomplete = false) {
        return isIncomplete ? _incompleteInstance : _instance;
    }
    UnknownType.create = create;
    function createPossibleType(possibleType, isIncomplete) {
        const unknownWithPossibleType = {
            category: 1 /* TypeCategory.Unknown */,
            flags: 1 /* TypeFlags.Instantiable */ | 2 /* TypeFlags.Instance */,
            isIncomplete,
            possibleType,
        };
        return unknownWithPossibleType;
    }
    UnknownType.createPossibleType = createPossibleType;
    function convertToInstance(type) {
        // Remove the "special form" if present. Otherwise return the existing type.
        return type.specialForm ? UnknownType.create(type.isIncomplete) : type;
    }
    UnknownType.convertToInstance = convertToInstance;
})(UnknownType || (exports.UnknownType = UnknownType = {}));
var ModuleType;
(function (ModuleType) {
    function create(moduleName, fileUri, symbolTable) {
        const newModuleType = {
            category: 7 /* TypeCategory.Module */,
            fields: symbolTable || new Map(),
            loaderFields: new Map(),
            flags: 1 /* TypeFlags.Instantiable */ | 1 /* TypeFlags.Instantiable */,
            moduleName,
            fileUri,
        };
        return newModuleType;
    }
    ModuleType.create = create;
    function getField(moduleType, name) {
        // Always look for the symbol in the module's fields before consulting
        // the loader fields. The loader runs before the module, so its values
        // will be overwritten by the module.
        let symbol = moduleType.fields.get(name);
        if (moduleType.loaderFields) {
            if (!symbol) {
                symbol = moduleType.loaderFields.get(name);
            }
            else if (symbol.getDeclarations().length === 1) {
                // If the symbol is hidden when accessed via the module but is
                // also accessible through a loader field, use the latter so it
                // isn't flagged as an error.
                const loaderSymbol = moduleType.loaderFields.get(name);
                if (loaderSymbol && !loaderSymbol.isExternallyHidden()) {
                    symbol = loaderSymbol;
                }
            }
        }
        return symbol;
    }
    ModuleType.getField = getField;
})(ModuleType || (exports.ModuleType = ModuleType = {}));
var ClassType;
(function (ClassType) {
    function createInstantiable(name, fullName, moduleName, fileUri, flags, typeSourceId, declaredMetaclass, effectiveMetaclass, docString) {
        const newClass = {
            category: 6 /* TypeCategory.Class */,
            details: {
                name,
                fullName,
                moduleName,
                fileUri,
                flags,
                typeSourceId,
                baseClasses: [],
                declaredMetaclass,
                effectiveMetaclass,
                mro: [],
                fields: new Map(),
                typeParameters: [],
                docString,
            },
            flags: 1 /* TypeFlags.Instantiable */,
        };
        return newClass;
    }
    ClassType.createInstantiable = createInstantiable;
    function cloneAsInstance(type, includeSubclasses = true) {
        var _a;
        if (TypeBase.isInstance(type)) {
            return type;
        }
        if (includeSubclasses && ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstanceType)) {
            return type.cached.typeBaseInstanceType;
        }
        const newInstance = TypeBase.cloneTypeAsInstance(type, /* cache */ includeSubclasses);
        delete newInstance.specialForm;
        if (includeSubclasses) {
            newInstance.includeSubclasses = true;
        }
        return newInstance;
    }
    ClassType.cloneAsInstance = cloneAsInstance;
    function cloneAsInstantiable(type, includeSubclasses = true) {
        var _a;
        if (includeSubclasses && ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstantiableType)) {
            return type.cached.typeBaseInstantiableType;
        }
        const newInstance = TypeBase.cloneTypeAsInstantiable(type, includeSubclasses);
        if (includeSubclasses) {
            newInstance.includeSubclasses = true;
        }
        return newInstance;
    }
    ClassType.cloneAsInstantiable = cloneAsInstantiable;
    function cloneForSpecialization(classType, typeArguments, isTypeArgumentExplicit, includeSubclasses = false, tupleTypeArguments, isEmptyContainer) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.typeArguments = (typeArguments === null || typeArguments === void 0 ? void 0 : typeArguments.length) === 0 ? undefined : typeArguments;
        newClassType.isTypeArgumentExplicit = isTypeArgumentExplicit;
        if (includeSubclasses) {
            newClassType.includeSubclasses = true;
        }
        newClassType.tupleTypeArguments = tupleTypeArguments
            ? tupleTypeArguments.map((t) => isNever(t.type)
                ? { type: UnknownType.create(), isUnbounded: t.isUnbounded, isOptional: t.isOptional }
                : t)
            : undefined;
        if (isEmptyContainer !== undefined) {
            newClassType.isEmptyContainer = isEmptyContainer;
        }
        return newClassType;
    }
    ClassType.cloneForSpecialization = cloneForSpecialization;
    function cloneIncludeSubclasses(classType, includeSubclasses = true) {
        if (!!classType.includeSubclasses === includeSubclasses) {
            return classType;
        }
        const newClassType = TypeBase.cloneType(classType);
        newClassType.includeSubclasses = includeSubclasses;
        return newClassType;
    }
    ClassType.cloneIncludeSubclasses = cloneIncludeSubclasses;
    function cloneWithLiteral(classType, value) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.literalValue = value;
        // Remove type alias information because the type will no longer match
        // that of the type alias definition if we change the literal type.
        delete newClassType.typeAliasInfo;
        return newClassType;
    }
    ClassType.cloneWithLiteral = cloneWithLiteral;
    function cloneForTypingAlias(classType, aliasName) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.aliasName = aliasName;
        return newClassType;
    }
    ClassType.cloneForTypingAlias = cloneForTypingAlias;
    function cloneForNarrowedTypedDictEntries(classType, narrowedEntries) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.typedDictNarrowedEntries = narrowedEntries;
        return newClassType;
    }
    ClassType.cloneForNarrowedTypedDictEntries = cloneForNarrowedTypedDictEntries;
    function cloneForPartialTypedDict(classType) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.isTypedDictPartial = true;
        return newClassType;
    }
    ClassType.cloneForPartialTypedDict = cloneForPartialTypedDict;
    function cloneRemoveTypePromotions(classType) {
        if (!classType.includePromotions) {
            return classType;
        }
        const newClassType = TypeBase.cloneType(classType);
        delete newClassType.includePromotions;
        return newClassType;
    }
    ClassType.cloneRemoveTypePromotions = cloneRemoveTypePromotions;
    function cloneForTypeGuard(classType, typeGuardType, isStrictTypeGuard) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.typeGuardType = typeGuardType;
        newClassType.isStrictTypeGuard = isStrictTypeGuard;
        return newClassType;
    }
    ClassType.cloneForTypeGuard = cloneForTypeGuard;
    function cloneForSymbolTableUpdate(classType) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.details = { ...newClassType.details };
        newClassType.details.fields = new Map(newClassType.details.fields);
        newClassType.details.mro = Array.from(newClassType.details.mro);
        newClassType.details.mro[0] = cloneAsInstantiable(newClassType);
        return newClassType;
    }
    ClassType.cloneForSymbolTableUpdate = cloneForSymbolTableUpdate;
    function cloneForUnpacked(classType, isUnpacked = true) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.isUnpacked = isUnpacked;
        return newClassType;
    }
    ClassType.cloneForUnpacked = cloneForUnpacked;
    function cloneWithNewFlags(classType, newFlags) {
        const newClassType = TypeBase.cloneType(classType);
        newClassType.details = { ...newClassType.details };
        newClassType.details.flags = newFlags;
        return newClassType;
    }
    ClassType.cloneWithNewFlags = cloneWithNewFlags;
    function isLiteralValueSame(type1, type2) {
        if (type1.literalValue === undefined) {
            return type2.literalValue === undefined;
        }
        else if (type2.literalValue === undefined) {
            return false;
        }
        if (type1.literalValue instanceof EnumLiteral) {
            if (type2.literalValue instanceof EnumLiteral) {
                return type1.literalValue.itemName === type2.literalValue.itemName;
            }
            return false;
        }
        return type1.literalValue === type2.literalValue;
    }
    ClassType.isLiteralValueSame = isLiteralValueSame;
    // Determines whether two typed dict classes are equivalent given
    // that one or both have narrowed entries (i.e. entries that are
    // guaranteed to be present).
    function isTypedDictNarrowedEntriesSame(type1, type2) {
        if (type1.typedDictNarrowedEntries) {
            if (!type2.typedDictNarrowedEntries) {
                return false;
            }
            const tdEntries1 = type1.typedDictNarrowedEntries;
            const tdEntries2 = type2.typedDictNarrowedEntries;
            if (tdEntries1.size !== tdEntries2.size) {
                return false;
            }
            let key;
            let entry1;
            for ([key, entry1] of tdEntries1.entries()) {
                const entry2 = tdEntries2.get(key);
                if (!entry2) {
                    return false;
                }
                if (entry1.isProvided !== entry2.isProvided) {
                    return false;
                }
            }
        }
        else if (type2.typedDictNarrowedEntries) {
            return false;
        }
        return true;
    }
    ClassType.isTypedDictNarrowedEntriesSame = isTypedDictNarrowedEntriesSame;
    // Determines whether typed dict class type1 is a narrower form of type2,
    // i.e. all of the "narrowed entries" found within type2 are also found
    // within type1.
    function isTypedDictNarrower(type1, type2) {
        var _a;
        const tdEntries2 = type2.typedDictNarrowedEntries;
        if (!tdEntries2) {
            return true;
        }
        const tdEntries1 = (_a = type1.typedDictNarrowedEntries) !== null && _a !== void 0 ? _a : new Map();
        let key;
        let entry2;
        for ([key, entry2] of tdEntries2.entries()) {
            if (entry2.isProvided) {
                const entry1 = tdEntries1.get(key);
                if (!(entry1 === null || entry1 === void 0 ? void 0 : entry1.isProvided)) {
                    return false;
                }
            }
        }
        return true;
    }
    ClassType.isTypedDictNarrower = isTypedDictNarrower;
    // Is the class generic but not specialized?
    function isUnspecialized(classType) {
        return classType.details.typeParameters.length > 0 && classType.typeArguments === undefined;
    }
    ClassType.isUnspecialized = isUnspecialized;
    function isSpecialBuiltIn(classType, className) {
        if (!(classType.details.flags & 2 /* ClassTypeFlags.SpecialBuiltIn */) && !classType.aliasName) {
            return false;
        }
        if (className !== undefined) {
            return classType.details.name === className;
        }
        return true;
    }
    ClassType.isSpecialBuiltIn = isSpecialBuiltIn;
    function isBuiltIn(classType, className) {
        if (!(classType.details.flags & 1 /* ClassTypeFlags.BuiltInClass */)) {
            return false;
        }
        if (className !== undefined) {
            const classArray = Array.isArray(className) ? className : [className];
            return (classArray.some((name) => name === classType.details.name) ||
                classArray.some((name) => name === classType.aliasName));
        }
        return true;
    }
    ClassType.isBuiltIn = isBuiltIn;
    function derivesFromAnyOrUnknown(classType) {
        return classType.details.mro.some((mroClass) => !isClass(mroClass));
    }
    ClassType.derivesFromAnyOrUnknown = derivesFromAnyOrUnknown;
    function supportsAbstractMethods(classType) {
        return !!(classType.details.flags & 2048 /* ClassTypeFlags.SupportsAbstractMethods */);
    }
    ClassType.supportsAbstractMethods = supportsAbstractMethods;
    function isDataClass(classType) {
        return !!(classType.details.flags & 4 /* ClassTypeFlags.DataClass */);
    }
    ClassType.isDataClass = isDataClass;
    function isSkipSynthesizedDataClassInit(classType) {
        return !!(classType.details.flags & 16 /* ClassTypeFlags.SkipSynthesizedDataClassInit */);
    }
    ClassType.isSkipSynthesizedDataClassInit = isSkipSynthesizedDataClassInit;
    function isSkipSynthesizedDataClassEq(classType) {
        return !!(classType.details.flags & 32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */);
    }
    ClassType.isSkipSynthesizedDataClassEq = isSkipSynthesizedDataClassEq;
    function isFrozenDataClass(classType) {
        return !!(classType.details.flags & 8 /* ClassTypeFlags.FrozenDataClass */);
    }
    ClassType.isFrozenDataClass = isFrozenDataClass;
    function isSynthesizedDataclassOrder(classType) {
        return !!(classType.details.flags & 64 /* ClassTypeFlags.SynthesizedDataClassOrder */);
    }
    ClassType.isSynthesizedDataclassOrder = isSynthesizedDataclassOrder;
    function isDataClassKeywordOnlyParams(classType) {
        return !!(classType.details.flags & 4194304 /* ClassTypeFlags.DataClassKeywordOnlyParams */);
    }
    ClassType.isDataClassKeywordOnlyParams = isDataClassKeywordOnlyParams;
    function isGeneratedDataClassSlots(classType) {
        return !!(classType.details.flags & 67108864 /* ClassTypeFlags.GenerateDataClassSlots */);
    }
    ClassType.isGeneratedDataClassSlots = isGeneratedDataClassSlots;
    function isSynthesizeDataClassUnsafeHash(classType) {
        return !!(classType.details.flags & 134217728 /* ClassTypeFlags.SynthesizeDataClassUnsafeHash */);
    }
    ClassType.isSynthesizeDataClassUnsafeHash = isSynthesizeDataClassUnsafeHash;
    function isTypeCheckOnly(classType) {
        return !!(classType.details.flags & 268435456 /* ClassTypeFlags.TypeCheckOnly */);
    }
    ClassType.isTypeCheckOnly = isTypeCheckOnly;
    function isNewTypeClass(classType) {
        return !!(classType.details.flags & 536870912 /* ClassTypeFlags.NewTypeClass */);
    }
    ClassType.isNewTypeClass = isNewTypeClass;
    function isValidTypeAliasClass(classType) {
        return !!(classType.details.flags & 1073741824 /* ClassTypeFlags.ValidTypeAliasClass */);
    }
    ClassType.isValidTypeAliasClass = isValidTypeAliasClass;
    function isSpecialFormClass(classType) {
        return !!(classType.details.flags & -2147483648 /* ClassTypeFlags.SpecialFormClass */);
    }
    ClassType.isSpecialFormClass = isSpecialFormClass;
    function isTypedDictClass(classType) {
        return !!(classType.details.flags & 128 /* ClassTypeFlags.TypedDictClass */);
    }
    ClassType.isTypedDictClass = isTypedDictClass;
    function isCanOmitDictValues(classType) {
        return !!(classType.details.flags & 1024 /* ClassTypeFlags.CanOmitDictValues */);
    }
    ClassType.isCanOmitDictValues = isCanOmitDictValues;
    function isTypedDictMarkedClosed(classType) {
        return !!(classType.details.flags & 256 /* ClassTypeFlags.TypedDictMarkedClosed */);
    }
    ClassType.isTypedDictMarkedClosed = isTypedDictMarkedClosed;
    function isTypedDictEffectivelyClosed(classType) {
        return !!(classType.details.flags & 512 /* ClassTypeFlags.TypedDictEffectivelyClosed */);
    }
    ClassType.isTypedDictEffectivelyClosed = isTypedDictEffectivelyClosed;
    function isEnumClass(classType) {
        return !!(classType.details.flags & 2097152 /* ClassTypeFlags.EnumClass */);
    }
    ClassType.isEnumClass = isEnumClass;
    function isPropertyClass(classType) {
        return !!(classType.details.flags & 4096 /* ClassTypeFlags.PropertyClass */);
    }
    ClassType.isPropertyClass = isPropertyClass;
    function isClassProperty(classType) {
        return !!(classType.details.flags & 8388608 /* ClassTypeFlags.ClassProperty */);
    }
    ClassType.isClassProperty = isClassProperty;
    function isFinal(classType) {
        return !!(classType.details.flags & 8192 /* ClassTypeFlags.Final */);
    }
    ClassType.isFinal = isFinal;
    function isProtocolClass(classType) {
        return !!(classType.details.flags & 16384 /* ClassTypeFlags.ProtocolClass */);
    }
    ClassType.isProtocolClass = isProtocolClass;
    function isDefinedInStub(classType) {
        return !!(classType.details.flags & 16777216 /* ClassTypeFlags.DefinedInStub */);
    }
    ClassType.isDefinedInStub = isDefinedInStub;
    function isPseudoGenericClass(classType) {
        return !!(classType.details.flags & 32768 /* ClassTypeFlags.PseudoGenericClass */);
    }
    ClassType.isPseudoGenericClass = isPseudoGenericClass;
    function getDataClassEntries(classType) {
        var _a, _b;
        (_b = (_a = classType.details).synthesizeMethodsDeferred) === null || _b === void 0 ? void 0 : _b.call(_a);
        return classType.details.dataClassEntries || [];
    }
    ClassType.getDataClassEntries = getDataClassEntries;
    function isRuntimeCheckable(classType) {
        return !!(classType.details.flags & 65536 /* ClassTypeFlags.RuntimeCheckable */);
    }
    ClassType.isRuntimeCheckable = isRuntimeCheckable;
    function isTypingExtensionClass(classType) {
        return !!(classType.details.flags & 131072 /* ClassTypeFlags.TypingExtensionClass */);
    }
    ClassType.isTypingExtensionClass = isTypingExtensionClass;
    function isPartiallyEvaluated(classType) {
        return !!(classType.details.flags & 262144 /* ClassTypeFlags.PartiallyEvaluated */);
    }
    ClassType.isPartiallyEvaluated = isPartiallyEvaluated;
    function hasCustomClassGetItem(classType) {
        return !!(classType.details.flags & 524288 /* ClassTypeFlags.HasCustomClassGetItem */);
    }
    ClassType.hasCustomClassGetItem = hasCustomClassGetItem;
    function isTupleClass(classType) {
        return !!(classType.details.flags & 1048576 /* ClassTypeFlags.TupleClass */);
    }
    ClassType.isTupleClass = isTupleClass;
    function isReadOnlyInstanceVariables(classType) {
        return !!(classType.details.flags & 33554432 /* ClassTypeFlags.ReadOnlyInstanceVariables */);
    }
    ClassType.isReadOnlyInstanceVariables = isReadOnlyInstanceVariables;
    function getTypeParameters(classType) {
        return classType.details.typeParameters;
    }
    ClassType.getTypeParameters = getTypeParameters;
    function hasUnknownBaseClass(classType) {
        return classType.details.mro.some((baseClass) => isAnyOrUnknown(baseClass));
    }
    ClassType.hasUnknownBaseClass = hasUnknownBaseClass;
    function getSymbolTable(classType) {
        var _a, _b;
        (_b = (_a = classType.details).synthesizeMethodsDeferred) === null || _b === void 0 ? void 0 : _b.call(_a);
        return classType.details.fields;
    }
    ClassType.getSymbolTable = getSymbolTable;
    function getInheritedSlotsNames(classType) {
        var _a, _b, _c, _d;
        // First synthesize methods if needed. The slots entries
        // can depend on synthesized methods.
        (_b = (_a = classType.details).synthesizeMethodsDeferred) === null || _b === void 0 ? void 0 : _b.call(_a);
        (_d = (_c = classType.details).calculateInheritedSlotsNamesDeferred) === null || _d === void 0 ? void 0 : _d.call(_c);
        return classType.details.inheritedSlotsNamesCached;
    }
    ClassType.getInheritedSlotsNames = getInheritedSlotsNames;
    // Similar to isPartiallyEvaluated except that it also looks at all of the
    // classes in the MRO list for this class to see if any of them are still
    // partially evaluated.
    function isHierarchyPartiallyEvaluated(classType) {
        return (ClassType.isPartiallyEvaluated(classType) ||
            classType.details.mro.some((mroClass) => isClass(mroClass) && ClassType.isPartiallyEvaluated(mroClass)));
    }
    ClassType.isHierarchyPartiallyEvaluated = isHierarchyPartiallyEvaluated;
    // Same as isTypeSame except that it doesn't compare type arguments.
    function isSameGenericClass(classType, type2, recursionCount = 0) {
        if (!classType.isTypedDictPartial !== !type2.isTypedDictPartial) {
            return false;
        }
        const class1Details = classType.details;
        const class2Details = type2.details;
        if (class1Details === class2Details) {
            return true;
        }
        // Compare most of the details fields. We intentionally skip the isAbstractClass
        // flag because it gets set dynamically.
        if (class1Details.fullName !== class2Details.fullName ||
            class1Details.flags !== class2Details.flags ||
            class1Details.typeSourceId !== class2Details.typeSourceId ||
            class1Details.baseClasses.length !== class2Details.baseClasses.length ||
            class1Details.typeParameters.length !== class2Details.typeParameters.length) {
            return false;
        }
        if (recursionCount > exports.maxTypeRecursionCount) {
            return true;
        }
        recursionCount++;
        // Special-case NamedTuple and Tuple classes because we rewrite the base classes
        // in these cases.
        if (ClassType.isBuiltIn(classType, 'NamedTuple') && ClassType.isBuiltIn(type2, 'NamedTuple')) {
            return true;
        }
        if (ClassType.isBuiltIn(classType, 'tuple') && ClassType.isBuiltIn(type2, 'tuple')) {
            return true;
        }
        // Make sure the base classes match.
        for (let i = 0; i < class1Details.baseClasses.length; i++) {
            if (!isTypeSame(class1Details.baseClasses[i], class2Details.baseClasses[i], { ignorePseudoGeneric: true }, recursionCount)) {
                return false;
            }
        }
        if (class1Details.declaredMetaclass || class2Details.declaredMetaclass) {
            if (!class1Details.declaredMetaclass ||
                !class2Details.declaredMetaclass ||
                !isTypeSame(class1Details.declaredMetaclass, class2Details.declaredMetaclass, { ignorePseudoGeneric: true }, recursionCount)) {
                return false;
            }
        }
        for (let i = 0; i < class1Details.typeParameters.length; i++) {
            if (!isTypeSame(class1Details.typeParameters[i], class2Details.typeParameters[i], { ignorePseudoGeneric: true }, recursionCount)) {
                return false;
            }
        }
        return true;
    }
    ClassType.isSameGenericClass = isSameGenericClass;
    // Determines whether this is a subclass (derived class)
    // of the specified class. If the caller passes an empty
    // array to inheritanceChain, it will be filled in by
    // the call to include the chain of inherited classes starting
    // with type2 and ending with this type.
    function isDerivedFrom(subclassType, parentClassType, inheritanceChain) {
        // Is it the exact same class?
        if (isSameGenericClass(subclassType, parentClassType)) {
            if (inheritanceChain) {
                inheritanceChain.push(subclassType);
            }
            return true;
        }
        // Handle built-in types like 'dict' and 'list', which are all
        // subclasses of object even though they are not explicitly declared
        // that way.
        if (isBuiltIn(subclassType) && isBuiltIn(parentClassType, 'object')) {
            if (inheritanceChain) {
                inheritanceChain.push(parentClassType);
            }
            return true;
        }
        // Handle the case where both source and dest are property objects. This
        // special case is needed because we synthesize a new class for each
        // property declaration.
        if (ClassType.isBuiltIn(subclassType, 'property') && ClassType.isBuiltIn(parentClassType, 'property')) {
            if (inheritanceChain) {
                inheritanceChain.push(subclassType);
            }
            return true;
        }
        for (const baseClass of subclassType.details.baseClasses) {
            if (isInstantiableClass(baseClass)) {
                if (isDerivedFrom(baseClass, parentClassType, inheritanceChain)) {
                    if (inheritanceChain) {
                        inheritanceChain.push(subclassType);
                    }
                    return true;
                }
            }
            else if (isAnyOrUnknown(baseClass)) {
                if (inheritanceChain) {
                    inheritanceChain.push(UnknownType.create());
                }
                return true;
            }
        }
        return false;
    }
    ClassType.isDerivedFrom = isDerivedFrom;
    function getReverseMro(classType) {
        return classType.details.mro.slice(0).reverse();
    }
    ClassType.getReverseMro = getReverseMro;
})(ClassType || (exports.ClassType = ClassType = {}));
function isPositionOnlySeparator(param) {
    // A simple parameter with no name is treated as a "/" separator.
    return param.category === 0 /* ParameterCategory.Simple */ && !param.name;
}
exports.isPositionOnlySeparator = isPositionOnlySeparator;
function isKeywordOnlySeparator(param) {
    // An *args parameter with no name is treated as a "*" separator.
    return param.category === 1 /* ParameterCategory.ArgsList */ && !param.name;
}
exports.isKeywordOnlySeparator = isKeywordOnlySeparator;
var FunctionType;
(function (FunctionType) {
    function createInstance(name, fullName, moduleName, functionFlags, docString) {
        return create(name, fullName, moduleName, functionFlags, 2 /* TypeFlags.Instance */, docString);
    }
    FunctionType.createInstance = createInstance;
    function createInstantiable(functionFlags, docString) {
        return create('', '', '', functionFlags, 1 /* TypeFlags.Instantiable */, docString);
    }
    FunctionType.createInstantiable = createInstantiable;
    function createSynthesizedInstance(name, additionalFlags = 0 /* FunctionTypeFlags.None */) {
        return create(name, '', '', additionalFlags | 64 /* FunctionTypeFlags.SynthesizedMethod */, 2 /* TypeFlags.Instance */);
    }
    FunctionType.createSynthesizedInstance = createSynthesizedInstance;
    function create(name, fullName, moduleName, functionFlags, typeFlags, docString) {
        const newFunctionType = {
            category: 4 /* TypeCategory.Function */,
            details: {
                name,
                fullName,
                moduleName,
                flags: functionFlags,
                parameters: [],
                typeParameters: [],
                docString,
            },
            flags: typeFlags,
        };
        return newFunctionType;
    }
    // Creates a deep copy of the function type, including a fresh
    // version of _functionDetails.
    function clone(type, stripFirstParam = false, boundToType, boundTypeVarScopeId) {
        var _a;
        const newFunction = create(type.details.name, type.details.fullName, type.details.moduleName, type.details.flags, type.flags, type.details.docString);
        newFunction.details = { ...type.details };
        newFunction.boundToType = boundToType !== null && boundToType !== void 0 ? boundToType : type.boundToType;
        newFunction.preBoundFlags = newFunction.details.flags;
        if (stripFirstParam) {
            if (type.details.parameters.length > 0) {
                if (type.details.parameters[0].category === 0 /* ParameterCategory.Simple */) {
                    if (type.details.parameters.length > 0 && !type.details.parameters[0].isTypeInferred) {
                        // Stash away the effective type of the first parameter if it
                        // wasn't synthesized.
                        newFunction.strippedFirstParamType = getEffectiveParameterType(type, 0);
                    }
                    newFunction.details.parameters = type.details.parameters.slice(1);
                }
            }
            else {
                stripFirstParam = false;
            }
            // If we strip off the first parameter, this is no longer an
            // instance method or class method.
            newFunction.details.flags &= ~(1 /* FunctionTypeFlags.ConstructorMethod */ | 2 /* FunctionTypeFlags.ClassMethod */);
            newFunction.details.flags |= 4 /* FunctionTypeFlags.StaticMethod */;
        }
        if (type.typeAliasInfo !== undefined) {
            newFunction.typeAliasInfo = type.typeAliasInfo;
        }
        if (type.specializedTypes) {
            newFunction.specializedTypes = {
                parameterTypes: stripFirstParam
                    ? type.specializedTypes.parameterTypes.slice(1)
                    : type.specializedTypes.parameterTypes,
                parameterDefaultArgs: stripFirstParam
                    ? (_a = type.specializedTypes.parameterDefaultArgs) === null || _a === void 0 ? void 0 : _a.slice(1)
                    : type.specializedTypes.parameterDefaultArgs,
                returnType: type.specializedTypes.returnType,
            };
        }
        newFunction.inferredReturnType = type.inferredReturnType;
        newFunction.boundTypeVarScopeId = boundTypeVarScopeId !== null && boundTypeVarScopeId !== void 0 ? boundTypeVarScopeId : type.boundTypeVarScopeId;
        return newFunction;
    }
    FunctionType.clone = clone;
    function cloneAsInstance(type) {
        var _a;
        if ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstanceType) {
            return type.cached.typeBaseInstanceType;
        }
        const newInstance = TypeBase.cloneTypeAsInstance(type, /* cache */ true);
        delete newInstance.specialForm;
        return newInstance;
    }
    FunctionType.cloneAsInstance = cloneAsInstance;
    function cloneAsInstantiable(type) {
        var _a;
        if ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstantiableType) {
            return type.cached.typeBaseInstantiableType;
        }
        const newInstance = TypeBase.cloneTypeAsInstantiable(type, /* cache */ true);
        return newInstance;
    }
    FunctionType.cloneAsInstantiable = cloneAsInstantiable;
    // Creates a shallow copy of the function type with new
    // specialized types. The clone shares the _functionDetails
    // with the object being cloned.
    function cloneForSpecialization(type, specializedTypes, specializedInferredReturnType) {
        const newFunction = create(type.details.name, type.details.fullName, type.details.moduleName, type.details.flags, type.flags, type.details.docString);
        newFunction.details = type.details;
        (0, debug_1.assert)(specializedTypes.parameterTypes.length === type.details.parameters.length);
        if (specializedTypes.parameterDefaultArgs) {
            (0, debug_1.assert)(specializedTypes.parameterDefaultArgs.length === type.details.parameters.length);
        }
        newFunction.specializedTypes = specializedTypes;
        if (specializedInferredReturnType) {
            newFunction.inferredReturnType = specializedInferredReturnType;
        }
        return newFunction;
    }
    FunctionType.cloneForSpecialization = cloneForSpecialization;
    // Creates a new function based on the parameters of another function.
    function cloneForParamSpec(type, paramSpecValue) {
        const newFunction = create(type.details.name, type.details.fullName, type.details.moduleName, type.details.flags, type.flags, type.details.docString);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        newFunction.details.typeParameters = newFunction.details.typeParameters.filter((t) => !newFunction.details.paramSpec || !isTypeSame(t, newFunction.details.paramSpec));
        // The clone should no longer have a parameter specification
        // since we're replacing it.
        delete newFunction.details.paramSpec;
        if (paramSpecValue) {
            const typeParameters = Array.from(type.details.parameters);
            let droppedLastParam = false;
            // If the paramSpec includes a position-only separator
            // and the existing function ends on a position-only separator,
            // we need to remove the latter in favor of the former.
            if (paramSpecValue.details.parameters.some((param) => isPositionOnlySeparator(param))) {
                if (typeParameters.length > 0 && isPositionOnlySeparator(typeParameters[typeParameters.length - 1])) {
                    typeParameters.pop();
                    droppedLastParam = true;
                }
            }
            newFunction.details.parameters = [
                ...typeParameters,
                ...paramSpecValue.details.parameters.map((param) => {
                    return {
                        category: param.category,
                        name: param.name,
                        hasDefault: param.hasDefault,
                        defaultValueExpression: param.defaultValueExpression,
                        isNameSynthesized: param.isNameSynthesized,
                        hasDeclaredType: true,
                        type: param.type,
                    };
                }),
            ];
            if (newFunction.details.docString === undefined) {
                newFunction.details.docString = paramSpecValue.details.docString;
            }
            if (newFunction.details.deprecatedMessage === undefined) {
                newFunction.details.deprecatedMessage = paramSpecValue.details.deprecatedMessage;
            }
            newFunction.details.flags =
                (paramSpecValue.details.flags &
                    (2 /* FunctionTypeFlags.ClassMethod */ |
                        4 /* FunctionTypeFlags.StaticMethod */ |
                        1 /* FunctionTypeFlags.ConstructorMethod */ |
                        256 /* FunctionTypeFlags.Overloaded */ |
                        32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */)) |
                    64 /* FunctionTypeFlags.SynthesizedMethod */;
            if (FunctionType.isParamSpecValue(type)) {
                newFunction.details.flags |= 65536 /* FunctionTypeFlags.ParamSpecValue */;
            }
            // Update the specialized parameter types as well.
            if (type.specializedTypes) {
                newFunction.specializedTypes = {
                    parameterTypes: Array.from(type.specializedTypes.parameterTypes),
                    returnType: type.specializedTypes.returnType,
                };
                if (droppedLastParam) {
                    newFunction.specializedTypes.parameterTypes.pop();
                }
                if (type.specializedTypes.parameterDefaultArgs) {
                    newFunction.specializedTypes.parameterDefaultArgs = Array.from(type.specializedTypes.parameterDefaultArgs);
                    if (droppedLastParam) {
                        newFunction.specializedTypes.parameterDefaultArgs.pop();
                    }
                }
                paramSpecValue.details.parameters.forEach((paramInfo) => {
                    newFunction.specializedTypes.parameterTypes.push(paramInfo.type);
                    if (newFunction.specializedTypes.parameterDefaultArgs) {
                        // Assume that the parameters introduced via paramSpec have no specialized
                        // default arg types. Fall back on the original default arg type in this case.
                        newFunction.specializedTypes.parameterDefaultArgs.push(undefined);
                    }
                });
            }
            FunctionType.addHigherOrderTypeVarScopeIds(newFunction, paramSpecValue.details.typeVarScopeId);
            FunctionType.addHigherOrderTypeVarScopeIds(newFunction, paramSpecValue.details.higherOrderTypeVarScopeIds);
            newFunction.details.paramSpec = paramSpecValue.details.paramSpec;
            newFunction.details.methodClass = paramSpecValue.details.methodClass;
        }
        return newFunction;
    }
    FunctionType.cloneForParamSpec = cloneForParamSpec;
    function cloneWithNewFlags(type, flags) {
        const newFunction = TypeBase.cloneType(type);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        newFunction.details.flags = flags;
        return newFunction;
    }
    FunctionType.cloneWithNewFlags = cloneWithNewFlags;
    function cloneWithNewTypeVarScopeId(type, newScopeId, typeParameters, trackedSignatures) {
        const newFunction = TypeBase.cloneType(type);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        newFunction.details.typeVarScopeId = newScopeId;
        newFunction.details.typeParameters = typeParameters;
        newFunction.trackedSignatures = trackedSignatures;
        FunctionType.addHigherOrderTypeVarScopeIds(newFunction, typeParameters.map((t) => t.scopeId));
        return newFunction;
    }
    FunctionType.cloneWithNewTypeVarScopeId = cloneWithNewTypeVarScopeId;
    function cloneWithDocString(type, docString) {
        const newFunction = TypeBase.cloneType(type);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        newFunction.details.docString = docString;
        return newFunction;
    }
    FunctionType.cloneWithDocString = cloneWithDocString;
    function cloneWithDeprecatedMessage(type, deprecatedMessage) {
        const newFunction = TypeBase.cloneType(type);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        newFunction.details.deprecatedMessage = deprecatedMessage;
        return newFunction;
    }
    FunctionType.cloneWithDeprecatedMessage = cloneWithDeprecatedMessage;
    // Creates a new function based on a solved ParamSpec. The input type is assumed to
    // have a signature that ends in "*args: P.args, **kwargs: P.kwargs". These will be
    // replaced by the parameters in the ParamSpec.
    function cloneForParamSpecApplication(type, paramSpecValue) {
        const newFunction = TypeBase.cloneType(type);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        // Remove the last two parameters, which are the *args and **kwargs.
        newFunction.details.parameters = newFunction.details.parameters.slice(0, newFunction.details.parameters.length - 2);
        if (newFunction.specializedTypes) {
            newFunction.specializedTypes.parameterTypes = newFunction.specializedTypes.parameterTypes.slice(0, newFunction.specializedTypes.parameterTypes.length - 2);
        }
        // Update the flags of the function.
        newFunction.details.flags &= ~32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
        if (paramSpecValue.details.flags & 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */) {
            newFunction.details.flags |= 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */;
        }
        // If there is a position-only separator in the captured param spec signature,
        // remove the position-only separator in the existing signature. Otherwise,
        // we'll end up with redundant position-only separators.
        if (paramSpecValue.details.parameters.some((entry) => isPositionOnlySeparator(entry))) {
            if (newFunction.details.parameters.length > 0) {
                const lastParam = newFunction.details.parameters[newFunction.details.parameters.length - 1];
                if (isPositionOnlySeparator(lastParam)) {
                    newFunction.details.parameters.pop();
                }
            }
        }
        paramSpecValue.details.parameters.forEach((param) => {
            newFunction.details.parameters.push({
                category: param.category,
                name: param.name,
                hasDefault: param.hasDefault,
                defaultValueExpression: param.defaultValueExpression,
                isNameSynthesized: param.isNameSynthesized,
                hasDeclaredType: true,
                type: param.type,
            });
        });
        newFunction.details.paramSpec = paramSpecValue.details.paramSpec;
        if (!newFunction.details.docString) {
            newFunction.details.docString = paramSpecValue.details.docString;
        }
        FunctionType.addHigherOrderTypeVarScopeIds(newFunction, paramSpecValue.details.typeVarScopeId);
        return newFunction;
    }
    FunctionType.cloneForParamSpecApplication = cloneForParamSpecApplication;
    function cloneRemoveParamSpecVariadics(type, paramSpec) {
        const newFunction = create(type.details.name, type.details.fullName, type.details.moduleName, type.details.flags, type.flags, type.details.docString);
        // Make a shallow clone of the details.
        newFunction.details = { ...type.details };
        // Remove the last two parameters, which are the *args and **kwargs.
        newFunction.details.parameters = newFunction.details.parameters.slice(0, newFunction.details.parameters.length - 2);
        if (type.specializedTypes) {
            newFunction.specializedTypes = { ...type.specializedTypes };
            newFunction.specializedTypes.parameterTypes = newFunction.specializedTypes.parameterTypes.slice(0, newFunction.specializedTypes.parameterTypes.length - 2);
            if (newFunction.specializedTypes.parameterDefaultArgs) {
                newFunction.specializedTypes.parameterDefaultArgs =
                    newFunction.specializedTypes.parameterDefaultArgs.slice(0, newFunction.specializedTypes.parameterDefaultArgs.length - 2);
            }
        }
        if (!newFunction.details.paramSpec) {
            newFunction.details.paramSpec = paramSpec;
        }
        if (type.inferredReturnType) {
            newFunction.inferredReturnType = type.inferredReturnType;
        }
        return newFunction;
    }
    FunctionType.cloneRemoveParamSpecVariadics = cloneRemoveParamSpecVariadics;
    function addDefaultParameters(functionType, useUnknown = false) {
        getDefaultParameters(useUnknown).forEach((param) => {
            FunctionType.addParameter(functionType, param);
        });
    }
    FunctionType.addDefaultParameters = addDefaultParameters;
    function addHigherOrderTypeVarScopeIds(functionType, scopeIds) {
        if (!scopeIds) {
            return;
        }
        if (!Array.isArray(scopeIds)) {
            scopeIds = [scopeIds];
        }
        if (!functionType.details.higherOrderTypeVarScopeIds) {
            functionType.details.higherOrderTypeVarScopeIds = [];
        }
        // Add the scope IDs to the function if they're unique.
        scopeIds.forEach((scopeId) => {
            if (!scopeId || scopeId === functionType.details.typeVarScopeId) {
                return;
            }
            if (!functionType.details.higherOrderTypeVarScopeIds.some((id) => id === scopeId)) {
                functionType.details.higherOrderTypeVarScopeIds.push(scopeId);
            }
        });
    }
    FunctionType.addHigherOrderTypeVarScopeIds = addHigherOrderTypeVarScopeIds;
    function getDefaultParameters(useUnknown = false) {
        return [
            {
                category: 1 /* ParameterCategory.ArgsList */,
                name: 'args',
                type: useUnknown ? UnknownType.create() : AnyType.create(),
                hasDeclaredType: !useUnknown,
            },
            {
                category: 2 /* ParameterCategory.KwargsDict */,
                name: 'kwargs',
                type: useUnknown ? UnknownType.create() : AnyType.create(),
                hasDeclaredType: !useUnknown,
            },
        ];
    }
    FunctionType.getDefaultParameters = getDefaultParameters;
    // Indicates whether the input signature consists of (*args: Any, **kwargs: Any).
    function hasDefaultParameters(functionType) {
        let sawArgs = false;
        let sawKwargs = false;
        for (let i = 0; i < functionType.details.parameters.length; i++) {
            const param = functionType.details.parameters[i];
            // Ignore nameless separator parameters.
            if (!param.name) {
                continue;
            }
            if (param.category === 0 /* ParameterCategory.Simple */) {
                return false;
            }
            else if (param.category === 1 /* ParameterCategory.ArgsList */) {
                sawArgs = true;
            }
            else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                sawKwargs = true;
            }
            if (!isAnyOrUnknown(FunctionType.getEffectiveParameterType(functionType, i))) {
                return false;
            }
        }
        return sawArgs && sawKwargs;
    }
    FunctionType.hasDefaultParameters = hasDefaultParameters;
    function isInstanceMethod(type) {
        return ((type.details.flags &
            (1 /* FunctionTypeFlags.ConstructorMethod */ |
                4 /* FunctionTypeFlags.StaticMethod */ |
                2 /* FunctionTypeFlags.ClassMethod */)) ===
            0);
    }
    FunctionType.isInstanceMethod = isInstanceMethod;
    function isConstructorMethod(type) {
        return (type.details.flags & 1 /* FunctionTypeFlags.ConstructorMethod */) !== 0;
    }
    FunctionType.isConstructorMethod = isConstructorMethod;
    function isStaticMethod(type) {
        return (type.details.flags & 4 /* FunctionTypeFlags.StaticMethod */) !== 0;
    }
    FunctionType.isStaticMethod = isStaticMethod;
    function isClassMethod(type) {
        return (type.details.flags & 2 /* FunctionTypeFlags.ClassMethod */) !== 0;
    }
    FunctionType.isClassMethod = isClassMethod;
    function isAbstractMethod(type) {
        return (type.details.flags & 8 /* FunctionTypeFlags.AbstractMethod */) !== 0;
    }
    FunctionType.isAbstractMethod = isAbstractMethod;
    function isGenerator(type) {
        return (type.details.flags & 16 /* FunctionTypeFlags.Generator */) !== 0;
    }
    FunctionType.isGenerator = isGenerator;
    function isSynthesizedMethod(type) {
        return (type.details.flags & 64 /* FunctionTypeFlags.SynthesizedMethod */) !== 0;
    }
    FunctionType.isSynthesizedMethod = isSynthesizedMethod;
    function isTypeCheckOnly(type) {
        return (type.details.flags & 128 /* FunctionTypeFlags.TypeCheckOnly */) !== 0;
    }
    FunctionType.isTypeCheckOnly = isTypeCheckOnly;
    function isOverloaded(type) {
        return (type.details.flags & 256 /* FunctionTypeFlags.Overloaded */) !== 0;
    }
    FunctionType.isOverloaded = isOverloaded;
    function isDefaultParameterCheckDisabled(type) {
        return (type.details.flags & 32 /* FunctionTypeFlags.DisableDefaultChecks */) !== 0;
    }
    FunctionType.isDefaultParameterCheckDisabled = isDefaultParameterCheckDisabled;
    function isAsync(type) {
        return (type.details.flags & 512 /* FunctionTypeFlags.Async */) !== 0;
    }
    FunctionType.isAsync = isAsync;
    function isStubDefinition(type) {
        return (type.details.flags & 2048 /* FunctionTypeFlags.StubDefinition */) !== 0;
    }
    FunctionType.isStubDefinition = isStubDefinition;
    function isPyTypedDefinition(type) {
        return (type.details.flags & 4096 /* FunctionTypeFlags.PyTypedDefinition */) !== 0;
    }
    FunctionType.isPyTypedDefinition = isPyTypedDefinition;
    function isFinal(type) {
        return (type.details.flags & 8192 /* FunctionTypeFlags.Final */) !== 0;
    }
    FunctionType.isFinal = isFinal;
    function hasUnannotatedParams(type) {
        return (type.details.flags & 16384 /* FunctionTypeFlags.UnannotatedParams */) !== 0;
    }
    FunctionType.hasUnannotatedParams = hasUnannotatedParams;
    function shouldSkipArgsKwargsCompatibilityCheck(type) {
        return (type.details.flags & 32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */) !== 0;
    }
    FunctionType.shouldSkipArgsKwargsCompatibilityCheck = shouldSkipArgsKwargsCompatibilityCheck;
    function isParamSpecValue(type) {
        return (type.details.flags & 65536 /* FunctionTypeFlags.ParamSpecValue */) !== 0;
    }
    FunctionType.isParamSpecValue = isParamSpecValue;
    function isPartiallyEvaluated(type) {
        return !!(type.details.flags & 131072 /* FunctionTypeFlags.PartiallyEvaluated */);
    }
    FunctionType.isPartiallyEvaluated = isPartiallyEvaluated;
    function isOverridden(type) {
        return !!(type.details.flags & 262144 /* FunctionTypeFlags.Overridden */);
    }
    FunctionType.isOverridden = isOverridden;
    function getEffectiveParameterType(type, index) {
        (0, debug_1.assert)(index < type.details.parameters.length, 'Parameter types array overflow');
        if (type.specializedTypes && index < type.specializedTypes.parameterTypes.length) {
            return type.specializedTypes.parameterTypes[index];
        }
        return type.details.parameters[index].type;
    }
    FunctionType.getEffectiveParameterType = getEffectiveParameterType;
    function getEffectiveParameterDefaultArgType(type, index) {
        var _a;
        (0, debug_1.assert)(index < type.details.parameters.length, 'Parameter types array overflow');
        if (((_a = type.specializedTypes) === null || _a === void 0 ? void 0 : _a.parameterDefaultArgs) && index < type.specializedTypes.parameterDefaultArgs.length) {
            const defaultArgType = type.specializedTypes.parameterDefaultArgs[index];
            if (defaultArgType) {
                return defaultArgType;
            }
        }
        return type.details.parameters[index].defaultType;
    }
    FunctionType.getEffectiveParameterDefaultArgType = getEffectiveParameterDefaultArgType;
    function addParameter(type, param) {
        type.details.parameters.push(param);
        if (type.specializedTypes) {
            type.specializedTypes.parameterTypes.push(param.type);
        }
    }
    FunctionType.addParameter = addParameter;
    function addPositionOnlyParameterSeparator(type) {
        addParameter(type, {
            category: 0 /* ParameterCategory.Simple */,
            type: AnyType.create(),
        });
    }
    FunctionType.addPositionOnlyParameterSeparator = addPositionOnlyParameterSeparator;
    function addKeywordOnlyParameterSeparator(type) {
        addParameter(type, {
            category: 1 /* ParameterCategory.ArgsList */,
            type: AnyType.create(),
        });
    }
    FunctionType.addKeywordOnlyParameterSeparator = addKeywordOnlyParameterSeparator;
    function getSpecializedReturnType(type, includeInferred = true) {
        var _a;
        if ((_a = type.specializedTypes) === null || _a === void 0 ? void 0 : _a.returnType) {
            return type.specializedTypes.returnType;
        }
        if (type.details.declaredReturnType) {
            return type.details.declaredReturnType;
        }
        if (includeInferred) {
            return type.inferredReturnType;
        }
        return undefined;
    }
    FunctionType.getSpecializedReturnType = getSpecializedReturnType;
})(FunctionType || (exports.FunctionType = FunctionType = {}));
var OverloadedFunctionType;
(function (OverloadedFunctionType) {
    function create(overloads) {
        const newType = {
            category: 5 /* TypeCategory.OverloadedFunction */,
            overloads: [],
            flags: 2 /* TypeFlags.Instance */,
        };
        overloads.forEach((overload) => {
            OverloadedFunctionType.addOverload(newType, overload);
        });
        return newType;
    }
    OverloadedFunctionType.create = create;
    // Adds a new overload or an implementation.
    function addOverload(type, functionType) {
        functionType.overloaded = type;
        type.overloads.push(functionType);
    }
    OverloadedFunctionType.addOverload = addOverload;
    function getOverloads(type) {
        return type.overloads.filter((func) => FunctionType.isOverloaded(func));
    }
    OverloadedFunctionType.getOverloads = getOverloads;
    function getImplementation(type) {
        return type.overloads.find((func) => !FunctionType.isOverloaded(func));
    }
    OverloadedFunctionType.getImplementation = getImplementation;
})(OverloadedFunctionType || (exports.OverloadedFunctionType = OverloadedFunctionType = {}));
var NeverType;
(function (NeverType) {
    const _neverInstance = {
        category: 3 /* TypeCategory.Never */,
        flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
        isNoReturn: false,
    };
    const _noReturnInstance = {
        category: 3 /* TypeCategory.Never */,
        flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
        isNoReturn: true,
    };
    function createNever() {
        return _neverInstance;
    }
    NeverType.createNever = createNever;
    function createNoReturn() {
        return _noReturnInstance;
    }
    NeverType.createNoReturn = createNoReturn;
    function convertToInstance(type) {
        // Remove the "special form" if present. Otherwise return the existing type.
        if (!type.specialForm) {
            return type;
        }
        return type.isNoReturn ? NeverType.createNoReturn() : NeverType.createNever();
    }
    NeverType.convertToInstance = convertToInstance;
})(NeverType || (exports.NeverType = NeverType = {}));
var AnyType;
(function (AnyType) {
    const _anyInstanceSpecialForm = {
        category: 2 /* TypeCategory.Any */,
        isEllipsis: false,
        flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
    };
    const _anyInstance = {
        category: 2 /* TypeCategory.Any */,
        isEllipsis: false,
        flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
    };
    const _ellipsisInstance = {
        category: 2 /* TypeCategory.Any */,
        isEllipsis: true,
        flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
    };
    function create(isEllipsis = false) {
        return isEllipsis ? _ellipsisInstance : _anyInstance;
    }
    AnyType.create = create;
    function createSpecialForm() {
        return _anyInstanceSpecialForm;
    }
    AnyType.createSpecialForm = createSpecialForm;
})(AnyType || (exports.AnyType = AnyType = {}));
(function (AnyType) {
    function convertToInstance(type) {
        // Remove the "special form" if present. Otherwise return the existing type.
        return type.specialForm ? AnyType.create() : type;
    }
    AnyType.convertToInstance = convertToInstance;
})(AnyType || (exports.AnyType = AnyType = {}));
var TypeCondition;
(function (TypeCondition) {
    function combine(conditions1, conditions2) {
        if (!conditions1) {
            return conditions2;
        }
        if (!conditions2) {
            return conditions1;
        }
        // Deduplicate the lists.
        const combined = Array.from(conditions1);
        conditions2.forEach((c1) => {
            if (!combined.some((c2) => _compare(c1, c2) === 0)) {
                combined.push(c1);
            }
        });
        // Always keep the conditions sorted for easier comparison.
        return combined.sort(_compare);
    }
    TypeCondition.combine = combine;
    function _compare(c1, c2) {
        if (c1.typeVar.details.name < c2.typeVar.details.name) {
            return -1;
        }
        else if (c1.typeVar.details.name > c2.typeVar.details.name) {
            return 1;
        }
        if (c1.constraintIndex < c2.constraintIndex) {
            return -1;
        }
        else if (c1.constraintIndex > c2.constraintIndex) {
            return 1;
        }
        return 0;
    }
    function isSame(conditions1, conditions2) {
        if (!conditions1) {
            return !conditions2;
        }
        if (!conditions2 || conditions1.length !== conditions2.length) {
            return false;
        }
        return (conditions1.find((c1, index) => c1.typeVar.nameWithScope !== conditions2[index].typeVar.nameWithScope ||
            c1.constraintIndex !== conditions2[index].constraintIndex) === undefined);
    }
    TypeCondition.isSame = isSame;
    // Determines if the two conditions can be used at the same time. If
    // one constraint list contains a constraint for a type variable, and the
    // same constraint is not in the other constraint list, the two are considered
    // incompatible.
    function isCompatible(conditions1, conditions2) {
        if (!conditions1 || !conditions2) {
            return true;
        }
        for (const c1 of conditions1) {
            let foundTypeVarMatch = false;
            const exactMatch = conditions2.find((c2) => {
                if (c1.typeVar.nameWithScope === c2.typeVar.nameWithScope) {
                    foundTypeVarMatch = true;
                    return c1.constraintIndex === c2.constraintIndex;
                }
                return false;
            });
            if (foundTypeVarMatch && !exactMatch) {
                return false;
            }
        }
        return true;
    }
    TypeCondition.isCompatible = isCompatible;
})(TypeCondition || (exports.TypeCondition = TypeCondition = {}));
var UnionType;
(function (UnionType) {
    function create() {
        const newUnionType = {
            category: 8 /* TypeCategory.Union */,
            subtypes: [],
            literalInstances: {},
            literalClasses: {},
            flags: 2 /* TypeFlags.Instance */ | 1 /* TypeFlags.Instantiable */,
        };
        return newUnionType;
    }
    UnionType.create = create;
    function addType(unionType, newType) {
        // If we're adding a string, integer or enum literal, add it to the
        // corresponding literal map to speed up some operations. It's not
        // uncommon for unions to contain hundreds of literals.
        if (isClass(newType) && newType.literalValue !== undefined && newType.condition === undefined) {
            const literalMaps = isClassInstance(newType) ? unionType.literalInstances : unionType.literalClasses;
            if (ClassType.isBuiltIn(newType, 'str')) {
                if (literalMaps.literalStrMap === undefined) {
                    literalMaps.literalStrMap = new Map();
                }
                literalMaps.literalStrMap.set(newType.literalValue, newType);
            }
            else if (ClassType.isBuiltIn(newType, 'int')) {
                if (literalMaps.literalIntMap === undefined) {
                    literalMaps.literalIntMap = new Map();
                }
                literalMaps.literalIntMap.set(newType.literalValue, newType);
            }
            else if (ClassType.isEnumClass(newType)) {
                if (literalMaps.literalEnumMap === undefined) {
                    literalMaps.literalEnumMap = new Map();
                }
                const enumLiteral = newType.literalValue;
                literalMaps.literalEnumMap.set(enumLiteral.getName(), newType);
            }
        }
        unionType.flags &= newType.flags;
        unionType.subtypes.push(newType);
        if (isTypeVar(newType) && newType.details.recursiveTypeAliasName) {
            // Note that at least one recursive type alias was included in
            // this union. We'll need to expand it before the union is used.
            unionType.includesRecursiveTypeAlias = true;
        }
    }
    UnionType.addType = addType;
    // Determines whether the union contains a specified subtype. If exclusionSet is passed,
    // the method skips any subtype indexes that are in the set and adds a found index to
    // the exclusion set. This speeds up union type comparisons.
    function containsType(unionType, subtype, exclusionSet, recursionCount = 0) {
        // Handle string literals as a special case because unions can sometimes
        // contain hundreds of string literal types.
        if (isClass(subtype) && subtype.condition === undefined && subtype.literalValue !== undefined) {
            const literalMaps = isClassInstance(subtype) ? unionType.literalInstances : unionType.literalClasses;
            if (ClassType.isBuiltIn(subtype, 'str') && literalMaps.literalStrMap !== undefined) {
                return literalMaps.literalStrMap.has(subtype.literalValue);
            }
            else if (ClassType.isBuiltIn(subtype, 'int') && literalMaps.literalIntMap !== undefined) {
                return literalMaps.literalIntMap.has(subtype.literalValue);
            }
            else if (ClassType.isEnumClass(subtype) && literalMaps.literalEnumMap !== undefined) {
                const enumLiteral = subtype.literalValue;
                return literalMaps.literalEnumMap.has(enumLiteral.getName());
            }
        }
        const foundIndex = unionType.subtypes.findIndex((t, i) => {
            if (exclusionSet === null || exclusionSet === void 0 ? void 0 : exclusionSet.has(i)) {
                return false;
            }
            return isTypeSame(t, subtype, {}, recursionCount);
        });
        if (foundIndex < 0) {
            return false;
        }
        exclusionSet === null || exclusionSet === void 0 ? void 0 : exclusionSet.add(foundIndex);
        return true;
    }
    UnionType.containsType = containsType;
    function addTypeAliasSource(unionType, typeAliasSource) {
        if (typeAliasSource.category === 8 /* TypeCategory.Union */) {
            const sourcesToAdd = typeAliasSource.typeAliasInfo ? [typeAliasSource] : typeAliasSource.typeAliasSources;
            if (sourcesToAdd) {
                if (!unionType.typeAliasSources) {
                    unionType.typeAliasSources = new Set();
                }
                sourcesToAdd.forEach((source) => {
                    unionType.typeAliasSources.add(source);
                });
            }
        }
    }
    UnionType.addTypeAliasSource = addTypeAliasSource;
})(UnionType || (exports.UnionType = UnionType = {}));
var TypeVarType;
(function (TypeVarType) {
    function createInstance(name) {
        return create(name, /* isParamSpec */ false, 2 /* TypeFlags.Instance */);
    }
    TypeVarType.createInstance = createInstance;
    function createInstantiable(name, isParamSpec = false) {
        return create(name, isParamSpec, 1 /* TypeFlags.Instantiable */);
    }
    TypeVarType.createInstantiable = createInstantiable;
    function cloneAsInstance(type) {
        var _a;
        (0, debug_1.assert)(TypeBase.isInstantiable(type));
        if ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstanceType) {
            return type.cached.typeBaseInstanceType;
        }
        const newInstance = TypeBase.cloneTypeAsInstance(type, /* cache */ true);
        delete newInstance.specialForm;
        return newInstance;
    }
    TypeVarType.cloneAsInstance = cloneAsInstance;
    function cloneAsInstantiable(type) {
        var _a;
        if ((_a = type.cached) === null || _a === void 0 ? void 0 : _a.typeBaseInstantiableType) {
            return type.cached.typeBaseInstantiableType;
        }
        const newInstance = TypeBase.cloneTypeAsInstantiable(type, /* cache */ true);
        return newInstance;
    }
    TypeVarType.cloneAsInstantiable = cloneAsInstantiable;
    function cloneForNewName(type, name) {
        const newInstance = TypeBase.cloneType(type);
        newInstance.details = { ...type.details };
        newInstance.details.name = name;
        if (newInstance.scopeId) {
            newInstance.nameWithScope = makeNameWithScope(name, newInstance.scopeId);
        }
        return newInstance;
    }
    TypeVarType.cloneForNewName = cloneForNewName;
    function cloneForScopeId(type, scopeId, scopeName, scopeType) {
        const newInstance = TypeBase.cloneType(type);
        newInstance.nameWithScope = makeNameWithScope(type.details.name, scopeId);
        newInstance.scopeId = scopeId;
        newInstance.scopeName = scopeName;
        newInstance.scopeType = scopeType;
        return newInstance;
    }
    TypeVarType.cloneForScopeId = cloneForScopeId;
    function cloneForUnpacked(type, isInUnion = false) {
        (0, debug_1.assert)(type.details.isVariadic);
        const newInstance = TypeBase.cloneType(type);
        newInstance.isVariadicUnpacked = true;
        newInstance.isVariadicInUnion = isInUnion;
        return newInstance;
    }
    TypeVarType.cloneForUnpacked = cloneForUnpacked;
    function cloneForPacked(type) {
        (0, debug_1.assert)(type.details.isVariadic);
        const newInstance = TypeBase.cloneType(type);
        newInstance.isVariadicUnpacked = false;
        newInstance.isVariadicInUnion = false;
        return newInstance;
    }
    TypeVarType.cloneForPacked = cloneForPacked;
    // Creates a "simplified" version of the TypeVar with invariance
    // and no bound or constraints. ParamSpecs and variadics are left
    // unmodified. So are auto-variant type variables.
    function cloneAsInvariant(type) {
        if (type.details.isParamSpec || type.details.isVariadic) {
            return type;
        }
        if (type.details.declaredVariance === 0 /* Variance.Auto */) {
            return type;
        }
        if (type.details.declaredVariance === 2 /* Variance.Invariant */) {
            if (type.details.boundType === undefined && type.details.constraints.length === 0) {
                return type;
            }
        }
        const newInstance = TypeBase.cloneType(type);
        newInstance.details = { ...newInstance.details };
        newInstance.details.declaredVariance = 2 /* Variance.Invariant */;
        newInstance.details.boundType = undefined;
        newInstance.details.constraints = [];
        return newInstance;
    }
    TypeVarType.cloneAsInvariant = cloneAsInvariant;
    function cloneForParamSpecAccess(type, access) {
        const newInstance = TypeBase.cloneType(type);
        newInstance.paramSpecAccess = access;
        return newInstance;
    }
    TypeVarType.cloneForParamSpecAccess = cloneForParamSpecAccess;
    function cloneAsSpecializedSelf(type, specializedBoundType) {
        (0, debug_1.assert)(type.details.isSynthesizedSelf);
        const newInstance = TypeBase.cloneType(type);
        newInstance.details = { ...newInstance.details };
        newInstance.details.boundType = specializedBoundType;
        return newInstance;
    }
    TypeVarType.cloneAsSpecializedSelf = cloneAsSpecializedSelf;
    function cloneAsInScopePlaceholder(type, usageOffset) {
        if (type.isInScopePlaceholder) {
            return type;
        }
        // If the caller specified a usage offset, append it to the TypeVar
        // internal name. This allows us to distinguish it from other uses
        // of the same TypeVar. For example nested calls to a generic
        // function like `foo(foo(1))`.
        let newNameWithScope = type.nameWithScope;
        if (usageOffset) {
            newNameWithScope = `${type.nameWithScope}-${usageOffset}`;
        }
        const newInstance = TypeBase.cloneType(type);
        newInstance.isInScopePlaceholder = true;
        newInstance.scopeId = exports.InScopePlaceholderScopeId;
        newInstance.nameWithScope = newNameWithScope;
        return newInstance;
    }
    TypeVarType.cloneAsInScopePlaceholder = cloneAsInScopePlaceholder;
    function makeNameWithScope(name, scopeId) {
        return `${name}.${scopeId}`;
    }
    TypeVarType.makeNameWithScope = makeNameWithScope;
    function create(name, isParamSpec, typeFlags) {
        const newTypeVarType = {
            category: 9 /* TypeCategory.TypeVar */,
            details: {
                name,
                constraints: [],
                declaredVariance: 2 /* Variance.Invariant */,
                isParamSpec,
                isVariadic: false,
                isSynthesized: false,
                defaultType: UnknownType.create(),
            },
            flags: typeFlags,
        };
        return newTypeVarType;
    }
    function addConstraint(typeVarType, constraintType) {
        typeVarType.details.constraints.push(constraintType);
    }
    TypeVarType.addConstraint = addConstraint;
    function getNameWithScope(typeVarType) {
        // If there is no name with scope, fall back on the (unscoped) name.
        return typeVarType.nameWithScope || typeVarType.details.name;
    }
    TypeVarType.getNameWithScope = getNameWithScope;
    function getReadableName(typeVarType) {
        if (typeVarType.scopeName) {
            return `${typeVarType.details.name}@${typeVarType.scopeName}`;
        }
        return typeVarType.details.name;
    }
    TypeVarType.getReadableName = getReadableName;
    function getVariance(type) {
        var _a;
        const variance = (_a = type.computedVariance) !== null && _a !== void 0 ? _a : type.details.declaredVariance;
        // By this point, the variance should have been inferred.
        (0, debug_1.assert)(variance !== 0 /* Variance.Auto */, 'Expected variance to be inferred');
        // If we're in the process of computing variance, it will still be
        // unknown. Default to covariant in this case.
        if (variance === 1 /* Variance.Unknown */) {
            return 3 /* Variance.Covariant */;
        }
        return variance;
    }
    TypeVarType.getVariance = getVariance;
    // Indicates whether the specified type is a recursive type alias
    // placeholder that has not yet been resolved.
    function isTypeAliasPlaceholder(type) {
        return !!type.details.recursiveTypeAliasName && !type.details.boundType;
    }
    TypeVarType.isTypeAliasPlaceholder = isTypeAliasPlaceholder;
})(TypeVarType || (exports.TypeVarType = TypeVarType = {}));
function isNever(type) {
    return type.category === 3 /* TypeCategory.Never */;
}
exports.isNever = isNever;
function isAny(type) {
    return type.category === 2 /* TypeCategory.Any */;
}
exports.isAny = isAny;
function isUnknown(type) {
    return type.category === 1 /* TypeCategory.Unknown */;
}
exports.isUnknown = isUnknown;
function isAnyOrUnknown(type) {
    if (type.category === 2 /* TypeCategory.Any */ || type.category === 1 /* TypeCategory.Unknown */) {
        return true;
    }
    if (isUnion(type)) {
        return type.subtypes.find((subtype) => !isAnyOrUnknown(subtype)) === undefined;
    }
    return false;
}
exports.isAnyOrUnknown = isAnyOrUnknown;
function isUnbound(type) {
    return type.category === 0 /* TypeCategory.Unbound */;
}
exports.isUnbound = isUnbound;
function isUnion(type) {
    return type.category === 8 /* TypeCategory.Union */;
}
exports.isUnion = isUnion;
function isPossiblyUnbound(type) {
    if (isUnbound(type)) {
        return true;
    }
    if (isUnion(type)) {
        return type.subtypes.find((subtype) => isPossiblyUnbound(subtype)) !== undefined;
    }
    return false;
}
exports.isPossiblyUnbound = isPossiblyUnbound;
function isClass(type) {
    return type.category === 6 /* TypeCategory.Class */;
}
exports.isClass = isClass;
function isInstantiableClass(type) {
    return type.category === 6 /* TypeCategory.Class */ && TypeBase.isInstantiable(type);
}
exports.isInstantiableClass = isInstantiableClass;
function isClassInstance(type) {
    return type.category === 6 /* TypeCategory.Class */ && TypeBase.isInstance(type);
}
exports.isClassInstance = isClassInstance;
function isModule(type) {
    return type.category === 7 /* TypeCategory.Module */;
}
exports.isModule = isModule;
function isTypeVar(type) {
    return type.category === 9 /* TypeCategory.TypeVar */;
}
exports.isTypeVar = isTypeVar;
function isVariadicTypeVar(type) {
    return type.category === 9 /* TypeCategory.TypeVar */ && type.details.isVariadic;
}
exports.isVariadicTypeVar = isVariadicTypeVar;
function isUnpackedVariadicTypeVar(type) {
    return (type.category === 9 /* TypeCategory.TypeVar */ &&
        type.details.isVariadic &&
        !!type.isVariadicUnpacked &&
        !type.isVariadicInUnion);
}
exports.isUnpackedVariadicTypeVar = isUnpackedVariadicTypeVar;
function isUnpackedClass(type) {
    if (!isClass(type) || !type.isUnpacked) {
        return false;
    }
    return true;
}
exports.isUnpackedClass = isUnpackedClass;
function isUnpacked(type) {
    return isUnpackedVariadicTypeVar(type) || isUnpackedClass(type);
}
exports.isUnpacked = isUnpacked;
function isParamSpec(type) {
    return type.category === 9 /* TypeCategory.TypeVar */ && type.details.isParamSpec;
}
exports.isParamSpec = isParamSpec;
function isFunction(type) {
    return type.category === 4 /* TypeCategory.Function */;
}
exports.isFunction = isFunction;
function isOverloadedFunction(type) {
    return type.category === 5 /* TypeCategory.OverloadedFunction */;
}
exports.isOverloadedFunction = isOverloadedFunction;
function getTypeAliasInfo(type) {
    if (type.typeAliasInfo) {
        return type.typeAliasInfo;
    }
    if (isTypeVar(type) &&
        type.details.recursiveTypeAliasName &&
        type.details.boundType &&
        type.details.boundType.typeAliasInfo) {
        return type.details.boundType.typeAliasInfo;
    }
    return undefined;
}
exports.getTypeAliasInfo = getTypeAliasInfo;
// Determines whether two types are the same. If ignorePseudoGeneric is true,
// type arguments for "pseudo-generic" classes (non-generic classes whose init
// methods are not annotated and are therefore treated as generic) are ignored.
function isTypeSame(type1, type2, options = {}, recursionCount = 0) {
    var _a, _b;
    if (type1 === type2) {
        return true;
    }
    if (type1.category !== type2.category) {
        if (options.treatAnySameAsUnknown) {
            if (type1.category === 2 /* TypeCategory.Any */ && type2.category === 1 /* TypeCategory.Unknown */) {
                return true;
            }
            if (type1.category === 1 /* TypeCategory.Unknown */ && type2.category === 2 /* TypeCategory.Any */) {
                return true;
            }
        }
        return false;
    }
    if (!options.ignoreTypeFlags) {
        if (type1.flags !== type2.flags) {
            return false;
        }
    }
    if (recursionCount > exports.maxTypeRecursionCount) {
        return true;
    }
    recursionCount++;
    switch (type1.category) {
        case 6 /* TypeCategory.Class */: {
            const classType2 = type2;
            // If the details are not the same it's not the same class.
            if (!ClassType.isSameGenericClass(type1, classType2, recursionCount)) {
                return false;
            }
            if (!options.ignoreConditions && !TypeCondition.isSame(type1.condition, type2.condition)) {
                return false;
            }
            if (!options.ignorePseudoGeneric || !ClassType.isPseudoGenericClass(type1)) {
                // Make sure the type args match.
                if (type1.tupleTypeArguments && classType2.tupleTypeArguments) {
                    const type1TupleTypeArgs = type1.tupleTypeArguments || [];
                    const type2TupleTypeArgs = classType2.tupleTypeArguments || [];
                    if (type1TupleTypeArgs.length !== type2TupleTypeArgs.length) {
                        return false;
                    }
                    for (let i = 0; i < type1TupleTypeArgs.length; i++) {
                        if (!isTypeSame(type1TupleTypeArgs[i].type, type2TupleTypeArgs[i].type, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                            return false;
                        }
                        if (type1TupleTypeArgs[i].isUnbounded !== type2TupleTypeArgs[i].isUnbounded) {
                            return false;
                        }
                    }
                }
                else {
                    const type1TypeArgs = type1.typeArguments || [];
                    const type2TypeArgs = classType2.typeArguments || [];
                    const typeArgCount = Math.max(type1TypeArgs.length, type2TypeArgs.length);
                    for (let i = 0; i < typeArgCount; i++) {
                        // Assume that missing type args are "Unknown".
                        const typeArg1 = i < type1TypeArgs.length ? type1TypeArgs[i] : UnknownType.create();
                        const typeArg2 = i < type2TypeArgs.length ? type2TypeArgs[i] : UnknownType.create();
                        if (!isTypeSame(typeArg1, typeArg2, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                            return false;
                        }
                    }
                }
            }
            if (!ClassType.isLiteralValueSame(type1, classType2)) {
                return false;
            }
            if (!type1.isTypedDictPartial !== !classType2.isTypedDictPartial) {
                return false;
            }
            if (!options.ignoreTypedDictNarrowEntries && !ClassType.isTypedDictNarrowedEntriesSame(type1, classType2)) {
                return false;
            }
            return true;
        }
        case 4 /* TypeCategory.Function */: {
            // Make sure the parameter counts match.
            const functionType2 = type2;
            const params1 = type1.details.parameters;
            const params2 = functionType2.details.parameters;
            if (params1.length !== params2.length) {
                return false;
            }
            const positionOnlyIndex1 = params1.findIndex((param) => isPositionOnlySeparator(param));
            const positionOnlyIndex2 = params2.findIndex((param) => isPositionOnlySeparator(param));
            // Make sure the parameter details match.
            for (let i = 0; i < params1.length; i++) {
                const param1 = params1[i];
                const param2 = params2[i];
                if (param1.category !== param2.category) {
                    return false;
                }
                const isName1Relevant = positionOnlyIndex1 !== undefined && i > positionOnlyIndex1;
                const isName2Relevant = positionOnlyIndex2 !== undefined && i > positionOnlyIndex2;
                if (isName1Relevant !== isName2Relevant) {
                    return false;
                }
                if (isName1Relevant) {
                    if (param1.name !== param2.name) {
                        return false;
                    }
                }
                else if (isPositionOnlySeparator(param1) && isPositionOnlySeparator(param2)) {
                    continue;
                }
                else if (isKeywordOnlySeparator(param1) && isKeywordOnlySeparator(param2)) {
                    continue;
                }
                const param1Type = FunctionType.getEffectiveParameterType(type1, i);
                const param2Type = FunctionType.getEffectiveParameterType(functionType2, i);
                if (!isTypeSame(param1Type, param2Type, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                    return false;
                }
            }
            // If the functions have ParamSpecs associated with them, make sure those match.
            const paramSpec1 = type1.details.paramSpec;
            const paramSpec2 = functionType2.details.paramSpec;
            if (paramSpec1) {
                if (!paramSpec2) {
                    return false;
                }
                if (!isTypeSame(paramSpec1, paramSpec2, options, recursionCount)) {
                    return false;
                }
            }
            else if (paramSpec2) {
                return false;
            }
            // Make sure the return types match.
            let return1Type = type1.details.declaredReturnType;
            if (type1.specializedTypes && type1.specializedTypes.returnType) {
                return1Type = type1.specializedTypes.returnType;
            }
            if (!return1Type && type1.inferredReturnType) {
                return1Type = type1.inferredReturnType;
            }
            let return2Type = functionType2.details.declaredReturnType;
            if (functionType2.specializedTypes && functionType2.specializedTypes.returnType) {
                return2Type = functionType2.specializedTypes.returnType;
            }
            if (!return2Type && functionType2.inferredReturnType) {
                return2Type = functionType2.inferredReturnType;
            }
            if (return1Type || return2Type) {
                if (!return1Type ||
                    !return2Type ||
                    !isTypeSame(return1Type, return2Type, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                    return false;
                }
            }
            return true;
        }
        case 5 /* TypeCategory.OverloadedFunction */: {
            // Make sure the overload counts match.
            const functionType2 = type2;
            if (type1.overloads.length !== functionType2.overloads.length) {
                return false;
            }
            // We assume here that overloaded functions always appear
            // in the same order from one analysis pass to another.
            for (let i = 0; i < type1.overloads.length; i++) {
                if (!isTypeSame(type1.overloads[i], functionType2.overloads[i], options, recursionCount)) {
                    return false;
                }
            }
            return true;
        }
        case 8 /* TypeCategory.Union */: {
            const unionType2 = type2;
            const subtypes1 = type1.subtypes;
            const subtypes2 = unionType2.subtypes;
            if (subtypes1.length !== subtypes2.length) {
                return false;
            }
            // The types do not have a particular order, so we need to
            // do the comparison in an order-independent manner.
            const exclusionSet = new Set();
            return (findSubtype(type1, (subtype) => !UnionType.containsType(unionType2, subtype, exclusionSet, recursionCount)) === undefined);
        }
        case 9 /* TypeCategory.TypeVar */: {
            const type2TypeVar = type2;
            if (type1.scopeId !== type2TypeVar.scopeId) {
                return false;
            }
            // Handle the case where this is a generic recursive type alias. Make
            // sure that the type argument types match.
            if (type1.details.recursiveTypeParameters && type2TypeVar.details.recursiveTypeParameters) {
                const type1TypeArgs = ((_a = type1 === null || type1 === void 0 ? void 0 : type1.typeAliasInfo) === null || _a === void 0 ? void 0 : _a.typeArguments) || [];
                const type2TypeArgs = ((_b = type2 === null || type2 === void 0 ? void 0 : type2.typeAliasInfo) === null || _b === void 0 ? void 0 : _b.typeArguments) || [];
                const typeArgCount = Math.max(type1TypeArgs.length, type2TypeArgs.length);
                for (let i = 0; i < typeArgCount; i++) {
                    // Assume that missing type args are "Any".
                    const typeArg1 = i < type1TypeArgs.length ? type1TypeArgs[i] : AnyType.create();
                    const typeArg2 = i < type2TypeArgs.length ? type2TypeArgs[i] : AnyType.create();
                    if (!isTypeSame(typeArg1, typeArg2, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                        return false;
                    }
                }
            }
            if (!type1.isVariadicInUnion !== !type2TypeVar.isVariadicInUnion) {
                return false;
            }
            if (type1.details === type2TypeVar.details) {
                return true;
            }
            if (type1.details.name !== type2TypeVar.details.name ||
                type1.details.isParamSpec !== type2TypeVar.details.isParamSpec ||
                type1.details.isVariadic !== type2TypeVar.details.isVariadic ||
                type1.details.isSynthesized !== type2TypeVar.details.isSynthesized ||
                type1.details.declaredVariance !== type2TypeVar.details.declaredVariance ||
                type1.scopeId !== type2TypeVar.scopeId) {
                return false;
            }
            const boundType1 = type1.details.boundType;
            const boundType2 = type2TypeVar.details.boundType;
            if (boundType1) {
                if (!boundType2 ||
                    !isTypeSame(boundType1, boundType2, { ...options, ignoreTypeFlags: false }, recursionCount)) {
                    return false;
                }
            }
            else {
                if (boundType2) {
                    return false;
                }
            }
            const constraints1 = type1.details.constraints;
            const constraints2 = type2TypeVar.details.constraints;
            if (constraints1.length !== constraints2.length) {
                return false;
            }
            for (let i = 0; i < constraints1.length; i++) {
                if (!isTypeSame(constraints1[i], constraints2[i], { ...options, ignoreTypeFlags: false }, recursionCount)) {
                    return false;
                }
            }
            return true;
        }
        case 7 /* TypeCategory.Module */: {
            const type2Module = type2;
            // Module types are the same if they share the same
            // module symbol table.
            if (type1.fields === type2Module.fields) {
                return true;
            }
            // If both symbol tables are empty, we can also assume
            // they're equal.
            if (type1.fields.size === 0 && type2Module.fields.size === 0) {
                return true;
            }
            return false;
        }
        case 1 /* TypeCategory.Unknown */: {
            const type2Unknown = type2;
            return type1.isIncomplete === type2Unknown.isIncomplete;
        }
    }
    return true;
}
exports.isTypeSame = isTypeSame;
// If the type is a union, remove an "unknown" type from the union,
// returning only the known types.
function removeUnknownFromUnion(type) {
    return removeFromUnion(type, (t) => isUnknown(t));
}
exports.removeUnknownFromUnion = removeUnknownFromUnion;
// If the type is a union, remove an "unbound" type from the union,
// returning only the known types.
function removeUnbound(type) {
    if (isUnion(type)) {
        return removeFromUnion(type, (t) => isUnbound(t));
    }
    if (isUnbound(type)) {
        return UnknownType.create();
    }
    return type;
}
exports.removeUnbound = removeUnbound;
function removeFromUnion(type, removeFilter) {
    if (isUnion(type)) {
        const remainingTypes = type.subtypes.filter((t) => !removeFilter(t));
        if (remainingTypes.length < type.subtypes.length) {
            const newType = combineTypes(remainingTypes);
            if (isUnion(newType)) {
                UnionType.addTypeAliasSource(newType, type);
            }
            return newType;
        }
    }
    return type;
}
exports.removeFromUnion = removeFromUnion;
function findSubtype(type, filter) {
    if (isUnion(type)) {
        return type.subtypes.find((subtype) => {
            return filter(subtype);
        });
    }
    return filter(type) ? type : undefined;
}
exports.findSubtype = findSubtype;
// Combines multiple types into a single type. If the types are
// the same, only one is returned. If they differ, they
// are combined into a UnionType. NeverTypes are filtered out.
// If no types remain in the end, a NeverType is returned.
function combineTypes(subtypes, maxSubtypeCount) {
    // Filter out any "Never" and "NoReturn" types.
    let sawNoReturn = false;
    if (subtypes.some((subtype) => subtype.category === 3 /* TypeCategory.Never */))
        subtypes = subtypes.filter((subtype) => {
            if (subtype.category === 3 /* TypeCategory.Never */ && subtype.isNoReturn) {
                sawNoReturn = true;
            }
            return subtype.category !== 3 /* TypeCategory.Never */;
        });
    if (subtypes.length === 0) {
        return sawNoReturn ? NeverType.createNoReturn() : NeverType.createNever();
    }
    // Handle the common case where there is only one type.
    // Also handle the common case where there are multiple copies of the same type.
    let allSubtypesAreSame = true;
    if (subtypes.length > 1) {
        for (let index = 1; index < subtypes.length; index++) {
            if (subtypes[index] !== subtypes[0]) {
                allSubtypesAreSame = false;
                break;
            }
        }
    }
    if (allSubtypesAreSame) {
        return subtypes[0];
    }
    // Expand all union types.
    let expandedTypes;
    const typeAliasSources = new Set();
    for (let i = 0; i < subtypes.length; i++) {
        const subtype = subtypes[i];
        if (isUnion(subtype)) {
            if (!expandedTypes) {
                expandedTypes = subtypes.slice(0, i);
            }
            expandedTypes = expandedTypes.concat(subtype.subtypes);
            if (subtype.typeAliasInfo) {
                typeAliasSources.add(subtype);
            }
            else if (subtype.typeAliasSources) {
                subtype.typeAliasSources.forEach((subtype) => {
                    typeAliasSources.add(subtype);
                });
            }
        }
        else if (expandedTypes) {
            expandedTypes.push(subtype);
        }
    }
    expandedTypes = expandedTypes !== null && expandedTypes !== void 0 ? expandedTypes : subtypes;
    // Sort all of the literal and empty types to the end.
    expandedTypes = expandedTypes.sort((type1, type2) => {
        if (isClass(type1) && type1.literalValue !== undefined) {
            return 1;
        }
        if (isClass(type2) && type2.literalValue !== undefined) {
            return -1;
        }
        if (isClassInstance(type1) && type1.isEmptyContainer) {
            return 1;
        }
        else if (isClassInstance(type2) && type2.isEmptyContainer) {
            return -1;
        }
        return 0;
    });
    // If removing all NoReturn types results in no remaining types,
    // convert it to an unknown.
    if (expandedTypes.length === 0) {
        return UnknownType.create();
    }
    const newUnionType = UnionType.create();
    if (typeAliasSources.size > 0) {
        newUnionType.typeAliasSources = typeAliasSources;
    }
    let hitMaxSubtypeCount = false;
    expandedTypes.forEach((subtype, index) => {
        if (index === 0) {
            UnionType.addType(newUnionType, subtype);
        }
        else {
            if (maxSubtypeCount === undefined || newUnionType.subtypes.length < maxSubtypeCount) {
                _addTypeIfUnique(newUnionType, subtype);
            }
            else {
                hitMaxSubtypeCount = true;
            }
        }
    });
    if (hitMaxSubtypeCount) {
        return AnyType.create();
    }
    // If only one type remains, convert it from a union to a simple type.
    if (newUnionType.subtypes.length === 1) {
        return newUnionType.subtypes[0];
    }
    return newUnionType;
}
exports.combineTypes = combineTypes;
// Determines whether the dest type is the same as the source type with
// the possible exception that the source type has a literal value when
// the dest does not.
function isSameWithoutLiteralValue(destType, srcType) {
    // If it's the same with literals, great.
    if (isTypeSame(destType, srcType)) {
        return true;
    }
    if (isInstantiableClass(srcType) && srcType.literalValue !== undefined) {
        // Strip the literal.
        srcType = ClassType.cloneWithLiteral(srcType, /* value */ undefined);
        return isTypeSame(destType, srcType);
    }
    if (isClassInstance(srcType) && srcType.literalValue !== undefined) {
        // Strip the literal.
        srcType = ClassType.cloneWithLiteral(srcType, /* value */ undefined);
        return isTypeSame(destType, srcType, { ignoreConditions: true });
    }
    return false;
}
exports.isSameWithoutLiteralValue = isSameWithoutLiteralValue;
function _addTypeIfUnique(unionType, typeToAdd) {
    // Handle the addition of a string literal in a special manner to
    // avoid n^2 behavior in unions that contain hundreds of string
    // literal types. Skip this for constrained types.
    if (isClass(typeToAdd) && typeToAdd.condition === undefined) {
        const literalMaps = isClassInstance(typeToAdd) ? unionType.literalInstances : unionType.literalClasses;
        if (ClassType.isBuiltIn(typeToAdd, 'str') &&
            typeToAdd.literalValue !== undefined &&
            literalMaps.literalStrMap !== undefined) {
            if (!literalMaps.literalStrMap.has(typeToAdd.literalValue)) {
                UnionType.addType(unionType, typeToAdd);
            }
            return;
        }
        else if (ClassType.isBuiltIn(typeToAdd, 'int') &&
            typeToAdd.literalValue !== undefined &&
            literalMaps.literalIntMap !== undefined) {
            if (!literalMaps.literalIntMap.has(typeToAdd.literalValue)) {
                UnionType.addType(unionType, typeToAdd);
            }
            return;
        }
        else if (ClassType.isEnumClass(typeToAdd) &&
            typeToAdd.literalValue !== undefined &&
            literalMaps.literalEnumMap !== undefined) {
            const enumLiteral = typeToAdd.literalValue;
            if (!literalMaps.literalEnumMap.has(enumLiteral.getName())) {
                UnionType.addType(unionType, typeToAdd);
            }
            return;
        }
    }
    const isPseudoGeneric = isClass(typeToAdd) && ClassType.isPseudoGenericClass(typeToAdd);
    for (let i = 0; i < unionType.subtypes.length; i++) {
        const type = unionType.subtypes[i];
        // Does this type already exist in the types array?
        if (isTypeSame(type, typeToAdd)) {
            return;
        }
        // Handle the case where pseudo-generic classes with different
        // type arguments are being combined. Rather than add multiple
        // specialized types, we will replace them with a single specialized
        // type that is specialized with Unknowns. This is important because
        // we can hit recursive cases (where a pseudo-generic class is
        // parameterized with its own class) ad infinitum.
        if (isPseudoGeneric) {
            if (isTypeSame(type, typeToAdd, { ignorePseudoGeneric: true })) {
                unionType.subtypes[i] = ClassType.cloneForSpecialization(typeToAdd, typeToAdd.details.typeParameters.map(() => UnknownType.create()), 
                /* isTypeArgumentExplicit */ true);
                return;
            }
        }
        // If the typeToAdd is a literal value and there's already
        // a non-literal type that matches, don't add the literal value.
        if (isClassInstance(type) && isClassInstance(typeToAdd)) {
            if (isSameWithoutLiteralValue(type, typeToAdd)) {
                if (type.literalValue === undefined) {
                    return;
                }
            }
            // If we're adding Literal[False] or Literal[True] to its
            // opposite, combine them into a non-literal 'bool' type.
            if (ClassType.isBuiltIn(type, 'bool') &&
                !type.condition &&
                ClassType.isBuiltIn(typeToAdd, 'bool') &&
                !typeToAdd.condition) {
                if (typeToAdd.literalValue !== undefined && !typeToAdd.literalValue === type.literalValue) {
                    unionType.subtypes[i] = ClassType.cloneWithLiteral(type, /* value */ undefined);
                    return;
                }
            }
            // If the typeToAdd is a TypedDict that is the same class as the
            // existing type, see if one of them is a proper subset of the other.
            if (ClassType.isTypedDictClass(type) && ClassType.isSameGenericClass(type, typeToAdd)) {
                if (ClassType.isTypedDictNarrower(typeToAdd, type)) {
                    return;
                }
                else if (ClassType.isTypedDictNarrower(type, typeToAdd)) {
                    unionType.subtypes[i] = typeToAdd;
                    return;
                }
            }
        }
        // If the typeToAdd is an empty container and there's already
        // non-empty container of the same type, don't add the empty container.
        if (isClassInstance(typeToAdd) && typeToAdd.isEmptyContainer) {
            if (isClassInstance(type) && ClassType.isSameGenericClass(type, typeToAdd)) {
                return;
            }
        }
    }
    UnionType.addType(unionType, typeToAdd);
}


/***/ }),

/***/ "../pyright-internal/src/backgroundAnalysis.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/backgroundAnalysis.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * backgroundAnalysis.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * run analyzer from background thread
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BackgroundAnalysisRunner = exports.BackgroundAnalysis = void 0;
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const importResolver_1 = __webpack_require__(/*! ./analyzer/importResolver */ "../pyright-internal/src/analyzer/importResolver.ts");
const backgroundAnalysisBase_1 = __webpack_require__(/*! ./backgroundAnalysisBase */ "../pyright-internal/src/backgroundAnalysisBase.ts");
const cancellationUtils_1 = __webpack_require__(/*! ./common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const fullAccessHost_1 = __webpack_require__(/*! ./common/fullAccessHost */ "../pyright-internal/src/common/fullAccessHost.ts");
const uriUtils_1 = __webpack_require__(/*! ./common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
class BackgroundAnalysis extends backgroundAnalysisBase_1.BackgroundAnalysisBase {
    constructor(serviceProvider) {
        var _a, _b, _c;
        super(serviceProvider.console());
        const initialData = {
            rootUri: (_b = (_a = (0, uriUtils_1.getRootUri)(serviceProvider)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
            cancellationFolderName: (0, cancellationUtils_1.getCancellationFolderName)(),
            runner: undefined,
            workerIndex: ++BackgroundAnalysis._workerIndex,
        };
        // this will load this same file in BG thread and start listener
        const worker = new worker_threads_1.Worker(__filename, { workerData: initialData });
        this.setup(worker);
        // Tell the cacheManager we have a worker that needs to share data.
        (_c = serviceProvider.cacheManager()) === null || _c === void 0 ? void 0 : _c.addWorker(initialData.workerIndex, worker);
    }
}
exports.BackgroundAnalysis = BackgroundAnalysis;
BackgroundAnalysis._workerIndex = 0;
class BackgroundAnalysisRunner extends backgroundAnalysisBase_1.BackgroundAnalysisRunnerBase {
    constructor(serviceProvider) {
        super(serviceProvider);
    }
    createHost() {
        return new fullAccessHost_1.FullAccessHost(this.getServiceProvider());
    }
    createImportResolver(serviceProvider, options, host) {
        return new importResolver_1.ImportResolver(serviceProvider, options, host);
    }
}
exports.BackgroundAnalysisRunner = BackgroundAnalysisRunner;


/***/ }),

/***/ "../pyright-internal/src/backgroundAnalysisBase.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/backgroundAnalysisBase.ts ***!
  \*********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * backgroundAnalysisBase.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * run analyzer from background thread
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BackgroundAnalysisRunnerBase = exports.BackgroundAnalysisBase = void 0;
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const analysis_1 = __webpack_require__(/*! ./analyzer/analysis */ "../pyright-internal/src/analyzer/analysis.ts");
const program_1 = __webpack_require__(/*! ./analyzer/program */ "../pyright-internal/src/analyzer/program.ts");
const backgroundThreadBase_1 = __webpack_require__(/*! ./backgroundThreadBase */ "../pyright-internal/src/backgroundThreadBase.ts");
const cancellationUtils_1 = __webpack_require__(/*! ./common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ./common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ./common/console */ "../pyright-internal/src/common/console.ts");
const debug = __importStar(__webpack_require__(/*! ./common/debug */ "../pyright-internal/src/common/debug.ts"));
const diagnostic_1 = __webpack_require__(/*! ./common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const fileBasedCancellationUtils_1 = __webpack_require__(/*! ./common/fileBasedCancellationUtils */ "../pyright-internal/src/common/fileBasedCancellationUtils.ts");
const logTracker_1 = __webpack_require__(/*! ./common/logTracker */ "../pyright-internal/src/common/logTracker.ts");
const uri_1 = __webpack_require__(/*! ./common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
class BackgroundAnalysisBase {
    constructor(console) {
        this.console = console;
        this._onAnalysisCompletion = analysis_1.nullCallback;
        // Don't allow instantiation of this type directly.
    }
    setCompletionCallback(callback) {
        this._onAnalysisCompletion = callback !== null && callback !== void 0 ? callback : analysis_1.nullCallback;
    }
    setImportResolver(importResolver) {
        this.enqueueRequest({ requestType: 'setImportResolver', data: (0, backgroundThreadBase_1.serialize)(importResolver.host.kind) });
    }
    setConfigOptions(configOptions) {
        this.enqueueRequest({ requestType: 'setConfigOptions', data: (0, backgroundThreadBase_1.serialize)(configOptions) });
    }
    setTrackedFiles(fileUris) {
        this.enqueueRequest({ requestType: 'setTrackedFiles', data: (0, backgroundThreadBase_1.serialize)(fileUris) });
    }
    setAllowedThirdPartyImports(importNames) {
        this.enqueueRequest({ requestType: 'setAllowedThirdPartyImports', data: (0, backgroundThreadBase_1.serialize)(importNames) });
    }
    ensurePartialStubPackages(executionRoot) {
        this.enqueueRequest({ requestType: 'ensurePartialStubPackages', data: (0, backgroundThreadBase_1.serialize)({ executionRoot }) });
    }
    setFileOpened(fileUri, version, contents, options) {
        this.enqueueRequest({
            requestType: 'setFileOpened',
            data: (0, backgroundThreadBase_1.serialize)({ fileUri, version, contents, options }),
        });
    }
    updateChainedUri(fileUri, chainedUri) {
        this.enqueueRequest({
            requestType: 'updateChainedFileUri',
            data: (0, backgroundThreadBase_1.serialize)({ fileUri, chainedUri }),
        });
    }
    setFileClosed(fileUri, isTracked) {
        this.enqueueRequest({ requestType: 'setFileClosed', data: (0, backgroundThreadBase_1.serialize)({ fileUri, isTracked }) });
    }
    addInterimFile(fileUri) {
        this.enqueueRequest({ requestType: 'addInterimFile', data: (0, backgroundThreadBase_1.serialize)({ fileUri }) });
    }
    markAllFilesDirty(evenIfContentsAreSame) {
        this.enqueueRequest({ requestType: 'markAllFilesDirty', data: (0, backgroundThreadBase_1.serialize)({ evenIfContentsAreSame }) });
    }
    markFilesDirty(fileUris, evenIfContentsAreSame) {
        this.enqueueRequest({
            requestType: 'markFilesDirty',
            data: (0, backgroundThreadBase_1.serialize)({ fileUris, evenIfContentsAreSame }),
        });
    }
    startAnalysis(program, token) {
        this._startOrResumeAnalysis('analyze', program, token);
    }
    async analyzeFile(fileUri, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const { port1, port2 } = new worker_threads_1.MessageChannel();
        const waiter = (0, backgroundThreadBase_1.getBackgroundWaiter)(port1);
        const cancellationId = (0, cancellationUtils_1.getCancellationTokenId)(token);
        this.enqueueRequest({
            requestType: 'analyzeFile',
            data: (0, backgroundThreadBase_1.serialize)({ fileUri, cancellationId }),
            port: port2,
        });
        const result = await waiter;
        port2.close();
        port1.close();
        return result;
    }
    async getDiagnosticsForRange(fileUri, range, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const { port1, port2 } = new worker_threads_1.MessageChannel();
        const waiter = (0, backgroundThreadBase_1.getBackgroundWaiter)(port1);
        const cancellationId = (0, cancellationUtils_1.getCancellationTokenId)(token);
        this.enqueueRequest({
            requestType: 'getDiagnosticsForRange',
            data: (0, backgroundThreadBase_1.serialize)({ fileUri, range, cancellationId }),
            port: port2,
        });
        const result = await waiter;
        port2.close();
        port1.close();
        return convertDiagnostics(result);
    }
    async writeTypeStub(targetImportPath, targetIsSingleFile, stubPath, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const { port1, port2 } = new worker_threads_1.MessageChannel();
        const waiter = (0, backgroundThreadBase_1.getBackgroundWaiter)(port1);
        const cancellationId = (0, cancellationUtils_1.getCancellationTokenId)(token);
        this.enqueueRequest({
            requestType: 'writeTypeStub',
            data: (0, backgroundThreadBase_1.serialize)({
                targetImportPath,
                targetIsSingleFile,
                stubPath,
                cancellationId,
            }),
            port: port2,
        });
        await waiter;
        port2.close();
        port1.close();
    }
    invalidateAndForceReanalysis(reason) {
        this.enqueueRequest({ requestType: 'invalidateAndForceReanalysis', data: (0, backgroundThreadBase_1.serialize)({ reason }) });
    }
    restart() {
        this.enqueueRequest({ requestType: 'restart', data: null });
    }
    shutdown() {
        this.enqueueRequest({ requestType: 'shutdown', data: null });
    }
    setup(worker) {
        this._worker = worker;
        // global channel to communicate from BG channel to main thread.
        worker.on('message', (msg) => this.onMessage(msg));
        // this will catch any exception thrown from background thread,
        // print log and ignore exception
        worker.on('error', (msg) => {
            this.log(console_1.LogLevel.Error, `Error occurred on background thread: ${JSON.stringify(msg)}`);
        });
    }
    onMessage(msg) {
        switch (msg.requestType) {
            case 'log': {
                const logData = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.log(logData.level, logData.message);
                break;
            }
            case 'analysisResult': {
                // Change in diagnostics due to host such as file closed rather than
                // analyzing files.
                this._onAnalysisCompletion(convertAnalysisResults((0, backgroundThreadBase_1.deserialize)(msg.data)));
                break;
            }
            default:
                debug.fail(`${msg.requestType} is not expected. Message structure: ${JSON.stringify(msg)}`);
        }
    }
    enqueueRequest(request) {
        if (this._worker) {
            this._worker.postMessage(request, request.port ? [request.port] : undefined);
        }
    }
    log(level, msg) {
        (0, console_1.log)(this.console, level, msg);
    }
    handleAnalysisResponse(msg, program, port1, port2, token) {
        switch (msg.requestType) {
            case 'analysisResult': {
                this._onAnalysisCompletion(convertAnalysisResults((0, backgroundThreadBase_1.deserialize)(msg.data)));
                break;
            }
            case 'analysisPaused': {
                port2.close();
                port1.close();
                // Analysis request has completed, but there is more to
                // analyze, so queue another message to resume later.
                this._startOrResumeAnalysis('resumeAnalysis', program, token);
                break;
            }
            case 'analysisDone': {
                (0, fileBasedCancellationUtils_1.disposeCancellationToken)(token);
                port2.close();
                port1.close();
                break;
            }
            default:
                debug.fail(`${msg.requestType} is not expected. Message structure: ${JSON.stringify(msg)}`);
        }
    }
    _startOrResumeAnalysis(requestType, program, token) {
        const { port1, port2 } = new worker_threads_1.MessageChannel();
        // Handle response from background thread to main thread.
        port1.on('message', (msg) => this.handleAnalysisResponse(msg, program, port1, port2, token));
        const cancellationId = (0, cancellationUtils_1.getCancellationTokenId)(token);
        this.enqueueRequest({ requestType, data: (0, backgroundThreadBase_1.serialize)(cancellationId), port: port2 });
    }
}
exports.BackgroundAnalysisBase = BackgroundAnalysisBase;
class BackgroundAnalysisRunnerBase extends backgroundThreadBase_1.BackgroundThreadBase {
    constructor(serviceProvider) {
        super(worker_threads_1.workerData, serviceProvider);
        this.serviceProvider = serviceProvider;
        this.isCaseSensitive = true;
        // Stash the base directory into a global variable.
        const data = worker_threads_1.workerData;
        this.log(console_1.LogLevel.Info, `Background analysis(${worker_threads_1.threadId}) root directory: ${data.rootUri}`);
        this._configOptions = new configOptions_1.BasedConfigOptions(uri_1.Uri.parse(data.rootUri, serviceProvider));
        this.importResolver = this.createImportResolver(serviceProvider, this._configOptions, this.createHost());
        const console = this.getConsole();
        this.logTracker = new logTracker_1.LogTracker(console, `BG(${worker_threads_1.threadId})`);
        this._program = new program_1.Program(this.importResolver, this._configOptions, serviceProvider, this.logTracker);
    }
    get program() {
        return this._program;
    }
    start() {
        this.log(console_1.LogLevel.Info, `Background analysis(${worker_threads_1.threadId}) started`);
        // Get requests from main thread.
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.on('message', this._onMessageWrapper.bind(this));
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.on('error', (msg) => debug.fail(`failed ${msg}`));
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.on('exit', (c) => {
            if (c !== 0) {
                debug.fail(`worker stopped with exit code ${c}`);
            }
        });
    }
    onMessage(msg) {
        var _a;
        switch (msg.requestType) {
            case 'cacheUsageBuffer': {
                (_a = this.serviceProvider.cacheManager()) === null || _a === void 0 ? void 0 : _a.handleCachedUsageBufferMessage(msg);
                break;
            }
            case 'analyze': {
                const port = msg.port;
                const data = (0, backgroundThreadBase_1.deserialize)(msg.data);
                const token = (0, fileBasedCancellationUtils_1.getCancellationTokenFromId)(data);
                this.handleAnalyze(port, data, token);
                break;
            }
            case 'resumeAnalysis': {
                const port = msg.port;
                const data = (0, backgroundThreadBase_1.deserialize)(msg.data);
                const token = (0, fileBasedCancellationUtils_1.getCancellationTokenFromId)(data);
                this.handleResumeAnalysis(port, data, token);
                break;
            }
            case 'analyzeFile': {
                (0, backgroundThreadBase_1.run)(() => {
                    const { fileUri, cancellationId } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                    const token = (0, fileBasedCancellationUtils_1.getCancellationTokenFromId)(cancellationId);
                    return this.handleAnalyzeFile(fileUri, token);
                }, msg.port);
                break;
            }
            case 'getDiagnosticsForRange': {
                (0, backgroundThreadBase_1.run)(() => {
                    const { fileUri, range, cancellationId } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                    const token = (0, fileBasedCancellationUtils_1.getCancellationTokenFromId)(cancellationId);
                    return this.handleGetDiagnosticsForRange(fileUri, range, token);
                }, msg.port);
                break;
            }
            case 'writeTypeStub': {
                (0, backgroundThreadBase_1.run)(() => {
                    const { targetImportPath, targetIsSingleFile, stubPath, cancellationId } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                    const token = (0, fileBasedCancellationUtils_1.getCancellationTokenFromId)(cancellationId);
                    this.handleWriteTypeStub(targetImportPath, targetIsSingleFile, stubPath, token);
                }, msg.port);
                break;
            }
            case 'setImportResolver': {
                this.handleSetImportResolver((0, backgroundThreadBase_1.deserialize)(msg.data));
                break;
            }
            case 'setConfigOptions': {
                this.handleSetConfigOptions((0, backgroundThreadBase_1.deserialize)(msg.data));
                break;
            }
            case 'setTrackedFiles': {
                this.handleSetTrackedFiles((0, backgroundThreadBase_1.deserialize)(msg.data));
                break;
            }
            case 'setAllowedThirdPartyImports': {
                this.handleSetAllowedThirdPartyImports((0, backgroundThreadBase_1.deserialize)(msg.data));
                break;
            }
            case 'ensurePartialStubPackages': {
                const { executionRoot } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleEnsurePartialStubPackages(executionRoot);
                break;
            }
            case 'setFileOpened': {
                const { fileUri, version, contents, options } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleSetFileOpened(fileUri, version, contents, options);
                break;
            }
            case 'updateChainedFileUri': {
                const { fileUri, chainedUri } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleUpdateChainedfileUri(fileUri, chainedUri);
                break;
            }
            case 'setFileClosed': {
                const { fileUri, isTracked } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleSetFileClosed(fileUri, isTracked);
                break;
            }
            case 'addInterimFile': {
                const { fileUri } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleAddInterimFile(fileUri);
                break;
            }
            case 'markAllFilesDirty': {
                const { evenIfContentsAreSame } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleMarkAllFilesDirty(evenIfContentsAreSame);
                break;
            }
            case 'markFilesDirty': {
                const { fileUris, evenIfContentsAreSame } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleMarkFilesDirty(fileUris, evenIfContentsAreSame);
                break;
            }
            case 'invalidateAndForceReanalysis': {
                const { reason } = (0, backgroundThreadBase_1.deserialize)(msg.data);
                this.handleInvalidateAndForceReanalysis(reason);
                break;
            }
            case 'restart': {
                // recycle import resolver
                this.handleRestart();
                break;
            }
            case 'shutdown': {
                this.handleShutdown();
                break;
            }
            default: {
                debug.fail(`${msg.requestType} is not expected. Message structure: ${JSON.stringify(msg)}`);
            }
        }
    }
    handleAnalyze(port, cancellationId, token) {
        // Report files to analyze first.
        const filesLeftToAnalyze = this.program.getFilesToAnalyzeCount();
        this.onAnalysisCompletion(port, {
            diagnostics: [],
            filesInProgram: this.program.getFileCount(),
            filesRequiringAnalysis: filesLeftToAnalyze,
            checkingOnlyOpenFiles: this.program.isCheckingOnlyOpenFiles(),
            fatalErrorOccurred: false,
            configParseErrorOccurred: false,
            elapsedTime: 0,
        });
        this.handleResumeAnalysis(port, cancellationId, token);
    }
    handleResumeAnalysis(port, cancellationId, token) {
        // Report results at the interval of the max analysis time.
        const maxTime = { openFilesTimeInMs: 50, noOpenFilesTimeInMs: 200 };
        const moreToAnalyze = (0, analysis_1.analyzeProgram)(this.program, maxTime, this._configOptions, (result) => this.onAnalysisCompletion(port, result), this.getConsole(), token);
        if (moreToAnalyze) {
            // There's more to analyze after we exceeded max time,
            // so report that we are paused. The foreground thread will
            // then queue up a message to resume the analysis.
            this._analysisPaused(port, cancellationId);
        }
        else {
            this.analysisDone(port, cancellationId);
        }
    }
    handleAnalyzeFile(fileUri, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        return this.program.analyzeFile(fileUri, token);
    }
    handleGetDiagnosticsForRange(fileUri, range, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        return this.program.getDiagnosticsForRange(fileUri, range);
    }
    handleWriteTypeStub(targetImportPath, targetIsSingleFile, stubPath, token) {
        (0, analysis_1.analyzeProgram)(this.program, 
        /* maxTime */ undefined, this._configOptions, analysis_1.nullCallback, this.getConsole(), token);
        this.program.writeTypeStub(targetImportPath, targetIsSingleFile, stubPath, token);
    }
    handleSetImportResolver(hostKind) {
        this.importResolver = this.createImportResolver(this.getServiceProvider(), this._configOptions, this.createHost());
        this.program.setImportResolver(this.importResolver);
    }
    handleSetConfigOptions(configOptions) {
        this._configOptions = configOptions;
        this.importResolver = this.createImportResolver(this.getServiceProvider(), this._configOptions, this.importResolver.host);
        this.program.setConfigOptions(this._configOptions);
        this.program.setImportResolver(this.importResolver);
    }
    handleSetTrackedFiles(fileUris) {
        const diagnostics = this.program.setTrackedFiles(fileUris);
        this._reportDiagnostics(diagnostics, this.program.getFilesToAnalyzeCount(), 0);
    }
    handleSetAllowedThirdPartyImports(importNames) {
        this.program.setAllowedThirdPartyImports(importNames);
    }
    handleEnsurePartialStubPackages(executionRoot) {
        const execEnv = this._configOptions
            .getExecutionEnvironments()
            .find((e) => { var _a; return ((_a = e.root) === null || _a === void 0 ? void 0 : _a.toString()) === executionRoot; });
        if (execEnv) {
            this.importResolver.ensurePartialStubPackages(execEnv);
        }
    }
    handleSetFileOpened(fileUri, version, contents, options) {
        this.program.setFileOpened(fileUri, version, contents, options
            ? {
                ...options,
                chainedFileUri: uri_1.Uri.fromJsonObj(options === null || options === void 0 ? void 0 : options.chainedFileUri),
            }
            : undefined);
    }
    handleUpdateChainedfileUri(fileUri, chainedfileUri) {
        this.program.updateChainedUri(fileUri, chainedfileUri);
    }
    handleSetFileClosed(fileUri, isTracked) {
        const diagnostics = this.program.setFileClosed(fileUri, isTracked);
        this._reportDiagnostics(diagnostics, this.program.getFilesToAnalyzeCount(), 0);
    }
    handleAddInterimFile(fileUri) {
        this.program.addInterimFile(fileUri);
    }
    handleMarkFilesDirty(fileUris, evenIfContentsAreSame) {
        this.program.markFilesDirty(fileUris, evenIfContentsAreSame);
    }
    handleMarkAllFilesDirty(evenIfContentsAreSame) {
        this.program.markAllFilesDirty(evenIfContentsAreSame);
    }
    handleInvalidateAndForceReanalysis(reason) {
        // Make sure the import resolver doesn't have invalid
        // cached entries.
        this.importResolver.invalidateCache();
        // Mark all files with one or more errors dirty.
        this.program.markAllFilesDirty(/* evenIfContentsAreSame */ true);
    }
    handleRestart() {
        this.importResolver = this.createImportResolver(this.getServiceProvider(), this._configOptions, this.importResolver.host);
        this.program.setImportResolver(this.importResolver);
    }
    handleShutdown() {
        this._program.dispose();
        super.handleShutdown();
    }
    analysisDone(port, cancellationId) {
        port.postMessage({ requestType: 'analysisDone', data: cancellationId });
    }
    onAnalysisCompletion(port, result) {
        // Result URIs can't be sent in current form as they contain methods on
        // them. This causes a DataCloneError when posting.
        // See https://stackoverflow.com/questions/68467946/datacloneerror-the-object-could-not-be-cloned-firefox-browser
        // We turn them back into JSON so we can use Uri.fromJsonObj on the other side.
        port.postMessage({ requestType: 'analysisResult', data: (0, backgroundThreadBase_1.serialize)(result) });
    }
    _onMessageWrapper(msg) {
        try {
            return this.onMessage(msg);
        }
        catch (e) {
            // Don't crash the worker, just send an exception or cancel message
            this.log(console_1.LogLevel.Log, `Background analysis exception leak: ${e}`);
            if (cancellationUtils_1.OperationCanceledException.is(e)) {
                worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.postMessage({ kind: 'cancelled', data: e.message });
                return;
            }
            worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.postMessage({
                kind: 'failed',
                data: `Exception: for msg ${msg.requestType}: ${e.message} in ${e.stack}`,
            });
        }
    }
    _reportDiagnostics(diagnostics, filesLeftToAnalyze, elapsedTime) {
        if (worker_threads_1.parentPort) {
            this.onAnalysisCompletion(worker_threads_1.parentPort, {
                diagnostics,
                filesInProgram: this.program.getFileCount(),
                filesRequiringAnalysis: filesLeftToAnalyze,
                checkingOnlyOpenFiles: this.program.isCheckingOnlyOpenFiles(),
                fatalErrorOccurred: false,
                configParseErrorOccurred: false,
                elapsedTime,
            });
        }
    }
    _analysisPaused(port, cancellationId) {
        port.postMessage({ requestType: 'analysisPaused', data: cancellationId });
    }
}
exports.BackgroundAnalysisRunnerBase = BackgroundAnalysisRunnerBase;
function convertAnalysisResults(result) {
    result.diagnostics = result.diagnostics.map((f) => {
        return {
            fileUri: uri_1.Uri.fromJsonObj(f.fileUri),
            version: f.version,
            diagnostics: convertDiagnostics(f.diagnostics),
        };
    });
    return result;
}
function convertDiagnostics(diagnostics) {
    // Elements are typed as "any" since data crossing the process
    // boundary loses type info.
    return diagnostics.map((d) => {
        const diag = new diagnostic_1.Diagnostic(d.category, d.message, d.range, d.priority);
        if (d._actions) {
            for (const action of d._actions) {
                diag.addAction(action);
            }
        }
        if (d._rule) {
            diag.setRule(d._rule);
        }
        if (d._relatedInfo) {
            for (const info of d._relatedInfo) {
                diag.addRelatedInfo(info.message, info.uri, info.range);
            }
        }
        return diag;
    });
}


/***/ }),

/***/ "../pyright-internal/src/backgroundThreadBase.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/backgroundThreadBase.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * backgroundThreadBase.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * base class for background worker thread.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getBackgroundWaiter = exports.run = exports.deserialize = exports.deserializeReviver = exports.serialize = exports.serializeReplacer = exports.BackgroundThreadBase = exports.BackgroundConsole = void 0;
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const cacheManager_1 = __webpack_require__(/*! ./analyzer/cacheManager */ "../pyright-internal/src/analyzer/cacheManager.ts");
const cancellationUtils_1 = __webpack_require__(/*! ./common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ./common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ./common/console */ "../pyright-internal/src/common/console.ts");
const core_1 = __webpack_require__(/*! ./common/core */ "../pyright-internal/src/common/core.ts");
const debug = __importStar(__webpack_require__(/*! ./common/debug */ "../pyright-internal/src/common/debug.ts"));
const pythonVersion_1 = __webpack_require__(/*! ./common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const realFileSystem_1 = __webpack_require__(/*! ./common/realFileSystem */ "../pyright-internal/src/common/realFileSystem.ts");
const serviceKeys_1 = __webpack_require__(/*! ./common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const serviceProvider_1 = __webpack_require__(/*! ./common/serviceProvider */ "../pyright-internal/src/common/serviceProvider.ts");
__webpack_require__(/*! ./common/serviceProviderExtensions */ "../pyright-internal/src/common/serviceProviderExtensions.ts");
const uri_1 = __webpack_require__(/*! ./common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
class BackgroundConsole {
    // We always generate logs in the background. For the foreground,
    // we'll decide based on user setting whether.
    get level() {
        return console_1.LogLevel.Log;
    }
    log(msg) {
        this.post(console_1.LogLevel.Log, msg);
    }
    info(msg) {
        this.post(console_1.LogLevel.Info, msg);
    }
    warn(msg) {
        this.post(console_1.LogLevel.Warn, msg);
    }
    error(msg) {
        this.post(console_1.LogLevel.Error, msg);
    }
    post(level, msg) {
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.postMessage({ requestType: 'log', data: serialize({ level: level, message: msg }) });
    }
}
exports.BackgroundConsole = BackgroundConsole;
class BackgroundThreadBase {
    constructor(data, serviceProvider) {
        (0, cancellationUtils_1.setCancellationFolderName)(data.cancellationFolderName);
        // Make sure there's a file system and a console interface.
        this._serviceProvider = serviceProvider !== null && serviceProvider !== void 0 ? serviceProvider : new serviceProvider_1.ServiceProvider();
        if (!this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.console)) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.console, new BackgroundConsole());
        }
        let tempFile = undefined;
        if (!this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.tempFile)) {
            tempFile = new realFileSystem_1.RealTempFile();
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.tempFile, tempFile);
        }
        if (!this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.caseSensitivityDetector)) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.caseSensitivityDetector, tempFile !== null && tempFile !== void 0 ? tempFile : new realFileSystem_1.RealTempFile());
        }
        if (!this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.fs)) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.fs, (0, realFileSystem_1.createFromRealFileSystem)(this._serviceProvider.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector), this.getConsole()));
        }
        if (!this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.cacheManager)) {
            this._serviceProvider.add(serviceKeys_1.ServiceKeys.cacheManager, new cacheManager_1.CacheManager());
        }
        // Stash the base directory into a global variable.
        global.__rootDirectory = uri_1.Uri.parse(data.rootUri, this._serviceProvider).getFilePath();
    }
    get fs() {
        return this._serviceProvider.fs();
    }
    log(level, msg) {
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.postMessage({ requestType: 'log', data: serialize({ level: level, message: msg }) });
    }
    getConsole() {
        return this._serviceProvider.console();
    }
    getServiceProvider() {
        return this._serviceProvider;
    }
    handleShutdown() {
        var _a;
        (_a = this._serviceProvider.tryGet(serviceKeys_1.ServiceKeys.tempFile)) === null || _a === void 0 ? void 0 : _a.dispose();
        worker_threads_1.parentPort === null || worker_threads_1.parentPort === void 0 ? void 0 : worker_threads_1.parentPort.close();
    }
}
exports.BackgroundThreadBase = BackgroundThreadBase;
// Function used to serialize specific types that can't automatically be serialized.
// Exposed here so it can be reused by a caller that wants to add more cases.
function serializeReplacer(value) {
    if (uri_1.Uri.is(value) && value.toJsonObj !== undefined) {
        return { __serialized_uri_val: value.toJsonObj() };
    }
    if (value instanceof pythonVersion_1.PythonVersion) {
        return { __serialized_version_val: value.toString() };
    }
    if (value instanceof Map) {
        return { __serialized_map_val: [...value] };
    }
    if (value instanceof Set) {
        return { __serialized_set_val: [...value] };
    }
    if (value instanceof RegExp) {
        return { __serialized_regexp_val: { source: value.source, flags: value.flags } };
    }
    if (value instanceof configOptions_1.ConfigOptions) {
        const entries = Object.entries(value);
        return { __serialized_config_options: entries.reduce((obj, e, i) => ({ ...obj, [e[0]]: e[1] }), {}) };
    }
    return value;
}
exports.serializeReplacer = serializeReplacer;
function serialize(obj) {
    // Convert the object to a string so it can be sent across a message port.
    return JSON.stringify(obj, (k, v) => serializeReplacer(v));
}
exports.serialize = serialize;
function deserializeReviver(value) {
    if (value && typeof value === 'object') {
        if (value.__serialized_uri_val !== undefined) {
            return uri_1.Uri.fromJsonObj(value.__serialized_uri_val);
        }
        if (value.__serialized_version_val) {
            return pythonVersion_1.PythonVersion.fromString(value.__serialized_version_val);
        }
        if (value.__serialized_map_val) {
            return new Map(value.__serialized_map_val);
        }
        if (value.__serialized_set_val) {
            return new Set(value.__serialized_set_val);
        }
        if (value.__serialized_regexp_val) {
            return new RegExp(value.__serialized_regexp_val.source, value.__serialized_regexp_val.flags);
        }
        if (value.__serialized_config_options) {
            const configOptions = new configOptions_1.BasedConfigOptions(value.__serialized_config_options.projectRoot);
            Object.assign(configOptions, value.__serialized_config_options);
            return configOptions;
        }
    }
    return value;
}
exports.deserializeReviver = deserializeReviver;
function deserialize(json) {
    if (!json) {
        return undefined;
    }
    // Convert the string back to an object.
    return JSON.parse(json, (k, v) => deserializeReviver(v));
}
exports.deserialize = deserialize;
function run(code, port, serializer = serialize) {
    try {
        const result = code();
        if (!(0, core_1.isThenable)(result)) {
            port.postMessage({ kind: 'ok', data: serializer(result) });
            return;
        }
        return result.then((r) => {
            port.postMessage({ kind: 'ok', data: serializer(r) });
        }, (e) => {
            if (cancellationUtils_1.OperationCanceledException.is(e)) {
                port.postMessage({ kind: 'cancelled', data: e.message });
                return;
            }
            port.postMessage({ kind: 'failed', data: `Exception: ${e.message} in ${e.stack}` });
        });
    }
    catch (e) {
        if (cancellationUtils_1.OperationCanceledException.is(e)) {
            port.postMessage({ kind: 'cancelled', data: e.message });
            return;
        }
        port.postMessage({ kind: 'failed', data: `Exception: ${e.message} in ${e.stack}` });
    }
}
exports.run = run;
function getBackgroundWaiter(port, deserializer = deserialize) {
    return new Promise((resolve, reject) => {
        port.on('message', (m) => {
            switch (m.kind) {
                case 'ok':
                    resolve(deserializer(m.data));
                    break;
                case 'cancelled':
                    reject(new cancellationUtils_1.OperationCanceledException());
                    break;
                case 'failed':
                    reject(m.data);
                    break;
                default:
                    debug.fail(`unknown kind ${m.kind}`);
            }
        });
    });
}
exports.getBackgroundWaiter = getBackgroundWaiter;


/***/ }),

/***/ "../pyright-internal/src/commands/commandController.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/commands/commandController.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * commandController.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements language server commands execution functionality.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CommandController = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const createTypeStub_1 = __webpack_require__(/*! ./createTypeStub */ "../pyright-internal/src/commands/createTypeStub.ts");
const dumpFileDebugInfoCommand_1 = __webpack_require__(/*! ./dumpFileDebugInfoCommand */ "../pyright-internal/src/commands/dumpFileDebugInfoCommand.ts");
const quickActionCommand_1 = __webpack_require__(/*! ./quickActionCommand */ "../pyright-internal/src/commands/quickActionCommand.ts");
const restartServer_1 = __webpack_require__(/*! ./restartServer */ "../pyright-internal/src/commands/restartServer.ts");
class CommandController {
    constructor(ls) {
        this._createStub = new createTypeStub_1.CreateTypeStubCommand(ls);
        this._restartServer = new restartServer_1.RestartServerCommand(ls);
        this._quickAction = new quickActionCommand_1.QuickActionCommand(ls);
        this._dumpFileDebugInfo = new dumpFileDebugInfoCommand_1.DumpFileDebugInfoCommand(ls);
    }
    async execute(cmdParams, token) {
        switch (cmdParams.command) {
            case "basedpyright.organizeimports" /* Commands.orderImports */: {
                return this._quickAction.execute(cmdParams, token);
            }
            case "basedpyright.createtypestub" /* Commands.createTypeStub */: {
                return this._createStub.execute(cmdParams, token);
            }
            case "basedpyright.restartserver" /* Commands.restartServer */: {
                return this._restartServer.execute(cmdParams);
            }
            case "basedpyright.dumpFileDebugInfo" /* Commands.dumpFileDebugInfo */: {
                return this._dumpFileDebugInfo.execute(cmdParams, token);
            }
            default: {
                return new vscode_languageserver_1.ResponseError(1, 'Unsupported command');
            }
        }
    }
    isLongRunningCommand(command) {
        switch (command) {
            case "basedpyright.createtypestub" /* Commands.createTypeStub */:
            case "basedpyright.restartserver" /* Commands.restartServer */:
                return true;
            default:
                return false;
        }
    }
    isRefactoringCommand(command) {
        return false;
    }
}
exports.CommandController = CommandController;


/***/ }),

/***/ "../pyright-internal/src/commands/commandResult.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/commands/commandResult.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * commandResult.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * wrapper for returning custom command data
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CommandResult = void 0;
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
var CommandResult;
(function (CommandResult) {
    function is(value) {
        return value && value.label !== undefined && value.edits && vscode_languageserver_types_1.WorkspaceEdit.is(value.edits);
    }
    CommandResult.is = is;
})(CommandResult || (exports.CommandResult = CommandResult = {}));


/***/ }),

/***/ "../pyright-internal/src/commands/createTypeStub.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/commands/createTypeStub.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * createTypeStub.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements 'create stub' command functionality.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CreateTypeStubCommand = void 0;
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const analyzerServiceExecutor_1 = __webpack_require__(/*! ../languageService/analyzerServiceExecutor */ "../pyright-internal/src/languageService/analyzerServiceExecutor.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
class CreateTypeStubCommand {
    constructor(_ls) {
        this._ls = _ls;
    }
    async execute(cmdParams, token) {
        if (cmdParams.arguments && cmdParams.arguments.length >= 2) {
            const workspaceRoot = uri_1.Uri.parse(cmdParams.arguments[0], this._ls.serviceProvider);
            const importName = cmdParams.arguments[1];
            const callingFile = uri_1.Uri.parse(cmdParams.arguments[2], this._ls.serviceProvider);
            const service = await analyzerServiceExecutor_1.AnalyzerServiceExecutor.cloneService(this._ls, await this._ls.getWorkspaceForFile(callingFile !== null && callingFile !== void 0 ? callingFile : workspaceRoot), {
                typeStubTargetImportName: importName,
            });
            try {
                await service.writeTypeStubInBackground(token);
                service.dispose();
                const infoMessage = `Type stub was successfully created for '${importName}'.`;
                this._ls.window.showInformationMessage(infoMessage);
                // This is called after a new type stub has been created. It allows
                // us to invalidate caches and force reanalysis of files that potentially
                // are affected by the appearance of a new type stub.
                this._ls.reanalyze();
            }
            catch (err) {
                const isCancellation = cancellationUtils_1.OperationCanceledException.is(err);
                if (isCancellation) {
                    const errMessage = `Type stub creation for '${importName}' was canceled`;
                    this._ls.console.error(errMessage);
                }
                else {
                    let errMessage = '';
                    if (err instanceof Error) {
                        errMessage = ': ' + err.message;
                    }
                    errMessage = `An error occurred when creating type stub for '${importName}'` + errMessage;
                    this._ls.console.error(errMessage);
                    this._ls.window.showErrorMessage(errMessage);
                }
            }
        }
    }
}
exports.CreateTypeStubCommand = CreateTypeStubCommand;


/***/ }),

/***/ "../pyright-internal/src/commands/dumpFileDebugInfoCommand.ts":
/*!********************************************************************!*\
  !*** ../pyright-internal/src/commands/dumpFileDebugInfoCommand.ts ***!
  \********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * dumpFileDebugInfoCommand.ts
 * Copyright (c) Microsoft Corporation.
 *
 * Dump various token/node/type info
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DumpFileDebugInfoCommand = void 0;
const analyzerNodeInfo_1 = __webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const parseTreeWalker_1 = __webpack_require__(/*! ../analyzer/parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
class DumpFileDebugInfoCommand {
    constructor(_ls) {
        this._ls = _ls;
    }
    async execute(params, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        if (!params.arguments || params.arguments.length < 2) {
            return [];
        }
        const fileUri = uri_1.Uri.parse(params.arguments[0], this._ls.serviceProvider);
        const kind = params.arguments[1];
        const workspace = await this._ls.getWorkspaceForFile(fileUri);
        const parseResults = workspace.service.getParseResults(workspace.service.fs.realCasePath(fileUri));
        if (!parseResults) {
            return [];
        }
        const output = [];
        const collectingConsole = {
            info: (m) => {
                output.push(m);
            },
            log: (m) => {
                output.push(m);
            },
            error: (m) => {
                output.push(m);
            },
            warn: (m) => {
                output.push(m);
            },
        };
        collectingConsole.info(`* Dump debug info for '${fileUri.toUserVisibleString()}'`);
        switch (kind) {
            case 'tokens': {
                collectingConsole.info(`* Token info (${parseResults.tokenizerOutput.tokens.count} tokens)`);
                for (let i = 0; i < parseResults.tokenizerOutput.tokens.count; i++) {
                    const token = parseResults.tokenizerOutput.tokens.getItemAt(i);
                    collectingConsole.info(`[${i}] ${getTokenString(fileUri, token, parseResults.tokenizerOutput.lines)}`);
                }
                break;
            }
            case 'nodes': {
                collectingConsole.info(`* Node info`);
                const dumper = new TreeDumper(fileUri, parseResults.tokenizerOutput.lines);
                dumper.walk(parseResults.parserOutput.parseTree);
                collectingConsole.info(dumper.output);
                break;
            }
            case 'types': {
                const evaluator = workspace.service.getEvaluator();
                const start = params.arguments[2];
                const end = params.arguments[3];
                if (!evaluator || !start || !end) {
                    return [];
                }
                collectingConsole.info(`* Type info`);
                collectingConsole.info(`${getTypeEvaluatorString(fileUri, evaluator, parseResults, start, end)}`);
                break;
            }
            case 'cachedtypes': {
                const evaluator = workspace.service.getEvaluator();
                const start = params.arguments[2];
                const end = params.arguments[3];
                if (!evaluator || !start || !end) {
                    return [];
                }
                collectingConsole.info(`* Cached Type info`);
                collectingConsole.info(`${getTypeEvaluatorString(fileUri, evaluator, parseResults, start, end, true)}`);
                break;
            }
            case 'codeflowgraph': {
                const evaluator = workspace.service.getEvaluator();
                const offset = params.arguments[2];
                if (!evaluator || offset === undefined) {
                    return [];
                }
                const node = (0, parseTreeUtils_1.findNodeByOffset)(parseResults.parserOutput.parseTree, offset);
                if (!node) {
                    return [];
                }
                const flowNode = (0, analyzerNodeInfo_1.getFlowNode)(node);
                if (!flowNode) {
                    return [];
                }
                collectingConsole.info(`* CodeFlow Graph`);
                evaluator.printControlFlowGraph(flowNode, undefined, 'Dump CodeFlowGraph', collectingConsole);
            }
        }
        // Print all of the output in one message so the trace log is smaller.
        this._ls.console.info(output.join('\n'));
    }
}
exports.DumpFileDebugInfoCommand = DumpFileDebugInfoCommand;
function stringify(value, replacer) {
    const json = JSON.stringify(value, replacer, 2);
    // Unescape any paths so VS code shows them as clickable.
    return json.replace(/\\\\/g, '\\');
}
function getTypeEvaluatorString(uri, evaluator, results, start, end, cacheOnly) {
    var _a, _b;
    const dumper = new TreeDumper(uri, results.tokenizerOutput.lines);
    const node = (_a = (0, parseTreeUtils_1.findNodeByOffset)(results.parserOutput.parseTree, start)) !== null && _a !== void 0 ? _a : (0, parseTreeUtils_1.findNodeByOffset)(results.parserOutput.parseTree, end);
    if (!node) {
        return 'N/A';
    }
    const set = new Set();
    if (node.nodeType === 38 /* ParseNodeType.Name */) {
        switch ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) {
            case 10 /* ParseNodeType.Class */: {
                const result = cacheOnly
                    ? evaluator.getCachedType(node.parent.name)
                    : evaluator.getTypeOfClass(node.parent);
                if (!result) {
                    return 'N/A';
                }
                return stringify(result, replacer);
            }
            case 28 /* ParseNodeType.Function */: {
                const result = cacheOnly
                    ? evaluator.getCachedType(node.parent.name)
                    : evaluator.getTypeOfFunction(node.parent);
                if (!result) {
                    return 'N/A';
                }
                return stringify(result, replacer);
            }
        }
    }
    const range = textRange_1.TextRange.fromBounds(start, end);
    const expr = getExpressionNodeWithRange(node, range);
    if (!expr) {
        return 'N/A';
    }
    const sb = `Expression node found at ${getTextSpanString(expr, results.tokenizerOutput.lines)} from the given span ${getTextSpanString(range, results.tokenizerOutput.lines)}\r\n`;
    const result = cacheOnly ? evaluator.getCachedType(expr) : evaluator.getType(expr);
    if (!result) {
        return sb + 'No result';
    }
    return sb + stringify(result, replacer);
    function getExpressionNodeWithRange(node, range) {
        // find best expression node that contains both start and end.
        let current = node;
        while (current && !textRange_1.TextRange.containsRange(current, range)) {
            current = current.parent;
        }
        if (!current) {
            return undefined;
        }
        while (!(0, parseNodes_1.isExpressionNode)(current)) {
            current = current.parent;
        }
        return current;
    }
    function replacer(key, value) {
        if (value === undefined) {
            return undefined;
        }
        if (!(0, core_1.isNumber)(value) && !(0, core_1.isString)(value)) {
            if (set.has(value)) {
                if (isClassType(value)) {
                    return `<cycle> class '${value.details.fullName}' typeSourceId:${value.details.typeSourceId}`;
                }
                if (isFunctionType(value)) {
                    return `<cycle> function '${value.details.fullName}' parameter count:${value.details.parameters.length}`;
                }
                if (isTypeVarType(value)) {
                    return `<cycle> function '${value.details.name}' scope id:${value.nameWithScope}`;
                }
                return undefined;
            }
            else {
                set.add(value);
            }
        }
        if (isTypeBase(this) && key === 'category') {
            return getTypeCategoryString(value, this);
        }
        if (isTypeBase(this) && key === 'flags') {
            return getTypeFlagsString(value);
        }
        if (isClassDetail(this) && key === 'flags') {
            return getClassTypeFlagsString(value);
        }
        if (isFunctionDetail(this) && key === 'flags') {
            return getFunctionTypeFlagsString(value);
        }
        if (isTypeVarDetails(this) && key === 'variance') {
            return getVarianceString(value);
        }
        if (isParameter(this) && key === 'category') {
            return getParameterCategoryString(value);
        }
        if (value.nodeType && value.id) {
            dumper.visitNode(value);
            const output = dumper.output;
            dumper.reset();
            return output;
        }
        return value;
    }
    function isTypeBase(type) {
        return type.category && type.flags;
    }
    function isClassType(type) {
        return isTypeBase(type) && type.details && isClassDetail(type.details);
    }
    function isClassDetail(type) {
        return (type.name !== undefined && type.fullName !== undefined && type.moduleName !== undefined && type.baseClasses);
    }
    function isFunctionType(type) {
        return isTypeBase(type) && type.details && isFunctionDetail(type.details);
    }
    function isFunctionDetail(type) {
        return (type.name !== undefined && type.fullName !== undefined && type.moduleName !== undefined && type.parameters);
    }
    function isTypeVarType(type) {
        return isTypeBase(type) && type.details && isTypeVarDetails(type.details);
    }
    function isTypeVarDetails(type) {
        return type.name !== undefined && type.constraints && type.variance !== undefined;
    }
    function isParameter(type) {
        return type.category && type.type;
    }
}
function getVarianceString(type) {
    switch (type) {
        case 2 /* Variance.Invariant */:
            return 'Invariant';
        case 3 /* Variance.Covariant */:
            return 'Covariant';
        case 4 /* Variance.Contravariant */:
            return 'Contravariant';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getFlagEnumString(enumMap, enumValue) {
    const str = [];
    enumMap.forEach((e) => {
        if (enumValue & e[0]) {
            str.push(e[1]);
        }
    });
    if (str.length === 0) {
        if (enumValue === 0) {
            return 'None';
        }
        return '<Unknown>';
    }
    return str.join(',');
}
const FunctionTypeFlagsToString = [
    [8 /* FunctionTypeFlags.AbstractMethod */, 'AbstractMethod'],
    [512 /* FunctionTypeFlags.Async */, 'Async'],
    [2 /* FunctionTypeFlags.ClassMethod */, 'ClassMethod'],
    [1 /* FunctionTypeFlags.ConstructorMethod */, 'ConstructorMethod'],
    [32 /* FunctionTypeFlags.DisableDefaultChecks */, 'DisableDefaultChecks'],
    [8192 /* FunctionTypeFlags.Final */, 'Final'],
    [16 /* FunctionTypeFlags.Generator */, 'Generator'],
    [256 /* FunctionTypeFlags.Overloaded */, 'Overloaded'],
    [65536 /* FunctionTypeFlags.ParamSpecValue */, 'ParamSpecValue'],
    [131072 /* FunctionTypeFlags.PartiallyEvaluated */, 'PartiallyEvaluated'],
    [4096 /* FunctionTypeFlags.PyTypedDefinition */, 'PyTypedDefinition'],
    [32768 /* FunctionTypeFlags.SkipArgsKwargsCompatibilityCheck */, 'SkipArgsKwargsCompatibilityCheck'],
    [4 /* FunctionTypeFlags.StaticMethod */, 'StaticMethod'],
    [2048 /* FunctionTypeFlags.StubDefinition */, 'StubDefinition'],
    [64 /* FunctionTypeFlags.SynthesizedMethod */, 'SynthesizedMethod'],
    [16384 /* FunctionTypeFlags.UnannotatedParams */, 'UnannotatedParams'],
];
function getFunctionTypeFlagsString(flags) {
    return getFlagEnumString(FunctionTypeFlagsToString, flags);
}
const ClassTypeFlagsToString = [
    [1 /* ClassTypeFlags.BuiltInClass */, 'BuiltInClass'],
    [1024 /* ClassTypeFlags.CanOmitDictValues */, 'CanOmitDictValues'],
    [8388608 /* ClassTypeFlags.ClassProperty */, 'ClassProperty'],
    [4 /* ClassTypeFlags.DataClass */, 'DataClass'],
    [4194304 /* ClassTypeFlags.DataClassKeywordOnlyParams */, 'DataClassKeywordOnlyParams'],
    [16777216 /* ClassTypeFlags.DefinedInStub */, 'DefinedInStub'],
    [2097152 /* ClassTypeFlags.EnumClass */, 'EnumClass'],
    [8192 /* ClassTypeFlags.Final */, 'Final'],
    [8 /* ClassTypeFlags.FrozenDataClass */, 'FrozenDataClass'],
    [67108864 /* ClassTypeFlags.GenerateDataClassSlots */, 'GenerateDataClassSlots'],
    [524288 /* ClassTypeFlags.HasCustomClassGetItem */, 'HasCustomClassGetItem'],
    [262144 /* ClassTypeFlags.PartiallyEvaluated */, 'PartiallyEvaluated'],
    [4096 /* ClassTypeFlags.PropertyClass */, 'PropertyClass'],
    [16384 /* ClassTypeFlags.ProtocolClass */, 'ProtocolClass'],
    [32768 /* ClassTypeFlags.PseudoGenericClass */, 'PseudoGenericClass'],
    [33554432 /* ClassTypeFlags.ReadOnlyInstanceVariables */, 'ReadOnlyInstanceVariables'],
    [65536 /* ClassTypeFlags.RuntimeCheckable */, 'RuntimeCheckable'],
    [32 /* ClassTypeFlags.SkipSynthesizedDataClassEq */, 'SkipSynthesizedDataClassEq'],
    [16 /* ClassTypeFlags.SkipSynthesizedDataClassInit */, 'SkipSynthesizedDataClassInit'],
    [2 /* ClassTypeFlags.SpecialBuiltIn */, 'SpecialBuiltIn'],
    [2048 /* ClassTypeFlags.SupportsAbstractMethods */, 'SupportsAbstractMethods'],
    [134217728 /* ClassTypeFlags.SynthesizeDataClassUnsafeHash */, 'SynthesizeDataClassUnsafeHash'],
    [64 /* ClassTypeFlags.SynthesizedDataClassOrder */, 'SynthesizedDataClassOrder'],
    [1048576 /* ClassTypeFlags.TupleClass */, 'TupleClass'],
    [128 /* ClassTypeFlags.TypedDictClass */, 'TypedDictClass'],
    [131072 /* ClassTypeFlags.TypingExtensionClass */, 'TypingExtensionClass'],
];
function getClassTypeFlagsString(flags) {
    return getFlagEnumString(ClassTypeFlagsToString, flags);
}
function getTypeFlagsString(flags) {
    const str = [];
    if (flags & 1 /* TypeFlags.Instantiable */) {
        str.push('Instantiable');
    }
    if (flags & 2 /* TypeFlags.Instance */) {
        str.push('Instance');
    }
    if (str.length === 0)
        return 'None';
    return str.join(',');
}
function getTypeCategoryString(typeCategory, type) {
    switch (typeCategory) {
        case 0 /* TypeCategory.Unbound */:
            return 'Unbound';
        case 1 /* TypeCategory.Unknown */:
            return 'Unknown';
        case 2 /* TypeCategory.Any */:
            return 'Any';
        case 3 /* TypeCategory.Never */:
            return 'Never';
        case 4 /* TypeCategory.Function */:
            return 'Function';
        case 5 /* TypeCategory.OverloadedFunction */:
            return 'OverloadedFunction';
        case 6 /* TypeCategory.Class */:
            if (types_1.TypeBase.isInstantiable(type)) {
                return 'Class';
            }
            else {
                return 'Object';
            }
        case 7 /* TypeCategory.Module */:
            return 'Module';
        case 8 /* TypeCategory.Union */:
            return 'Union';
        case 9 /* TypeCategory.TypeVar */:
            return 'TypeVar';
        default:
            return `Unknown Value!! (${typeCategory})`;
    }
}
class TreeDumper extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_uri, _lines) {
        super();
        this._uri = _uri;
        this._lines = _lines;
        this._indentation = '';
        this._output = '';
    }
    get output() {
        return this._output;
    }
    walk(node) {
        const childrenToWalk = this.visitNode(node);
        if (childrenToWalk.length > 0) {
            this._indentation += '  ';
            this.walkMultiple(childrenToWalk);
            this._indentation = this._indentation.substr(0, this._indentation.length - 2);
        }
    }
    reset() {
        this._indentation = '';
        this._output = '';
    }
    visitArgument(node) {
        this._log(`${this._getPrefix(node)} ${getArgumentCategoryString(node.argumentCategory)}`);
        return true;
    }
    visitAssert(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitAssignment(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitAssignmentExpression(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitAugmentedAssignment(node) {
        this._log(`${this._getPrefix(node)} ${getOperatorTypeString(node.operator)}`);
        return true;
    }
    visitAwait(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitBinaryOperation(node) {
        this._log(`${this._getPrefix(node)} ${getTokenString(this._uri, node.operatorToken, this._lines)} ${getOperatorTypeString(node.operator)}} parenthesized:(${node.parenthesized})`);
        return true;
    }
    visitBreak(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitCall(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitClass(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitTernary(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitContinue(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitConstant(node) {
        this._log(`${this._getPrefix(node)} ${getKeywordTypeString(node.constType)}`);
        return true;
    }
    visitDecorator(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitDel(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitDictionary(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitDictionaryKeyEntry(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitDictionaryExpandEntry(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitError(node) {
        this._log(`${this._getPrefix(node)} ${getErrorExpressionCategoryString(node.category)}`);
        return true;
    }
    visitEllipsis(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitIf(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitImport(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitImportAs(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitImportFrom(node) {
        this._log(`${this._getPrefix(node)} wildcard import:(${node.isWildcardImport}) paren:(${node.usesParens}) wildcard token:(${node.wildcardToken ? getTokenString(this._uri, node.wildcardToken, this._lines) : 'N/A'}) missing import keyword:(${node.missingImportKeyword})`);
        return true;
    }
    visitImportFromAs(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitIndex(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitExcept(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitFor(node) {
        this._log(`${this._getPrefix(node)} async:(${node.isAsync})`);
        return true;
    }
    visitFormatString(node) {
        this._log(`${this._getPrefix(node)} f-string`);
        return true;
    }
    visitFunction(node) {
        this._log(`${this._getPrefix(node)} async:(${node.isAsync})`);
        return true;
    }
    visitFunctionAnnotation(node) {
        this._log(`${this._getPrefix(node)} ellipsis:(${node.isParamListEllipsis})`);
        return true;
    }
    visitGlobal(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitLambda(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitList(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitListComprehension(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitListComprehensionFor(node) {
        this._log(`${this._getPrefix(node)} async:(${node.isAsync})`);
        return true;
    }
    visitListComprehensionIf(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitMemberAccess(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitModule(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitModuleName(node) {
        this._log(`${this._getPrefix(node)} leading dots:(${node.leadingDots}) trailing dot:(${node.hasTrailingDot})`);
        return true;
    }
    visitName(node) {
        this._log(`${this._getPrefix(node)} ${getTokenString(this._uri, node.token, this._lines)} ${node.value}`);
        return true;
    }
    visitNonlocal(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitNumber(node) {
        this._log(`${this._getPrefix(node)} ${node.value} int:(${node.isInteger}) imaginary:(${node.isImaginary})`);
        return true;
    }
    visitParameter(node) {
        this._log(`${this._getPrefix(node)} ${getParameterCategoryString(node.category)}`);
        return true;
    }
    visitPass(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitRaise(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitReturn(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitSet(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitSlice(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitStatementList(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitString(node) {
        this._log(`${this._getPrefix(node)} ${getTokenString(this._uri, node.token, this._lines)} ${node.value}`);
        return true;
    }
    visitStringList(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitSuite(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitTuple(node) {
        this._log(`${this._getPrefix(node)} paren:(${node.enclosedInParens})`);
        return true;
    }
    visitTry(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitTypeAnnotation(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitUnaryOperation(node) {
        this._log(`${this._getPrefix(node)} ${getTokenString(this._uri, node.operatorToken, this._lines)} ${getOperatorTypeString(node.operator)}`);
        return true;
    }
    visitUnpack(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitWhile(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitWith(node) {
        this._log(`${this._getPrefix(node)} async:(${node.isAsync})`);
        return true;
    }
    visitWithItem(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitYield(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitYieldFrom(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitCase(node) {
        this._log(`${this._getPrefix(node)} isIrrefutable: ${node.isIrrefutable}`);
        return true;
    }
    visitMatch(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternAs(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternCapture(node) {
        this._log(`${this._getPrefix(node)} isStar:${node.isStar} isWildcard:${node.isWildcard}`);
        return true;
    }
    visitPatternClass(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternClassArgument(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternLiteral(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternMapping(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternMappingExpandEntry(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternMappingKeyEntry(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitPatternSequence(node) {
        this._log(`${this._getPrefix(node)} starEntryIndex: ${node.starEntryIndex}`);
        return true;
    }
    visitPatternValue(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitTypeAlias(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    visitTypeParameter(node) {
        this._log(`${this._getPrefix(node)} typeParamCategory:${getTypeParameterCategoryString(node.typeParamCategory)}`);
        return true;
    }
    visitTypeParameterList(node) {
        this._log(`${this._getPrefix(node)}`);
        return true;
    }
    _log(value) {
        this._output += `${this._indentation}${value}\r\n`;
    }
    _getPrefix(node) {
        const pos = (0, positionUtils_1.convertOffsetToPosition)(node.start, this._lines);
        // VS code's output window expects 1 based values, print the line/char with 1 based.
        return `[${node.id}] '${this._uri.toString()}:${pos.line + 1}:${pos.character + 1}' => ${(0, parseTreeUtils_1.printParseNodeType)(node.nodeType)} ${getTextSpanString(node, this._lines)} =>`;
    }
}
function getTypeParameterCategoryString(type) {
    switch (type) {
        case parseNodes_1.TypeParameterCategory.TypeVar:
            return 'TypeVar';
        case parseNodes_1.TypeParameterCategory.TypeVarTuple:
            return 'TypeVarTuple';
        case parseNodes_1.TypeParameterCategory.ParamSpec:
            return 'ParamSpec';
    }
}
function getParameterCategoryString(type) {
    switch (type) {
        case 0 /* ParameterCategory.Simple */:
            return 'Simple';
        case 1 /* ParameterCategory.ArgsList */:
            return 'VarArgList';
        case 2 /* ParameterCategory.KwargsDict */:
            return 'VarArgDictionary';
    }
}
function getArgumentCategoryString(type) {
    switch (type) {
        case 0 /* ArgumentCategory.Simple */:
            return 'Simple';
        case 1 /* ArgumentCategory.UnpackedList */:
            return 'UnpackedList';
        case 2 /* ArgumentCategory.UnpackedDictionary */:
            return 'UnpackedDictionary';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getErrorExpressionCategoryString(type) {
    switch (type) {
        case 0 /* ErrorExpressionCategory.MissingIn */:
            return 'MissingIn';
        case 1 /* ErrorExpressionCategory.MissingElse */:
            return 'MissingElse';
        case 2 /* ErrorExpressionCategory.MissingExpression */:
            return 'MissingExpression';
        case 3 /* ErrorExpressionCategory.MissingIndexOrSlice */:
            return 'MissingIndexOrSlice';
        case 4 /* ErrorExpressionCategory.MissingDecoratorCallName */:
            return 'MissingDecoratorCallName';
        case 5 /* ErrorExpressionCategory.MissingCallCloseParen */:
            return 'MissingCallCloseParen';
        case 6 /* ErrorExpressionCategory.MissingIndexCloseBracket */:
            return 'MissingIndexCloseBracket';
        case 7 /* ErrorExpressionCategory.MissingMemberAccessName */:
            return 'MissingMemberAccessName';
        case 8 /* ErrorExpressionCategory.MissingTupleCloseParen */:
            return 'MissingTupleCloseParen';
        case 9 /* ErrorExpressionCategory.MissingListCloseBracket */:
            return 'MissingListCloseBracket';
        case 10 /* ErrorExpressionCategory.MissingFunctionParameterList */:
            return 'MissingFunctionParameterList';
        case 11 /* ErrorExpressionCategory.MissingPattern */:
            return 'MissingPattern';
        case 12 /* ErrorExpressionCategory.MissingPatternSubject */:
            return 'MissingPatternSubject';
        case 13 /* ErrorExpressionCategory.MissingDictValue */:
            return 'MissingDictValue';
        case 14 /* ErrorExpressionCategory.MaxDepthExceeded */:
            return 'MaxDepthExceeded';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getTokenString(uri, token, lines) {
    const pos = (0, positionUtils_1.convertOffsetToPosition)(token.start, lines);
    let str = `'${uri.toUserVisibleString()}:${pos.line + 1}:${pos.character + 1}' (`;
    str += getTokenTypeString(token.type);
    str += getNewLineInfo(token);
    str += getOperatorInfo(token);
    str += getKeywordInfo(token);
    str += getStringTokenFlags(token);
    str += `, ${getTextSpanString(token, lines)}`;
    str += ') ';
    str += JSON.stringify(token);
    return str;
    function getNewLineInfo(t) {
        return t.newLineType ? `, ${getNewLineTypeString(t.newLineType)}` : '';
    }
    function getOperatorInfo(t) {
        return t.operatorType ? `, ${getOperatorTypeString(t.operatorType)}` : '';
    }
    function getKeywordInfo(t) {
        return t.keywordType ? `, ${getKeywordTypeString(t.keywordType)}` : '';
    }
    function getStringTokenFlags(t) {
        return t.flags ? `, [${getStringTokenFlagsString(t.flags)}]` : '';
    }
}
function getTextSpanString(span, lines) {
    const range = (0, positionUtils_1.convertOffsetsToRange)(span.start, textRange_1.TextRange.getEnd(span), lines);
    return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`;
}
function getTokenTypeString(type) {
    switch (type) {
        case 0 /* TokenType.Invalid */:
            return 'Invalid';
        case 1 /* TokenType.EndOfStream */:
            return 'EndOfStream';
        case 2 /* TokenType.NewLine */:
            return 'NewLine';
        case 3 /* TokenType.Indent */:
            return 'Indent';
        case 4 /* TokenType.Dedent */:
            return 'Dedent';
        case 5 /* TokenType.String */:
            return 'String';
        case 6 /* TokenType.Number */:
            return 'Number';
        case 7 /* TokenType.Identifier */:
            return 'Identifier';
        case 8 /* TokenType.Keyword */:
            return 'Keyword';
        case 9 /* TokenType.Operator */:
            return 'Operator';
        case 10 /* TokenType.Colon */:
            return 'Colon';
        case 11 /* TokenType.Semicolon */:
            return 'Semicolon';
        case 12 /* TokenType.Comma */:
            return 'Comma';
        case 13 /* TokenType.OpenParenthesis */:
            return 'OpenParenthesis';
        case 14 /* TokenType.CloseParenthesis */:
            return 'CloseParenthesis';
        case 15 /* TokenType.OpenBracket */:
            return 'OpenBracket';
        case 16 /* TokenType.CloseBracket */:
            return 'CloseBracket';
        case 17 /* TokenType.OpenCurlyBrace */:
            return 'OpenCurlyBrace';
        case 18 /* TokenType.CloseCurlyBrace */:
            return 'CloseCurlyBrace';
        case 19 /* TokenType.Ellipsis */:
            return 'Ellipsis';
        case 20 /* TokenType.Dot */:
            return 'Dot';
        case 21 /* TokenType.Arrow */:
            return 'Arrow';
        case 22 /* TokenType.Backtick */:
            return 'Backtick';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getNewLineTypeString(type) {
    switch (type) {
        case 0 /* NewLineType.CarriageReturn */:
            return 'CarriageReturn';
        case 1 /* NewLineType.LineFeed */:
            return 'LineFeed';
        case 2 /* NewLineType.CarriageReturnLineFeed */:
            return 'CarriageReturnLineFeed';
        case 3 /* NewLineType.Implied */:
            return 'Implied';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getOperatorTypeString(type) {
    switch (type) {
        case 0 /* OperatorType.Add */:
            return 'Add';
        case 1 /* OperatorType.AddEqual */:
            return 'AddEqual';
        case 2 /* OperatorType.Assign */:
            return 'Assign';
        case 3 /* OperatorType.BitwiseAnd */:
            return 'BitwiseAnd';
        case 4 /* OperatorType.BitwiseAndEqual */:
            return 'BitwiseAndEqual';
        case 5 /* OperatorType.BitwiseInvert */:
            return 'BitwiseInvert';
        case 6 /* OperatorType.BitwiseOr */:
            return 'BitwiseOr';
        case 7 /* OperatorType.BitwiseOrEqual */:
            return 'BitwiseOrEqual';
        case 8 /* OperatorType.BitwiseXor */:
            return 'BitwiseXor';
        case 9 /* OperatorType.BitwiseXorEqual */:
            return 'BitwiseXorEqual';
        case 10 /* OperatorType.Divide */:
            return 'Divide';
        case 11 /* OperatorType.DivideEqual */:
            return 'DivideEqual';
        case 12 /* OperatorType.Equals */:
            return 'Equals';
        case 13 /* OperatorType.FloorDivide */:
            return 'FloorDivide';
        case 14 /* OperatorType.FloorDivideEqual */:
            return 'FloorDivideEqual';
        case 15 /* OperatorType.GreaterThan */:
            return 'GreaterThan';
        case 16 /* OperatorType.GreaterThanOrEqual */:
            return 'GreaterThanOrEqual';
        case 17 /* OperatorType.LeftShift */:
            return 'LeftShift';
        case 18 /* OperatorType.LeftShiftEqual */:
            return 'LeftShiftEqual';
        case 19 /* OperatorType.LessOrGreaterThan */:
            return 'LessOrGreaterThan';
        case 20 /* OperatorType.LessThan */:
            return 'LessThan';
        case 21 /* OperatorType.LessThanOrEqual */:
            return 'LessThanOrEqual';
        case 22 /* OperatorType.MatrixMultiply */:
            return 'MatrixMultiply';
        case 23 /* OperatorType.MatrixMultiplyEqual */:
            return 'MatrixMultiplyEqual';
        case 24 /* OperatorType.Mod */:
            return 'Mod';
        case 25 /* OperatorType.ModEqual */:
            return 'ModEqual';
        case 26 /* OperatorType.Multiply */:
            return 'Multiply';
        case 27 /* OperatorType.MultiplyEqual */:
            return 'MultiplyEqual';
        case 28 /* OperatorType.NotEquals */:
            return 'NotEquals';
        case 29 /* OperatorType.Power */:
            return 'Power';
        case 30 /* OperatorType.PowerEqual */:
            return 'PowerEqual';
        case 31 /* OperatorType.RightShift */:
            return 'RightShift';
        case 32 /* OperatorType.RightShiftEqual */:
            return 'RightShiftEqual';
        case 33 /* OperatorType.Subtract */:
            return 'Subtract';
        case 34 /* OperatorType.SubtractEqual */:
            return 'SubtractEqual';
        case 35 /* OperatorType.Walrus */:
            return 'Walrus';
        case 36 /* OperatorType.And */:
            return 'And';
        case 37 /* OperatorType.Or */:
            return 'Or';
        case 38 /* OperatorType.Not */:
            return 'Not';
        case 39 /* OperatorType.Is */:
            return 'Is';
        case 40 /* OperatorType.IsNot */:
            return 'IsNot';
        case 41 /* OperatorType.In */:
            return 'In';
        case 42 /* OperatorType.NotIn */:
            return 'NotIn';
        default:
            return `Unknown Value!! (${type})`;
    }
}
function getKeywordTypeString(type) {
    switch (type) {
        case 0 /* KeywordType.And */:
            return 'And';
        case 1 /* KeywordType.As */:
            return 'As';
        case 2 /* KeywordType.Assert */:
            return 'Assert';
        case 3 /* KeywordType.Async */:
            return 'Async';
        case 4 /* KeywordType.Await */:
            return 'Await';
        case 5 /* KeywordType.Break */:
            return 'Break';
        case 7 /* KeywordType.Class */:
            return 'Class';
        case 8 /* KeywordType.Continue */:
            return 'Continue';
        case 9 /* KeywordType.Debug */:
            return 'Debug';
        case 10 /* KeywordType.Def */:
            return 'Def';
        case 11 /* KeywordType.Del */:
            return 'Del';
        case 12 /* KeywordType.Elif */:
            return 'Elif';
        case 13 /* KeywordType.Else */:
            return 'Else';
        case 14 /* KeywordType.Except */:
            return 'Except';
        case 15 /* KeywordType.False */:
            return 'False';
        case 16 /* KeywordType.Finally */:
            return 'Finally';
        case 17 /* KeywordType.For */:
            return 'For';
        case 18 /* KeywordType.From */:
            return 'From';
        case 19 /* KeywordType.Global */:
            return 'Global';
        case 20 /* KeywordType.If */:
            return 'If';
        case 21 /* KeywordType.Import */:
            return 'Import';
        case 22 /* KeywordType.In */:
            return 'In';
        case 23 /* KeywordType.Is */:
            return 'Is';
        case 24 /* KeywordType.Lambda */:
            return 'Lambda';
        case 26 /* KeywordType.None */:
            return 'None';
        case 27 /* KeywordType.Nonlocal */:
            return 'Nonlocal';
        case 28 /* KeywordType.Not */:
            return 'Not';
        case 29 /* KeywordType.Or */:
            return 'Or';
        case 30 /* KeywordType.Pass */:
            return 'Pass';
        case 31 /* KeywordType.Raise */:
            return 'Raise';
        case 32 /* KeywordType.Return */:
            return 'Return';
        case 33 /* KeywordType.True */:
            return 'True';
        case 34 /* KeywordType.Try */:
            return 'Try';
        case 36 /* KeywordType.While */:
            return 'While';
        case 37 /* KeywordType.With */:
            return 'With';
        case 38 /* KeywordType.Yield */:
            return 'Yield';
        default:
            return `Unknown Value!! (${type})`;
    }
}
const StringTokenFlagsStrings = [
    [32 /* StringTokenFlags.Bytes */, 'Bytes'],
    [2 /* StringTokenFlags.DoubleQuote */, 'DoubleQuote'],
    [64 /* StringTokenFlags.Format */, 'Format'],
    [8 /* StringTokenFlags.Raw */, 'Raw'],
    [1 /* StringTokenFlags.SingleQuote */, 'SingleQuote'],
    [4 /* StringTokenFlags.Triplicate */, 'Triplicate'],
    [16 /* StringTokenFlags.Unicode */, 'Unicode'],
    [65536 /* StringTokenFlags.Unterminated */, 'Unterminated'],
];
function getStringTokenFlagsString(flags) {
    return getFlagEnumString(StringTokenFlagsStrings, flags);
}


/***/ }),

/***/ "../pyright-internal/src/commands/quickActionCommand.ts":
/*!**************************************************************!*\
  !*** ../pyright-internal/src/commands/quickActionCommand.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * quickActionCommand.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements command that maps to a quick action.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.QuickActionCommand = void 0;
const workspaceEditUtils_1 = __webpack_require__(/*! ../common/workspaceEditUtils */ "../pyright-internal/src/common/workspaceEditUtils.ts");
const quickActions_1 = __webpack_require__(/*! ../languageService/quickActions */ "../pyright-internal/src/languageService/quickActions.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
class QuickActionCommand {
    constructor(_ls) {
        this._ls = _ls;
    }
    async execute(params, token) {
        if (params.arguments && params.arguments.length >= 1) {
            const docUri = uri_1.Uri.parse(params.arguments[0], this._ls.serviceProvider);
            const otherArgs = params.arguments.slice(1);
            const workspace = await this._ls.getWorkspaceForFile(docUri);
            if (params.command === "basedpyright.organizeimports" /* Commands.orderImports */ && workspace.disableOrganizeImports) {
                return [];
            }
            const editActions = workspace.service.run((p) => {
                return (0, quickActions_1.performQuickAction)(p, docUri, params.command, otherArgs, token);
            }, token);
            return (0, workspaceEditUtils_1.convertToWorkspaceEdit)(workspace.service.fs, (0, workspaceEditUtils_1.convertToFileTextEdits)(docUri, editActions !== null && editActions !== void 0 ? editActions : []));
        }
    }
}
exports.QuickActionCommand = QuickActionCommand;


/***/ }),

/***/ "../pyright-internal/src/commands/restartServer.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/commands/restartServer.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * restartServer.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements 'restart server' command functionality.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RestartServerCommand = void 0;
class RestartServerCommand {
    constructor(_ls) {
        this._ls = _ls;
    }
    async execute(cmdParams) {
        this._ls.restart();
    }
}
exports.RestartServerCommand = RestartServerCommand;


/***/ }),

/***/ "../pyright-internal/src/common/cancellationUtils.ts":
/*!***********************************************************!*\
  !*** ../pyright-internal/src/common/cancellationUtils.ts ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * cancellationUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper methods relating to cancellation.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.raceCancellation = exports.CancellationThrottle = exports.FileBasedToken = exports.getCancellationTokenId = exports.DefaultCancellationProvider = exports.CancelAfter = exports.onCancellationRequested = exports.throwIfCancellationRequested = exports.OperationCanceledException = exports.setCancellationFolderName = exports.getCancellationFolderName = void 0;
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
let cancellationFolderName;
function getCancellationFolderName() {
    return cancellationFolderName;
}
exports.getCancellationFolderName = getCancellationFolderName;
function setCancellationFolderName(folderName) {
    cancellationFolderName = folderName;
}
exports.setCancellationFolderName = setCancellationFolderName;
class OperationCanceledException extends vscode_languageserver_1.ResponseError {
    constructor() {
        super(vscode_languageserver_1.LSPErrorCodes.RequestCancelled, 'request cancelled');
        // If true, indicates that the cancellation may have left the type cache
        // in an invalid state.
        this.isTypeCacheInvalid = false;
    }
    static is(e) {
        return e.code === vscode_languageserver_1.LSPErrorCodes.RequestCancelled;
    }
}
exports.OperationCanceledException = OperationCanceledException;
function throwIfCancellationRequested(token) {
    // Don't use cancellation in debug mode because it interferes with
    // debugging if requests are cancelled.
    if (!(0, core_1.isDebugMode)() && token.isCancellationRequested) {
        throw new OperationCanceledException();
    }
}
exports.throwIfCancellationRequested = throwIfCancellationRequested;
const nullDisposable = vscode_languageserver_1.Disposable.create(() => { });
function onCancellationRequested(token, func) {
    try {
        return token.onCancellationRequested(func);
    }
    catch {
        // Certain cancellation token implementations, like SharedArrayCancellation
        // (https://github.com/microsoft/vscode-languageserver-node/blob/main/jsonrpc/src/common/sharedArrayCancellation.ts#L70),
        // do not support the `onCancellationRequested` method. In such cases, proceed to the next token.
        return nullDisposable;
    }
}
exports.onCancellationRequested = onCancellationRequested;
function CancelAfter(provider, ...tokens) {
    const source = provider.createCancellationTokenSource();
    const disposables = [];
    for (const token of tokens) {
        disposables.push(onCancellationRequested(token, () => {
            source.cancel();
        }));
    }
    disposables.push(onCancellationRequested(source.token, () => {
        disposables.forEach((d) => d.dispose());
    }));
    return source;
}
exports.CancelAfter = CancelAfter;
class DefaultCancellationProvider {
    createCancellationTokenSource() {
        return new vscode_jsonrpc_1.CancellationTokenSource();
    }
}
exports.DefaultCancellationProvider = DefaultCancellationProvider;
function getCancellationTokenId(token) {
    return token instanceof FileBasedToken ? token.id : undefined;
}
exports.getCancellationTokenId = getCancellationTokenId;
class FileBasedToken {
    constructor(cancellationId, _fs) {
        this._fs = _fs;
        this.isCancelled = false;
        this.cancellationFilePath = uriUtils_1.UriEx.file(cancellationId);
    }
    get id() {
        return this.cancellationFilePath.toString();
    }
    get isCancellationRequested() {
        if (this.isCancelled) {
            return true;
        }
        if (CancellationThrottle.shouldCheck() && this._pipeExists()) {
            // The first time it encounters the cancellation file, it will
            // cancel itself and raise a cancellation event.
            // In this mode, cancel() might not be called explicitly by
            // jsonrpc layer.
            this.cancel();
        }
        return this.isCancelled;
    }
    get onCancellationRequested() {
        if (!this._emitter) {
            this._emitter = new vscode_jsonrpc_1.Emitter();
        }
        return this._emitter.event;
    }
    cancel() {
        if (!this.isCancelled) {
            this.isCancelled = true;
            if (this._emitter) {
                this._emitter.fire(undefined);
                this._disposeEmitter();
            }
        }
    }
    dispose() {
        this._disposeEmitter();
    }
    _disposeEmitter() {
        if (this._emitter) {
            this._emitter.dispose();
            this._emitter = undefined;
        }
    }
    _pipeExists() {
        try {
            this._fs.statSync(this.cancellationFilePath);
            return true;
        }
        catch (e) {
            return false;
        }
    }
}
exports.FileBasedToken = FileBasedToken;
class CancellationThrottle {
    static shouldCheck() {
        // Throttle cancellation checks to one every 5ms. This value
        // was selected through empirical testing. If we call the
        // file system more often than this, type analysis performance
        // is affected. If we call it less often, performance doesn't
        // improve much, but responsiveness suffers.
        const minTimeBetweenChecksInMs = 5;
        const curTimestamp = Date.now().valueOf();
        const timeSinceLastCheck = curTimestamp - this._lastCheckTimestamp;
        if (timeSinceLastCheck >= minTimeBetweenChecksInMs) {
            this._lastCheckTimestamp = curTimestamp;
            return true;
        }
        return false;
    }
}
exports.CancellationThrottle = CancellationThrottle;
CancellationThrottle._lastCheckTimestamp = 0;
async function raceCancellation(token, ...promises) {
    if (!token) {
        return Promise.race(promises);
    }
    if (token.isCancellationRequested) {
        throw new OperationCanceledException();
    }
    return new Promise((resolve, reject) => {
        if (token.isCancellationRequested) {
            return reject(new OperationCanceledException());
        }
        const disposable = onCancellationRequested(token, () => {
            disposable.dispose();
            reject(new OperationCanceledException());
        });
        Promise.race(promises)
            .then(resolve, reject)
            .finally(() => disposable.dispose());
    });
}
exports.raceCancellation = raceCancellation;


/***/ }),

/***/ "../pyright-internal/src/common/caseSensitivityDetector.ts":
/*!*****************************************************************!*\
  !*** ../pyright-internal/src/common/caseSensitivityDetector.ts ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * caseSensitivityDetector.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * interface to determine whether the given uri string should be case sensitive or not.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CaseSensitivityDetector = void 0;
var CaseSensitivityDetector;
(function (CaseSensitivityDetector) {
    function is(value) {
        return !!value.isCaseSensitive;
    }
    CaseSensitivityDetector.is = is;
})(CaseSensitivityDetector || (exports.CaseSensitivityDetector = CaseSensitivityDetector = {}));


/***/ }),

/***/ "../pyright-internal/src/common/collectionUtils.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/common/collectionUtils.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * collectionUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper functions relating to collections and arrays.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.arrayEquals = exports.addIfNotNull = exports.getMapValues = exports.addIfUnique = exports.createMapFromItems = exports.removeArrayElements = exports.getOrAdd = exports.getNestedProperty = exports.flatten = exports.binarySearchKey = exports.binarySearch = exports.every = exports.some = exports.map = exports.stableSort = exports.cloneAndSort = exports.insertAt = exports.addRange = exports.find = exports.appendArray = exports.append = exports.contains = exports.emptyArray = void 0;
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
exports.emptyArray = [];
function contains(array, value, equalityComparer = core_1.equateValues) {
    if (array) {
        for (const v of array) {
            if (equalityComparer(v, value)) {
                return true;
            }
        }
    }
    return false;
}
exports.contains = contains;
function append(to, value) {
    if (value === undefined) {
        return to;
    }
    if (to === undefined) {
        return [value];
    }
    to.push(value);
    return to;
}
exports.append = append;
/**
 * Safely pushes the values of one array onto another array. This is the
 * same as receiver.push(...elementsToPush) except that it doesn't risk overflowing
 * the stack if elementsToPush is very large.
 */
function appendArray(to, elementsToPush) {
    if (elementsToPush.length < 256) {
        to.push(...elementsToPush);
        return;
    }
    for (const elem of elementsToPush) {
        to.push(elem);
    }
}
exports.appendArray = appendArray;
function find(array, predicate) {
    for (let i = 0; i < array.length; i++) {
        const value = array[i];
        if (predicate(value, i)) {
            return value;
        }
    }
    return undefined;
}
exports.find = find;
/**
 * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
 * position offset from the end of the array.
 */
function toOffset(array, offset) {
    return offset < 0 ? array.length + offset : offset;
}
function addRange(to, from, start, end) {
    if (from === undefined || from.length === 0) {
        return to;
    }
    if (to === undefined) {
        return from.slice(start, end);
    }
    start = start === undefined ? 0 : toOffset(from, start);
    end = end === undefined ? from.length : toOffset(from, end);
    for (let i = start; i < end && i < from.length; i++) {
        if (from[i] !== undefined) {
            to.push(from[i]);
        }
    }
    return to;
}
exports.addRange = addRange;
function insertAt(array, index, value) {
    if (index === 0) {
        array.unshift(value);
    }
    else if (index === array.length) {
        array.push(value);
    }
    else {
        for (let i = array.length; i > index; i--) {
            array[i] = array[i - 1];
        }
        array[index] = value;
    }
    return array;
}
exports.insertAt = insertAt;
/**
 * Returns a new sorted array.
 */
function cloneAndSort(array, comparer) {
    return (array.length === 0 ? array : array.slice().sort(comparer));
}
exports.cloneAndSort = cloneAndSort;
function selectIndex(_, i) {
    return i;
}
function indicesOf(array) {
    return array.map(selectIndex);
}
/**
 * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
 */
function stableSort(array, comparer) {
    const indices = indicesOf(array);
    stableSortIndices(array, indices, comparer);
    return indices.map((i) => array[i]);
}
exports.stableSort = stableSort;
function stableSortIndices(array, indices, comparer) {
    // sort indices by value then position
    indices.sort((x, y) => comparer(array[x], array[y]) || (0, core_1.compareValues)(x, y));
}
function map(array, f) {
    if (array) {
        return array.map(f);
    }
    return undefined;
}
exports.map = map;
function some(array, predicate) {
    if (array) {
        if (predicate) {
            return array.some(predicate);
        }
        else {
            return array.length > 0;
        }
    }
    return false;
}
exports.some = some;
/**
 * Iterates through `array` by index and performs the callback on each element of array until the callback
 * returns a falsey value, then returns false.
 * If no such value is found, the callback is applied to each element of array and `true` is returned.
 */
function every(array, callback) {
    if (array) {
        return array.every(callback);
    }
    return true;
}
exports.every = every;
/**
 * Performs a binary search, finding the index at which `value` occurs in `array`.
 * If no such index is found, returns the 2's-complement of first index at which
 * `array[index]` exceeds `value`.
 * @param array A sorted array whose first element must be no larger than number
 * @param value The value to be searched for in the array.
 * @param keySelector A callback used to select the search key from `value` and each element of
 * `array`.
 * @param keyComparer A callback used to compare two keys in a sorted array.
 * @param offset An offset into `array` at which to start the search.
 */
function binarySearch(array, value, keySelector, keyComparer, offset) {
    return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
}
exports.binarySearch = binarySearch;
/**
 * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
 * If no such index is found, returns the 2's-complement of first index at which
 * `array[index]` exceeds `key`.
 * @param array A sorted array whose first element must be no larger than number
 * @param key The key to be searched for in the array.
 * @param keySelector A callback used to select the search key from each element of `array`.
 * @param keyComparer A callback used to compare two keys in a sorted array.
 * @param offset An offset into `array` at which to start the search.
 */
function binarySearchKey(array, key, keySelector, keyComparer, offset) {
    if (!some(array)) {
        return -1;
    }
    let low = offset || 0;
    let high = array.length - 1;
    while (low <= high) {
        const middle = low + ((high - low) >> 1);
        const midKey = keySelector(array[middle]);
        switch (keyComparer(midKey, key)) {
            case -1 /* Comparison.LessThan */:
                low = middle + 1;
                break;
            case 0 /* Comparison.EqualTo */:
                return middle;
            case 1 /* Comparison.GreaterThan */:
                high = middle - 1;
                break;
        }
    }
    return ~low;
}
exports.binarySearchKey = binarySearchKey;
/**
 * Flattens an array containing a mix of array or non-array elements.
 *
 * @param array The array to flatten.
 */
function flatten(array) {
    const result = [];
    for (const v of array) {
        if (v) {
            if ((0, core_1.isArray)(v)) {
                addRange(result, v);
            }
            else {
                result.push(v);
            }
        }
    }
    return result;
}
exports.flatten = flatten;
/**
 * Retrieves nested objects by parsing chained properties. ie. "a.b.c"
 * Returns undefined if not found
 * @param object The object to query
 * @param property The property to be searched for in the object ie. "a.b.c"
 */
function getNestedProperty(object, property) {
    const value = property.split('.').reduce((obj, prop) => {
        return obj && obj[prop];
    }, object);
    return value;
}
exports.getNestedProperty = getNestedProperty;
function getOrAdd(map, key, newValueFactory) {
    const value = map.get(key);
    if (value !== undefined) {
        return value;
    }
    const newValue = newValueFactory();
    map.set(key, newValue);
    return newValue;
}
exports.getOrAdd = getOrAdd;
/**
 * Remove matching item from the array in place.
 * Returns the given array itself.
 * @param array The array to operate on.
 * @param predicate Return true for an item to delete.
 */
function removeArrayElements(array, predicate) {
    for (let i = 0; i < array.length; i++) {
        if (predicate(array[i])) {
            array.splice(i, 1);
            // Array is modified in place, we need to look at the same index again.
            i--;
        }
    }
    return array;
}
exports.removeArrayElements = removeArrayElements;
function createMapFromItems(items, keyGetter) {
    return items
        .map((t) => keyGetter(t))
        .reduce((map, key, i) => {
        map.set(key, (map.get(key) || []).concat(items[i]));
        return map;
    }, new Map());
}
exports.createMapFromItems = createMapFromItems;
function addIfUnique(arr, t, equalityComparer = core_1.equateValues) {
    if (contains(arr, t, equalityComparer)) {
        return arr;
    }
    arr.push(t);
    return arr;
}
exports.addIfUnique = addIfUnique;
function getMapValues(m, predicate) {
    const values = [];
    m.forEach((v, k) => {
        if (predicate(k, v)) {
            values.push(v);
        }
    });
    return values;
}
exports.getMapValues = getMapValues;
function addIfNotNull(arr, t) {
    if (t === undefined) {
        return arr;
    }
    arr.push(t);
    return arr;
}
exports.addIfNotNull = addIfNotNull;
function arrayEquals(c1, c2, predicate) {
    if (c1.length !== c2.length) {
        return false;
    }
    return c1.every((v, i) => predicate(v, c2[i]));
}
exports.arrayEquals = arrayEquals;


/***/ }),

/***/ "../pyright-internal/src/common/commandLineOptions.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/common/commandLineOptions.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * commandLineOptions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that holds the command-line options (those that can be
 * passed into the main entry point of the command-line version
 * of the analyzer).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CommandLineOptions = exports.getDiagnosticSeverityOverrides = void 0;
function getDiagnosticSeverityOverrides() {
    return [
        "error" /* DiagnosticSeverityOverrides.Error */,
        "warning" /* DiagnosticSeverityOverrides.Warning */,
        "information" /* DiagnosticSeverityOverrides.Information */,
        "none" /* DiagnosticSeverityOverrides.None */,
    ];
}
exports.getDiagnosticSeverityOverrides = getDiagnosticSeverityOverrides;
// Some options can be specified from a source other than the pyright config file.
// This can be from command-line parameters or some other settings mechanism, like
// that provided through a language client like the VS Code editor. These options
// are later combined with those from the config file to produce the final configuration.
class CommandLineOptions {
    constructor(executionRoot, fromVsCodeExtension) {
        // A list of file specs to include in the analysis. Can contain
        // directories, in which case all "*.py" files within those directories
        // are included.
        this.includeFileSpecs = [];
        // A list of file specs to exclude in the analysis. Can contain
        // directories, in which case all "*.py" files within those directories
        // are excluded.
        this.excludeFileSpecs = [];
        // A list of file specs whose errors and warnings should be ignored even
        // if they are included in the transitive closure of included files.
        this.ignoreFileSpecs = [];
        // Use type evaluator call tracking.
        this.logTypeEvaluationTime = false;
        // Minimum threshold for type eval logging.
        this.typeEvaluationTimeThreshold = 50;
        // Run ambient analysis.
        this.enableAmbientAnalysis = true;
        this.executionRoot = executionRoot;
        this.fromVsCodeExtension = fromVsCodeExtension;
    }
}
exports.CommandLineOptions = CommandLineOptions;


/***/ }),

/***/ "../pyright-internal/src/common/commandUtils.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/common/commandUtils.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * commandUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Utilities for working with LSP commands.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createCommand = void 0;
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
function createCommand(title, command, ...args) {
    // Make sure if any of the args are URIs, we convert them to strings.
    const convertedArgs = args.map((arg) => {
        if (uri_1.Uri.is(arg)) {
            return arg.toString();
        }
        return arg;
    });
    return vscode_languageserver_types_1.Command.create(title, command, ...convertedArgs);
}
exports.createCommand = createCommand;


/***/ }),

/***/ "../pyright-internal/src/common/configOptions.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/common/configOptions.ts ***!
  \*******************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * configOptions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that holds the configuration options for the analyzer.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseDiagLevel = exports.BasedConfigOptions = exports.ConfigOptions = exports.matchFileSpecs = exports.getStrictDiagnosticRuleSet = exports.getAllDiagnosticRuleSet = exports.getStandardDiagnosticRuleSet = exports.getBasicDiagnosticRuleSet = exports.getOffDiagnosticRuleSet = exports.getStrictModeNotOverriddenRules = exports.getDiagLevelDiagnosticRules = exports.getBooleanDiagnosticRules = exports.cloneDiagnosticRuleSet = exports.SignatureDisplayType = exports.ExecutionEnvironment = exports.PythonPlatform = void 0;
const path_1 = __webpack_require__(/*! path */ "path");
const pythonPathUtils_1 = __webpack_require__(/*! ../analyzer/pythonPathUtils */ "../pyright-internal/src/analyzer/pythonPathUtils.ts");
const pathConsts = __importStar(__webpack_require__(/*! ../common/pathConsts */ "../pyright-internal/src/common/pathConsts.ts"));
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const console_1 = __webpack_require__(/*! ./console */ "../pyright-internal/src/common/console.ts");
const diagnosticRules_1 = __webpack_require__(/*! ./diagnosticRules */ "../pyright-internal/src/common/diagnosticRules.ts");
const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const serviceKeys_1 = __webpack_require__(/*! ./serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const stringUtils_1 = __webpack_require__(/*! ./stringUtils */ "../pyright-internal/src/common/stringUtils.ts");
// prevent upstream changes from sneaking in and adding errors using console.error,
// which is cringe because it doesn't change the exit code
/* eslint no-console: ["error", { allow: ["log"] }] */
var PythonPlatform;
(function (PythonPlatform) {
    PythonPlatform["Darwin"] = "Darwin";
    PythonPlatform["Windows"] = "Windows";
    PythonPlatform["Linux"] = "Linux";
})(PythonPlatform || (exports.PythonPlatform = PythonPlatform = {}));
class ExecutionEnvironment {
    // Default to "." which indicates every file in the project.
    constructor(name, root, defaultPythonVersion, defaultPythonPlatform, defaultExtraPaths) {
        // Default to no extra paths.
        this.extraPaths = [];
        this.name = name;
        this.root = root;
        this.pythonVersion = defaultPythonVersion !== null && defaultPythonVersion !== void 0 ? defaultPythonVersion : pythonVersion_1.latestStablePythonVersion;
        this.pythonPlatform = defaultPythonPlatform;
        this.extraPaths = Array.from(defaultExtraPaths !== null && defaultExtraPaths !== void 0 ? defaultExtraPaths : []);
    }
}
exports.ExecutionEnvironment = ExecutionEnvironment;
var SignatureDisplayType;
(function (SignatureDisplayType) {
    SignatureDisplayType["compact"] = "compact";
    SignatureDisplayType["formatted"] = "formatted";
})(SignatureDisplayType || (exports.SignatureDisplayType = SignatureDisplayType = {}));
function cloneDiagnosticRuleSet(diagSettings) {
    // Create a shallow copy of the existing object.
    return Object.assign({}, diagSettings);
}
exports.cloneDiagnosticRuleSet = cloneDiagnosticRuleSet;
// Returns a list of the diagnostic rules that are configured with
// a true or false value.
function getBooleanDiagnosticRules(includeNonOverridable = false) {
    const boolRules = [
        diagnosticRules_1.DiagnosticRule.strictListInference,
        diagnosticRules_1.DiagnosticRule.strictSetInference,
        diagnosticRules_1.DiagnosticRule.strictDictionaryInference,
        diagnosticRules_1.DiagnosticRule.analyzeUnannotatedFunctions,
        diagnosticRules_1.DiagnosticRule.strictParameterNoneValue,
        diagnosticRules_1.DiagnosticRule.enableExperimentalFeatures,
        diagnosticRules_1.DiagnosticRule.deprecateTypingAliases,
        diagnosticRules_1.DiagnosticRule.disableBytesTypePromotions,
    ];
    if (includeNonOverridable) {
        // Do not include this these because we don't
        // want to override it in strict mode or support
        // it within pyright comments.
        boolRules.push(diagnosticRules_1.DiagnosticRule.enableTypeIgnoreComments);
    }
    return boolRules;
}
exports.getBooleanDiagnosticRules = getBooleanDiagnosticRules;
// Returns a list of the diagnostic rules that are configured with
// a diagnostic level ('none', 'error', etc.).
function getDiagLevelDiagnosticRules() {
    return [
        diagnosticRules_1.DiagnosticRule.reportGeneralTypeIssues,
        diagnosticRules_1.DiagnosticRule.reportPropertyTypeMismatch,
        diagnosticRules_1.DiagnosticRule.reportFunctionMemberAccess,
        diagnosticRules_1.DiagnosticRule.reportMissingImports,
        diagnosticRules_1.DiagnosticRule.reportMissingModuleSource,
        diagnosticRules_1.DiagnosticRule.reportInvalidTypeForm,
        diagnosticRules_1.DiagnosticRule.reportMissingTypeStubs,
        diagnosticRules_1.DiagnosticRule.reportImportCycles,
        diagnosticRules_1.DiagnosticRule.reportUnusedImport,
        diagnosticRules_1.DiagnosticRule.reportUnusedClass,
        diagnosticRules_1.DiagnosticRule.reportUnusedFunction,
        diagnosticRules_1.DiagnosticRule.reportUnusedVariable,
        diagnosticRules_1.DiagnosticRule.reportDuplicateImport,
        diagnosticRules_1.DiagnosticRule.reportWildcardImportFromLibrary,
        diagnosticRules_1.DiagnosticRule.reportAbstractUsage,
        diagnosticRules_1.DiagnosticRule.reportArgumentType,
        diagnosticRules_1.DiagnosticRule.reportAssertTypeFailure,
        diagnosticRules_1.DiagnosticRule.reportAssignmentType,
        diagnosticRules_1.DiagnosticRule.reportAttributeAccessIssue,
        diagnosticRules_1.DiagnosticRule.reportCallIssue,
        diagnosticRules_1.DiagnosticRule.reportInconsistentOverload,
        diagnosticRules_1.DiagnosticRule.reportIndexIssue,
        diagnosticRules_1.DiagnosticRule.reportInvalidTypeArguments,
        diagnosticRules_1.DiagnosticRule.reportNoOverloadImplementation,
        diagnosticRules_1.DiagnosticRule.reportOperatorIssue,
        diagnosticRules_1.DiagnosticRule.reportOptionalSubscript,
        diagnosticRules_1.DiagnosticRule.reportOptionalMemberAccess,
        diagnosticRules_1.DiagnosticRule.reportOptionalCall,
        diagnosticRules_1.DiagnosticRule.reportOptionalIterable,
        diagnosticRules_1.DiagnosticRule.reportOptionalContextManager,
        diagnosticRules_1.DiagnosticRule.reportOptionalOperand,
        diagnosticRules_1.DiagnosticRule.reportRedeclaration,
        diagnosticRules_1.DiagnosticRule.reportReturnType,
        diagnosticRules_1.DiagnosticRule.reportTypedDictNotRequiredAccess,
        diagnosticRules_1.DiagnosticRule.reportUntypedFunctionDecorator,
        diagnosticRules_1.DiagnosticRule.reportUntypedClassDecorator,
        diagnosticRules_1.DiagnosticRule.reportUntypedBaseClass,
        diagnosticRules_1.DiagnosticRule.reportUntypedNamedTuple,
        diagnosticRules_1.DiagnosticRule.reportPrivateUsage,
        diagnosticRules_1.DiagnosticRule.reportTypeCommentUsage,
        diagnosticRules_1.DiagnosticRule.reportPrivateImportUsage,
        diagnosticRules_1.DiagnosticRule.reportConstantRedefinition,
        diagnosticRules_1.DiagnosticRule.reportDeprecated,
        diagnosticRules_1.DiagnosticRule.reportIncompatibleMethodOverride,
        diagnosticRules_1.DiagnosticRule.reportIncompatibleVariableOverride,
        diagnosticRules_1.DiagnosticRule.reportInconsistentConstructor,
        diagnosticRules_1.DiagnosticRule.reportOverlappingOverload,
        diagnosticRules_1.DiagnosticRule.reportPossiblyUnboundVariable,
        diagnosticRules_1.DiagnosticRule.reportMissingSuperCall,
        diagnosticRules_1.DiagnosticRule.reportUninitializedInstanceVariable,
        diagnosticRules_1.DiagnosticRule.reportInvalidStringEscapeSequence,
        diagnosticRules_1.DiagnosticRule.reportUnknownParameterType,
        diagnosticRules_1.DiagnosticRule.reportUnknownArgumentType,
        diagnosticRules_1.DiagnosticRule.reportUnknownLambdaType,
        diagnosticRules_1.DiagnosticRule.reportUnknownVariableType,
        diagnosticRules_1.DiagnosticRule.reportUnknownMemberType,
        diagnosticRules_1.DiagnosticRule.reportMissingParameterType,
        diagnosticRules_1.DiagnosticRule.reportMissingTypeArgument,
        diagnosticRules_1.DiagnosticRule.reportInvalidTypeVarUse,
        diagnosticRules_1.DiagnosticRule.reportCallInDefaultInitializer,
        diagnosticRules_1.DiagnosticRule.reportUnnecessaryIsInstance,
        diagnosticRules_1.DiagnosticRule.reportUnnecessaryCast,
        diagnosticRules_1.DiagnosticRule.reportUnnecessaryComparison,
        diagnosticRules_1.DiagnosticRule.reportUnnecessaryContains,
        diagnosticRules_1.DiagnosticRule.reportAssertAlwaysTrue,
        diagnosticRules_1.DiagnosticRule.reportSelfClsParameterName,
        diagnosticRules_1.DiagnosticRule.reportImplicitStringConcatenation,
        diagnosticRules_1.DiagnosticRule.reportUndefinedVariable,
        diagnosticRules_1.DiagnosticRule.reportUnhashable,
        diagnosticRules_1.DiagnosticRule.reportUnboundVariable,
        diagnosticRules_1.DiagnosticRule.reportInvalidStubStatement,
        diagnosticRules_1.DiagnosticRule.reportIncompleteStub,
        diagnosticRules_1.DiagnosticRule.reportUnsupportedDunderAll,
        diagnosticRules_1.DiagnosticRule.reportUnusedCallResult,
        diagnosticRules_1.DiagnosticRule.reportUnusedCoroutine,
        diagnosticRules_1.DiagnosticRule.reportUnusedExcept,
        diagnosticRules_1.DiagnosticRule.reportUnusedExpression,
        diagnosticRules_1.DiagnosticRule.reportUnnecessaryTypeIgnoreComment,
        diagnosticRules_1.DiagnosticRule.reportMatchNotExhaustive,
        diagnosticRules_1.DiagnosticRule.reportShadowedImports,
        diagnosticRules_1.DiagnosticRule.reportImplicitOverride,
        diagnosticRules_1.DiagnosticRule.reportUnreachable,
        diagnosticRules_1.DiagnosticRule.reportAny,
        diagnosticRules_1.DiagnosticRule.reportIgnoreCommentWithoutRule,
        diagnosticRules_1.DiagnosticRule.reportInvalidCast,
        diagnosticRules_1.DiagnosticRule.reportImplicitRelativeImport,
        diagnosticRules_1.DiagnosticRule.reportPrivateLocalImportUsage,
    ];
}
exports.getDiagLevelDiagnosticRules = getDiagLevelDiagnosticRules;
function getStrictModeNotOverriddenRules() {
    // In strict mode, the value in the user config file should be honored and
    // not overwritten by the value from the strict rule set.
    return [diagnosticRules_1.DiagnosticRule.reportMissingModuleSource];
}
exports.getStrictModeNotOverriddenRules = getStrictModeNotOverriddenRules;
function getOffDiagnosticRuleSet() {
    const diagSettings = {
        printUnknownAsAny: true,
        omitTypeArgsIfUnknown: true,
        omitUnannotatedParamType: true,
        omitConditionalConstraint: true,
        pep604Printing: true,
        strictListInference: false,
        strictSetInference: false,
        strictDictionaryInference: false,
        analyzeUnannotatedFunctions: true,
        strictParameterNoneValue: false,
        enableExperimentalFeatures: false,
        enableTypeIgnoreComments: true,
        deprecateTypingAliases: false,
        disableBytesTypePromotions: false,
        reportGeneralTypeIssues: 'none',
        reportPropertyTypeMismatch: 'none',
        reportFunctionMemberAccess: 'none',
        reportMissingImports: 'none',
        reportMissingModuleSource: 'none',
        reportInvalidTypeForm: 'none',
        reportMissingTypeStubs: 'none',
        reportImportCycles: 'none',
        reportUnusedImport: 'none',
        reportUnusedClass: 'none',
        reportUnusedFunction: 'none',
        reportUnusedVariable: 'none',
        reportDuplicateImport: 'none',
        reportWildcardImportFromLibrary: 'none',
        reportAbstractUsage: 'none',
        reportArgumentType: 'none',
        reportAssertTypeFailure: 'none',
        reportAssignmentType: 'none',
        reportAttributeAccessIssue: 'none',
        reportCallIssue: 'none',
        reportInconsistentOverload: 'none',
        reportIndexIssue: 'none',
        reportInvalidTypeArguments: 'none',
        reportNoOverloadImplementation: 'none',
        reportOperatorIssue: 'none',
        reportOptionalSubscript: 'none',
        reportOptionalMemberAccess: 'none',
        reportOptionalCall: 'none',
        reportOptionalIterable: 'none',
        reportOptionalContextManager: 'none',
        reportOptionalOperand: 'none',
        reportRedeclaration: 'none',
        reportReturnType: 'none',
        reportTypedDictNotRequiredAccess: 'none',
        reportUntypedFunctionDecorator: 'none',
        reportUntypedClassDecorator: 'none',
        reportUntypedBaseClass: 'none',
        reportUntypedNamedTuple: 'none',
        reportPrivateUsage: 'none',
        reportTypeCommentUsage: 'none',
        reportPrivateImportUsage: 'none',
        reportConstantRedefinition: 'none',
        reportDeprecated: 'none',
        reportIncompatibleMethodOverride: 'none',
        reportIncompatibleVariableOverride: 'none',
        reportInconsistentConstructor: 'none',
        reportOverlappingOverload: 'none',
        reportPossiblyUnboundVariable: 'none',
        reportMissingSuperCall: 'none',
        reportUninitializedInstanceVariable: 'none',
        reportInvalidStringEscapeSequence: 'none',
        reportUnknownParameterType: 'none',
        reportUnknownArgumentType: 'none',
        reportUnknownLambdaType: 'none',
        reportUnknownVariableType: 'none',
        reportUnknownMemberType: 'none',
        reportMissingParameterType: 'none',
        reportMissingTypeArgument: 'none',
        reportInvalidTypeVarUse: 'none',
        reportCallInDefaultInitializer: 'none',
        reportUnnecessaryIsInstance: 'none',
        reportUnnecessaryCast: 'none',
        reportUnnecessaryComparison: 'none',
        reportUnnecessaryContains: 'none',
        reportAssertAlwaysTrue: 'none',
        reportSelfClsParameterName: 'none',
        reportImplicitStringConcatenation: 'none',
        reportUnboundVariable: 'none',
        reportUnhashable: 'none',
        reportUndefinedVariable: 'none',
        reportInvalidStubStatement: 'none',
        reportIncompleteStub: 'none',
        reportUnsupportedDunderAll: 'none',
        reportUnusedCallResult: 'none',
        reportUnusedCoroutine: 'none',
        reportUnusedExcept: 'none',
        reportUnusedExpression: 'none',
        reportUnnecessaryTypeIgnoreComment: 'none',
        reportMatchNotExhaustive: 'none',
        reportShadowedImports: 'none',
        reportImplicitOverride: 'none',
        reportUnreachable: 'none',
        reportAny: 'none',
        reportIgnoreCommentWithoutRule: 'none',
        reportPrivateLocalImportUsage: 'none',
        reportImplicitRelativeImport: 'none',
        reportInvalidCast: 'none',
    };
    return diagSettings;
}
exports.getOffDiagnosticRuleSet = getOffDiagnosticRuleSet;
function getBasicDiagnosticRuleSet() {
    const diagSettings = {
        printUnknownAsAny: false,
        omitTypeArgsIfUnknown: false,
        omitUnannotatedParamType: true,
        omitConditionalConstraint: false,
        pep604Printing: true,
        strictListInference: false,
        strictSetInference: false,
        strictDictionaryInference: false,
        analyzeUnannotatedFunctions: true,
        strictParameterNoneValue: true,
        enableExperimentalFeatures: false,
        enableTypeIgnoreComments: true,
        deprecateTypingAliases: false,
        disableBytesTypePromotions: false,
        reportGeneralTypeIssues: 'error',
        reportPropertyTypeMismatch: 'none',
        reportFunctionMemberAccess: 'none',
        reportMissingImports: 'error',
        reportMissingModuleSource: 'warning',
        reportInvalidTypeForm: 'error',
        reportMissingTypeStubs: 'none',
        reportImportCycles: 'none',
        reportUnusedImport: 'none',
        reportUnusedClass: 'none',
        reportUnusedFunction: 'none',
        reportUnusedVariable: 'none',
        reportDuplicateImport: 'none',
        reportWildcardImportFromLibrary: 'warning',
        reportAbstractUsage: 'error',
        reportArgumentType: 'error',
        reportAssertTypeFailure: 'error',
        reportAssignmentType: 'error',
        reportAttributeAccessIssue: 'error',
        reportCallIssue: 'error',
        reportInconsistentOverload: 'error',
        reportIndexIssue: 'error',
        reportInvalidTypeArguments: 'error',
        reportNoOverloadImplementation: 'error',
        reportOperatorIssue: 'error',
        reportOptionalSubscript: 'error',
        reportOptionalMemberAccess: 'error',
        reportOptionalCall: 'error',
        reportOptionalIterable: 'error',
        reportOptionalContextManager: 'error',
        reportOptionalOperand: 'error',
        reportRedeclaration: 'error',
        reportReturnType: 'error',
        reportTypedDictNotRequiredAccess: 'error',
        reportUntypedFunctionDecorator: 'none',
        reportUntypedClassDecorator: 'none',
        reportUntypedBaseClass: 'none',
        reportUntypedNamedTuple: 'none',
        reportPrivateUsage: 'none',
        reportTypeCommentUsage: 'none',
        reportPrivateImportUsage: 'error',
        reportConstantRedefinition: 'none',
        reportDeprecated: 'none',
        reportIncompatibleMethodOverride: 'none',
        reportIncompatibleVariableOverride: 'none',
        reportInconsistentConstructor: 'none',
        reportOverlappingOverload: 'none',
        reportPossiblyUnboundVariable: 'none',
        reportMissingSuperCall: 'none',
        reportUninitializedInstanceVariable: 'none',
        reportInvalidStringEscapeSequence: 'warning',
        reportUnknownParameterType: 'none',
        reportUnknownArgumentType: 'none',
        reportUnknownLambdaType: 'none',
        reportUnknownVariableType: 'none',
        reportUnknownMemberType: 'none',
        reportMissingParameterType: 'none',
        reportMissingTypeArgument: 'none',
        reportInvalidTypeVarUse: 'warning',
        reportCallInDefaultInitializer: 'none',
        reportUnnecessaryIsInstance: 'none',
        reportUnnecessaryCast: 'none',
        reportUnnecessaryComparison: 'none',
        reportUnnecessaryContains: 'none',
        reportAssertAlwaysTrue: 'warning',
        reportSelfClsParameterName: 'warning',
        reportImplicitStringConcatenation: 'none',
        reportUnboundVariable: 'error',
        reportUnhashable: 'error',
        reportUndefinedVariable: 'error',
        reportInvalidStubStatement: 'none',
        reportIncompleteStub: 'none',
        reportUnsupportedDunderAll: 'warning',
        reportUnusedCallResult: 'none',
        reportUnusedCoroutine: 'error',
        reportUnusedExcept: 'error',
        reportUnusedExpression: 'warning',
        reportUnnecessaryTypeIgnoreComment: 'none',
        reportMatchNotExhaustive: 'none',
        reportShadowedImports: 'none',
        reportImplicitOverride: 'none',
        reportUnreachable: 'none',
        reportAny: 'none',
        reportIgnoreCommentWithoutRule: 'none',
        reportPrivateLocalImportUsage: 'none',
        reportImplicitRelativeImport: 'none',
        reportInvalidCast: 'none',
    };
    return diagSettings;
}
exports.getBasicDiagnosticRuleSet = getBasicDiagnosticRuleSet;
function getStandardDiagnosticRuleSet() {
    const diagSettings = {
        printUnknownAsAny: false,
        omitTypeArgsIfUnknown: false,
        omitUnannotatedParamType: true,
        omitConditionalConstraint: false,
        pep604Printing: true,
        strictListInference: false,
        strictSetInference: false,
        strictDictionaryInference: false,
        analyzeUnannotatedFunctions: true,
        strictParameterNoneValue: true,
        enableExperimentalFeatures: false,
        enableTypeIgnoreComments: true,
        deprecateTypingAliases: false,
        disableBytesTypePromotions: false,
        reportGeneralTypeIssues: 'error',
        reportPropertyTypeMismatch: 'none',
        reportFunctionMemberAccess: 'error',
        reportMissingImports: 'error',
        reportMissingModuleSource: 'warning',
        reportInvalidTypeForm: 'error',
        reportMissingTypeStubs: 'none',
        reportImportCycles: 'none',
        reportUnusedImport: 'none',
        reportUnusedClass: 'none',
        reportUnusedFunction: 'none',
        reportUnusedVariable: 'none',
        reportDuplicateImport: 'none',
        reportWildcardImportFromLibrary: 'warning',
        reportAbstractUsage: 'error',
        reportArgumentType: 'error',
        reportAssertTypeFailure: 'error',
        reportAssignmentType: 'error',
        reportAttributeAccessIssue: 'error',
        reportCallIssue: 'error',
        reportInconsistentOverload: 'error',
        reportIndexIssue: 'error',
        reportInvalidTypeArguments: 'error',
        reportNoOverloadImplementation: 'error',
        reportOperatorIssue: 'error',
        reportOptionalSubscript: 'error',
        reportOptionalMemberAccess: 'error',
        reportOptionalCall: 'error',
        reportOptionalIterable: 'error',
        reportOptionalContextManager: 'error',
        reportOptionalOperand: 'error',
        reportRedeclaration: 'error',
        reportReturnType: 'error',
        reportTypedDictNotRequiredAccess: 'error',
        reportUntypedFunctionDecorator: 'none',
        reportUntypedClassDecorator: 'none',
        reportUntypedBaseClass: 'none',
        reportUntypedNamedTuple: 'none',
        reportPrivateUsage: 'none',
        reportTypeCommentUsage: 'none',
        reportPrivateImportUsage: 'error',
        reportConstantRedefinition: 'none',
        reportDeprecated: 'none',
        reportIncompatibleMethodOverride: 'error',
        reportIncompatibleVariableOverride: 'error',
        reportInconsistentConstructor: 'none',
        reportOverlappingOverload: 'error',
        reportPossiblyUnboundVariable: 'error',
        reportMissingSuperCall: 'none',
        reportUninitializedInstanceVariable: 'none',
        reportInvalidStringEscapeSequence: 'warning',
        reportUnknownParameterType: 'none',
        reportUnknownArgumentType: 'none',
        reportUnknownLambdaType: 'none',
        reportUnknownVariableType: 'none',
        reportUnknownMemberType: 'none',
        reportMissingParameterType: 'none',
        reportMissingTypeArgument: 'none',
        reportInvalidTypeVarUse: 'warning',
        reportCallInDefaultInitializer: 'none',
        reportUnnecessaryIsInstance: 'none',
        reportUnnecessaryCast: 'none',
        reportUnnecessaryComparison: 'none',
        reportUnnecessaryContains: 'none',
        reportAssertAlwaysTrue: 'warning',
        reportSelfClsParameterName: 'warning',
        reportImplicitStringConcatenation: 'none',
        reportUnboundVariable: 'error',
        reportUnhashable: 'error',
        reportUndefinedVariable: 'error',
        reportInvalidStubStatement: 'none',
        reportIncompleteStub: 'none',
        reportUnsupportedDunderAll: 'warning',
        reportUnusedCallResult: 'none',
        reportUnusedCoroutine: 'error',
        reportUnusedExcept: 'error',
        reportUnusedExpression: 'warning',
        reportUnnecessaryTypeIgnoreComment: 'none',
        reportMatchNotExhaustive: 'none',
        reportShadowedImports: 'none',
        reportImplicitOverride: 'none',
        reportUnreachable: 'none',
        reportAny: 'none',
        reportIgnoreCommentWithoutRule: 'none',
        reportPrivateLocalImportUsage: 'none',
        reportImplicitRelativeImport: 'none',
        reportInvalidCast: 'none',
    };
    return diagSettings;
}
exports.getStandardDiagnosticRuleSet = getStandardDiagnosticRuleSet;
const getAllDiagnosticRuleSet = () => ({
    printUnknownAsAny: false,
    omitTypeArgsIfUnknown: false,
    omitUnannotatedParamType: false,
    omitConditionalConstraint: false,
    pep604Printing: true,
    strictListInference: true,
    strictSetInference: true,
    strictDictionaryInference: true,
    analyzeUnannotatedFunctions: true,
    strictParameterNoneValue: true,
    enableExperimentalFeatures: true,
    enableTypeIgnoreComments: true,
    deprecateTypingAliases: true,
    disableBytesTypePromotions: true,
    reportGeneralTypeIssues: 'error',
    reportPropertyTypeMismatch: 'error',
    reportFunctionMemberAccess: 'error',
    reportMissingImports: 'error',
    reportMissingModuleSource: 'error',
    reportInvalidTypeForm: 'error',
    reportMissingTypeStubs: 'error',
    reportImportCycles: 'error',
    reportUnusedImport: 'error',
    reportUnusedClass: 'error',
    reportUnusedFunction: 'error',
    reportUnusedVariable: 'error',
    reportDuplicateImport: 'error',
    reportWildcardImportFromLibrary: 'error',
    reportAbstractUsage: 'error',
    reportArgumentType: 'error',
    reportAssertTypeFailure: 'error',
    reportAssignmentType: 'error',
    reportAttributeAccessIssue: 'error',
    reportCallIssue: 'error',
    reportInconsistentOverload: 'error',
    reportIndexIssue: 'error',
    reportInvalidTypeArguments: 'error',
    reportNoOverloadImplementation: 'error',
    reportOperatorIssue: 'error',
    reportOptionalSubscript: 'error',
    reportOptionalMemberAccess: 'error',
    reportOptionalCall: 'error',
    reportOptionalIterable: 'error',
    reportOptionalContextManager: 'error',
    reportOptionalOperand: 'error',
    reportRedeclaration: 'error',
    reportReturnType: 'error',
    reportTypedDictNotRequiredAccess: 'error',
    reportUntypedFunctionDecorator: 'error',
    reportUntypedClassDecorator: 'error',
    reportUntypedBaseClass: 'error',
    reportUntypedNamedTuple: 'error',
    reportPrivateUsage: 'error',
    reportTypeCommentUsage: 'error',
    reportPrivateImportUsage: 'error',
    reportConstantRedefinition: 'error',
    reportDeprecated: 'error',
    reportIncompatibleMethodOverride: 'error',
    reportIncompatibleVariableOverride: 'error',
    reportInconsistentConstructor: 'error',
    reportOverlappingOverload: 'error',
    reportPossiblyUnboundVariable: 'error',
    reportMissingSuperCall: 'error',
    reportUninitializedInstanceVariable: 'error',
    reportInvalidStringEscapeSequence: 'error',
    reportUnknownParameterType: 'error',
    reportUnknownArgumentType: 'error',
    reportUnknownLambdaType: 'error',
    reportUnknownVariableType: 'error',
    reportUnknownMemberType: 'error',
    reportMissingParameterType: 'error',
    reportMissingTypeArgument: 'error',
    reportInvalidTypeVarUse: 'error',
    reportCallInDefaultInitializer: 'error',
    reportUnnecessaryIsInstance: 'error',
    reportUnnecessaryCast: 'error',
    reportUnnecessaryComparison: 'error',
    reportUnnecessaryContains: 'error',
    reportAssertAlwaysTrue: 'error',
    reportSelfClsParameterName: 'error',
    reportImplicitStringConcatenation: 'error',
    reportUnboundVariable: 'error',
    reportUnhashable: 'error',
    reportUndefinedVariable: 'error',
    reportInvalidStubStatement: 'error',
    reportIncompleteStub: 'error',
    reportUnsupportedDunderAll: 'error',
    reportUnusedCallResult: 'error',
    reportUnusedCoroutine: 'error',
    reportUnusedExcept: 'error',
    reportUnusedExpression: 'error',
    reportUnnecessaryTypeIgnoreComment: 'error',
    reportMatchNotExhaustive: 'error',
    reportShadowedImports: 'error',
    reportImplicitOverride: 'error',
    reportUnreachable: 'error',
    reportAny: 'error',
    reportIgnoreCommentWithoutRule: 'error',
    reportPrivateLocalImportUsage: 'error',
    reportImplicitRelativeImport: 'error',
    reportInvalidCast: 'error',
});
exports.getAllDiagnosticRuleSet = getAllDiagnosticRuleSet;
function getStrictDiagnosticRuleSet() {
    const diagSettings = {
        printUnknownAsAny: false,
        omitTypeArgsIfUnknown: false,
        omitUnannotatedParamType: false,
        omitConditionalConstraint: false,
        pep604Printing: true,
        strictListInference: true,
        strictSetInference: true,
        strictDictionaryInference: true,
        analyzeUnannotatedFunctions: true,
        strictParameterNoneValue: true,
        enableExperimentalFeatures: false,
        enableTypeIgnoreComments: true,
        deprecateTypingAliases: false,
        disableBytesTypePromotions: true,
        reportGeneralTypeIssues: 'error',
        reportPropertyTypeMismatch: 'none',
        reportFunctionMemberAccess: 'error',
        reportMissingImports: 'error',
        reportMissingModuleSource: 'warning',
        reportInvalidTypeForm: 'error',
        reportMissingTypeStubs: 'error',
        reportImportCycles: 'none',
        reportUnusedImport: 'error',
        reportUnusedClass: 'error',
        reportUnusedFunction: 'error',
        reportUnusedVariable: 'error',
        reportDuplicateImport: 'error',
        reportWildcardImportFromLibrary: 'error',
        reportAbstractUsage: 'error',
        reportArgumentType: 'error',
        reportAssertTypeFailure: 'error',
        reportAssignmentType: 'error',
        reportAttributeAccessIssue: 'error',
        reportCallIssue: 'error',
        reportInconsistentOverload: 'error',
        reportIndexIssue: 'error',
        reportInvalidTypeArguments: 'error',
        reportNoOverloadImplementation: 'error',
        reportOperatorIssue: 'error',
        reportOptionalSubscript: 'error',
        reportOptionalMemberAccess: 'error',
        reportOptionalCall: 'error',
        reportOptionalIterable: 'error',
        reportOptionalContextManager: 'error',
        reportOptionalOperand: 'error',
        reportRedeclaration: 'error',
        reportReturnType: 'error',
        reportTypedDictNotRequiredAccess: 'error',
        reportUntypedFunctionDecorator: 'error',
        reportUntypedClassDecorator: 'error',
        reportUntypedBaseClass: 'error',
        reportUntypedNamedTuple: 'error',
        reportPrivateUsage: 'error',
        reportTypeCommentUsage: 'error',
        reportPrivateImportUsage: 'error',
        reportConstantRedefinition: 'error',
        reportDeprecated: 'error',
        reportIncompatibleMethodOverride: 'error',
        reportIncompatibleVariableOverride: 'error',
        reportInconsistentConstructor: 'error',
        reportOverlappingOverload: 'error',
        reportPossiblyUnboundVariable: 'error',
        reportMissingSuperCall: 'none',
        reportUninitializedInstanceVariable: 'none',
        reportInvalidStringEscapeSequence: 'error',
        reportUnknownParameterType: 'error',
        reportUnknownArgumentType: 'error',
        reportUnknownLambdaType: 'error',
        reportUnknownVariableType: 'error',
        reportUnknownMemberType: 'error',
        reportMissingParameterType: 'error',
        reportMissingTypeArgument: 'error',
        reportInvalidTypeVarUse: 'error',
        reportCallInDefaultInitializer: 'none',
        reportUnnecessaryIsInstance: 'error',
        reportUnnecessaryCast: 'error',
        reportUnnecessaryComparison: 'error',
        reportUnnecessaryContains: 'error',
        reportAssertAlwaysTrue: 'error',
        reportSelfClsParameterName: 'error',
        reportImplicitStringConcatenation: 'none',
        reportUnboundVariable: 'error',
        reportUnhashable: 'error',
        reportUndefinedVariable: 'error',
        reportInvalidStubStatement: 'error',
        reportIncompleteStub: 'error',
        reportUnsupportedDunderAll: 'error',
        reportUnusedCallResult: 'none',
        reportUnusedCoroutine: 'error',
        reportUnusedExcept: 'error',
        reportUnusedExpression: 'error',
        reportUnnecessaryTypeIgnoreComment: 'none',
        reportMatchNotExhaustive: 'error',
        reportShadowedImports: 'none',
        reportImplicitOverride: 'none',
        reportUnreachable: 'none',
        reportAny: 'none',
        reportIgnoreCommentWithoutRule: 'none',
        reportPrivateLocalImportUsage: 'none',
        reportImplicitRelativeImport: 'none',
        reportInvalidCast: 'none',
    };
    return diagSettings;
}
exports.getStrictDiagnosticRuleSet = getStrictDiagnosticRuleSet;
function matchFileSpecs(configOptions, uri, isFile = true) {
    for (const includeSpec of configOptions.include) {
        if (uriUtils_1.FileSpec.matchIncludeFileSpec(includeSpec.regExp, configOptions.exclude, uri, isFile)) {
            return true;
        }
    }
    return false;
}
exports.matchFileSpecs = matchFileSpecs;
// Internal configuration options. These are derived from a combination
// of the command line and from a JSON-based config file.
class ConfigOptions {
    constructor(projectRoot, typeCheckingMode) {
        // A list of file specs to include in the analysis. Can contain
        // directories, in which case all "*.py" files within those directories
        // are included.
        this.include = [];
        // A list of file specs to exclude from the analysis (overriding include
        // if necessary). Can contain directories, in which case all "*.py" files
        // within those directories are included.
        this.exclude = [];
        // A list of file specs whose errors and warnings should be ignored even
        // if they are included in the transitive closure of included files.
        this.ignore = [];
        // A list of file specs that should be analyzed using "strict" mode.
        this.strict = [];
        // A set of defined constants that are used by the binder to determine
        // whether runtime conditions should evaluate to True or False.
        this.defineConstant = new Map();
        // Offer auto-import completions.
        this.autoImportCompletions = true;
        // Use indexing.
        this.indexing = false;
        // Use type evaluator call tracking
        this.logTypeEvaluationTime = false;
        // Minimum threshold for type eval logging
        this.typeEvaluationTimeThreshold = 50;
        // Was this config initialized from JSON (pyrightconfig/pyproject)?
        this.initializedFromJson = false;
        // Filter out any hint diagnostics with tags?
        this.disableTaggedHints = false;
        //---------------------------------------------------------------
        // Parsing and Import Resolution Settings
        // Parameters that specify the execution environment for
        // the files being analyzed.
        this.executionEnvironments = [];
        this.projectRoot = projectRoot;
        this.typeCheckingMode = typeCheckingMode;
        this.diagnosticRuleSet = this.constructor.getDiagnosticRuleSet(typeCheckingMode);
        this.functionSignatureDisplay = SignatureDisplayType.formatted;
    }
    static getDiagnosticRuleSet(typeCheckingMode) {
        if (typeCheckingMode === 'all') {
            return (0, exports.getAllDiagnosticRuleSet)();
        }
        if (typeCheckingMode === 'strict') {
            return getStrictDiagnosticRuleSet();
        }
        if (typeCheckingMode === 'basic') {
            return getBasicDiagnosticRuleSet();
        }
        if (typeCheckingMode === 'off') {
            return getOffDiagnosticRuleSet();
        }
        return getStandardDiagnosticRuleSet();
    }
    getDefaultExecEnvironment() {
        return new ExecutionEnvironment(this._getEnvironmentName(), this.projectRoot, this.defaultPythonVersion, this.defaultPythonPlatform, this.defaultExtraPaths);
    }
    // Finds the best execution environment for a given file uri. The
    // specified file path should be absolute.
    // If no matching execution environment can be found, a default
    // execution environment is used.
    findExecEnvironment(file) {
        var _a;
        return ((_a = this.executionEnvironments.find((env) => {
            const envRoot = uri_1.Uri.is(env.root) ? env.root : this.projectRoot.resolvePaths(env.root || '');
            return file.startsWith(envRoot);
        })) !== null && _a !== void 0 ? _a : this.getDefaultExecEnvironment());
    }
    getExecutionEnvironments() {
        if (this.executionEnvironments.length > 0) {
            return this.executionEnvironments;
        }
        return [this.getDefaultExecEnvironment()];
    }
    // Initialize the structure from a JSON object.
    initializeFromJson(configObj, typeCheckingMode, serviceProvider, host, commandLineOptions) {
        var _a;
        this.initializedFromJson = true;
        const console = (_a = serviceProvider.tryGet(serviceKeys_1.ServiceKeys.console)) !== null && _a !== void 0 ? _a : new console_1.NullConsole();
        const errors = [];
        // keep track of which options have been parsed so we can raise an error on unknown options later
        // this is pretty cringe and we should just replace all this with some sort of schema validator thingy
        // https://github.com/DetachHead/basedpyright/issues/64
        const readOptions = [];
        configObj = new Proxy(configObj, {
            get: (target, name) => {
                const result = target[name];
                if (!readOptions.includes(name)) {
                    readOptions.push(name);
                }
                return result;
            },
        });
        // Read the entries that should be an array of relative file paths
        for (const key of ['include', 'exclude', 'ignore', 'strict']) {
            const configValue = configObj[key];
            if (configValue !== undefined) {
                if (!Array.isArray(configValue)) {
                    errors.push(`Config "${key}" entry must must contain an array.`);
                }
                else {
                    this[key] = [];
                    configValue.forEach((fileSpec, index) => {
                        if (typeof fileSpec !== 'string') {
                            errors.push(`Index ${index} of "${key}" array should be a string.`);
                        }
                        else if ((0, path_1.isAbsolute)(fileSpec)) {
                            errors.push(`path "${fileSpec}" in "${key}" array should be relative.`);
                        }
                        else {
                            this[key].push((0, uriUtils_1.getFileSpec)(this.projectRoot, fileSpec));
                        }
                    });
                }
            }
        }
        // If there is a "typeCheckingMode", it can override the provided setting.
        let configTypeCheckingMode;
        if (configObj.typeCheckingMode !== undefined) {
            const validTypeCheckingModes = ['off', 'basic', 'standard', 'strict', 'all'];
            if (validTypeCheckingModes.includes(configObj.typeCheckingMode)) {
                configTypeCheckingMode = configObj.typeCheckingMode;
            }
            else {
                errors.push(`Config "typeCheckingMode" entry must contain ${(0, stringUtils_1.userFacingOptionsList)(validTypeCheckingModes)}.`);
            }
        }
        if (configObj.useLibraryCodeForTypes !== undefined) {
            if (typeof configObj.useLibraryCodeForTypes === 'boolean') {
                this.useLibraryCodeForTypes = configObj.useLibraryCodeForTypes;
            }
            else {
                errors.push(`Config "useLibraryCodeForTypes" entry must be true or false.`);
            }
        }
        this.typeCheckingMode = configTypeCheckingMode || typeCheckingMode;
        const defaultSettings = ConfigOptions.getDiagnosticRuleSet(this.typeCheckingMode);
        // Start with the default values for all rules in the rule set.
        this.diagnosticRuleSet = { ...defaultSettings };
        // Apply host-provided overrides.
        this.applyDiagnosticOverrides(commandLineOptions === null || commandLineOptions === void 0 ? void 0 : commandLineOptions.diagnosticSeverityOverrides);
        // Apply overrides from the config file for the boolean rules.
        getBooleanDiagnosticRules(/* includeNonOverridable */ true).forEach((ruleName) => {
            this.diagnosticRuleSet[ruleName] = this._convertBoolean(configObj[ruleName], ruleName, this.diagnosticRuleSet[ruleName]);
        });
        // Apply overrides from the config file for the diagnostic level rules.
        getDiagLevelDiagnosticRules().forEach((ruleName) => {
            this.diagnosticRuleSet[ruleName] = this._convertDiagnosticLevel(configObj[ruleName], ruleName, this.diagnosticRuleSet[ruleName]);
        });
        // Read the "venvPath".
        this.venvPath = undefined;
        if (configObj.venvPath !== undefined) {
            if (typeof configObj.venvPath !== 'string') {
                errors.push(`Config "venvPath" field must contain a string.`);
            }
            else {
                this.venvPath = this.projectRoot.resolvePaths(configObj.venvPath);
            }
        }
        // Read the "venv" name.
        this.venv = undefined;
        if (configObj.venv !== undefined) {
            if (typeof configObj.venv !== 'string') {
                errors.push(`Config "venv" field must contain a string.`);
            }
            else {
                this.venv = configObj.venv;
            }
        }
        // Read the default "extraPaths".
        if (configObj.extraPaths !== undefined) {
            this.defaultExtraPaths = [];
            if (!Array.isArray(configObj.extraPaths)) {
                errors.push(`Config "extraPaths" field must contain an array.`);
            }
            else {
                const pathList = configObj.extraPaths;
                pathList.forEach((path, pathIndex) => {
                    if (typeof path !== 'string') {
                        errors.push(`Config "extraPaths" field ${pathIndex} must be a string.`);
                    }
                    else {
                        this.defaultExtraPaths.push(this.projectRoot.resolvePaths(path));
                    }
                });
            }
        }
        // Read the default "pythonVersion".
        if (configObj.pythonVersion !== undefined) {
            if (typeof configObj.pythonVersion === 'string') {
                const version = pythonVersion_1.PythonVersion.fromString(configObj.pythonVersion);
                if (version) {
                    this.defaultPythonVersion = version;
                }
                else {
                    errors.push(`Config "pythonVersion" field contains unsupported version.`);
                }
            }
            else {
                errors.push(`Config "pythonVersion" field must contain a string.`);
            }
        }
        // Override the default python version if it was specified on the command line.
        if (commandLineOptions === null || commandLineOptions === void 0 ? void 0 : commandLineOptions.pythonVersion) {
            this.defaultPythonVersion = commandLineOptions.pythonVersion;
        }
        this.ensureDefaultPythonVersion(host, console);
        // Read the default "pythonPlatform".
        if (configObj.pythonPlatform !== undefined) {
            if (typeof configObj.pythonPlatform !== 'string') {
                errors.push(`Config "pythonPlatform" field must contain a string.`);
            }
            else if (!['Linux', 'Windows', 'Darwin', 'All'].includes(configObj.pythonPlatform)) {
                `'${configObj.pythonPlatform}' is not a supported Python platform; specify All, Darwin, Linux, or Windows.`;
            }
            else {
                this.defaultPythonPlatform = configObj.pythonPlatform;
            }
        }
        if (commandLineOptions === null || commandLineOptions === void 0 ? void 0 : commandLineOptions.pythonPlatform) {
            this.defaultPythonPlatform = commandLineOptions.pythonPlatform;
        }
        this.ensureDefaultPythonPlatform(host, console);
        // Read the "typeshedPath" setting.
        this.typeshedPath = undefined;
        if (configObj.typeshedPath !== undefined) {
            if (typeof configObj.typeshedPath !== 'string') {
                errors.push(`Config "typeshedPath" field must contain a string.`);
            }
            else {
                this.typeshedPath = configObj.typeshedPath
                    ? this.projectRoot.resolvePaths(configObj.typeshedPath)
                    : undefined;
            }
        }
        // Read the "stubPath" setting.
        this.stubPath = undefined;
        // Keep this for backward compatibility
        if (configObj.typingsPath !== undefined) {
            if (typeof configObj.typingsPath !== 'string') {
                errors.push(`Config "typingsPath" field must contain a string.`);
            }
            else {
                errors.push(`Config "typingsPath" is now deprecated. Please, use stubPath instead.`);
                this.stubPath = this.projectRoot.resolvePaths(configObj.typingsPath);
            }
        }
        if (configObj.stubPath !== undefined) {
            if (typeof configObj.stubPath !== 'string') {
                errors.push(`Config "stubPath" field must contain a string.`);
            }
            else {
                this.stubPath = this.projectRoot.resolvePaths(configObj.stubPath);
            }
        }
        // Read the "verboseOutput" setting.
        // Don't initialize to a default value because we want the command-line "verbose"
        // switch to apply if this setting isn't specified in the config file.
        if (configObj.verboseOutput !== undefined) {
            if (typeof configObj.verboseOutput !== 'boolean') {
                errors.push(`Config "verboseOutput" field must be true or false.`);
            }
            else {
                this.verboseOutput = configObj.verboseOutput;
            }
        }
        // Read the "defineConstant" setting.
        if (configObj.defineConstant !== undefined) {
            if (typeof configObj.defineConstant !== 'object' || Array.isArray(configObj.defineConstant)) {
                errors.push(`Config "defineConstant" field must contain a map indexed by constant names.`);
            }
            else {
                const keys = Object.getOwnPropertyNames(configObj.defineConstant);
                keys.forEach((key) => {
                    const value = configObj.defineConstant[key];
                    const valueType = typeof value;
                    if (valueType !== 'boolean' && valueType !== 'string') {
                        errors.push(`Defined constant "${key}" must be associated with a boolean or string value.`);
                    }
                    else {
                        this.defineConstant.set(key, value);
                    }
                });
            }
        }
        // Read the "useLibraryCodeForTypes" setting.
        if (configObj.useLibraryCodeForTypes !== undefined) {
            if (typeof configObj.useLibraryCodeForTypes !== 'boolean') {
                errors.push(`Config "useLibraryCodeForTypes" field must be true or false.`);
            }
            else {
                this.useLibraryCodeForTypes = configObj.useLibraryCodeForTypes;
            }
        }
        // Read the "executionEnvironments" array. This should be done at the end
        // after we've established default values.
        this.executionEnvironments = [];
        if (configObj.executionEnvironments !== undefined) {
            if (!Array.isArray(configObj.executionEnvironments)) {
                errors.push(`Config "executionEnvironments" field must contain an array.`);
            }
            else {
                const execEnvironments = configObj.executionEnvironments;
                execEnvironments.forEach((env, index) => {
                    const result = this._initExecutionEnvironmentFromJson(env, index, commandLineOptions);
                    if (result instanceof ExecutionEnvironment) {
                        this.executionEnvironments.push(result);
                    }
                    else {
                        errors.push(...result);
                    }
                });
            }
        }
        // read the boolean settings
        for (const key of ['autoImportCompletions', 'indexing', 'logTypeEvaluationTime']) {
            const value = configObj[key];
            if (value !== undefined) {
                if (typeof value !== 'boolean') {
                    errors.push(`Config "${key}" field must be true or false.`);
                }
                else {
                    this[key] = value;
                }
            }
        }
        // Read the "typeEvaluationTimeThreshold" setting.
        if (configObj.typeEvaluationTimeThreshold !== undefined) {
            if (typeof configObj.typeEvaluationTimeThreshold !== 'number') {
                errors.push(`Config "typeEvaluationTimeThreshold" field must be a number.`);
            }
            else {
                this.typeEvaluationTimeThreshold = configObj.typeEvaluationTimeThreshold;
            }
        }
        // Read the "functionSignatureDisplay" setting.
        if (configObj.functionSignatureDisplay !== undefined) {
            if (typeof configObj.functionSignatureDisplay !== 'string') {
                errors.push(`Config "functionSignatureDisplay" field must be true or false.`);
            }
            else {
                if (configObj.functionSignatureDisplay === 'compact' ||
                    configObj.functionSignatureDisplay === 'formatted') {
                    this.functionSignatureDisplay = configObj.functionSignatureDisplay;
                }
            }
        }
        for (const key of Object.keys(configObj)) {
            if (!readOptions.includes(key)) {
                errors.push(`unknown config option: ${key}`);
            }
        }
        return errors;
    }
    ensureDefaultPythonPlatform(host, console) {
        // If no default python platform was specified, assume that the
        // user wants to use all mode
        if (this.defaultPythonPlatform !== undefined) {
            return;
        }
        this.defaultPythonPlatform = 'All';
    }
    ensureDefaultPythonVersion(host, console) {
        // If no default python version was specified, retrieve the version
        // from the currently-selected python interpreter.
        if (this.defaultPythonVersion !== undefined) {
            return;
        }
        const importFailureInfo = [];
        this.defaultPythonVersion = host.getPythonVersion(this.pythonPath, importFailureInfo);
        if (this.defaultPythonVersion !== undefined) {
            console.info(`Assuming Python version ${this.defaultPythonVersion.toString()}`);
        }
        for (const log of importFailureInfo) {
            console.info(log);
        }
    }
    ensureDefaultExtraPaths(fs, autoSearchPaths, extraPaths) {
        const paths = [];
        if (autoSearchPaths) {
            // Auto-detect the common scenario where the sources are under the src folder
            const srcPath = this.projectRoot.resolvePaths(pathConsts.src);
            if (fs.existsSync(srcPath) && !fs.existsSync(srcPath.resolvePaths('__init__.py'))) {
                paths.push(fs.realCasePath(srcPath));
            }
        }
        if (extraPaths && extraPaths.length > 0) {
            for (const p of extraPaths) {
                const path = this.projectRoot.resolvePaths(p);
                paths.push(fs.realCasePath(path));
                if ((0, uriUtils_1.isDirectory)(fs, path)) {
                    (0, collectionUtils_1.appendArray)(paths, (0, pythonPathUtils_1.getPathsFromPthFiles)(fs, path));
                }
            }
        }
        if (paths.length > 0) {
            this.defaultExtraPaths = paths;
        }
    }
    applyDiagnosticOverrides(diagnosticSeverityOverrides) {
        if (!diagnosticSeverityOverrides) {
            return;
        }
        for (const ruleName of getDiagLevelDiagnosticRules()) {
            const severity = diagnosticSeverityOverrides[ruleName];
            if (severity !== undefined) {
                this.diagnosticRuleSet[ruleName] = severity;
            }
        }
    }
    _getEnvironmentName() {
        var _a;
        return this.pythonEnvironmentName || ((_a = this.pythonPath) === null || _a === void 0 ? void 0 : _a.toString()) || 'python';
    }
    _convertBoolean(value, fieldName, defaultValue) {
        if (value === undefined) {
            return defaultValue;
        }
        else if (typeof value === 'boolean') {
            return value ? true : false;
        }
        console.log(`Config "${fieldName}" entry must be true or false.`);
        return defaultValue;
    }
    _convertDiagnosticLevel(value, fieldName, defaultValue) {
        if (value === undefined) {
            return defaultValue;
        }
        else if (typeof value === 'boolean') {
            return value ? 'error' : 'none';
        }
        else if (typeof value === 'string') {
            if (value === 'error' || value === 'warning' || value === 'information' || value === 'none') {
                return value;
            }
        }
        console.log(`Config "${fieldName}" entry must be true, false, "error", "warning", "information" or "none".`);
        return defaultValue;
    }
    _initExecutionEnvironmentFromJson(envObj, index, commandLineOptions) {
        const errors = [];
        try {
            const newExecEnv = new ExecutionEnvironment(this._getEnvironmentName(), this.projectRoot, this.defaultPythonVersion, this.defaultPythonPlatform, this.defaultExtraPaths);
            // Validate the root.
            if (envObj.root && typeof envObj.root === 'string') {
                newExecEnv.root = this.projectRoot.resolvePaths(envObj.root);
            }
            else {
                errors.push(`Config executionEnvironments index ${index}: missing root value.`);
            }
            // Validate the extraPaths.
            if (envObj.extraPaths) {
                if (!Array.isArray(envObj.extraPaths)) {
                    errors.push(`Config executionEnvironments index ${index}: extraPaths field must contain an array.`);
                }
                else {
                    const pathList = envObj.extraPaths;
                    pathList.forEach((path, pathIndex) => {
                        if (typeof path !== 'string') {
                            errors.push(`Config executionEnvironments index ${index}:` +
                                ` extraPaths field ${pathIndex} must be a string.`);
                        }
                        else {
                            newExecEnv.extraPaths.push(this.projectRoot.resolvePaths(path));
                        }
                    });
                }
            }
            // Validate the pythonVersion.
            if (envObj.pythonVersion) {
                if (typeof envObj.pythonVersion === 'string') {
                    const version = pythonVersion_1.PythonVersion.fromString(envObj.pythonVersion);
                    if (version) {
                        newExecEnv.pythonVersion = version;
                    }
                    else {
                        errors.push(`Config executionEnvironments index ${index} contains unsupported pythonVersion.`);
                    }
                }
                else {
                    errors.push(`Config executionEnvironments index ${index} pythonVersion must be a string.`);
                }
            }
            // If the pythonVersion was specified on the command line, it overrides
            // the configuration settings for the execution environment.
            if (commandLineOptions === null || commandLineOptions === void 0 ? void 0 : commandLineOptions.pythonVersion) {
                newExecEnv.pythonVersion = commandLineOptions.pythonVersion;
            }
            // Validate the pythonPlatform.
            if (envObj.pythonPlatform) {
                if (typeof envObj.pythonPlatform === 'string') {
                    newExecEnv.pythonPlatform = envObj.pythonPlatform;
                }
                else {
                    errors.push(`Config executionEnvironments index ${index} pythonPlatform must be a string.`);
                }
            }
            // If the pythonPlatform was specified on the command line, it overrides
            // the configuration settings for the execution environment.
            if (commandLineOptions === null || commandLineOptions === void 0 ? void 0 : commandLineOptions.pythonPlatform) {
                newExecEnv.pythonPlatform = commandLineOptions.pythonPlatform;
            }
            // Validate the name
            if (envObj.name) {
                if (typeof envObj.name === 'string') {
                    newExecEnv.name = envObj.name;
                }
                else {
                    errors.push(`Config executionEnvironments index ${index} pythonPlatform must be a string.`);
                }
            }
            return errors.length > 0 ? errors : newExecEnv;
        }
        catch {
            errors.push(`Config executionEnvironments index ${index} is not accessible.`);
            return errors;
        }
    }
}
exports.ConfigOptions = ConfigOptions;
/**
 * {@link ConfigOptions} except it defaults to typeCheckingMode=all. this is a separate subclass to
 * preserve the behavior of the original in tests and anything else that i'm too scared to touch
 */
class BasedConfigOptions extends ConfigOptions {
    static getDiagnosticRuleSet(typeCheckingMode) {
        if (typeCheckingMode === undefined) {
            return (0, exports.getAllDiagnosticRuleSet)();
        }
        return super.getDiagnosticRuleSet(typeCheckingMode);
    }
}
exports.BasedConfigOptions = BasedConfigOptions;
function parseDiagLevel(value) {
    switch (value) {
        case false:
        case 'none':
            return "none" /* DiagnosticSeverityOverrides.None */;
        case true:
        case 'error':
            return "error" /* DiagnosticSeverityOverrides.Error */;
        case 'warning':
            return "warning" /* DiagnosticSeverityOverrides.Warning */;
        case 'information':
            return "information" /* DiagnosticSeverityOverrides.Information */;
        default:
            return undefined;
    }
}
exports.parseDiagLevel = parseDiagLevel;


/***/ }),

/***/ "../pyright-internal/src/common/console.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/common/console.ts ***!
  \*************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * console.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides an abstraction for console logging and error-reporting
 * methods.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertLogLevel = exports.log = exports.ConsoleWithLogLevel = exports.StderrConsole = exports.StandardConsole = exports.NullConsole = exports.getLevelNumber = exports.ConsoleInterface = exports.LogLevel = void 0;
const debug = __importStar(__webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts"));
var LogLevel;
(function (LogLevel) {
    LogLevel["Error"] = "error";
    LogLevel["Warn"] = "warn";
    LogLevel["Info"] = "info";
    LogLevel["Log"] = "log";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
var ConsoleInterface;
(function (ConsoleInterface) {
    function is(obj) {
        return obj.error !== undefined && obj.warn !== undefined && obj.info !== undefined && obj.log !== undefined;
    }
    ConsoleInterface.is = is;
})(ConsoleInterface || (exports.ConsoleInterface = ConsoleInterface = {}));
const levelMap = new Map([
    [LogLevel.Error, 0],
    [LogLevel.Warn, 1],
    [LogLevel.Info, 2],
    [LogLevel.Log, 3],
]);
function getLevelNumber(level) {
    var _a;
    return (_a = levelMap.get(level)) !== null && _a !== void 0 ? _a : 3;
}
exports.getLevelNumber = getLevelNumber;
// Avoids outputting errors to the console but counts
// the number of logs and errors, which can be useful
// for unit tests.
class NullConsole {
    constructor() {
        this.logCount = 0;
        this.infoCount = 0;
        this.warnCount = 0;
        this.errorCount = 0;
    }
    log(message) {
        this.logCount++;
    }
    info(message) {
        this.infoCount++;
    }
    warn(message) {
        this.warnCount++;
    }
    error(message) {
        this.errorCount++;
    }
}
exports.NullConsole = NullConsole;
class StandardConsole {
    constructor(_maxLevel = LogLevel.Log) {
        this._maxLevel = _maxLevel;
    }
    get level() {
        return this._maxLevel;
    }
    log(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Log)) {
            console.log(message);
        }
    }
    info(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Info)) {
            console.info(message);
        }
    }
    warn(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Warn)) {
            console.warn(message);
        }
    }
    error(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Error)) {
            console.error(message);
        }
    }
}
exports.StandardConsole = StandardConsole;
class StderrConsole {
    constructor(_maxLevel = LogLevel.Log) {
        this._maxLevel = _maxLevel;
    }
    get level() {
        return this._maxLevel;
    }
    log(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Log)) {
            console.error(message);
        }
    }
    info(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Info)) {
            console.error(message);
        }
    }
    warn(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Warn)) {
            console.error(message);
        }
    }
    error(message) {
        if (getLevelNumber(this._maxLevel) >= getLevelNumber(LogLevel.Error)) {
            console.error(message);
        }
    }
}
exports.StderrConsole = StderrConsole;
class ConsoleWithLogLevel {
    constructor(_console, _name = '') {
        this._console = _console;
        this._name = _name;
        this._maxLevel = 2;
        this._disposed = false;
    }
    get level() {
        switch (this._maxLevel) {
            case 0:
                return LogLevel.Error;
            case 1:
                return LogLevel.Warn;
            case 2:
                return LogLevel.Info;
        }
        return LogLevel.Log;
    }
    set level(value) {
        let maxLevel = getLevelNumber(value);
        if (maxLevel === undefined) {
            maxLevel = getLevelNumber(LogLevel.Info);
        }
        this._maxLevel = maxLevel;
    }
    dispose() {
        this._disposed = true;
    }
    error(message) {
        this._log(LogLevel.Error, `${this._prefix}${message}`);
    }
    warn(message) {
        this._log(LogLevel.Warn, `${this._prefix}${message}`);
    }
    info(message) {
        this._log(LogLevel.Info, `${this._prefix}${message}`);
    }
    log(message) {
        this._log(LogLevel.Log, `${this._prefix}${message}`);
    }
    get _prefix() {
        return this._name ? `(${this._name}) ` : '';
    }
    _log(level, message) {
        if (this._getNumericalLevel(level) > this._maxLevel) {
            return;
        }
        if (this._disposed) {
            return;
        }
        log(this._console, level, message);
    }
    _getNumericalLevel(level) {
        const numericLevel = getLevelNumber(level);
        debug.assert(numericLevel !== undefined, 'Logger: unknown log level.');
        return numericLevel !== undefined ? numericLevel : 2;
    }
}
exports.ConsoleWithLogLevel = ConsoleWithLogLevel;
function log(console, logType, msg) {
    switch (logType) {
        case LogLevel.Log:
            console.log(msg);
            break;
        case LogLevel.Info:
            console.info(msg);
            break;
        case LogLevel.Warn:
            console.warn(msg);
            break;
        case LogLevel.Error:
            console.error(msg);
            break;
        default:
            debug.fail(`${logType} is not expected`);
    }
}
exports.log = log;
function convertLogLevel(logLevelValue) {
    if (!logLevelValue) {
        return LogLevel.Info;
    }
    switch (logLevelValue.toLowerCase()) {
        case 'error':
            return LogLevel.Error;
        case 'warning':
            return LogLevel.Warn;
        case 'information':
            return LogLevel.Info;
        case 'trace':
            return LogLevel.Log;
        default:
            return LogLevel.Info;
    }
}
exports.convertLogLevel = convertLogLevel;


/***/ }),

/***/ "../pyright-internal/src/common/core.ts":
/*!**********************************************!*\
  !*** ../pyright-internal/src/common/core.ts ***!
  \**********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * core.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Various helpers that don't have a dependency on other code files.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.containsOnlyWhitespace = exports.getEnumNames = exports.isDefined = exports.isThenable = exports.isDebugMode = exports.test_setDebugMode = exports.toBoolean = exports.hasProperty = exports.isBoolean = exports.isNumber = exports.isString = exports.isArray = exports.compareValues = exports.compareComparableValues = exports.equateValues = exports.toLowerCase = exports.identity = exports.returnUndefined = exports.returnTrue = exports.returnFalse = void 0;
const textRange_1 = __webpack_require__(/*! ./textRange */ "../pyright-internal/src/common/textRange.ts");
/** Do nothing and return false */
function returnFalse() {
    return false;
}
exports.returnFalse = returnFalse;
/** Do nothing and return true */
function returnTrue() {
    return true;
}
exports.returnTrue = returnTrue;
/** Do nothing and return undefined */
function returnUndefined() {
    return undefined;
}
exports.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) {
    return x;
}
exports.identity = identity;
/** Returns lower case string */
function toLowerCase(x) {
    return x.toLowerCase();
}
exports.toLowerCase = toLowerCase;
function equateValues(a, b) {
    return a === b;
}
exports.equateValues = equateValues;
function compareComparableValues(a, b) {
    return a === b
        ? 0 /* Comparison.EqualTo */
        : a === undefined
            ? -1 /* Comparison.LessThan */
            : b === undefined
                ? 1 /* Comparison.GreaterThan */
                : a < b
                    ? -1 /* Comparison.LessThan */
                    : 1 /* Comparison.GreaterThan */;
}
exports.compareComparableValues = compareComparableValues;
/**
 * Compare two numeric values for their order relative to each other.
 * To compare strings, use any of the `compareStrings` functions.
 */
function compareValues(a, b) {
    return compareComparableValues(a, b);
}
exports.compareValues = compareValues;
/**
 * Tests whether a value is an array.
 */
function isArray(value) {
    return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
exports.isArray = isArray;
/**
 * Tests whether a value is string
 */
function isString(text) {
    return typeof text === 'string';
}
exports.isString = isString;
function isNumber(x) {
    return typeof x === 'number';
}
exports.isNumber = isNumber;
function isBoolean(x) {
    return typeof x === 'boolean';
}
exports.isBoolean = isBoolean;
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
 * Indicates whether a map-like contains an own property with the specified key.
 *
 * @param map A map-like.
 * @param key A property key.
 */
function hasProperty(map, key) {
    return hasOwnProperty.call(map, key);
}
exports.hasProperty = hasProperty;
/**
 * Convert the given value to boolean
 * @param trueOrFalse string value 'true' or 'false'
 */
function toBoolean(trueOrFalse) {
    const normalized = trueOrFalse === null || trueOrFalse === void 0 ? void 0 : trueOrFalse.trim().toUpperCase();
    if (normalized === 'TRUE') {
        return true;
    }
    return false;
}
exports.toBoolean = toBoolean;
let _debugMode = undefined;
function test_setDebugMode(debugMode) {
    const oldValue = _debugMode;
    _debugMode = debugMode;
    return oldValue;
}
exports.test_setDebugMode = test_setDebugMode;
function isDebugMode() {
    if (_debugMode === undefined) {
        // Cache debugging mode since it can't be changed while process is running.
        const argv = process.execArgv.join();
        _debugMode = argv.includes('inspect') || argv.includes('debug');
    }
    return _debugMode;
}
exports.isDebugMode = isDebugMode;
function isThenable(v) {
    return typeof (v === null || v === void 0 ? void 0 : v.then) === 'function';
}
exports.isThenable = isThenable;
function isDefined(element) {
    return element !== undefined;
}
exports.isDefined = isDefined;
function getEnumNames(enumType) {
    const result = [];
    for (const value in enumType) {
        if (isNaN(Number(value))) {
            result.push(value);
        }
    }
    return result;
}
exports.getEnumNames = getEnumNames;
function containsOnlyWhitespace(text, span) {
    if (span) {
        text = text.substring(span.start, textRange_1.TextRange.getEnd(span));
    }
    return /^\s*$/.test(text);
}
exports.containsOnlyWhitespace = containsOnlyWhitespace;


/***/ }),

/***/ "../pyright-internal/src/common/crypto.ts":
/*!************************************************!*\
  !*** ../pyright-internal/src/common/crypto.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * crypto.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Platform-independent helper functions for crypto.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.randomBytesHex = void 0;
const debug_1 = __webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts");
let nodeCrypto;
try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    nodeCrypto = __webpack_require__(/*! crypto */ "crypto");
    if (!(nodeCrypto === null || nodeCrypto === void 0 ? void 0 : nodeCrypto.randomBytes)) {
        nodeCrypto = undefined;
    }
}
catch {
    // Not running in node.
}
function arrayToHex(arr) {
    return [...arr].map((x) => x.toString(16).padStart(2, '0')).join('');
}
function randomBytesHex(size) {
    if (nodeCrypto) {
        return nodeCrypto.randomBytes(size).toString('hex');
    }
    if (crypto) {
        const buf = crypto.getRandomValues(new Uint8Array(size));
        return arrayToHex(buf);
    }
    (0, debug_1.fail)('crypto library not found');
}
exports.randomBytesHex = randomBytesHex;


/***/ }),

/***/ "../pyright-internal/src/common/debug.ts":
/*!***********************************************!*\
  !*** ../pyright-internal/src/common/debug.ts ***!
  \***********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * debug.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper functions that display user friendly debugging info.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSerializableError = exports.getErrorString = exports.formatEnum = exports.getFunctionName = exports.assertNever = exports.assertEachDefined = exports.assertDefined = exports.fail = exports.assert = void 0;
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
    if (!expression) {
        if (verboseDebugInfo) {
            message +=
                '\r\nVerbose Debug Information: ' +
                    (typeof verboseDebugInfo === 'string' ? verboseDebugInfo : verboseDebugInfo());
        }
        fail(message ? 'False expression: ' + message : 'False expression.', stackCrawlMark || assert);
    }
}
exports.assert = assert;
function fail(message, stackCrawlMark) {
    // debugger;
    const e = new Error(message ? `Debug Failure. ${message}` : 'Debug Failure.');
    if (Error.captureStackTrace) {
        Error.captureStackTrace(e, stackCrawlMark || fail);
    }
    throw e;
}
exports.fail = fail;
function assertDefined(value, message, stackCrawlMark) {
    if (value === undefined || value === null) {
        fail(message, stackCrawlMark || assertDefined);
    }
}
exports.assertDefined = assertDefined;
function assertEachDefined(value, message, stackCrawlMark) {
    for (const v of value) {
        assertDefined(v, message, stackCrawlMark || assertEachDefined);
    }
}
exports.assertEachDefined = assertEachDefined;
function assertNever(member, message = 'Illegal value:', stackCrawlMark) {
    let detail = '';
    try {
        detail = JSON.stringify(member);
    }
    catch {
        // Do nothing.
    }
    fail(`${message} ${detail}`, stackCrawlMark || assertNever);
}
exports.assertNever = assertNever;
function getFunctionName(func) {
    if (typeof func !== 'function') {
        return '';
    }
    else if ((0, core_1.hasProperty)(func, 'name')) {
        return func.name;
    }
    else {
        const text = Function.prototype.toString.call(func);
        const match = /^function\s+([\w$]+)\s*\(/.exec(text);
        return match ? match[1] : '';
    }
}
exports.getFunctionName = getFunctionName;
/**
 * Formats an enum value as a string for debugging and debug assertions.
 */
function formatEnum(value = 0, enumObject, isFlags) {
    const members = getEnumMembers(enumObject);
    if (value === 0) {
        return members.length > 0 && members[0][0] === 0 ? members[0][1] : '0';
    }
    if (isFlags) {
        let result = '';
        let remainingFlags = value;
        for (const [enumValue, enumName] of members) {
            if (enumValue > value) {
                break;
            }
            if (enumValue !== 0 && enumValue & value) {
                result = `${result}${result ? '|' : ''}${enumName}`;
                remainingFlags &= ~enumValue;
            }
        }
        if (remainingFlags === 0) {
            return result;
        }
    }
    else {
        for (const [enumValue, enumName] of members) {
            if (enumValue === value) {
                return enumName;
            }
        }
    }
    return value.toString();
}
exports.formatEnum = formatEnum;
function getErrorString(error) {
    return ((error.stack ? error.stack.toString() : undefined) ||
        (typeof error.message === 'string' ? error.message : undefined) ||
        JSON.stringify(error));
}
exports.getErrorString = getErrorString;
function getSerializableError(error) {
    if (!error) {
        return undefined;
    }
    const exception = JSON.stringify(error);
    if (exception.length > 2) {
        // Given error object is JSON.stringify serializable. Use it as it is
        // to preserve properties.
        return error;
    }
    // Convert error to JSON.stringify serializable Error shape.
    const name = error.name ? ((0, core_1.isString)(error.name) ? error.name : 'noname') : 'noname';
    const message = error.message ? ((0, core_1.isString)(error.message) ? error.message : 'nomessage') : 'nomessage';
    const stack = error.stack ? ((0, core_1.isString)(error.stack) ? error.stack : undefined) : undefined;
    return { name, message, stack };
}
exports.getSerializableError = getSerializableError;
function getEnumMembers(enumObject) {
    const result = [];
    for (const name of Object.keys(enumObject)) {
        const value = enumObject[name];
        if (typeof value === 'number') {
            result.push([value, name]);
        }
    }
    return (0, collectionUtils_1.stableSort)(result, (x, y) => (0, core_1.compareValues)(x[0], y[0]));
}


/***/ }),

/***/ "../pyright-internal/src/common/deferred.ts":
/*!**************************************************!*\
  !*** ../pyright-internal/src/common/deferred.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * deferred.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Promise utilities for async operations.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDeferredFromPromise = exports.createDeferredFrom = exports.createDeferred = void 0;
class DeferredImpl {
    constructor(_scope = null) {
        this._scope = _scope;
        this._resolved = false;
        this._rejected = false;
        this._promise = new Promise((res, rej) => {
            this._resolve = res;
            this._reject = rej;
        });
    }
    get promise() {
        return this._promise;
    }
    get resolved() {
        return this._resolved;
    }
    get rejected() {
        return this._rejected;
    }
    get completed() {
        return this._rejected || this._resolved;
    }
    resolve(_value) {
        // eslint-disable-next-line prefer-rest-params
        this._resolve.apply(this._scope ? this._scope : this, arguments);
        this._resolved = true;
    }
    reject(_reason) {
        // eslint-disable-next-line prefer-rest-params
        this._reject.apply(this._scope ? this._scope : this, arguments);
        this._rejected = true;
    }
}
function createDeferred(scope = null) {
    return new DeferredImpl(scope);
}
exports.createDeferred = createDeferred;
function createDeferredFrom(...promises) {
    const deferred = createDeferred();
    Promise.all(promises)
        .then(deferred.resolve.bind(deferred))
        .catch(deferred.reject.bind(deferred));
    return deferred;
}
exports.createDeferredFrom = createDeferredFrom;
function createDeferredFromPromise(promise) {
    const deferred = createDeferred();
    promise.then(deferred.resolve.bind(deferred)).catch(deferred.reject.bind(deferred));
    return deferred;
}
exports.createDeferredFromPromise = createDeferredFromPromise;


/***/ }),

/***/ "../pyright-internal/src/common/diagnostic.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/diagnostic.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * diagnostics.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that represents errors and warnings.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticAddendum = exports.compareDiagnostics = exports.Diagnostic = exports.convertLevelToCategory = exports.TaskListPriority = void 0;
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const defaultMaxDepth = 5;
const defaultMaxLineCount = 8;
const maxRecursionCount = 64;
// Corresponds to the CommentTaskPriority enum at https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/VS?path=src/env/shell/PackageFramework/Framework/CommentTaskPriority.cs
var TaskListPriority;
(function (TaskListPriority) {
    TaskListPriority["High"] = "High";
    TaskListPriority["Normal"] = "Normal";
    TaskListPriority["Low"] = "Low";
})(TaskListPriority || (exports.TaskListPriority = TaskListPriority = {}));
function convertLevelToCategory(level) {
    switch (level) {
        case 'error':
            return 0 /* DiagnosticCategory.Error */;
        case 'warning':
            return 1 /* DiagnosticCategory.Warning */;
        case 'information':
            return 2 /* DiagnosticCategory.Information */;
        default:
            throw new Error(`${level} is not expected`);
    }
}
exports.convertLevelToCategory = convertLevelToCategory;
// Represents a single error or warning.
class Diagnostic {
    constructor(category, message, range, priority = TaskListPriority.Normal) {
        this.category = category;
        this.message = message;
        this.range = range;
        this.priority = priority;
        this._relatedInfo = [];
    }
    addAction(action) {
        if (this._actions === undefined) {
            this._actions = [action];
        }
        else {
            this._actions.push(action);
        }
    }
    getActions() {
        return this._actions;
    }
    setRule(rule) {
        this._rule = rule;
    }
    getRule() {
        return this._rule;
    }
    addRelatedInfo(message, fileUri, range, priority = TaskListPriority.Normal) {
        this._relatedInfo.push({ uri: fileUri, message, range, priority });
    }
    getRelatedInfo() {
        return this._relatedInfo;
    }
}
exports.Diagnostic = Diagnostic;
// Compares two diagnostics by location for sorting.
function compareDiagnostics(d1, d2) {
    if (d1.range.start.line < d2.range.start.line) {
        return -1;
    }
    else if (d1.range.start.line > d2.range.start.line) {
        return 1;
    }
    if (d1.range.start.character < d2.range.start.character) {
        return -1;
    }
    else if (d1.range.start.character > d2.range.start.character) {
        return 1;
    }
    return 0;
}
exports.compareDiagnostics = compareDiagnostics;
// Helps to build additional information that can be appended to a diagnostic
// message. It supports hierarchical information and flexible formatting.
class DiagnosticAddendum {
    constructor() {
        this._messages = [];
        this._childAddenda = [];
    }
    addMessage(message) {
        this._messages.push(message);
    }
    addTextRange(range) {
        this._range = range;
    }
    // Create a new (nested) addendum to which messages can be added.
    createAddendum() {
        const newAddendum = new DiagnosticAddendum();
        this.addAddendum(newAddendum);
        return newAddendum;
    }
    getString(maxDepth = defaultMaxDepth, maxLineCount = defaultMaxLineCount) {
        let lines = this._getLinesRecursive(maxDepth, maxLineCount);
        if (lines.length > maxLineCount) {
            lines = lines.slice(0, maxLineCount);
            lines.push('  ...');
        }
        const text = lines.join('\n');
        if (text.length > 0) {
            return '\n' + text;
        }
        return '';
    }
    isEmpty() {
        return this._getMessageCount() === 0;
    }
    addAddendum(addendum) {
        this._childAddenda.push(addendum);
    }
    getChildren() {
        return this._childAddenda;
    }
    getMessages() {
        return this._messages;
    }
    // Returns undefined if no range is associated with this addendum
    // or its children. Returns a non-empty range if there is a single range
    // associated.
    getEffectiveTextRange() {
        const range = this._getTextRangeRecursive();
        // If we received an empty range, it means that there were multiple
        // non-overlapping ranges associated with this addendum.
        if ((range === null || range === void 0 ? void 0 : range.length) === 0) {
            return undefined;
        }
        return range;
    }
    _getTextRangeRecursive(recursionCount = 0) {
        if (recursionCount > maxRecursionCount) {
            return undefined;
        }
        recursionCount++;
        const childRanges = this._childAddenda
            .map((child) => child._getTextRangeRecursive(recursionCount))
            .filter((r) => !!r);
        if (childRanges.length > 1) {
            return { start: 0, length: 0 };
        }
        if (childRanges.length === 1) {
            return childRanges[0];
        }
        if (this._range) {
            return this._range;
        }
        return undefined;
    }
    _getMessageCount(recursionCount = 0) {
        if (recursionCount > maxRecursionCount) {
            return 0;
        }
        // Get the nested message count.
        let messageCount = this._messages.length;
        for (const diag of this._childAddenda) {
            messageCount += diag._getMessageCount(recursionCount + 1);
        }
        return messageCount;
    }
    _getLinesRecursive(maxDepth, maxLineCount, recursionCount = 0) {
        if (maxDepth <= 0 || recursionCount > maxRecursionCount) {
            return [];
        }
        let childLines = [];
        for (const addendum of this._childAddenda) {
            const maxDepthRemaining = this._messages.length > 0 ? maxDepth - 1 : maxDepth;
            (0, collectionUtils_1.appendArray)(childLines, addendum._getLinesRecursive(maxDepthRemaining, maxLineCount, recursionCount + 1));
            // If the number of lines exceeds our max line count, don't bother adding more.
            if (childLines.length >= maxLineCount) {
                childLines = childLines.slice(0, maxLineCount);
                break;
            }
        }
        // Prepend indentation for readability. Skip if there are no
        // messages at this level.
        const extraSpace = this._messages.length > 0 ? '  ' : '';
        return this._messages.concat(childLines).map((line) => extraSpace + line);
    }
}
exports.DiagnosticAddendum = DiagnosticAddendum;


/***/ }),

/***/ "../pyright-internal/src/common/diagnosticRules.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/common/diagnosticRules.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * diagnosticRules.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Strings that represent each of the diagnostic rules
 * that can be enabled or disabled in the configuration.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagnosticRule = void 0;
// Not const enum since keys need to be inspected in tests
// to match declaration of user-visible settings in package.json
var DiagnosticRule;
(function (DiagnosticRule) {
    DiagnosticRule["strictListInference"] = "strictListInference";
    DiagnosticRule["strictSetInference"] = "strictSetInference";
    DiagnosticRule["strictDictionaryInference"] = "strictDictionaryInference";
    DiagnosticRule["analyzeUnannotatedFunctions"] = "analyzeUnannotatedFunctions";
    DiagnosticRule["strictParameterNoneValue"] = "strictParameterNoneValue";
    DiagnosticRule["enableExperimentalFeatures"] = "enableExperimentalFeatures";
    DiagnosticRule["enableTypeIgnoreComments"] = "enableTypeIgnoreComments";
    DiagnosticRule["deprecateTypingAliases"] = "deprecateTypingAliases";
    DiagnosticRule["disableBytesTypePromotions"] = "disableBytesTypePromotions";
    DiagnosticRule["reportGeneralTypeIssues"] = "reportGeneralTypeIssues";
    DiagnosticRule["reportPropertyTypeMismatch"] = "reportPropertyTypeMismatch";
    DiagnosticRule["reportFunctionMemberAccess"] = "reportFunctionMemberAccess";
    DiagnosticRule["reportMissingImports"] = "reportMissingImports";
    DiagnosticRule["reportMissingModuleSource"] = "reportMissingModuleSource";
    DiagnosticRule["reportInvalidTypeForm"] = "reportInvalidTypeForm";
    DiagnosticRule["reportMissingTypeStubs"] = "reportMissingTypeStubs";
    DiagnosticRule["reportImportCycles"] = "reportImportCycles";
    DiagnosticRule["reportUnusedImport"] = "reportUnusedImport";
    DiagnosticRule["reportUnusedClass"] = "reportUnusedClass";
    DiagnosticRule["reportUnusedFunction"] = "reportUnusedFunction";
    DiagnosticRule["reportUnusedVariable"] = "reportUnusedVariable";
    DiagnosticRule["reportDuplicateImport"] = "reportDuplicateImport";
    DiagnosticRule["reportWildcardImportFromLibrary"] = "reportWildcardImportFromLibrary";
    DiagnosticRule["reportAbstractUsage"] = "reportAbstractUsage";
    DiagnosticRule["reportArgumentType"] = "reportArgumentType";
    DiagnosticRule["reportAssertTypeFailure"] = "reportAssertTypeFailure";
    DiagnosticRule["reportAssignmentType"] = "reportAssignmentType";
    DiagnosticRule["reportAttributeAccessIssue"] = "reportAttributeAccessIssue";
    DiagnosticRule["reportCallIssue"] = "reportCallIssue";
    DiagnosticRule["reportInconsistentOverload"] = "reportInconsistentOverload";
    DiagnosticRule["reportIndexIssue"] = "reportIndexIssue";
    DiagnosticRule["reportInvalidTypeArguments"] = "reportInvalidTypeArguments";
    DiagnosticRule["reportNoOverloadImplementation"] = "reportNoOverloadImplementation";
    DiagnosticRule["reportOperatorIssue"] = "reportOperatorIssue";
    DiagnosticRule["reportOptionalSubscript"] = "reportOptionalSubscript";
    DiagnosticRule["reportOptionalMemberAccess"] = "reportOptionalMemberAccess";
    DiagnosticRule["reportOptionalCall"] = "reportOptionalCall";
    DiagnosticRule["reportOptionalIterable"] = "reportOptionalIterable";
    DiagnosticRule["reportOptionalContextManager"] = "reportOptionalContextManager";
    DiagnosticRule["reportOptionalOperand"] = "reportOptionalOperand";
    DiagnosticRule["reportRedeclaration"] = "reportRedeclaration";
    DiagnosticRule["reportReturnType"] = "reportReturnType";
    DiagnosticRule["reportTypedDictNotRequiredAccess"] = "reportTypedDictNotRequiredAccess";
    DiagnosticRule["reportUntypedFunctionDecorator"] = "reportUntypedFunctionDecorator";
    DiagnosticRule["reportUntypedClassDecorator"] = "reportUntypedClassDecorator";
    DiagnosticRule["reportUntypedBaseClass"] = "reportUntypedBaseClass";
    DiagnosticRule["reportUntypedNamedTuple"] = "reportUntypedNamedTuple";
    DiagnosticRule["reportPrivateUsage"] = "reportPrivateUsage";
    DiagnosticRule["reportTypeCommentUsage"] = "reportTypeCommentUsage";
    DiagnosticRule["reportPrivateImportUsage"] = "reportPrivateImportUsage";
    DiagnosticRule["reportConstantRedefinition"] = "reportConstantRedefinition";
    DiagnosticRule["reportDeprecated"] = "reportDeprecated";
    DiagnosticRule["reportIncompatibleMethodOverride"] = "reportIncompatibleMethodOverride";
    DiagnosticRule["reportIncompatibleVariableOverride"] = "reportIncompatibleVariableOverride";
    DiagnosticRule["reportInconsistentConstructor"] = "reportInconsistentConstructor";
    DiagnosticRule["reportOverlappingOverload"] = "reportOverlappingOverload";
    DiagnosticRule["reportPossiblyUnboundVariable"] = "reportPossiblyUnboundVariable";
    DiagnosticRule["reportMissingSuperCall"] = "reportMissingSuperCall";
    DiagnosticRule["reportUninitializedInstanceVariable"] = "reportUninitializedInstanceVariable";
    DiagnosticRule["reportInvalidStringEscapeSequence"] = "reportInvalidStringEscapeSequence";
    DiagnosticRule["reportUnknownParameterType"] = "reportUnknownParameterType";
    DiagnosticRule["reportUnknownArgumentType"] = "reportUnknownArgumentType";
    DiagnosticRule["reportUnknownLambdaType"] = "reportUnknownLambdaType";
    DiagnosticRule["reportUnknownVariableType"] = "reportUnknownVariableType";
    DiagnosticRule["reportUnknownMemberType"] = "reportUnknownMemberType";
    DiagnosticRule["reportMissingParameterType"] = "reportMissingParameterType";
    DiagnosticRule["reportMissingTypeArgument"] = "reportMissingTypeArgument";
    DiagnosticRule["reportInvalidTypeVarUse"] = "reportInvalidTypeVarUse";
    DiagnosticRule["reportCallInDefaultInitializer"] = "reportCallInDefaultInitializer";
    DiagnosticRule["reportUnnecessaryIsInstance"] = "reportUnnecessaryIsInstance";
    DiagnosticRule["reportUnnecessaryCast"] = "reportUnnecessaryCast";
    DiagnosticRule["reportUnnecessaryComparison"] = "reportUnnecessaryComparison";
    DiagnosticRule["reportUnnecessaryContains"] = "reportUnnecessaryContains";
    DiagnosticRule["reportAssertAlwaysTrue"] = "reportAssertAlwaysTrue";
    DiagnosticRule["reportSelfClsParameterName"] = "reportSelfClsParameterName";
    DiagnosticRule["reportImplicitStringConcatenation"] = "reportImplicitStringConcatenation";
    DiagnosticRule["reportUndefinedVariable"] = "reportUndefinedVariable";
    DiagnosticRule["reportUnboundVariable"] = "reportUnboundVariable";
    DiagnosticRule["reportUnhashable"] = "reportUnhashable";
    DiagnosticRule["reportInvalidStubStatement"] = "reportInvalidStubStatement";
    DiagnosticRule["reportIncompleteStub"] = "reportIncompleteStub";
    DiagnosticRule["reportUnsupportedDunderAll"] = "reportUnsupportedDunderAll";
    DiagnosticRule["reportUnusedCallResult"] = "reportUnusedCallResult";
    DiagnosticRule["reportUnusedCoroutine"] = "reportUnusedCoroutine";
    DiagnosticRule["reportUnusedExcept"] = "reportUnusedExcept";
    DiagnosticRule["reportUnusedExpression"] = "reportUnusedExpression";
    DiagnosticRule["reportUnnecessaryTypeIgnoreComment"] = "reportUnnecessaryTypeIgnoreComment";
    DiagnosticRule["reportMatchNotExhaustive"] = "reportMatchNotExhaustive";
    DiagnosticRule["reportShadowedImports"] = "reportShadowedImports";
    DiagnosticRule["reportImplicitOverride"] = "reportImplicitOverride";
    // basedpyright options:
    DiagnosticRule["reportUnreachable"] = "reportUnreachable";
    DiagnosticRule["reportAny"] = "reportAny";
    DiagnosticRule["reportIgnoreCommentWithoutRule"] = "reportIgnoreCommentWithoutRule";
    DiagnosticRule["reportPrivateLocalImportUsage"] = "reportPrivateLocalImportUsage";
    DiagnosticRule["reportImplicitRelativeImport"] = "reportImplicitRelativeImport";
    DiagnosticRule["reportInvalidCast"] = "reportInvalidCast";
})(DiagnosticRule || (exports.DiagnosticRule = DiagnosticRule = {}));


/***/ }),

/***/ "../pyright-internal/src/common/diagnosticSink.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/common/diagnosticSink.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * diagnostics.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Class that collects and deduplicates diagnostics.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TextRangeDiagnosticSink = exports.DiagnosticSink = void 0;
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const diagnostic_1 = __webpack_require__(/*! ./diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const positionUtils_1 = __webpack_require__(/*! ./positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const stringUtils_1 = __webpack_require__(/*! ./stringUtils */ "../pyright-internal/src/common/stringUtils.ts");
// Creates and tracks a list of diagnostics.
class DiagnosticSink {
    constructor(diagnostics) {
        this._diagnosticList = diagnostics || [];
        this._diagnosticMap = new Map();
    }
    fetchAndClear() {
        const prevDiagnostics = this._diagnosticList;
        this._diagnosticList = [];
        this._diagnosticMap.clear();
        return prevDiagnostics;
    }
    addError(message, range) {
        return this.addDiagnostic(new diagnostic_1.Diagnostic(0 /* DiagnosticCategory.Error */, message, range));
    }
    addWarning(message, range) {
        return this.addDiagnostic(new diagnostic_1.Diagnostic(1 /* DiagnosticCategory.Warning */, message, range));
    }
    addInformation(message, range) {
        return this.addDiagnostic(new diagnostic_1.Diagnostic(2 /* DiagnosticCategory.Information */, message, range));
    }
    addUnusedCode(message, range, action) {
        const diag = new diagnostic_1.Diagnostic(3 /* DiagnosticCategory.UnusedCode */, message, range);
        if (action) {
            diag.addAction(action);
        }
        return this.addDiagnostic(diag);
    }
    addUnreachableCode(message, range, action) {
        const diag = new diagnostic_1.Diagnostic(4 /* DiagnosticCategory.UnreachableCode */, message, range);
        if (action) {
            diag.addAction(action);
        }
        return this.addDiagnostic(diag);
    }
    addDeprecated(message, range, action) {
        const diag = new diagnostic_1.Diagnostic(5 /* DiagnosticCategory.Deprecated */, message, range);
        if (action) {
            diag.addAction(action);
        }
        return this.addDiagnostic(diag);
    }
    addDiagnostic(diag) {
        // Create a unique key for the diagnostic to prevent
        // adding duplicates.
        const key = `${diag.range.start.line},${diag.range.start.character}-` +
            `${diag.range.end.line}-${diag.range.end.character}:${(0, stringUtils_1.hashString)(diag.message)}}`;
        if (!this._diagnosticMap.has(key)) {
            this._diagnosticList.push(diag);
            this._diagnosticMap.set(key, diag);
        }
        return diag;
    }
    addDiagnostics(diagsToAdd) {
        (0, collectionUtils_1.appendArray)(this._diagnosticList, diagsToAdd);
    }
    getErrors() {
        return this._diagnosticList.filter((diag) => diag.category === 0 /* DiagnosticCategory.Error */);
    }
    getWarnings() {
        return this._diagnosticList.filter((diag) => diag.category === 1 /* DiagnosticCategory.Warning */);
    }
    getInformation() {
        return this._diagnosticList.filter((diag) => diag.category === 2 /* DiagnosticCategory.Information */);
    }
    getUnusedCode() {
        return this._diagnosticList.filter((diag) => diag.category === 3 /* DiagnosticCategory.UnusedCode */);
    }
    getUnreachableCode() {
        return this._diagnosticList.filter((diag) => diag.category === 4 /* DiagnosticCategory.UnreachableCode */);
    }
    getDeprecated() {
        return this._diagnosticList.filter((diag) => diag.category === 5 /* DiagnosticCategory.Deprecated */);
    }
}
exports.DiagnosticSink = DiagnosticSink;
// Specialized version of DiagnosticSink that works with TextRange objects
// and converts text ranges to line and column numbers.
class TextRangeDiagnosticSink extends DiagnosticSink {
    constructor(lines, diagnostics) {
        super(diagnostics);
        this._lines = lines;
    }
    addDiagnosticWithTextRange(level, message, range) {
        const positionRange = (0, positionUtils_1.convertOffsetsToRange)(range.start, range.start + range.length, this._lines);
        switch (level) {
            case 'error':
                return this.addError(message, positionRange);
            case 'warning':
                return this.addWarning(message, positionRange);
            case 'information':
                return this.addInformation(message, positionRange);
            default:
                throw new Error(`${level} is not expected value`);
        }
    }
    addUnusedCodeWithTextRange(message, range, action) {
        return this.addUnusedCode(message, (0, positionUtils_1.convertOffsetsToRange)(range.start, range.start + range.length, this._lines), action);
    }
    addUnreachableCodeWithTextRange(message, range, action) {
        return this.addUnreachableCode(message, (0, positionUtils_1.convertOffsetsToRange)(range.start, range.start + range.length, this._lines), action);
    }
    addDeprecatedWithTextRange(message, range, action) {
        return this.addDeprecated(message, (0, positionUtils_1.convertOffsetsToRange)(range.start, range.start + range.length, this._lines), action);
    }
}
exports.TextRangeDiagnosticSink = TextRangeDiagnosticSink;


/***/ }),

/***/ "../pyright-internal/src/common/envVarUtils.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/envVarUtils.ts ***!
  \*****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * envVarUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Utils functions that handles environment variables.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.expandPathVariables = exports.resolvePathWithEnvVariables = void 0;
const os = __importStar(__webpack_require__(/*! os */ "os"));
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const pathUtils_1 = __webpack_require__(/*! ./pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ./serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
function resolvePathWithEnvVariables(workspace, path, workspaces) {
    const rootUri = workspace.rootUri;
    const expanded = expandPathVariables(path, rootUri !== null && rootUri !== void 0 ? rootUri : uri_1.Uri.empty(), workspaces);
    const caseDetector = workspace.service.serviceProvider.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
    if (maybeUri(expanded)) {
        // If path is expanded to uri, no need to resolve it against the workspace root.
        return uri_1.Uri.parse((0, pathUtils_1.normalizeSlashes)(expanded, '/'), caseDetector);
    }
    if (rootUri) {
        // normal case, resolve the path against workspace root.
        return rootUri.resolvePaths((0, pathUtils_1.normalizeSlashes)(expanded, '/'));
    }
    // We don't have workspace root. but path contains something that require `workspace root`
    if (path.includes('${workspaceFolder')) {
        return undefined;
    }
    // Without workspace root, we can't handle any `relative path`.
    if (!(0, pathUtils_1.isRootedDiskPath)((0, pathUtils_1.normalizeSlashes)(expanded))) {
        return undefined;
    }
    // We have absolute file path.
    return uri_1.Uri.file(expanded, caseDetector);
}
exports.resolvePathWithEnvVariables = resolvePathWithEnvVariables;
// Expands certain predefined variables supported within VS Code settings.
// Ideally, VS Code would provide an API for doing this expansion, but
// it doesn't. We'll handle the most common variables here as a convenience.
function expandPathVariables(path, rootPath, workspaces) {
    // Make sure all replacements look like URI paths too.
    const replace = (match, replaceValue) => {
        path = path.replace(match, replaceValue);
    };
    // Replace everything inline.
    path = path.replace(/\$\{workspaceFolder\}/g, rootPath.getPath());
    // this is for vscode multiroot workspace supports.
    // https://code.visualstudio.com/docs/editor/variables-reference#_variables-scoped-per-workspace-folder
    for (const workspace of workspaces) {
        if (!workspace.rootUri) {
            continue;
        }
        const ws_regexp = RegExp(`\\$\\{workspaceFolder:${workspace.workspaceName}\\}`, 'g');
        path = path.replace(ws_regexp, workspace.rootUri.getPath());
    }
    if (process.env.HOME !== undefined) {
        replace(/\$\{env:HOME\}/g, process.env.HOME || '');
    }
    if (process.env.USERNAME !== undefined) {
        replace(/\$\{env:USERNAME\}/g, process.env.USERNAME || '');
    }
    if (process.env.VIRTUAL_ENV !== undefined) {
        replace(/\$\{env:VIRTUAL_ENV\}/g, process.env.VIRTUAL_ENV || '');
    }
    if (os.homedir) {
        replace(/\/~/g, os.homedir() || process.env.HOME || process.env.USERPROFILE || '~');
        replace(/^~/g, os.homedir() || process.env.HOME || process.env.USERPROFILE || '~');
    }
    return path;
}
exports.expandPathVariables = expandPathVariables;
function maybeUri(value) {
    const windows = /^[a-zA-Z]:\\?/;
    const uri = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/?\/?/;
    return uri.test(value) && !windows.test(value);
}


/***/ }),

/***/ "../pyright-internal/src/common/extensibility.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/common/extensibility.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
* extensibility.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.

* Language service extensibility.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReferenceUseCase = void 0;
var ReferenceUseCase;
(function (ReferenceUseCase) {
    ReferenceUseCase[ReferenceUseCase["Rename"] = 0] = "Rename";
    ReferenceUseCase[ReferenceUseCase["References"] = 1] = "References";
})(ReferenceUseCase || (exports.ReferenceUseCase = ReferenceUseCase = {}));


/***/ }),

/***/ "../pyright-internal/src/common/extensions.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/extensions.ts ***!
  \****************************************************/
/***/ (() => {

"use strict";

/*
 * extensions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Extension methods to various types.
 */
/* eslint-disable @typescript-eslint/no-empty-function */
// Explicitly tells that promise should be run asynchronously.
Promise.prototype.ignoreErrors = function () {
    this.catch((e) => {
        console.log(e);
    });
};


/***/ }),

/***/ "../pyright-internal/src/common/fileBasedCancellationUtils.ts":
/*!********************************************************************!*\
  !*** ../pyright-internal/src/common/fileBasedCancellationUtils.ts ***!
  \********************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * fileBasedCancellationUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper methods relating to file-based cancellation.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FileBasedCancellationProvider = exports.getCancellationTokenFromId = exports.disposeCancellationToken = exports.getCancellationStrategyFromArgv = void 0;
const fs = __importStar(__webpack_require__(/*! fs */ "fs"));
const os = __importStar(__webpack_require__(/*! os */ "os"));
const path = __importStar(__webpack_require__(/*! path */ "path"));
const vscode_jsonrpc_1 = __webpack_require__(/*! vscode-jsonrpc */ "../pyright-internal/node_modules/vscode-jsonrpc/lib/node/main.js");
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const cancellationUtils_1 = __webpack_require__(/*! ./cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
class StatSyncFromFs {
    statSync(uri) {
        return fs.statSync(uri.getFilePath());
    }
}
class OwningFileToken extends cancellationUtils_1.FileBasedToken {
    constructor(cancellationId) {
        super(cancellationId, new StatSyncFromFs());
        this._disposed = false;
    }
    get isCancellationRequested() {
        // Since this object owns the file and it gets created when the
        // token is cancelled, there's no point in checking the pipe.
        return this.isCancelled;
    }
    cancel() {
        if (!this._disposed && !this.isCancelled) {
            this._createPipe();
            super.cancel();
        }
    }
    dispose() {
        this._disposed = true;
        super.dispose();
        this._removePipe();
    }
    _createPipe() {
        try {
            fs.writeFileSync(this.cancellationFilePath.getFilePath(), '', { flag: 'w' });
        }
        catch {
            // Ignore the exception.
        }
    }
    _removePipe() {
        try {
            fs.unlinkSync(this.cancellationFilePath.getFilePath());
        }
        catch {
            // Ignore the exception.
        }
    }
}
class FileBasedCancellationTokenSource {
    constructor(_cancellationId, _ownFile = false) {
        this._cancellationId = _cancellationId;
        this._ownFile = _ownFile;
    }
    get token() {
        if (!this._token) {
            // Be lazy and create the token only when actually needed.
            this._token = this._ownFile
                ? new OwningFileToken(this._cancellationId)
                : new cancellationUtils_1.FileBasedToken(this._cancellationId, new StatSyncFromFs());
        }
        return this._token;
    }
    cancel() {
        if (!this._token) {
            // Save an object by returning the default
            // cancelled token when cancellation happens
            // before someone asks for the token.
            this._token = vscode_languageserver_1.CancellationToken.Cancelled;
        }
        else if (this._token.isCancellationRequested) {
            // Already cancelled.
            return;
        }
        else {
            this._token.cancel();
        }
    }
    dispose() {
        if (!this._token) {
            // Make sure to initialize with an empty token if we had none.
            this._token = vscode_languageserver_1.CancellationToken.None;
        }
        else if (this._token instanceof cancellationUtils_1.FileBasedToken) {
            // Actually dispose.
            this._token.dispose();
        }
    }
}
function getCancellationFolderPath(folderName) {
    return path.join(os.tmpdir(), 'python-languageserver-cancellation', folderName);
}
function getCancellationFileUri(folderName, id) {
    return uriUtils_1.UriEx.file(path.join(getCancellationFolderPath(folderName), `cancellation-${String(id)}.tmp`)).toString();
}
class FileCancellationReceiverStrategy {
    constructor(folderName) {
        this.folderName = folderName;
    }
    createCancellationTokenSource(id) {
        return new FileBasedCancellationTokenSource(getCancellationFileUri(this.folderName, id));
    }
}
function getCancellationStrategyFromArgv(argv) {
    let receiver;
    for (let i = 0; i < argv.length; i++) {
        const arg = argv[i];
        if (arg === '--cancellationReceive') {
            receiver = createReceiverStrategyFromArgv(argv[i + 1]);
        }
        else {
            const args = arg.split('=');
            if (args[0] === '--cancellationReceive') {
                receiver = createReceiverStrategyFromArgv(args[1]);
            }
        }
    }
    if (receiver && !(0, cancellationUtils_1.getCancellationFolderName)()) {
        (0, cancellationUtils_1.setCancellationFolderName)(receiver.folderName);
    }
    receiver = receiver ? receiver : vscode_languageserver_1.CancellationReceiverStrategy.Message;
    return { receiver, sender: vscode_languageserver_1.CancellationSenderStrategy.Message };
    function createReceiverStrategyFromArgv(arg) {
        const folderName = extractCancellationFolderName(arg);
        return folderName ? new FileCancellationReceiverStrategy(folderName) : undefined;
    }
    function extractCancellationFolderName(arg) {
        const fileRegex = /^file:(.+)$/;
        const folderName = arg.match(fileRegex);
        return folderName ? folderName[1] : undefined;
    }
}
exports.getCancellationStrategyFromArgv = getCancellationStrategyFromArgv;
function disposeCancellationToken(token) {
    if (token instanceof cancellationUtils_1.FileBasedToken) {
        token.dispose();
    }
}
exports.disposeCancellationToken = disposeCancellationToken;
function getCancellationTokenFromId(cancellationId) {
    if (!cancellationId) {
        return vscode_languageserver_1.CancellationToken.None;
    }
    return new cancellationUtils_1.FileBasedToken(cancellationId, new StatSyncFromFs());
}
exports.getCancellationTokenFromId = getCancellationTokenFromId;
let cancellationSourceId = 0;
class FileBasedCancellationProvider {
    constructor(_prefix) {
        this._prefix = _prefix;
        // empty
    }
    createCancellationTokenSource() {
        const folderName = (0, cancellationUtils_1.getCancellationFolderName)();
        if (!folderName) {
            // File-based cancellation is not used.
            // Return regular cancellation token source.
            return new vscode_jsonrpc_1.CancellationTokenSource();
        }
        return new FileBasedCancellationTokenSource(getCancellationFileUri(folderName, `${this._prefix}-${String(cancellationSourceId++)}`), 
        /* ownFile */ true);
    }
}
exports.FileBasedCancellationProvider = FileBasedCancellationProvider;


/***/ }),

/***/ "../pyright-internal/src/common/fileSystem.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/fileSystem.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * fileSystem.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * A "file system provider" abstraction that allows us to swap out a
 * real file system implementation for a virtual (mocked) implementation
 * for testing.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VirtualDirent = exports.TempFile = exports.FileSystem = void 0;
var FileSystem;
(function (FileSystem) {
    function is(value) {
        return value.createFileSystemWatcher && value.createReadStream && value.createWriteStream && value.copyFileSync;
    }
    FileSystem.is = is;
})(FileSystem || (exports.FileSystem = FileSystem = {}));
var TempFile;
(function (TempFile) {
    function is(value) {
        return value.tmpdir && value.tmpfile && value.dispose;
    }
    TempFile.is = is;
})(TempFile || (exports.TempFile = TempFile = {}));
class VirtualDirent {
    constructor(name, _file) {
        this.name = name;
        this._file = _file;
    }
    isFile() {
        return this._file;
    }
    isDirectory() {
        return !this._file;
    }
    isBlockDevice() {
        return false;
    }
    isCharacterDevice() {
        return false;
    }
    isSymbolicLink() {
        return false;
    }
    isFIFO() {
        return false;
    }
    isSocket() {
        return false;
    }
}
exports.VirtualDirent = VirtualDirent;


/***/ }),

/***/ "../pyright-internal/src/common/fileWatcher.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/fileWatcher.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ignoredWatchEventFunction = exports.nullFileWatcherProvider = exports.nullFileWatcherHandler = void 0;
exports.nullFileWatcherHandler = {
    onFileChange(_1, _2) {
        // do nothing
    },
};
exports.nullFileWatcherProvider = {
    createFileWatcher(_1, _2) {
        return nullFileWatcher;
    },
};
// File watchers can give "changed" event even for a file open. but for those cases,
// it will give relative path rather than absolute path. To get rid of such cases,
// we will drop any event with relative paths. this trick is copied from VS Code
// (https://github.com/microsoft/vscode/blob/main/src/vs/platform/files/node/watcher/unix/chokidarWatcherService.ts)
function ignoredWatchEventFunction(paths) {
    const normalizedPaths = paths.map((p) => p.toLowerCase());
    return (path) => {
        if (!path || path.indexOf('__pycache__') >= 0) {
            return true;
        }
        const normalizedPath = path.toLowerCase();
        return normalizedPaths.every((p) => normalizedPath.indexOf(p) < 0);
    };
}
exports.ignoredWatchEventFunction = ignoredWatchEventFunction;
const nullFileWatcher = {
    close() {
        // empty;
    },
};


/***/ }),

/***/ "../pyright-internal/src/common/fullAccessHost.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/common/fullAccessHost.ts ***!
  \********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * fullAccessHost.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implementation of host where it is allowed to run external executables.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FullAccessHost = exports.LimitedAccessHost = void 0;
const child_process = __importStar(__webpack_require__(/*! child_process */ "child_process"));
const cancellationUtils_1 = __webpack_require__(/*! ./cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ./configOptions */ "../pyright-internal/src/common/configOptions.ts");
const debug_1 = __webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts");
const host_1 = __webpack_require__(/*! ./host */ "../pyright-internal/src/common/host.ts");
const pathUtils_1 = __webpack_require__(/*! ./pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const pythonVersion_1 = __webpack_require__(/*! ./pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ./serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
// preventLocalImports removes the working directory from sys.path.
// The -c flag adds it automatically, which can allow some stdlib
// modules (like json) to be overridden by other files (like json.py).
const removeCwdFromSysPath = [
    'import os, os.path, sys',
    'normalize = lambda p: os.path.normcase(os.path.normpath(p))',
    'cwd = normalize(os.getcwd())',
    'orig_sys_path = [p for p in sys.path if p != ""]',
    'sys.path[:] = [p for p in sys.path if p != "" and normalize(p) != cwd]',
];
const extractSys = [
    ...removeCwdFromSysPath,
    'import sys, json',
    'json.dump(dict(path=orig_sys_path, prefix=sys.prefix), sys.stdout)',
].join('; ');
const extractVersion = [
    ...removeCwdFromSysPath,
    'import sys, json',
    'json.dump(tuple(sys.version_info), sys.stdout)',
].join('; ');
class LimitedAccessHost extends host_1.NoAccessHost {
    get kind() {
        return 1 /* HostKind.LimitedAccess */;
    }
    getPythonPlatform(logInfo) {
        if (process.platform === 'darwin') {
            return configOptions_1.PythonPlatform.Darwin;
        }
        else if (process.platform === 'linux') {
            return configOptions_1.PythonPlatform.Linux;
        }
        else if (process.platform === 'win32') {
            return configOptions_1.PythonPlatform.Windows;
        }
        return undefined;
    }
}
exports.LimitedAccessHost = LimitedAccessHost;
class FullAccessHost extends LimitedAccessHost {
    constructor(serviceProvider) {
        super();
        this.serviceProvider = serviceProvider;
    }
    get kind() {
        return 0 /* HostKind.FullAccess */;
    }
    static createHost(kind, serviceProvider) {
        switch (kind) {
            case 2 /* HostKind.NoAccess */:
                return new host_1.NoAccessHost();
            case 1 /* HostKind.LimitedAccess */:
                return new LimitedAccessHost();
            case 0 /* HostKind.FullAccess */:
                return new FullAccessHost(serviceProvider);
            default:
                (0, debug_1.assertNever)(kind);
        }
    }
    getPythonSearchPaths(pythonPath, logInfo) {
        const importFailureInfo = logInfo !== null && logInfo !== void 0 ? logInfo : [];
        let result = this._executePythonInterpreter(pythonPath === null || pythonPath === void 0 ? void 0 : pythonPath.getFilePath(), (p) => this._getSearchPathResultFromInterpreter(p, importFailureInfo));
        if (!result) {
            result = {
                paths: [],
                prefix: undefined,
            };
        }
        importFailureInfo.push(`Received ${result.paths.length} paths from interpreter`);
        result.paths.forEach((path) => {
            importFailureInfo.push(`  ${path}`);
        });
        return result;
    }
    getPythonVersion(pythonPath, logInfo) {
        const importFailureInfo = logInfo !== null && logInfo !== void 0 ? logInfo : [];
        try {
            const commandLineArgs = ['-c', extractVersion];
            const execOutput = this._executePythonInterpreter(pythonPath === null || pythonPath === void 0 ? void 0 : pythonPath.getFilePath(), (p) => child_process.execFileSync(p, commandLineArgs, { encoding: 'utf8' }));
            const versionJson = JSON.parse(execOutput);
            if (!Array.isArray(versionJson) || versionJson.length < 5) {
                importFailureInfo.push(`Python version ${execOutput} from interpreter is unexpected format`);
                return undefined;
            }
            const version = new pythonVersion_1.PythonVersion(versionJson[0], versionJson[1], versionJson[2], versionJson[3], versionJson[4]);
            if (version === undefined) {
                importFailureInfo.push(`Python version ${execOutput} from interpreter is unsupported`);
                return undefined;
            }
            return version;
        }
        catch {
            importFailureInfo.push('Unable to get Python version from interpreter');
            return undefined;
        }
    }
    runScript(pythonPath, script, args, cwd, token) {
        // If it is already cancelled, don't bother to run script.
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        // What to do about conda here?
        return new Promise((resolve, reject) => {
            let stdout = '';
            let stderr = '';
            const commandLineArgs = [script.getFilePath(), ...args];
            const child = this._executePythonInterpreter(pythonPath === null || pythonPath === void 0 ? void 0 : pythonPath.getFilePath(), (p) => child_process.spawn(p, commandLineArgs, { cwd: cwd.getFilePath() }));
            const tokenWatch = (0, cancellationUtils_1.onCancellationRequested)(token, () => {
                if (child) {
                    try {
                        if (child.pid && child.exitCode === null) {
                            if (process.platform === 'win32') {
                                // Windows doesn't support SIGTERM, so execute taskkill to kill the process
                                child_process.execSync(`taskkill /pid ${child.pid} /T /F > NUL 2>&1`);
                            }
                            else {
                                process.kill(child.pid);
                            }
                        }
                    }
                    catch {
                        // Ignore.
                    }
                }
                reject(new cancellationUtils_1.OperationCanceledException());
            });
            if (child) {
                child.stdout.on('data', (d) => (stdout = stdout.concat(d)));
                child.stderr.on('data', (d) => (stderr = stderr.concat(d)));
                child.on('error', (e) => {
                    tokenWatch.dispose();
                    reject(e);
                });
                child.on('exit', () => {
                    tokenWatch.dispose();
                    resolve({ stdout, stderr });
                });
            }
            else {
                tokenWatch.dispose();
                reject(new Error(`Cannot start python interpreter with script ${script}`));
            }
        });
    }
    _executePythonInterpreter(pythonPath, execute) {
        if (pythonPath) {
            return execute(pythonPath);
        }
        else {
            let result;
            try {
                // On non-Windows platforms, always default to python3 first. We want to
                // avoid this on Windows because it might invoke a script that displays
                // a dialog box indicating that python can be downloaded from the app store.
                if (process.platform !== 'win32') {
                    result = execute('python3');
                }
            }
            catch {
                // Ignore failure on python3
            }
            if (result !== undefined) {
                return result;
            }
            // On some platforms, 'python3' might not exist. Try 'python' instead.
            return execute('python');
        }
    }
    _getSearchPathResultFromInterpreter(interpreterPath, importFailureInfo) {
        const result = {
            paths: [],
            prefix: undefined,
        };
        try {
            const commandLineArgs = ['-c', extractSys];
            importFailureInfo.push(`Executing interpreter: '${interpreterPath}'`);
            const execOutput = child_process.execFileSync(interpreterPath, commandLineArgs, { encoding: 'utf8' });
            const caseDetector = this.serviceProvider.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
            // Parse the execOutput. It should be a JSON-encoded array of paths.
            try {
                const execSplit = JSON.parse(execOutput);
                for (let execSplitEntry of execSplit.path) {
                    execSplitEntry = execSplitEntry.trim();
                    if (execSplitEntry) {
                        const normalizedPath = (0, pathUtils_1.normalizePath)(execSplitEntry);
                        const normalizedUri = uri_1.Uri.file(normalizedPath, caseDetector);
                        // Skip non-existent paths and broken zips/eggs.
                        if (this.serviceProvider.fs().existsSync(normalizedUri) &&
                            (0, uriUtils_1.isDirectory)(this.serviceProvider.fs(), normalizedUri)) {
                            result.paths.push(normalizedUri);
                        }
                        else {
                            importFailureInfo.push(`Skipping '${normalizedPath}' because it is not a valid directory`);
                        }
                    }
                }
                result.prefix = uri_1.Uri.file(execSplit.prefix, caseDetector);
                if (result.paths.length === 0) {
                    importFailureInfo.push(`Found no valid directories`);
                }
            }
            catch (err) {
                importFailureInfo.push(`Could not parse output: '${execOutput}'`);
                throw err;
            }
        }
        catch {
            return undefined;
        }
        return result;
    }
}
exports.FullAccessHost = FullAccessHost;


/***/ }),

/***/ "../pyright-internal/src/common/host.ts":
/*!**********************************************!*\
  !*** ../pyright-internal/src/common/host.ts ***!
  \**********************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * host.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Provides access to the host environment the language service is running on.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoAccessHost = void 0;
class NoAccessHost {
    get kind() {
        return 2 /* HostKind.NoAccess */;
    }
    getPythonSearchPaths(pythonPath, logInfo) {
        logInfo === null || logInfo === void 0 ? void 0 : logInfo.push('No access to python executable.');
        return {
            paths: [],
            prefix: undefined,
        };
    }
    getPythonVersion(pythonPath, logInfo) {
        return undefined;
    }
    getPythonPlatform(logInfo) {
        return undefined;
    }
    async runScript(pythonPath, scriptPath, args, cwd, token) {
        return { stdout: '', stderr: '' };
    }
}
exports.NoAccessHost = NoAccessHost;


/***/ }),

/***/ "../pyright-internal/src/common/logTracker.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/logTracker.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * logTracker.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * A simple logging class that can be used to track nested loggings.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LogTracker = exports.getPathForLogging = void 0;
const console_1 = __webpack_require__(/*! ./console */ "../pyright-internal/src/common/console.ts");
const timing_1 = __webpack_require__(/*! ./timing */ "../pyright-internal/src/common/timing.ts");
// Consider an operation "long running" if it goes longer than this.
const durationThresholdForInfoInMs = 2000;
function getPathForLogging(fs, fileUri) {
    if (fs.isMappedUri(fileUri)) {
        return fs.getOriginalUri(fileUri);
    }
    return fileUri;
}
exports.getPathForLogging = getPathForLogging;
class LogTracker {
    constructor(_console, prefix) {
        this._console = _console;
        this.prefix = prefix;
        this._dummyState = new State();
        this._previousTitles = [];
        this._indentation = '';
        // Empty
    }
    get logLevel() {
        const level = this._console.level;
        return level !== null && level !== void 0 ? level : console_1.LogLevel.Error;
    }
    log(title, callback, minimalDuration = -1, logParsingPerf = false) {
        // If no console is given, don't do anything.
        if (this._console === undefined) {
            return callback(this._dummyState);
        }
        // This is enabled only when level is LogLevel.Log or does not exist.
        const level = this._console.level;
        if (level === undefined || (level !== console_1.LogLevel.Log && level !== console_1.LogLevel.Info)) {
            return callback(this._dummyState);
        }
        // Since this is only used when LogLevel.Log or LogLevel.Info is set or BG,
        // we don't care much about extra logging cost.
        const current = this._indentation;
        this._previousTitles.push(`${current}${title} ...`);
        this._indentation += '  ';
        const state = new State();
        try {
            return callback(state);
        }
        finally {
            const msDuration = state.duration;
            this._indentation = current;
            // if we already printed our header (by nested calls), then it can't be skipped.
            if (this._previousTitles.length > 0 && (state.isSuppressed() || msDuration <= minimalDuration)) {
                // Get rid of myself so we don't even show header.
                this._previousTitles.pop();
            }
            else {
                this._printPreviousTitles();
                let output = `[${this.prefix}] ${this._indentation}${title}${state.get()} (${msDuration}ms)`;
                // Report parsing related perf info only if they occurred.
                if (logParsingPerf &&
                    state.fileReadTotal +
                        state.tokenizeTotal +
                        state.parsingTotal +
                        state.resolveImportsTotal +
                        state.bindingTotal >
                        0) {
                    output += ` [f:${state.fileReadTotal}, t:${state.tokenizeTotal}, p:${state.parsingTotal}, i:${state.resolveImportsTotal}, b:${state.bindingTotal}]`;
                }
                this._console.log(output);
                // If the operation took really long, log it as "info" so it is more visible.
                if (msDuration >= durationThresholdForInfoInMs) {
                    this._console.info(`[${this.prefix}] Long operation: ${title} (${msDuration}ms)`);
                }
            }
        }
    }
    _printPreviousTitles() {
        // Get rid of myself
        this._previousTitles.pop();
        if (this._previousTitles.length <= 0) {
            return;
        }
        for (const previousTitle of this._previousTitles) {
            this._console.log(`[${this.prefix}] ${previousTitle}`);
        }
        this._previousTitles.length = 0;
    }
}
exports.LogTracker = LogTracker;
class State {
    constructor() {
        this._start = new timing_1.Duration();
        this._startFile = timing_1.timingStats.readFileTime.totalTime;
        this._startToken = timing_1.timingStats.tokenizeFileTime.totalTime;
        this._startParse = timing_1.timingStats.parseFileTime.totalTime;
        this._startImport = timing_1.timingStats.resolveImportsTime.totalTime;
        this._startBind = timing_1.timingStats.bindTime.totalTime;
    }
    get duration() {
        return this._start.getDurationInMilliseconds();
    }
    get fileReadTotal() {
        return timing_1.timingStats.readFileTime.totalTime - this._startFile;
    }
    get tokenizeTotal() {
        return timing_1.timingStats.tokenizeFileTime.totalTime - this._startToken;
    }
    get parsingTotal() {
        return timing_1.timingStats.parseFileTime.totalTime - this._startParse;
    }
    get resolveImportsTotal() {
        return timing_1.timingStats.resolveImportsTime.totalTime - this._startImport;
    }
    get bindingTotal() {
        return timing_1.timingStats.bindTime.totalTime - this._startBind;
    }
    add(addendum) {
        if (addendum) {
            this._addendum = addendum;
        }
    }
    get() {
        if (this._addendum) {
            return ` [${this._addendum}]`;
        }
        return '';
    }
    suppress() {
        this._suppress = true;
    }
    isSuppressed() {
        return !!this._suppress;
    }
}


/***/ }),

/***/ "../pyright-internal/src/common/lspUtils.ts":
/*!**************************************************!*\
  !*** ../pyright-internal/src/common/lspUtils.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * lspUtils.ts
 * Copyright (c) Microsoft Corporation.
 *
 * Helper functions related to the Language Server Protocol (LSP).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSymbolKind = exports.fromLSPAny = exports.toLSPAny = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
// Converts an internal object to LSPAny to be sent out via LSP
function toLSPAny(obj) {
    return obj;
}
exports.toLSPAny = toLSPAny;
// Converts an LSPAny object received via LSP to our internal representation.
function fromLSPAny(lspAny) {
    return lspAny;
}
exports.fromLSPAny = fromLSPAny;
function getSymbolKind(declaration, evaluator, name = '') {
    var _a;
    switch (declaration.type) {
        case 6 /* DeclarationType.Class */:
        case 7 /* DeclarationType.SpecialBuiltInClass */:
            return vscode_languageserver_1.SymbolKind.Class;
        case 5 /* DeclarationType.Function */: {
            if (!declaration.isMethod) {
                return vscode_languageserver_1.SymbolKind.Function;
            }
            const declType = (_a = evaluator === null || evaluator === void 0 ? void 0 : evaluator.getTypeForDeclaration(declaration)) === null || _a === void 0 ? void 0 : _a.type;
            if (declType && (0, typeUtils_1.isMaybeDescriptorInstance)(declType, /* requireSetter */ false)) {
                return vscode_languageserver_1.SymbolKind.Property;
            }
            return vscode_languageserver_1.SymbolKind.Method;
        }
        case 8 /* DeclarationType.Alias */:
            return vscode_languageserver_1.SymbolKind.Module;
        case 2 /* DeclarationType.Parameter */:
            if (name === 'self' || name === 'cls' || name === '_') {
                return undefined;
            }
            return vscode_languageserver_1.SymbolKind.Variable;
        case 3 /* DeclarationType.TypeParameter */:
            return vscode_languageserver_1.SymbolKind.TypeParameter;
        case 1 /* DeclarationType.Variable */:
            if (name === '_') {
                return undefined;
            }
            return declaration.isConstant || declaration.isFinal ? vscode_languageserver_1.SymbolKind.Constant : vscode_languageserver_1.SymbolKind.Variable;
        default:
            return vscode_languageserver_1.SymbolKind.Variable;
    }
}
exports.getSymbolKind = getSymbolKind;


/***/ }),

/***/ "../pyright-internal/src/common/memUtils.ts":
/*!**************************************************!*\
  !*** ../pyright-internal/src/common/memUtils.ts ***!
  \**************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * memUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Platform-independent helper functions for memory.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getHeapStatistics = void 0;
function getHeapStatisticsFunc() {
    try {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const getHeapStatistics = (__webpack_require__(/*! v8 */ "v8").getHeapStatistics);
        if (getHeapStatistics) {
            return getHeapStatistics;
        }
    }
    catch {
        // empty on purpose
    }
    return () => ({
        total_heap_size: 0,
        total_heap_size_executable: 0,
        total_physical_size: 0,
        total_available_size: 0,
        used_heap_size: 0,
        heap_size_limit: 0,
        malloced_memory: 0,
        peak_malloced_memory: 0,
        does_zap_garbage: 0,
        number_of_native_contexts: 0,
        number_of_detached_contexts: 0,
    });
}
exports.getHeapStatistics = getHeapStatisticsFunc();


/***/ }),

/***/ "../pyright-internal/src/common/pathConsts.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/pathConsts.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * pathConsts.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Path-related constants.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.defaultStubsDirectory = exports.stubsSuffix = exports.src = exports.distPackages = exports.sitePackages = exports.lib64 = exports.libAlternate = exports.lib = exports.typeshedFallback = void 0;
exports.typeshedFallback = 'typeshed-fallback';
exports.lib = 'lib';
exports.libAlternate = 'Lib';
exports.lib64 = 'lib64';
exports.sitePackages = 'site-packages';
exports.distPackages = 'dist-packages';
exports.src = 'src';
exports.stubsSuffix = '-stubs';
exports.defaultStubsDirectory = 'typings';


/***/ }),

/***/ "../pyright-internal/src/common/pathUtils.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/common/pathUtils.ts ***!
  \***************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * pathUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Pathname utility functions.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isDiskPathRoot = exports.isRootedDiskPath = exports.getRegexEscapedSeparator = exports.hasPythonExtension = exports.getWildcardRoot = exports.isDirectoryWildcardPatternPresent = exports.getWildcardRegexPattern = exports.normalizePath = exports.stripFileExtension = exports.getShortenedFileName = exports.getFileName = exports.getFileExtension = exports.stripTrailingDirectorySeparator = exports.hasTrailingDirectorySeparator = exports.ensureTrailingDirectorySeparator = exports.getRelativePathComponentsFromDirectory = exports.getRelativePathFromDirectory = exports.getBaseFileName = exports.getAnyExtensionFromPath = exports.changeAnyExtension = exports.containsPath = exports.combinePaths = exports.resolvePaths = exports.normalizeSlashes = exports.getRelativePath = exports.combinePathComponents = exports.reducePathComponents = exports.getPathComponents = exports.getPathSeparator = exports.getRootLength = exports.getDirectoryPath = exports.FileSpec = void 0;
const path = __importStar(__webpack_require__(/*! path */ "path"));
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
const debug = __importStar(__webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts"));
const stringUtils_1 = __webpack_require__(/*! ./stringUtils */ "../pyright-internal/src/common/stringUtils.ts");
const _includeFileRegex = /\.pyi?$/;
var FileSpec;
(function (FileSpec) {
    function is(value) {
        const candidate = value;
        return candidate && !!candidate.wildcardRoot && !!candidate.regExp;
    }
    FileSpec.is = is;
    function isInPath(path, paths) {
        return !!paths.find((p) => p.regExp.test(path));
    }
    FileSpec.isInPath = isInPath;
    function matchesIncludeFileRegex(filePath, isFile = true) {
        return isFile ? _includeFileRegex.test(filePath) : true;
    }
    FileSpec.matchesIncludeFileRegex = matchesIncludeFileRegex;
    function matchIncludeFileSpec(includeRegExp, exclude, filePath, isFile = true) {
        if (includeRegExp.test(filePath)) {
            if (!FileSpec.isInPath(filePath, exclude) && FileSpec.matchesIncludeFileRegex(filePath, isFile)) {
                return true;
            }
        }
        return false;
    }
    FileSpec.matchIncludeFileSpec = matchIncludeFileSpec;
})(FileSpec || (exports.FileSpec = FileSpec = {}));
function getDirectoryPath(pathString) {
    return pathString.substr(0, Math.max(getRootLength(pathString), pathString.lastIndexOf(path.sep)));
}
exports.getDirectoryPath = getDirectoryPath;
/**
 * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/").
 */
function getRootLength(pathString, sep = path.sep) {
    if (pathString.charAt(0) === sep) {
        if (pathString.charAt(1) !== sep) {
            return 1; // POSIX: "/" (or non-normalized "\")
        }
        const p1 = pathString.indexOf(sep, 2);
        if (p1 < 0) {
            return pathString.length; // UNC: "//server" or "\\server"
        }
        return p1 + 1; // UNC: "//server/" or "\\server\"
    }
    if (pathString.charAt(1) === ':') {
        if (pathString.charAt(2) === sep) {
            return 3; // DOS: "c:/" or "c:\"
        }
        if (pathString.length === 2) {
            return 2; // DOS: "c:" (but not "c:d")
        }
    }
    return 0;
}
exports.getRootLength = getRootLength;
function getPathSeparator(pathString) {
    return path.sep;
}
exports.getPathSeparator = getPathSeparator;
function getPathComponents(pathString) {
    const normalizedPath = normalizeSlashes(pathString);
    const rootLength = getRootLength(normalizedPath);
    const root = normalizedPath.substring(0, rootLength);
    const sep = getPathSeparator(pathString);
    const rest = normalizedPath.substring(rootLength).split(sep);
    if (rest.length > 0 && !rest[rest.length - 1]) {
        rest.pop();
    }
    return reducePathComponents([root, ...rest]);
}
exports.getPathComponents = getPathComponents;
function reducePathComponents(components) {
    if (!(0, collectionUtils_1.some)(components)) {
        return [];
    }
    // Reduce the path components by eliminating
    // any '.' or '..'.
    const reduced = [components[0]];
    for (let i = 1; i < components.length; i++) {
        const component = components[i];
        if (!component || component === '.') {
            continue;
        }
        if (component === '..') {
            if (reduced.length > 1) {
                if (reduced[reduced.length - 1] !== '..') {
                    reduced.pop();
                    continue;
                }
            }
            else if (reduced[0]) {
                continue;
            }
        }
        reduced.push(component);
    }
    return reduced;
}
exports.reducePathComponents = reducePathComponents;
function combinePathComponents(components) {
    if (components.length === 0) {
        return '';
    }
    const root = components[0] && ensureTrailingDirectorySeparator(components[0]);
    const sep = getPathSeparator(root);
    return normalizeSlashes(root + components.slice(1).join(sep));
}
exports.combinePathComponents = combinePathComponents;
function getRelativePath(dirPath, relativeTo) {
    if (!dirPath.startsWith(ensureTrailingDirectorySeparator(relativeTo))) {
        return undefined;
    }
    const pathComponents = getPathComponents(dirPath);
    const relativeToComponents = getPathComponents(relativeTo);
    const sep = getPathSeparator(dirPath);
    let relativePath = '.';
    for (let i = relativeToComponents.length; i < pathComponents.length; i++) {
        relativePath += sep + pathComponents[i];
    }
    return relativePath;
}
exports.getRelativePath = getRelativePath;
const getInvalidSeparator = (sep) => (sep === '/' ? '\\' : '/');
function normalizeSlashes(pathString, sep = path.sep) {
    if (pathString.includes(getInvalidSeparator(sep))) {
        const separatorRegExp = /[\\/]/g;
        return pathString.replace(separatorRegExp, sep);
    }
    return pathString;
}
exports.normalizeSlashes = normalizeSlashes;
/**
 * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
 * `.` and `..` path components are resolved. Trailing directory separators are preserved.
 *
 * ```ts
 * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
 * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
 * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
 * ```
 */
function resolvePaths(path, ...paths) {
    return normalizePath((0, collectionUtils_1.some)(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path));
}
exports.resolvePaths = resolvePaths;
function combinePaths(pathString, ...paths) {
    if (pathString) {
        pathString = normalizeSlashes(pathString);
    }
    for (let relativePath of paths) {
        if (!relativePath) {
            continue;
        }
        relativePath = normalizeSlashes(relativePath);
        if (!pathString || getRootLength(relativePath) !== 0) {
            pathString = relativePath;
        }
        else {
            pathString = ensureTrailingDirectorySeparator(pathString) + relativePath;
        }
    }
    return pathString;
}
exports.combinePaths = combinePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
    if (typeof currentDirectory === 'string') {
        parent = combinePaths(currentDirectory, parent);
        child = combinePaths(currentDirectory, child);
    }
    else if (typeof currentDirectory === 'boolean') {
        ignoreCase = currentDirectory;
    }
    if (parent === undefined || child === undefined) {
        return false;
    }
    if (parent === child) {
        return true;
    }
    const parentComponents = getPathComponents(parent);
    const childComponents = getPathComponents(child);
    if (childComponents.length < parentComponents.length) {
        return false;
    }
    const componentEqualityComparer = ignoreCase ? stringUtils_1.equateStringsCaseInsensitive : stringUtils_1.equateStringsCaseSensitive;
    for (let i = 0; i < parentComponents.length; i++) {
        const equalityComparer = i === 0 ? stringUtils_1.equateStringsCaseInsensitive : componentEqualityComparer;
        if (!equalityComparer(parentComponents[i], childComponents[i])) {
            return false;
        }
    }
    return true;
}
exports.containsPath = containsPath;
function changeAnyExtension(path, ext, extensions, ignoreCase) {
    const pathExt = extensions !== undefined && ignoreCase !== undefined
        ? getAnyExtensionFromPath(path, extensions, ignoreCase)
        : getAnyExtensionFromPath(path);
    return pathExt ? path.slice(0, path.length - pathExt.length) + (ext.startsWith('.') ? ext : '.' + ext) : path;
}
exports.changeAnyExtension = changeAnyExtension;
function getAnyExtensionFromPath(path, extensions, ignoreCase) {
    // Retrieves any string from the final "." onwards from a base file name.
    // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
    if (extensions) {
        return getAnyExtensionFromPathWorker(stripTrailingDirectorySeparator(path), extensions, ignoreCase ? stringUtils_1.equateStringsCaseInsensitive : stringUtils_1.equateStringsCaseSensitive);
    }
    const baseFileName = getBaseFileName(path);
    const extensionIndex = baseFileName.lastIndexOf('.');
    if (extensionIndex >= 0) {
        return baseFileName.substring(extensionIndex);
    }
    return '';
}
exports.getAnyExtensionFromPath = getAnyExtensionFromPath;
function getBaseFileName(pathString, extensions, ignoreCase) {
    pathString = normalizeSlashes(pathString);
    // if the path provided is itself the root, then it has not file name.
    const rootLength = getRootLength(pathString);
    if (rootLength === pathString.length) {
        return '';
    }
    // return the trailing portion of the path starting after the last (non-terminal) directory
    // separator but not including any trailing directory separator.
    pathString = stripTrailingDirectorySeparator(pathString);
    const name = pathString.slice(Math.max(getRootLength(pathString), pathString.lastIndexOf(path.sep) + 1));
    const extension = extensions !== undefined && ignoreCase !== undefined
        ? getAnyExtensionFromPath(name, extensions, ignoreCase)
        : undefined;
    return extension ? name.slice(0, name.length - extension.length) : name;
}
exports.getBaseFileName = getBaseFileName;
function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
    const pathComponents = getRelativePathComponentsFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase);
    return combinePathComponents(pathComponents);
}
exports.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathComponentsFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
    debug.assert(getRootLength(fromDirectory) > 0 === getRootLength(to) > 0, 'Paths must either both be absolute or both be relative');
    const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === 'function' ? getCanonicalFileNameOrIgnoreCase : core_1.identity;
    const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === 'boolean' ? getCanonicalFileNameOrIgnoreCase : false;
    const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? stringUtils_1.equateStringsCaseInsensitive : stringUtils_1.equateStringsCaseSensitive, getCanonicalFileName);
    return pathComponents;
}
exports.getRelativePathComponentsFromDirectory = getRelativePathComponentsFromDirectory;
function ensureTrailingDirectorySeparator(pathString) {
    const sep = getPathSeparator(pathString);
    if (!hasTrailingDirectorySeparator(pathString)) {
        return pathString + sep;
    }
    return pathString;
}
exports.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
function hasTrailingDirectorySeparator(pathString) {
    if (pathString.length === 0) {
        return false;
    }
    const ch = pathString.charCodeAt(pathString.length - 1);
    return ch === 47 /* Char.Slash */ || ch === 92 /* Char.Backslash */;
}
exports.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function stripTrailingDirectorySeparator(pathString) {
    if (!hasTrailingDirectorySeparator(pathString)) {
        return pathString;
    }
    return pathString.slice(0, pathString.length - 1);
}
exports.stripTrailingDirectorySeparator = stripTrailingDirectorySeparator;
function getFileExtension(fileName, multiDotExtension = false) {
    if (!multiDotExtension) {
        return path.extname(fileName);
    }
    fileName = getFileName(fileName);
    const firstDotIndex = fileName.indexOf('.');
    return fileName.slice(firstDotIndex);
}
exports.getFileExtension = getFileExtension;
function getFileName(pathString) {
    return path.basename(pathString);
}
exports.getFileName = getFileName;
function getShortenedFileName(pathString, maxDirLength = 15) {
    const fileName = getFileName(pathString);
    const dirName = getDirectoryPath(pathString);
    if (dirName.length > maxDirLength) {
        return `...${dirName.slice(dirName.length - maxDirLength)}${path.sep}${fileName}`;
    }
    return pathString;
}
exports.getShortenedFileName = getShortenedFileName;
function stripFileExtension(fileName, multiDotExtension = false) {
    const ext = getFileExtension(fileName, multiDotExtension);
    return fileName.substr(0, fileName.length - ext.length);
}
exports.stripFileExtension = stripFileExtension;
function normalizePath(pathString) {
    return normalizeSlashes(path.normalize(pathString));
}
exports.normalizePath = normalizePath;
// Transforms a relative file spec (one that potentially contains
// escape characters **, * or ?) and returns a regular expression
// that can be used for matching against.
function getWildcardRegexPattern(rootPath, fileSpec) {
    let absolutePath = normalizePath(combinePaths(rootPath, fileSpec));
    if (!hasPythonExtension(absolutePath)) {
        absolutePath = ensureTrailingDirectorySeparator(absolutePath);
    }
    const pathComponents = getPathComponents(absolutePath);
    const escapedSeparator = getRegexEscapedSeparator(getPathSeparator(rootPath));
    const doubleAsteriskRegexFragment = `(${escapedSeparator}[^${escapedSeparator}][^${escapedSeparator}]*)*?`;
    const reservedCharacterPattern = new RegExp(`[^\\w\\s${escapedSeparator}]`, 'g');
    // Strip the directory separator from the root component.
    if (pathComponents.length > 0) {
        pathComponents[0] = stripTrailingDirectorySeparator(pathComponents[0]);
        if (pathComponents[0].startsWith('\\\\')) {
            pathComponents[0] = '\\\\' + pathComponents[0];
        }
    }
    let regExPattern = '';
    let firstComponent = true;
    for (let component of pathComponents) {
        if (component === '**') {
            regExPattern += doubleAsteriskRegexFragment;
        }
        else {
            if (!firstComponent) {
                component = escapedSeparator + component;
            }
            regExPattern += component.replace(reservedCharacterPattern, (match) => {
                if (match === '*') {
                    return `[^${escapedSeparator}]*`;
                }
                else if (match === '?') {
                    return `[^${escapedSeparator}]`;
                }
                else {
                    // escaping anything that is not reserved characters - word/space/separator
                    return '\\' + match;
                }
            });
            firstComponent = false;
        }
    }
    return regExPattern;
}
exports.getWildcardRegexPattern = getWildcardRegexPattern;
// Determines whether the file spec contains a directory wildcard pattern ("**").
function isDirectoryWildcardPatternPresent(fileSpec) {
    const path = normalizePath(fileSpec);
    const pathComponents = getPathComponents(path);
    for (const component of pathComponents) {
        if (component === '**') {
            return true;
        }
    }
    return false;
}
exports.isDirectoryWildcardPatternPresent = isDirectoryWildcardPatternPresent;
// Returns the topmost path that contains no wildcard characters.
function getWildcardRoot(rootPath, fileSpec) {
    let absolutePath = normalizePath(combinePaths(rootPath, fileSpec));
    if (!hasPythonExtension(absolutePath)) {
        absolutePath = ensureTrailingDirectorySeparator(absolutePath);
    }
    const pathComponents = getPathComponents(absolutePath);
    const sep = getPathSeparator(absolutePath);
    // Strip the directory separator from the root component.
    if (pathComponents.length > 0) {
        pathComponents[0] = stripTrailingDirectorySeparator(pathComponents[0]);
    }
    if (pathComponents.length === 1 && !pathComponents[0]) {
        return sep;
    }
    let wildcardRoot = '';
    let firstComponent = true;
    for (let component of pathComponents) {
        if (component === '**') {
            break;
        }
        else {
            if (component.match(/[*?]/)) {
                break;
            }
            if (!firstComponent) {
                component = sep + component;
            }
            wildcardRoot += component;
            firstComponent = false;
        }
    }
    return wildcardRoot;
}
exports.getWildcardRoot = getWildcardRoot;
function hasPythonExtension(path) {
    return path.endsWith('.py') || path.endsWith('.pyi');
}
exports.hasPythonExtension = hasPythonExtension;
function getRegexEscapedSeparator(pathSep = path.sep) {
    // we don't need to escape "/" in typescript regular expression
    return pathSep === '/' ? '/' : '\\\\';
}
exports.getRegexEscapedSeparator = getRegexEscapedSeparator;
/**
 * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
 * like `c:`, `c:\` or `c:/`).
 */
function isRootedDiskPath(path) {
    return getRootLength(path) > 0;
}
exports.isRootedDiskPath = isRootedDiskPath;
/**
 * Determines whether a path consists only of a path root.
 */
function isDiskPathRoot(path) {
    const rootLength = getRootLength(path);
    return rootLength > 0 && rootLength === path.length;
}
exports.isDiskPathRoot = isDiskPathRoot;
function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
    if (typeof extensions === 'string') {
        return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || '';
    }
    for (const extension of extensions) {
        const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
        if (result) {
            return result;
        }
    }
    return '';
}
function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
    if (!extension.startsWith('.')) {
        extension = '.' + extension;
    }
    if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* Char.Period */) {
        const pathExtension = path.slice(path.length - extension.length);
        if (stringEqualityComparer(pathExtension, extension)) {
            return pathExtension;
        }
    }
    return undefined;
}
function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
    const fromComponents = getPathComponents(from);
    const toComponents = getPathComponents(to);
    let start;
    for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
        const fromComponent = getCanonicalFileName(fromComponents[start]);
        const toComponent = getCanonicalFileName(toComponents[start]);
        const comparer = start === 0 ? stringUtils_1.equateStringsCaseInsensitive : stringEqualityComparer;
        if (!comparer(fromComponent, toComponent)) {
            break;
        }
    }
    if (start === 0) {
        return toComponents;
    }
    const components = toComponents.slice(start);
    const relative = [];
    for (; start < fromComponents.length; start++) {
        relative.push('..');
    }
    return ['', ...relative, ...components];
}


/***/ }),

/***/ "../pyright-internal/src/common/positionUtils.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/common/positionUtils.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * positionUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility routines for converting between file offsets and
 * line/column positions.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getLineEndOffset = exports.getLineEndPosition = exports.convertTextRangeToRange = exports.convertRangeToTextRange = exports.convertPositionToOffset = exports.convertOffsetsToRange = exports.convertOffsetToPosition = void 0;
const debug_1 = __webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts");
const textRange_1 = __webpack_require__(/*! ./textRange */ "../pyright-internal/src/common/textRange.ts");
// Translates a file offset into a line/column pair.
function convertOffsetToPosition(offset, lines) {
    // Handle the case where the file is empty.
    if (lines.end === 0) {
        return {
            line: 0,
            character: 0,
        };
    }
    const itemIndex = offset >= lines.end ? lines.count - 1 : lines.getItemContaining(offset);
    (0, debug_1.assert)(itemIndex >= 0 && itemIndex <= lines.count);
    const lineRange = lines.getItemAt(itemIndex);
    (0, debug_1.assert)(lineRange !== undefined);
    return {
        line: itemIndex,
        character: Math.max(0, Math.min(lineRange.length, offset - lineRange.start)),
    };
}
exports.convertOffsetToPosition = convertOffsetToPosition;
// Translates a start/end file offset into a pair of line/column positions.
function convertOffsetsToRange(startOffset, endOffset, lines) {
    const start = convertOffsetToPosition(startOffset, lines);
    const end = convertOffsetToPosition(endOffset, lines);
    return { start, end };
}
exports.convertOffsetsToRange = convertOffsetsToRange;
// Translates a position (line and col) into a file offset.
function convertPositionToOffset(position, lines) {
    if (position.line >= lines.count) {
        return undefined;
    }
    return lines.getItemAt(position.line).start + position.character;
}
exports.convertPositionToOffset = convertPositionToOffset;
function convertRangeToTextRange(range, lines) {
    const start = convertPositionToOffset(range.start, lines);
    if (start === undefined) {
        return undefined;
    }
    const end = convertPositionToOffset(range.end, lines);
    if (end === undefined) {
        return undefined;
    }
    return textRange_1.TextRange.fromBounds(start, end);
}
exports.convertRangeToTextRange = convertRangeToTextRange;
function convertTextRangeToRange(range, lines) {
    return convertOffsetsToRange(range.start, textRange_1.TextRange.getEnd(range), lines);
}
exports.convertTextRangeToRange = convertTextRangeToRange;
// Returns the position of the last character in a line (before the newline).
function getLineEndPosition(tokenizerOutput, text, line) {
    return convertOffsetToPosition(getLineEndOffset(tokenizerOutput, text, line), tokenizerOutput.lines);
}
exports.getLineEndPosition = getLineEndPosition;
function getLineEndOffset(tokenizerOutput, text, line) {
    const lineRange = tokenizerOutput.lines.getItemAt(line);
    const lineEndOffset = textRange_1.TextRange.getEnd(lineRange);
    let newLineLength = 0;
    for (let i = lineEndOffset - 1; i >= lineRange.start; i--) {
        const char = text[i];
        if (char !== '\r' && char !== '\n') {
            break;
        }
        newLineLength++;
    }
    // Character should be at the end of the line but before the newline.
    return lineEndOffset - newLineLength;
}
exports.getLineEndOffset = getLineEndOffset;


/***/ }),

/***/ "../pyright-internal/src/common/progressReporter.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/common/progressReporter.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * progressReporter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Implements a mechanism for reporting progress in a language server client.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProgressReportTracker = void 0;
class ProgressReportTracker {
    constructor(_reporter) {
        this._reporter = _reporter;
        // Tracks whether we're currently displaying progress.
        this._isDisplayingProgress = false;
    }
    isEnabled(data) {
        var _a;
        if (this._isDisplayingProgress) {
            return true;
        }
        return (_a = this._reporter.isEnabled(data)) !== null && _a !== void 0 ? _a : false;
    }
    begin() {
        if (this._isDisplayingProgress) {
            return;
        }
        this._isDisplayingProgress = true;
        this._reporter.begin();
    }
    report(message) {
        if (!this._isDisplayingProgress) {
            return;
        }
        this._reporter.report(message);
    }
    end() {
        if (!this._isDisplayingProgress) {
            return;
        }
        this._isDisplayingProgress = false;
        this._reporter.end();
    }
}
exports.ProgressReportTracker = ProgressReportTracker;


/***/ }),

/***/ "../pyright-internal/src/common/pythonVersion.ts":
/*!*******************************************************!*\
  !*** ../pyright-internal/src/common/pythonVersion.ts ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * pythonLanguageVersion.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Types and functions that relate to the Python language version.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.latestStablePythonVersion = exports.pythonVersion3_13 = exports.pythonVersion3_12 = exports.pythonVersion3_11 = exports.pythonVersion3_10 = exports.pythonVersion3_9 = exports.pythonVersion3_8 = exports.pythonVersion3_7 = exports.pythonVersion3_6 = exports.pythonVersion3_5 = exports.pythonVersion3_4 = exports.pythonVersion3_3 = exports.pythonVersion3_2 = exports.pythonVersion3_1 = exports.pythonVersion3_0 = exports.PythonVersion = void 0;
class PythonVersion {
    constructor(_major, _minor, _micro, _releaseLevel, _serial) {
        this._major = _major;
        this._minor = _minor;
        this._micro = _micro;
        this._releaseLevel = _releaseLevel;
        this._serial = _serial;
    }
    get major() {
        return this._major;
    }
    get minor() {
        return this._minor;
    }
    get micro() {
        return this._micro;
    }
    get releaseLevel() {
        return this._releaseLevel;
    }
    get serial() {
        return this._serial;
    }
    isEqualTo(other) {
        if (this.major !== other.major || this.minor !== other.minor) {
            return false;
        }
        if (this._micro === undefined || other._micro === undefined) {
            return true;
        }
        else if (this._micro !== other._micro) {
            return false;
        }
        if (this._releaseLevel === undefined || other._releaseLevel === undefined) {
            return true;
        }
        else if (this._releaseLevel !== other._releaseLevel) {
            return false;
        }
        if (this._serial === undefined || other._serial === undefined) {
            return true;
        }
        else if (this._serial !== other._serial) {
            return false;
        }
        return true;
    }
    isGreaterThan(other) {
        if (this.major > other.major) {
            return true;
        }
        else if (this.major < other.major) {
            return false;
        }
        if (this.minor > other.minor) {
            return true;
        }
        else if (this.minor < other.minor) {
            return false;
        }
        if (this._micro === undefined || other._micro === undefined || this._micro < other._micro) {
            return false;
        }
        else if (this._micro > other._micro) {
            return true;
        }
        // We leverage the fact that the alphabetical ordering
        // of the release level designators are ordered by increasing
        // release level.
        if (this._releaseLevel === undefined ||
            other._releaseLevel === undefined ||
            this._releaseLevel < other._releaseLevel) {
            return false;
        }
        else if (this._releaseLevel > other._releaseLevel) {
            return true;
        }
        if (this._serial === undefined || other._serial === undefined || this._serial < other._serial) {
            return false;
        }
        else if (this._serial > other._serial) {
            return true;
        }
        // They are exactly equal!
        return false;
    }
    isGreaterOrEqualTo(other) {
        return this.isEqualTo(other) || this.isGreaterThan(other);
    }
    isLessThan(other) {
        return !this.isGreaterOrEqualTo(other);
    }
    isLessOrEqualTo(other) {
        return !this.isGreaterThan(other);
    }
    toMajorMinorString() {
        return `${this._major}.${this._minor}`;
    }
    toString() {
        let version = this.toMajorMinorString();
        if (this._micro === undefined) {
            return version;
        }
        version += `.${this._micro}`;
        if (this._releaseLevel === undefined) {
            return version;
        }
        version += `.${this._releaseLevel}`;
        if (this._serial === undefined) {
            return version;
        }
        version += `.${this._serial}`;
        return version;
    }
    static fromString(val) {
        const split = val.split('.');
        if (split.length < 2) {
            return undefined;
        }
        const major = parseInt(split[0], 10);
        const minor = parseInt(split[1], 10);
        if (isNaN(major) || isNaN(minor)) {
            return undefined;
        }
        let micro;
        if (split.length >= 3) {
            micro = parseInt(split[2], 10);
            if (isNaN(micro)) {
                micro = undefined;
            }
        }
        let releaseLevel;
        if (split.length >= 4) {
            const releaseLevels = ['alpha', 'beta', 'candidate', 'final'];
            if (releaseLevels.some((level) => level === split[3])) {
                releaseLevel = split[3];
            }
        }
        let serial;
        if (split.length >= 5) {
            serial = parseInt(split[4], 10);
            if (isNaN(serial)) {
                serial = undefined;
            }
        }
        return new PythonVersion(major, minor, micro, releaseLevel, serial);
    }
}
exports.PythonVersion = PythonVersion;
// Predefine some versions.
exports.pythonVersion3_0 = new PythonVersion(3, 0);
exports.pythonVersion3_1 = new PythonVersion(3, 1);
exports.pythonVersion3_2 = new PythonVersion(3, 2);
exports.pythonVersion3_3 = new PythonVersion(3, 3);
exports.pythonVersion3_4 = new PythonVersion(3, 4);
exports.pythonVersion3_5 = new PythonVersion(3, 5);
exports.pythonVersion3_6 = new PythonVersion(3, 6);
exports.pythonVersion3_7 = new PythonVersion(3, 7);
exports.pythonVersion3_8 = new PythonVersion(3, 8);
exports.pythonVersion3_9 = new PythonVersion(3, 9);
exports.pythonVersion3_10 = new PythonVersion(3, 10);
exports.pythonVersion3_11 = new PythonVersion(3, 11);
exports.pythonVersion3_12 = new PythonVersion(3, 12);
exports.pythonVersion3_13 = new PythonVersion(3, 13);
exports.latestStablePythonVersion = exports.pythonVersion3_12;


/***/ }),

/***/ "../pyright-internal/src/common/realFileSystem.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/common/realFileSystem.ts ***!
  \********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * realFileSystem.ts
 *
 * Helper functions that require real filesystem access.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RealTempFile = exports.WorkspaceFileWatcherProvider = exports.createFromRealFileSystem = void 0;
const fslib_1 = __webpack_require__(/*! @yarnpkg/fslib */ "../pyright-internal/node_modules/@yarnpkg/fslib/lib/index.js");
const libzip_1 = __webpack_require__(/*! @yarnpkg/libzip */ "../pyright-internal/node_modules/@yarnpkg/libzip/lib/sync.js");
const fs = __importStar(__webpack_require__(/*! fs */ "fs"));
const tmp = __importStar(__webpack_require__(/*! tmp */ "../pyright-internal/node_modules/tmp/lib/tmp.js"));
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const console_1 = __webpack_require__(/*! ./console */ "../pyright-internal/src/common/console.ts");
const fileWatcher_1 = __webpack_require__(/*! ./fileWatcher */ "../pyright-internal/src/common/fileWatcher.ts");
const pathUtils_1 = __webpack_require__(/*! ./pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const fileUri_1 = __webpack_require__(/*! ./uri/fileUri */ "../pyright-internal/src/common/uri/fileUri.ts");
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const crypto_1 = __webpack_require__(/*! ./crypto */ "../pyright-internal/src/common/crypto.ts");
// Automatically remove files created by tmp at process exit.
tmp.setGracefulCleanup();
// Callers can specify a different file watcher provider if desired.
// By default, we'll use the file watcher based on chokidar.
function createFromRealFileSystem(caseSensitiveDetector, console, fileWatcherProvider) {
    return new RealFileSystem(caseSensitiveDetector, console !== null && console !== void 0 ? console : new console_1.NullConsole(), fileWatcherProvider !== null && fileWatcherProvider !== void 0 ? fileWatcherProvider : fileWatcher_1.nullFileWatcherProvider);
}
exports.createFromRealFileSystem = createFromRealFileSystem;
const DOT_ZIP = `.zip`;
const DOT_EGG = `.egg`;
const DOT_JAR = `.jar`;
// Exactly the same as ZipOpenFS's getArchivePart, but supporting .egg files.
// https://github.com/yarnpkg/berry/blob/64a16b3603ef2ccb741d3c44f109c9cfc14ba8dd/packages/yarnpkg-fslib/sources/ZipOpenFS.ts#L23
function getArchivePart(path) {
    let idx = path.indexOf(DOT_ZIP);
    if (idx <= 0) {
        idx = path.indexOf(DOT_EGG);
        if (idx <= 0) {
            idx = path.indexOf(DOT_JAR);
            if (idx <= 0) {
                return null;
            }
        }
    }
    // Disallow files named ".zip"
    if (path[idx - 1] === fslib_1.ppath.sep)
        return null;
    const nextCharIdx = idx + DOT_ZIP.length; // DOT_ZIP and DOT_EGG are the same length.
    // The path either has to end in ".zip" or contain an archive subpath (".zip/...")
    if (path.length > nextCharIdx && path[nextCharIdx] !== fslib_1.ppath.sep)
        return null;
    return path.slice(0, nextCharIdx);
}
function hasZipExtension(p) {
    return p.endsWith(DOT_ZIP) || p.endsWith(DOT_EGG) || p.endsWith(DOT_JAR);
}
// "Magic" values for the zip file type. https://en.wikipedia.org/wiki/List_of_file_signatures
const zipMagic = [
    Buffer.from([0x50, 0x4b, 0x03, 0x04]),
    Buffer.from([0x50, 0x4b, 0x05, 0x06]),
    Buffer.from([0x50, 0x4b, 0x07, 0x08]),
];
function hasZipMagic(fs, p) {
    let fd;
    try {
        fd = fs.openSync(p, 'r');
        const buffer = Buffer.alloc(4);
        const bytesRead = fs.readSync(fd, buffer, 0, 4, 0);
        if (bytesRead < 4) {
            return false;
        }
        for (const magic of zipMagic) {
            if (buffer.compare(magic) === 0) {
                return true;
            }
        }
        return false;
    }
    catch {
        return false;
    }
    finally {
        if (fd !== undefined) {
            fs.closeSync(fd);
        }
    }
}
/* eslint-disable @typescript-eslint/naming-convention */
// Patch fslib's ZipOpenFS to also consider .egg files to be .zip files.
//
// For now, override findZip (even though it's private), with the intent
// to upstream a change to allow overriding getArchivePart or add some
// other mechanism to support more extensions as zips (or, to remove this
// hack in favor of a full ZipOpenFS fork).
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-expect-error
class EggZipOpenFS extends fslib_1.ZipOpenFS {
    findZip(p) {
        if (this.filter && !this.filter.test(p))
            return null;
        let filePath = ``;
        while (true) {
            const archivePart = getArchivePart(p.substr(filePath.length));
            if (!archivePart)
                return null;
            filePath = this.pathUtils.join(filePath, archivePart);
            if (this.isZip.has(filePath) === false) {
                if (this.notZip.has(filePath))
                    continue;
                try {
                    if (!this.baseFs.lstatSync(filePath).isFile()) {
                        this.notZip.add(filePath);
                        continue;
                    }
                    if (!hasZipMagic(this.baseFs, filePath)) {
                        this.notZip.add(filePath);
                        continue;
                    }
                    try {
                        // We're pretty sure that it's a zip at this point (it has the magic), but
                        // try accessing the zipfile anyway; if it's corrupt in some way, this will throw.
                        // We don't need to do anything with the ZipFS instance given to the callback
                        // below; ZipOpenFS already manages their lifetimes and we're very likely to
                        // immediately call back into the FS to obtain info from the zip anyway.
                        // eslint-disable-next-line @typescript-eslint/no-empty-function
                        this.getZipSync(filePath, () => { });
                    }
                    catch {
                        this.notZip.add(filePath);
                        continue;
                    }
                }
                catch {
                    return null;
                }
                this.isZip.add(filePath);
            }
            return {
                archivePath: filePath,
                subPath: this.pathUtils.join(fslib_1.PortablePath.root, p.substr(filePath.length)),
            };
        }
    }
    // Hack to provide typed access to this private method.
    getZipSync(p, accept) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        //@ts-expect-error
        return super.getZipSync(p, accept);
    }
}
/* eslint-enable @typescript-eslint/naming-convention */
class YarnFS extends fslib_1.PosixFS {
    constructor() {
        const eggZipOpenFS = new EggZipOpenFS({
            libzip: () => (0, libzip_1.getLibzipSync)(),
            useCache: true,
            maxOpenFiles: 80,
            readOnlyArchives: true,
        });
        super(new fslib_1.VirtualFS({
            baseFs: eggZipOpenFS,
        }));
        this._eggZipOpenFS = eggZipOpenFS;
    }
    isZip(p) {
        return !!this._eggZipOpenFS.findZip(this.mapToBase(p));
    }
}
const yarnFS = new YarnFS();
class RealFileSystem {
    constructor(_caseSensitiveDectector, _console, _fileWatcherProvider) {
        this._caseSensitiveDectector = _caseSensitiveDectector;
        this._console = _console;
        this._fileWatcherProvider = _fileWatcherProvider;
        // Empty
    }
    existsSync(uri) {
        if (uri.isEmpty() || !fileUri_1.FileUri.isFileUri(uri)) {
            return false;
        }
        const path = uri.getFilePath();
        try {
            // Catch zip open errors. existsSync is assumed to never throw by callers.
            return yarnFS.existsSync(path);
        }
        catch {
            return false;
        }
    }
    mkdirSync(uri, options) {
        const path = uri.getFilePath();
        yarnFS.mkdirSync(path, options);
    }
    chdir(uri) {
        const path = uri.getFilePath();
        // If this file system happens to be running in a worker thread,
        // then we can't call 'chdir'.
        if (worker_threads_1.isMainThread) {
            process.chdir(path);
        }
    }
    readdirSync(uri) {
        const path = uri.getFilePath();
        return yarnFS.readdirSync(path);
    }
    readdirEntriesSync(uri) {
        const path = uri.getFilePath();
        return yarnFS.readdirSync(path, { withFileTypes: true }).map((entry) => {
            // Treat zip/egg files as directories.
            // See: https://github.com/yarnpkg/berry/blob/master/packages/vscode-zipfs/sources/ZipFSProvider.ts
            if (hasZipExtension(entry.name)) {
                if (entry.isFile() && yarnFS.isZip(path)) {
                    return {
                        name: entry.name,
                        isFile: () => false,
                        isDirectory: () => true,
                        isBlockDevice: () => false,
                        isCharacterDevice: () => false,
                        isSymbolicLink: () => false,
                        isFIFO: () => false,
                        isSocket: () => false,
                    };
                }
            }
            return entry;
        });
    }
    readFileSync(uri, encoding = null) {
        const path = uri.getFilePath();
        if (encoding === 'utf8' || encoding === 'utf-8') {
            return yarnFS.readFileSync(path, 'utf8');
        }
        return yarnFS.readFileSync(path);
    }
    writeFileSync(uri, data, encoding) {
        const path = uri.getFilePath();
        yarnFS.writeFileSync(path, data, encoding || undefined);
    }
    statSync(uri) {
        if (fileUri_1.FileUri.isFileUri(uri)) {
            const path = uri.getFilePath();
            const stat = yarnFS.statSync(path);
            // Treat zip/egg files as directories.
            // See: https://github.com/yarnpkg/berry/blob/master/packages/vscode-zipfs/sources/ZipFSProvider.ts
            if (hasZipExtension(path)) {
                if (stat.isFile() && yarnFS.isZip(path)) {
                    stat.isFile = () => false;
                    stat.isDirectory = () => true;
                    stat.isZipDirectory = () => true;
                    return stat;
                }
            }
            return stat;
        }
        else {
            return {
                isFile: () => false,
                isDirectory: () => false,
                isBlockDevice: () => false,
                isCharacterDevice: () => false,
                isSymbolicLink: () => false,
                isFIFO: () => false,
                isSocket: () => false,
                dev: 0,
                atimeMs: 0,
                mtimeMs: 0,
                ctimeMs: 0,
                birthtimeMs: 0,
                size: 0,
                blksize: 0,
                blocks: 0,
                ino: 0,
                mode: 0,
                nlink: 0,
                uid: 0,
                gid: 0,
                rdev: 0,
                atime: new Date(),
                mtime: new Date(),
                ctime: new Date(),
                birthtime: new Date(),
            };
        }
    }
    rmdirSync(uri) {
        const path = uri.getFilePath();
        yarnFS.rmdirSync(path);
    }
    unlinkSync(uri) {
        const path = uri.getFilePath();
        yarnFS.unlinkSync(path);
    }
    realpathSync(uri) {
        try {
            const path = uri.getFilePath();
            return uri_1.Uri.file(yarnFS.realpathSync(path), this._caseSensitiveDectector);
        }
        catch (e) {
            return uri;
        }
    }
    getModulePath() {
        // The entry point to the tool should have set the __rootDirectory
        // global variable to point to the directory that contains the
        // typeshed-fallback directory.
        return (0, uriUtils_1.getRootUri)(this._caseSensitiveDectector) || uri_1.Uri.empty();
    }
    createFileSystemWatcher(paths, listener) {
        return this._fileWatcherProvider.createFileWatcher(paths.map((p) => p.getFilePath()), listener);
    }
    createReadStream(uri) {
        const path = uri.getFilePath();
        return yarnFS.createReadStream(path);
    }
    createWriteStream(uri) {
        const path = uri.getFilePath();
        return yarnFS.createWriteStream(path);
    }
    copyFileSync(src, dst) {
        const srcPath = src.getFilePath();
        const destPath = dst.getFilePath();
        yarnFS.copyFileSync(srcPath, destPath);
    }
    readFile(uri) {
        const path = uri.getFilePath();
        return yarnFS.readFilePromise(path);
    }
    async readFileText(uri, encoding) {
        const path = uri.getFilePath();
        if (encoding === 'utf8' || encoding === 'utf-8') {
            return yarnFS.readFilePromise(path, 'utf8');
        }
        const buffer = await yarnFS.readFilePromise(path);
        return buffer.toString(encoding);
    }
    realCasePath(uri) {
        try {
            // If it doesn't exist in the real FS, then just use this path.
            if (!this.existsSync(uri)) {
                return uri;
            }
            // realpathSync.native will return casing as in OS rather than
            // trying to preserve casing given.
            const realCase = fs.realpathSync.native(uri.getFilePath());
            // If the original and real case paths differ by anything other than case,
            // then there's a symbolic link or something of that sort involved. Return
            // the original path instead.
            if (uri.getFilePath().toLowerCase() !== realCase.toLowerCase()) {
                return uri;
            }
            // On UNC mapped drives we want to keep the original drive letter.
            if ((0, pathUtils_1.getRootLength)(realCase) !== (0, pathUtils_1.getRootLength)(uri.getFilePath())) {
                return uri;
            }
            return uri_1.Uri.file(realCase, this._caseSensitiveDectector);
        }
        catch (e) {
            // Return as it is, if anything failed.
            this._console.log(`Failed to get real file system casing for ${uri}: ${e}`);
            return uri;
        }
    }
    isMappedUri(uri) {
        return false;
    }
    getOriginalUri(mappedUri) {
        return mappedUri;
    }
    getMappedUri(originalUri) {
        return originalUri;
    }
    isInZip(uri) {
        const path = uri.getFilePath();
        return /[^\\/]\.(?:egg|zip|jar)[\\/]/.test(path) && yarnFS.isZip(path);
    }
}
class WorkspaceFileWatcherProvider {
    constructor() {
        this._fileWatchers = [];
    }
    createFileWatcher(workspacePaths, listener) {
        const self = this;
        const fileWatcher = {
            close() {
                // Stop listening for workspace paths.
                self._fileWatchers = self._fileWatchers.filter((watcher) => watcher !== fileWatcher);
            },
            workspacePaths,
            eventHandler: listener,
        };
        // Record the file watcher.
        self._fileWatchers.push(fileWatcher);
        return fileWatcher;
    }
    onFileChange(eventType, fileUri) {
        // Since file watcher is a server wide service, we don't know which watcher is
        // for which workspace (for multi workspace case), also, we don't know which watcher
        // is for source or library. so we need to solely rely on paths that can cause us
        // to raise events both for source and library if .venv is inside of workspace root
        // for a file change. It is event handler's job to filter those out.
        this._fileWatchers.forEach((watcher) => {
            if (watcher.workspacePaths.some((dirPath) => fileUri.getFilePath().startsWith(dirPath))) {
                watcher.eventHandler(eventType, fileUri.getFilePath());
            }
        });
    }
}
exports.WorkspaceFileWatcherProvider = WorkspaceFileWatcherProvider;
class RealTempFile {
    constructor() {
        // Empty
    }
    tmpdir() {
        return uri_1.Uri.file(this._getTmpDir().name, this);
    }
    tmpfile(options) {
        const f = tmp.fileSync({ dir: this._getTmpDir().name, discardDescriptor: true, ...options });
        return uri_1.Uri.file(f.name, this);
    }
    dispose() {
        var _a;
        try {
            (_a = this._tmpdir) === null || _a === void 0 ? void 0 : _a.removeCallback();
            this._tmpdir = undefined;
        }
        catch {
            // ignore
        }
    }
    isCaseSensitive(uri) {
        if (uri.startsWith(fileUri_1.FileUriSchema)) {
            return this._isLocalFileSystemCaseSensitive();
        }
        return true;
    }
    _isLocalFileSystemCaseSensitive() {
        if (this._caseSensitivity === undefined) {
            this._caseSensitivity = this._isFileSystemCaseSensitiveInternal();
        }
        return this._caseSensitivity;
    }
    _getTmpDir() {
        if (!this._tmpdir) {
            this._tmpdir = tmp.dirSync({ prefix: 'pyright' });
        }
        return this._tmpdir;
    }
    _isFileSystemCaseSensitiveInternal() {
        let filePath = undefined;
        try {
            // Make unique file name.
            let name;
            let mangledFilePath;
            do {
                name = `${(0, crypto_1.randomBytesHex)(21)}-a`;
                filePath = (0, pathUtils_1.combinePaths)(this._getTmpDir().name, name);
                mangledFilePath = (0, pathUtils_1.combinePaths)(this._getTmpDir().name, name.toUpperCase());
            } while (fs.existsSync(filePath) || fs.existsSync(mangledFilePath));
            fs.writeFileSync(filePath, '', 'utf8');
            // If file exists, then it is insensitive.
            return !fs.existsSync(mangledFilePath);
        }
        catch (e) {
            return false;
        }
        finally {
            if (filePath) {
                // remove temp file created
                try {
                    fs.unlinkSync(filePath);
                }
                catch (e) {
                    /* ignored */
                }
            }
        }
    }
}
exports.RealTempFile = RealTempFile;


/***/ }),

/***/ "../pyright-internal/src/common/serviceKeys.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/serviceKeys.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * serviceKeys.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Define service keys.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ServiceKeys = void 0;
const serviceProvider_1 = __webpack_require__(/*! ./serviceProvider */ "../pyright-internal/src/common/serviceProvider.ts");
var ServiceKeys;
(function (ServiceKeys) {
    ServiceKeys.fs = new serviceProvider_1.ServiceKey();
    ServiceKeys.console = new serviceProvider_1.ServiceKey();
    ServiceKeys.sourceFileFactory = new serviceProvider_1.ServiceKey();
    ServiceKeys.partialStubs = new serviceProvider_1.ServiceKey();
    ServiceKeys.symbolDefinitionProvider = new serviceProvider_1.GroupServiceKey();
    ServiceKeys.symbolUsageProviderFactory = new serviceProvider_1.GroupServiceKey();
    ServiceKeys.stateMutationListeners = new serviceProvider_1.GroupServiceKey();
    ServiceKeys.tempFile = new serviceProvider_1.ServiceKey();
    ServiceKeys.cacheManager = new serviceProvider_1.ServiceKey();
    ServiceKeys.debugInfoInspector = new serviceProvider_1.ServiceKey();
    ServiceKeys.caseSensitivityDetector = new serviceProvider_1.ServiceKey();
})(ServiceKeys || (exports.ServiceKeys = ServiceKeys = {}));


/***/ }),

/***/ "../pyright-internal/src/common/serviceProvider.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/common/serviceProvider.ts ***!
  \*********************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * serviceProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Container for different services used within the application.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ServiceProvider = exports.GroupServiceKey = exports.ServiceKey = void 0;
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug = __importStar(__webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts"));
class InternalKey {
}
/**
 * Key for singleton service T.
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class ServiceKey extends InternalKey {
    constructor() {
        super(...arguments);
        this.kind = 'singleton';
    }
}
exports.ServiceKey = ServiceKey;
/**
 * Key for group of service T.
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class GroupServiceKey extends InternalKey {
    constructor() {
        super(...arguments);
        this.kind = 'group';
    }
}
exports.GroupServiceKey = GroupServiceKey;
class ServiceProvider {
    constructor() {
        this._container = new Map();
    }
    add(key, value) {
        if (key.kind === 'group') {
            this._addGroupService(key, value);
            return;
        }
        if (key.kind === 'singleton') {
            if (value !== undefined) {
                this._container.set(key, value);
            }
            else {
                this.remove(key);
            }
            return;
        }
        debug.assertNever(key, `Unknown key type ${typeof key}`);
    }
    remove(key, value) {
        if (key.kind === 'group') {
            this._removeGroupService(key, value);
            return;
        }
        if (key.kind === 'singleton') {
            this._container.delete(key);
            return;
        }
        debug.assertNever(key, `Unknown key type ${typeof key}`);
    }
    tryGet(key) {
        return this._container.get(key);
    }
    get(key) {
        const value = key.kind === 'group' ? this.tryGet(key) : this.tryGet(key);
        if (value === undefined) {
            throw new Error(`Global service provider not initialized for ${key.toString()}`);
        }
        return value;
    }
    clone() {
        const serviceProvider = new ServiceProvider();
        this._container.forEach((value, key) => {
            if (key.kind === 'group') {
                serviceProvider._container.set(key, [...(value !== null && value !== void 0 ? value : [])]);
            }
            else {
                serviceProvider._container.set(key, value);
            }
        });
        return serviceProvider;
    }
    _addGroupService(key, newValue) {
        // Explicitly cast to remove `readonly`
        const services = this.tryGet(key);
        if (services === undefined) {
            this._container.set(key, [newValue]);
            return;
        }
        if (newValue !== undefined) {
            (0, collectionUtils_1.addIfUnique)(services, newValue);
        }
    }
    _removeGroupService(key, oldValue) {
        const services = this.tryGet(key);
        if (services === undefined) {
            return;
        }
        (0, collectionUtils_1.removeArrayElements)(services, (s) => s === oldValue);
    }
}
exports.ServiceProvider = ServiceProvider;


/***/ }),

/***/ "../pyright-internal/src/common/serviceProviderExtensions.ts":
/*!*******************************************************************!*\
  !*** ../pyright-internal/src/common/serviceProviderExtensions.ts ***!
  \*******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createServiceProvider = void 0;
/*
 * serviceProviderExtensions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Shortcuts to common services.
 */
const cacheManager_1 = __webpack_require__(/*! ../analyzer/cacheManager */ "../pyright-internal/src/analyzer/cacheManager.ts");
const programTypes_1 = __webpack_require__(/*! ../analyzer/programTypes */ "../pyright-internal/src/analyzer/programTypes.ts");
const sourceFile_1 = __webpack_require__(/*! ../analyzer/sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const pyrightFileSystem_1 = __webpack_require__(/*! ../pyrightFileSystem */ "../pyright-internal/src/pyrightFileSystem.ts");
const serviceKeys_1 = __webpack_require__(/*! ./serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const caseSensitivityDetector_1 = __webpack_require__(/*! ./caseSensitivityDetector */ "../pyright-internal/src/common/caseSensitivityDetector.ts");
const console_1 = __webpack_require__(/*! ./console */ "../pyright-internal/src/common/console.ts");
const fileSystem_1 = __webpack_require__(/*! ./fileSystem */ "../pyright-internal/src/common/fileSystem.ts");
const serviceProvider_1 = __webpack_require__(/*! ./serviceProvider */ "../pyright-internal/src/common/serviceProvider.ts");
function createServiceProvider(...services) {
    const sp = new serviceProvider_1.ServiceProvider();
    // For known interfaces, register the service.
    services.forEach((service) => {
        if (fileSystem_1.FileSystem.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.fs, service);
        }
        if (console_1.ConsoleInterface.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.console, service);
        }
        if (programTypes_1.ISourceFileFactory.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.sourceFileFactory, service);
        }
        if (pyrightFileSystem_1.SupportPartialStubs.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.partialStubs, service);
        }
        if (fileSystem_1.TempFile.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.tempFile, service);
        }
        if (caseSensitivityDetector_1.CaseSensitivityDetector.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.caseSensitivityDetector, service);
        }
        if (cacheManager_1.CacheManager.is(service)) {
            sp.add(serviceKeys_1.ServiceKeys.cacheManager, service);
        }
    });
    return sp;
}
exports.createServiceProvider = createServiceProvider;
serviceProvider_1.ServiceProvider.prototype.fs = function () {
    return this.get(serviceKeys_1.ServiceKeys.fs);
};
serviceProvider_1.ServiceProvider.prototype.console = function () {
    return this.get(serviceKeys_1.ServiceKeys.console);
};
serviceProvider_1.ServiceProvider.prototype.partialStubs = function () {
    return this.get(serviceKeys_1.ServiceKeys.partialStubs);
};
serviceProvider_1.ServiceProvider.prototype.tmp = function () {
    return this.tryGet(serviceKeys_1.ServiceKeys.tempFile);
};
serviceProvider_1.ServiceProvider.prototype.sourceFileFactory = function () {
    const result = this.tryGet(serviceKeys_1.ServiceKeys.sourceFileFactory);
    return result || DefaultSourceFileFactory;
};
serviceProvider_1.ServiceProvider.prototype.cacheManager = function () {
    const result = this.tryGet(serviceKeys_1.ServiceKeys.cacheManager);
    return result;
};
const DefaultSourceFileFactory = {
    createSourceFile(serviceProvider, fileUri, moduleName, isThirdPartyImport, isThirdPartyPyTypedPresent, editMode, console, logTracker, ipythonMode) {
        return new sourceFile_1.SourceFile(serviceProvider, fileUri, moduleName, isThirdPartyImport, isThirdPartyPyTypedPresent, editMode, console, logTracker, ipythonMode);
    },
};


/***/ }),

/***/ "../pyright-internal/src/common/stringUtils.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/stringUtils.ts ***!
  \*****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * stringUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Utility methods for manipulating and comparing strings.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.userFacingOptionsList = exports.truncate = exports.getLastDottedString = exports.getCharacterCount = exports.equateStringsCaseSensitive = exports.equateStringsCaseInsensitive = exports.getStringComparer = exports.compareStringsCaseSensitive = exports.compareStringsCaseInsensitive = exports.hashString = exports.isPatternInSymbol = exports.computeCompletionSimilarity = void 0;
const leven_1 = __importDefault(__webpack_require__(/*! leven */ "../pyright-internal/node_modules/leven/index.js"));
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
// Determines how closely a typed string matches a symbol
// name. An exact match returns 1. A match that differs
// only in case returns a slightly lower number. A match
// that involves a few missing or added characters returns
// an even lower number.
function computeCompletionSimilarity(typedValue, symbolName) {
    if (symbolName.startsWith(typedValue)) {
        return 1;
    }
    const symbolLower = symbolName.toLocaleLowerCase();
    const typedLower = typedValue.toLocaleLowerCase();
    if (symbolLower.startsWith(typedLower)) {
        return 0.75;
    }
    // How far apart are the two strings? Find the smallest edit
    // distance for each of the substrings taken from the start of
    // symbolName.
    let symbolSubstrLength = symbolLower.length;
    let smallestEditDistance = Number.MAX_VALUE;
    while (symbolSubstrLength > 0) {
        const editDistance = (0, leven_1.default)(symbolLower.substr(0, symbolSubstrLength), typedLower);
        if (editDistance < smallestEditDistance) {
            smallestEditDistance = editDistance;
        }
        symbolSubstrLength--;
    }
    // We'll take into account the length of the typed value. If the user
    // has typed more characters, and they largely match the symbol name,
    // it is considered more similar. If the the edit distance is similar
    // to the number of characters the user has typed, then there's almost
    // no similarity.
    if (smallestEditDistance >= typedValue.length) {
        return 0;
    }
    const similarity = (typedValue.length - smallestEditDistance) / typedValue.length;
    return 0.5 * similarity;
}
exports.computeCompletionSimilarity = computeCompletionSimilarity;
// Determines if typed string matches a symbol
// name. Characters must appear in order.
// Return true if all typed characters are in symbol
function isPatternInSymbol(typedValue, symbolName) {
    const typedLower = typedValue.toLocaleLowerCase();
    const symbolLower = symbolName.toLocaleLowerCase();
    const typedLength = typedLower.length;
    const symbolLength = symbolLower.length;
    let typedPos = 0;
    let symbolPos = 0;
    while (typedPos < typedLength && symbolPos < symbolLength) {
        if (typedLower[typedPos] === symbolLower[symbolPos]) {
            typedPos += 1;
        }
        symbolPos += 1;
    }
    return typedPos === typedLength;
}
exports.isPatternInSymbol = isPatternInSymbol;
// This is a simple, non-cryptographic hash function for text.
function hashString(contents) {
    let hash = 0;
    for (let i = 0; i < contents.length; i++) {
        hash = ((hash << 5) - hash + contents.charCodeAt(i)) | 0;
    }
    return hash;
}
exports.hashString = hashString;
/**
 * Compare two strings using a case-insensitive ordinal comparison.
 *
 * Ordinal comparisons are based on the difference between the unicode code points of both
 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
 * comparisons provide predictable ordering, but place "a" after "B".
 *
 * Case-insensitive comparisons compare both strings one code-point at a time using the integer
 * value of each code-point after applying `toUpperCase` to each string. We always map both
 * strings to their upper-case form as some unicode characters do not properly round-trip to
 * lowercase (such as `áºž` (German sharp capital s)).
 */
function compareStringsCaseInsensitive(a, b) {
    return a === b
        ? 0 /* Comparison.EqualTo */
        : a === undefined
            ? -1 /* Comparison.LessThan */
            : b === undefined
                ? 1 /* Comparison.GreaterThan */
                : (0, core_1.compareComparableValues)(a.toUpperCase(), b.toUpperCase());
}
exports.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
/**
 * Compare two strings using a case-sensitive ordinal comparison.
 *
 * Ordinal comparisons are based on the difference between the unicode code points of both
 * strings. Characters with multiple unicode representations are considered unequal. Ordinal
 * comparisons provide predictable ordering, but place "a" after "B".
 *
 * Case-sensitive comparisons compare both strings one code-point at a time using the integer
 * value of each code-point.
 */
function compareStringsCaseSensitive(a, b) {
    return (0, core_1.compareComparableValues)(a, b);
}
exports.compareStringsCaseSensitive = compareStringsCaseSensitive;
function getStringComparer(ignoreCase) {
    return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
}
exports.getStringComparer = getStringComparer;
/**
 * Compare the equality of two strings using a case-insensitive ordinal comparison.
 *
 * Case-insensitive comparisons compare both strings one code-point at a time using the integer
 * value of each code-point after applying `toUpperCase` to each string. We always map both
 * strings to their upper-case form as some unicode characters do not properly round-trip to
 * lowercase (such as `ẞ` (German sharp capital s)).
 */
function equateStringsCaseInsensitive(a, b) {
    return compareStringsCaseInsensitive(a, b) === 0 /* Comparison.EqualTo */;
}
exports.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
/**
 * Compare the equality of two strings using a case-sensitive ordinal comparison.
 *
 * Case-sensitive comparisons compare both strings one code-point at a time using the
 * integer value of each code-point.
 */
function equateStringsCaseSensitive(a, b) {
    return compareStringsCaseSensitive(a, b) === 0 /* Comparison.EqualTo */;
}
exports.equateStringsCaseSensitive = equateStringsCaseSensitive;
function getCharacterCount(value, ch) {
    let result = 0;
    for (let i = 0; i < value.length; i++) {
        if (value[i] === ch) {
            result++;
        }
    }
    return result;
}
exports.getCharacterCount = getCharacterCount;
function getLastDottedString(text) {
    const index = text.lastIndexOf('.');
    return index > 0 ? text.substring(index + 1) : text;
}
exports.getLastDottedString = getLastDottedString;
function truncate(text, maxLength) {
    if (text.length > maxLength) {
        return text.substring(0, maxLength - '...'.length) + '...';
    }
    return text;
}
exports.truncate = truncate;
/** turns an array into a list of options to be presented to the user
 * @example
 * userFacingOptionsList(['a', 'b', 'c']) // `"a", "b" or "c"`
 */
const userFacingOptionsList = (values) => values.map((mode, index) => (index < values.length - 1 ? `"${mode}", ` : `or "${mode}"`)).join('');
exports.userFacingOptionsList = userFacingOptionsList;


/***/ }),

/***/ "../pyright-internal/src/common/textRange.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/common/textRange.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * textRange.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Specifies the range of text within a larger string.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.combineRange = exports.extendRange = exports.isEmptyRange = exports.isEmptyPosition = exports.getEmptyRange = exports.rangesAreEqual = exports.positionsAreEqual = exports.doesRangeContain = exports.doRangesIntersect = exports.doRangesOverlap = exports.getEmptyPosition = exports.comparePositions = exports.Range = exports.Position = exports.TextRange = void 0;
var TextRange;
(function (TextRange) {
    function create(start, length) {
        if (start < 0) {
            throw new Error('start must be non-negative');
        }
        if (length < 0) {
            throw new Error('length must be non-negative');
        }
        return { start, length };
    }
    TextRange.create = create;
    function fromBounds(start, end) {
        if (start < 0) {
            throw new Error('start must be non-negative');
        }
        if (start > end) {
            throw new Error('end must be greater than or equal to start');
        }
        return create(start, end - start);
    }
    TextRange.fromBounds = fromBounds;
    function getEnd(range) {
        return range.start + range.length;
    }
    TextRange.getEnd = getEnd;
    function contains(range, position) {
        return position >= range.start && position < getEnd(range);
    }
    TextRange.contains = contains;
    function containsRange(range, span) {
        return span.start >= range.start && getEnd(span) <= getEnd(range);
    }
    TextRange.containsRange = containsRange;
    function overlaps(range, position) {
        return position >= range.start && position <= getEnd(range);
    }
    TextRange.overlaps = overlaps;
    function overlapsRange(range, other) {
        return overlaps(range, other.start) || overlaps(other, range.start);
    }
    TextRange.overlapsRange = overlapsRange;
    function extend(range, extension) {
        let result = range;
        if (extension) {
            if (Array.isArray(extension)) {
                extension.forEach((r) => {
                    result = extend(result, r);
                });
            }
            else {
                if (extension.start < result.start) {
                    result = {
                        start: extension.start,
                        length: result.length + result.start - extension.start,
                    };
                }
                const extensionEnd = getEnd(extension);
                const resultEnd = getEnd(result);
                if (extensionEnd > resultEnd) {
                    result = {
                        start: result.start,
                        length: result.length + extensionEnd - resultEnd,
                    };
                }
            }
        }
        return result;
    }
    TextRange.extend = extend;
    function combine(ranges) {
        if (ranges.length === 0) {
            return undefined;
        }
        let combinedRange = { start: ranges[0].start, length: ranges[0].length };
        for (let i = 1; i < ranges.length; i++) {
            combinedRange = extend(combinedRange, ranges[i]);
        }
        return combinedRange;
    }
    TextRange.combine = combine;
})(TextRange || (exports.TextRange = TextRange = {}));
var Position;
(function (Position) {
    function is(value) {
        const candidate = value;
        return candidate && candidate.line !== void 0 && candidate.character !== void 0;
    }
    Position.is = is;
    function print(value) {
        return `(${value.line}:${value.character})`;
    }
    Position.print = print;
})(Position || (exports.Position = Position = {}));
var Range;
(function (Range) {
    function is(value) {
        const candidate = value;
        return candidate && candidate.start !== void 0 && candidate.end !== void 0;
    }
    Range.is = is;
    function print(value) {
        return `${Position.print(value.start)}-${Position.print(value.end)}`;
    }
    Range.print = print;
})(Range || (exports.Range = Range = {}));
function comparePositions(a, b) {
    if (a.line < b.line) {
        return -1;
    }
    else if (a.line > b.line) {
        return 1;
    }
    else if (a.character < b.character) {
        return -1;
    }
    else if (a.character > b.character) {
        return 1;
    }
    return 0;
}
exports.comparePositions = comparePositions;
function getEmptyPosition() {
    return {
        line: 0,
        character: 0,
    };
}
exports.getEmptyPosition = getEmptyPosition;
function doRangesOverlap(a, b) {
    if (comparePositions(b.start, a.end) >= 0) {
        return false;
    }
    else if (comparePositions(a.start, b.end) >= 0) {
        return false;
    }
    return true;
}
exports.doRangesOverlap = doRangesOverlap;
function doRangesIntersect(a, b) {
    if (comparePositions(b.start, a.end) > 0) {
        return false;
    }
    else if (comparePositions(a.start, b.end) > 0) {
        return false;
    }
    return true;
}
exports.doRangesIntersect = doRangesIntersect;
function doesRangeContain(range, positionOrRange) {
    if (Position.is(positionOrRange)) {
        return comparePositions(range.start, positionOrRange) <= 0 && comparePositions(range.end, positionOrRange) >= 0;
    }
    return doesRangeContain(range, positionOrRange.start) && doesRangeContain(range, positionOrRange.end);
}
exports.doesRangeContain = doesRangeContain;
function positionsAreEqual(a, b) {
    return comparePositions(a, b) === 0;
}
exports.positionsAreEqual = positionsAreEqual;
function rangesAreEqual(a, b) {
    return positionsAreEqual(a.start, b.start) && positionsAreEqual(a.end, b.end);
}
exports.rangesAreEqual = rangesAreEqual;
function getEmptyRange() {
    return {
        start: getEmptyPosition(),
        end: getEmptyPosition(),
    };
}
exports.getEmptyRange = getEmptyRange;
function isEmptyPosition(pos) {
    return pos.character === 0 && pos.line === 0;
}
exports.isEmptyPosition = isEmptyPosition;
function isEmptyRange(range) {
    return isEmptyPosition(range.start) && isEmptyPosition(range.end);
}
exports.isEmptyRange = isEmptyRange;
function extendRange(range, extension) {
    if (extension) {
        if (Array.isArray(extension)) {
            extension.forEach((r) => {
                extendRange(range, r);
            });
        }
        else {
            if (comparePositions(extension.start, range.start) < 0) {
                range.start = extension.start;
            }
            if (comparePositions(extension.end, range.end) > 0) {
                range.end = extension.end;
            }
        }
    }
}
exports.extendRange = extendRange;
function combineRange(ranges) {
    if (ranges.length === 0) {
        return undefined;
    }
    const combinedRange = ranges[0];
    for (let i = 1; i < ranges.length; i++) {
        extendRange(combinedRange, ranges[i]);
    }
    return combinedRange;
}
exports.combineRange = combineRange;


/***/ }),

/***/ "../pyright-internal/src/common/textRangeCollection.ts":
/*!*************************************************************!*\
  !*** ../pyright-internal/src/common/textRangeCollection.ts ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * textRangeCollection.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from vscode-python repository:
 *  https://github.com/Microsoft/vscode-python
 *
 * Class that maintains an ordered list of text ranges and allows
 * for indexing and fast lookups within this list.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getIndexContaining = exports.TextRangeCollection = void 0;
const textRange_1 = __webpack_require__(/*! ./textRange */ "../pyright-internal/src/common/textRange.ts");
class TextRangeCollection {
    constructor(items) {
        this._items = items;
    }
    get start() {
        return this._items.length > 0 ? this._items[0].start : 0;
    }
    get end() {
        const lastItem = this._items[this._items.length - 1];
        return this._items.length > 0 ? lastItem.start + lastItem.length : 0;
    }
    get length() {
        return this.end - this.start;
    }
    get count() {
        return this._items.length;
    }
    contains(position) {
        return position >= this.start && position < this.end;
    }
    getItemAt(index) {
        if (index < 0 || index >= this._items.length) {
            throw new Error('index is out of range');
        }
        return this._items[index];
    }
    // Returns the nearest item prior to the position.
    // The position may not be contained within the item.
    getItemAtPosition(position) {
        if (this.count === 0) {
            return -1;
        }
        if (position < this.start) {
            return -1;
        }
        if (position > this.end) {
            return -1;
        }
        let min = 0;
        let max = this.count - 1;
        while (min < max) {
            const mid = Math.floor(min + (max - min) / 2);
            const item = this._items[mid];
            // Is the position past the start of this item but before
            // the start of the next item? If so, we found our item.
            if (position >= item.start) {
                if (mid >= this.count - 1 || position < this._items[mid + 1].start) {
                    return mid;
                }
            }
            if (position < item.start) {
                max = mid - 1;
            }
            else {
                min = mid + 1;
            }
        }
        return min;
    }
    getItemContaining(position) {
        if (this.count === 0) {
            return -1;
        }
        if (position < this.start) {
            return -1;
        }
        if (position > this.end) {
            return -1;
        }
        return getIndexContaining(this._items, position);
    }
}
exports.TextRangeCollection = TextRangeCollection;
function getIndexContaining(arr, position) {
    if (arr.length === 0) {
        return -1;
    }
    let min = 0;
    let max = arr.length - 1;
    while (min <= max) {
        const mid = Math.floor(min + (max - min) / 2);
        const item = findNonNullElement(arr, mid, min, max);
        if (item === undefined) {
            return -1;
        }
        if (textRange_1.TextRange.contains(item, position)) {
            return mid;
        }
        const nextItem = findNonNullElement(arr, mid + 1, mid + 1, max);
        if (nextItem === undefined) {
            return -1;
        }
        if (mid < arr.length - 1 && textRange_1.TextRange.getEnd(item) <= position && position < nextItem.start) {
            return -1;
        }
        if (position < item.start) {
            max = mid - 1;
        }
        else {
            min = mid + 1;
        }
    }
    return -1;
}
exports.getIndexContaining = getIndexContaining;
function findNonNullElement(arr, position, min, max) {
    const item = arr[position];
    if (item) {
        return item;
    }
    // Search forward and backward until it finds non-null value.
    for (let i = position + 1; i <= max; i++) {
        const item = arr[position];
        if (item) {
            return item;
        }
    }
    for (let i = position - 1; i >= min; i--) {
        const item = arr[position];
        if (item) {
            return item;
        }
    }
    return undefined;
}


/***/ }),

/***/ "../pyright-internal/src/common/timing.ts":
/*!************************************************!*\
  !*** ../pyright-internal/src/common/timing.ts ***!
  \************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * timing.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * A simple duration class that can be used to record and report
 * durations at the millisecond level of resolution.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.timingStats = exports.TimingStats = exports.TimingStat = exports.Duration = void 0;
class Duration {
    constructor() {
        this._startTime = Date.now();
    }
    getDurationInMilliseconds() {
        const curTime = Date.now();
        return curTime - this._startTime;
    }
    getDurationInSeconds() {
        return this.getDurationInMilliseconds() / 1000;
    }
}
exports.Duration = Duration;
class TimingStat {
    constructor() {
        this.totalTime = 0;
        this.callCount = 0;
        this.isTiming = false;
    }
    timeOperation(callback, ...args) {
        this.callCount++;
        // Handle reentrancy.
        if (this.isTiming) {
            return callback(...args);
        }
        else {
            this.isTiming = true;
            const duration = new Duration();
            const result = callback(...args);
            this.totalTime += duration.getDurationInMilliseconds();
            this.isTiming = false;
            return result;
        }
    }
    subtractFromTime(callback) {
        if (this.isTiming) {
            this.isTiming = false;
            const duration = new Duration();
            callback();
            this.totalTime -= duration.getDurationInMilliseconds();
            this.isTiming = true;
        }
        else {
            callback();
        }
    }
    printTime() {
        const totalTimeInSec = this.totalTime / 1000;
        const roundedTime = Math.round(totalTimeInSec * 100) / 100;
        return roundedTime.toString() + 'sec';
    }
}
exports.TimingStat = TimingStat;
class TimingStats {
    constructor() {
        this.totalDuration = new Duration();
        this.findFilesTime = new TimingStat();
        this.readFileTime = new TimingStat();
        this.tokenizeFileTime = new TimingStat();
        this.parseFileTime = new TimingStat();
        this.resolveImportsTime = new TimingStat();
        this.cycleDetectionTime = new TimingStat();
        this.bindTime = new TimingStat();
        this.typeCheckerTime = new TimingStat();
        this.typeEvaluationTime = new TimingStat();
    }
    printSummary(console) {
        console.info(`Completed in ${this.totalDuration.getDurationInSeconds()}sec`);
    }
    printDetails(console) {
        console.info('');
        console.info('Timing stats');
        console.info('Find Source Files:    ' + this.findFilesTime.printTime());
        console.info('Read Source Files:    ' + this.readFileTime.printTime());
        console.info('Tokenize:             ' + this.tokenizeFileTime.printTime());
        console.info('Parse:                ' + this.parseFileTime.printTime());
        console.info('Resolve Imports:      ' + this.resolveImportsTime.printTime());
        console.info('Bind:                 ' + this.bindTime.printTime());
        console.info('Check:                ' + this.typeCheckerTime.printTime());
        console.info('Detect Cycles:        ' + this.cycleDetectionTime.printTime());
    }
    getTotalDuration() {
        return this.totalDuration.getDurationInSeconds();
    }
}
exports.TimingStats = TimingStats;
exports.timingStats = new TimingStats();


/***/ }),

/***/ "../pyright-internal/src/common/uri/baseUri.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/uri/baseUri.ts ***!
  \*****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * baseUri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Base URI class for storing and manipulating URIs.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BaseUri = void 0;
const collectionUtils_1 = __webpack_require__(/*! ../collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const pathUtils_1 = __webpack_require__(/*! ../pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const memoization_1 = __webpack_require__(/*! ./memoization */ "../pyright-internal/src/common/uri/memoization.ts");
class BaseUri {
    constructor(_key) {
        this._key = _key;
    }
    // Unique key for storing in maps.
    get key() {
        return this._key;
    }
    // Returns just the fileName without any extensions
    get fileNameWithoutExtensions() {
        const fileName = this.fileName;
        const index = fileName.lastIndexOf('.');
        if (index > 0) {
            return fileName.slice(0, index);
        }
        else {
            return fileName;
        }
    }
    // Returns a URI where the path contains the path with .py appended.
    get packageUri() {
        // This is assuming that the current path is a file already.
        return this.addExtension('.py');
    }
    // Returns a URI where the path contains the path with .pyi appended.
    get packageStubUri() {
        // This is assuming that the current path is a file already.
        return this.addExtension('.pyi');
    }
    // Returns a URI where the path has __init__.py appended.
    get initPyUri() {
        // This is assuming that the current path is a directory already.
        return this.combinePathsUnsafe('__init__.py');
    }
    // Returns a URI where the path has __init__.pyi appended.
    get initPyiUri() {
        // This is assuming that the current path is a directory already.
        return this.combinePathsUnsafe('__init__.pyi');
    }
    // Returns a URI where the path has py.typed appended.
    get pytypedUri() {
        // This is assuming that the current path is a directory already.
        return this.combinePathsUnsafe('py.typed');
    }
    isEmpty() {
        return false;
    }
    replaceExtension(ext) {
        const dir = this.getDirectory();
        const base = this.fileName;
        const newBase = base.slice(0, base.length - this.lastExtension.length) + ext;
        return dir.combinePathsUnsafe(newBase);
    }
    addExtension(ext) {
        return this.addPath(ext);
    }
    hasExtension(ext) {
        return this.isCaseSensitive
            ? this.lastExtension === ext
            : this.lastExtension.toLowerCase() === ext.toLowerCase();
    }
    containsExtension(ext) {
        const fileName = this.fileName;
        // Use a regex so we keep the . on the front of the extension.
        const extensions = fileName.split(/(?=\.)/g);
        return extensions.some((e) => (this.isCaseSensitive ? e === ext : e.toLowerCase() === ext.toLowerCase()));
    }
    getRootPathLength() {
        return this.getRootPath().length;
    }
    isUntitled() {
        return this.scheme === 'untitled';
    }
    equals(other) {
        return this.key === (other === null || other === void 0 ? void 0 : other.key);
    }
    pathStartsWith(name) {
        // We're making an assumption here that the name is already normalized.
        return this.getComparablePath().startsWith(name);
    }
    pathEndsWith(name) {
        // We're making an assumption here that the name is already normalized.
        return this.getComparablePath().endsWith(name);
    }
    pathIncludes(include) {
        // We're making an assumption here that the name is already normalized.
        return this.getComparablePath().includes(include);
    }
    getRelativePath(child) {
        if (this.scheme !== child.scheme) {
            return undefined;
        }
        // Unlike getRelativePathComponents, this function should not return relative path
        // markers for non children.
        if (child.isChild(this)) {
            const relativeToComponents = this.getRelativePathComponents(child);
            if (relativeToComponents.length > 0) {
                return ['.', ...relativeToComponents].join('/');
            }
        }
        return undefined;
    }
    getPathComponents() {
        // Make sure to freeze the result so that it can't be modified.
        return Object.freeze(this.getPathComponentsImpl());
    }
    getRelativePathComponents(to) {
        const fromComponents = this.getPathComponents();
        const toComponents = to.getPathComponents();
        let start;
        for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
            const fromComponent = fromComponents[start];
            const toComponent = toComponents[start];
            const match = this.isCaseSensitive
                ? fromComponent === toComponent
                : fromComponent.toLowerCase() === toComponent.toLowerCase();
            if (!match) {
                break;
            }
        }
        if (start === 0) {
            return toComponents;
        }
        const components = toComponents.slice(start);
        const relative = [];
        for (; start < fromComponents.length; start++) {
            relative.push('..');
        }
        return [...relative, ...components];
    }
    getShortenedFileName(maxDirLength = 15) {
        return (0, pathUtils_1.getShortenedFileName)(this.getPath(), maxDirLength);
    }
    normalizeSlashes(path) {
        if (path.includes('\\')) {
            return path.replace(/\\/g, '/');
        }
        return path;
    }
    static combinePathElements(pathString, separator, ...paths) {
        // Borrowed this algorithm from the pathUtils combinePaths function. This is
        // a quicker implementation that's possible because we assume all paths are normalized already.
        for (const relativePath of paths) {
            if (!relativePath) {
                continue;
            }
            if (!pathString || (0, pathUtils_1.getRootLength)(relativePath) !== 0) {
                pathString = relativePath;
            }
            else if (pathString.endsWith(separator)) {
                pathString += relativePath;
            }
            else {
                pathString += separator + relativePath;
            }
        }
        return pathString;
    }
    reducePathComponents(components) {
        if (!(0, collectionUtils_1.some)(components)) {
            return [];
        }
        // Reduce the path components by eliminating
        // any '.' or '..'. We start at 1 because the first component is
        // always the root.
        const reduced = [components[0]];
        for (let i = 1; i < components.length; i++) {
            const component = components[i];
            if (!component || component === '.') {
                continue;
            }
            if (component === '..') {
                if (reduced.length > 1) {
                    if (reduced[reduced.length - 1] !== '..') {
                        reduced.pop();
                        continue;
                    }
                }
                else if (reduced[0]) {
                    continue;
                }
            }
            reduced.push(component);
        }
        return reduced;
    }
}
exports.BaseUri = BaseUri;
__decorate([
    (0, memoization_1.cacheProperty)()
], BaseUri.prototype, "packageUri", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], BaseUri.prototype, "packageStubUri", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], BaseUri.prototype, "initPyUri", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], BaseUri.prototype, "initPyiUri", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], BaseUri.prototype, "pytypedUri", null);


/***/ }),

/***/ "../pyright-internal/src/common/uri/constantUri.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/common/uri/constantUri.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * constantUri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * URI class that represents a constant/marker URI.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConstantUri = void 0;
const baseUri_1 = __webpack_require__(/*! ./baseUri */ "../pyright-internal/src/common/uri/baseUri.ts");
class ConstantUri extends baseUri_1.BaseUri {
    constructor(name) {
        super(name);
    }
    get scheme() {
        return '';
    }
    get isCaseSensitive() {
        return true;
    }
    get fileName() {
        return '';
    }
    get lastExtension() {
        return '';
    }
    get root() {
        return this;
    }
    get fragment() {
        return '';
    }
    get query() {
        return '';
    }
    equals(other) {
        // For constant Uri, reference equality must be used instead of value equality.
        return this === other;
    }
    toJsonObj() {
        throw new Error(`constant uri can't be serialized`);
    }
    toString() {
        return this.key;
    }
    toUserVisibleString() {
        return '';
    }
    matchesRegex(regex) {
        return false;
    }
    withFragment(fragment) {
        return this;
    }
    withQuery(query) {
        return this;
    }
    addPath(extra) {
        return this;
    }
    getDirectory() {
        return this;
    }
    isRoot() {
        return false;
    }
    isChild(parent, ignoreCase) {
        return false;
    }
    isLocal() {
        return false;
    }
    startsWith(other, ignoreCase) {
        return false;
    }
    getPathLength() {
        return 0;
    }
    resolvePaths(...paths) {
        return this;
    }
    combinePaths(...paths) {
        return this;
    }
    combinePathsUnsafe(...paths) {
        return this;
    }
    getPath() {
        return '';
    }
    getFilePath() {
        return '';
    }
    stripExtension() {
        return this;
    }
    stripAllExtensions() {
        return this;
    }
    getRootPath() {
        return '';
    }
    getComparablePath() {
        return '';
    }
    getPathComponentsImpl() {
        return [];
    }
}
exports.ConstantUri = ConstantUri;


/***/ }),

/***/ "../pyright-internal/src/common/uri/emptyUri.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/common/uri/emptyUri.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * emptyUri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * URI class that represents an empty URI.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EmptyUri = void 0;
const constantUri_1 = __webpack_require__(/*! ./constantUri */ "../pyright-internal/src/common/uri/constantUri.ts");
const EmptyKey = '<empty>';
class EmptyUri extends constantUri_1.ConstantUri {
    constructor() {
        super(EmptyKey);
    }
    static get instance() {
        return EmptyUri._instance;
    }
    toJsonObj() {
        return {
            _key: EmptyKey,
        };
    }
    static isEmptyUri(uri) {
        return (uri === null || uri === void 0 ? void 0 : uri._key) === EmptyKey;
    }
    isEmpty() {
        return true;
    }
    toString() {
        return '';
    }
}
exports.EmptyUri = EmptyUri;
EmptyUri._instance = new EmptyUri();


/***/ }),

/***/ "../pyright-internal/src/common/uri/fileUri.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/common/uri/fileUri.ts ***!
  \*****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * fileUri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * URI class that represents a file path. These URIs are always 'file' schemed.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FileUri = exports.FileUriSchema = void 0;
const vscode_uri_1 = __webpack_require__(/*! vscode-uri */ "../pyright-internal/node_modules/vscode-uri/lib/umd/index.js");
const core_1 = __webpack_require__(/*! ../core */ "../pyright-internal/src/common/core.ts");
const pathUtils_1 = __webpack_require__(/*! ../pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const baseUri_1 = __webpack_require__(/*! ./baseUri */ "../pyright-internal/src/common/uri/baseUri.ts");
const memoization_1 = __webpack_require__(/*! ./memoization */ "../pyright-internal/src/common/uri/memoization.ts");
exports.FileUriSchema = 'file';
class FileUri extends baseUri_1.BaseUri {
    constructor(key, _filePath, _query, _fragment, _originalString, _isCaseSensitive) {
        super(_isCaseSensitive ? key : key.toLowerCase());
        this._filePath = _filePath;
        this._query = _query;
        this._fragment = _fragment;
        this._originalString = _originalString;
        this._isCaseSensitive = _isCaseSensitive;
    }
    get scheme() {
        return exports.FileUriSchema;
    }
    get fragment() {
        return this._fragment;
    }
    get query() {
        return this._query;
    }
    get fileName() {
        return (0, pathUtils_1.getFileName)(this._filePath);
    }
    get lastExtension() {
        return (0, pathUtils_1.getFileExtension)(this._filePath);
    }
    get root() {
        const rootPath = this.getRootPath();
        if (rootPath !== this._filePath) {
            return FileUri.createFileUri(rootPath, '', '', undefined, this._isCaseSensitive);
        }
        return this;
    }
    get isCaseSensitive() {
        return this._isCaseSensitive;
    }
    static createFileUri(filePath, query, fragment, originalString, isCaseSensitive) {
        const key = FileUri._createKey(filePath, query, fragment);
        return new FileUri(key, filePath, query, fragment, originalString, isCaseSensitive);
    }
    static isFileUri(uri) {
        return (uri === null || uri === void 0 ? void 0 : uri._filePath) !== undefined && (uri === null || uri === void 0 ? void 0 : uri._key) !== undefined;
    }
    static fromJsonObj(obj) {
        if ((0, core_1.isArray)(obj)) {
            const so = obj;
            return FileUri.createFileUri(so[1], so[2], so[3], so[4], so[5] === 1 ? true : false);
        }
        return FileUri.createFileUri(obj._filePath, obj._query, obj._fragment, obj._originalString, obj._isCaseSensitive);
    }
    toJsonObj() {
        const jsonObj = [
            0 /* UriKinds.file */,
            this._filePath,
            this._query,
            this._fragment,
            this._originalString,
            this._isCaseSensitive ? 1 : 0,
        ];
        return jsonObj;
    }
    matchesRegex(regex) {
        // Compare the regex to our path but normalize it for comparison.
        // The regex assumes it's comparing itself to a URI path.
        return regex.test(this._getNormalizedPath());
    }
    toString() {
        if (!this._formattedString) {
            this._formattedString =
                this._originalString ||
                    vscode_uri_1.URI.file(this._filePath).with({ query: this._query, fragment: this._fragment }).toString();
        }
        return this._formattedString;
    }
    toUserVisibleString() {
        return this._filePath;
    }
    addPath(extra) {
        return FileUri.createFileUri(this._filePath + extra, '', '', undefined, this._isCaseSensitive);
    }
    isRoot() {
        return (0, pathUtils_1.isDiskPathRoot)(this._filePath);
    }
    isChild(parent) {
        if (!FileUri.isFileUri(parent)) {
            return false;
        }
        return parent._filePath.length < this._filePath.length && this.startsWith(parent);
    }
    isLocal() {
        return true;
    }
    startsWith(other) {
        if ((other === null || other === void 0 ? void 0 : other.scheme) !== this.scheme) {
            return false;
        }
        const otherFileUri = other;
        if (this._filePath.length >= otherFileUri._filePath.length) {
            // Make sure the other ends with a / when comparing longer paths, otherwise we might
            // say that /a/food is a child of /a/foo.
            const otherPath = this._filePath.length > otherFileUri._filePath.length &&
                !(0, pathUtils_1.hasTrailingDirectorySeparator)(otherFileUri._filePath)
                ? (0, pathUtils_1.ensureTrailingDirectorySeparator)(otherFileUri._filePath)
                : otherFileUri._filePath;
            if (!this.isCaseSensitive) {
                return this._filePath.toLowerCase().startsWith(otherPath.toLowerCase());
            }
            return this._filePath.startsWith(otherPath);
        }
        return false;
    }
    getPathLength() {
        return this._filePath.length;
    }
    getPath() {
        return this._getNormalizedPath();
    }
    getFilePath() {
        return this._filePath;
    }
    resolvePaths(...paths) {
        // Resolve and combine paths, never want URIs with '..' in the middle.
        let combined = (0, pathUtils_1.resolvePaths)(this._filePath, ...paths);
        // Make sure to remove any trailing directory chars.
        if ((0, pathUtils_1.hasTrailingDirectorySeparator)(combined) && combined.length > 1) {
            combined = combined.slice(0, combined.length - 1);
        }
        if (combined !== this._filePath) {
            return FileUri.createFileUri(combined, '', '', undefined, this._isCaseSensitive);
        }
        return this;
    }
    combinePaths(...paths) {
        if (paths.some((p) => p.includes('..') || p.includes(FileUri._separator) || p.includes('/') || p === '.')) {
            // This is a slow path that handles paths that contain '..' or '.'.
            return this.resolvePaths(...paths);
        }
        // Paths don't have any thing special that needs to be combined differently, so just
        // use the quick method.
        return this.combinePathsUnsafe(...paths);
    }
    combinePathsUnsafe(...paths) {
        // Combine paths using the quicker path implementation as we
        // assume all data is already normalized.
        const combined = baseUri_1.BaseUri.combinePathElements(this._filePath, FileUri._separator, ...paths);
        if (combined !== this._filePath) {
            return FileUri.createFileUri(combined, '', '', undefined, this._isCaseSensitive);
        }
        return this;
    }
    getDirectory() {
        const filePath = this._filePath;
        let dir = (0, pathUtils_1.getDirectoryPath)(filePath);
        if ((0, pathUtils_1.hasTrailingDirectorySeparator)(dir) && dir.length > 1) {
            dir = dir.slice(0, -1);
        }
        if (dir !== filePath) {
            return FileUri.createFileUri(dir, '', '', undefined, this._isCaseSensitive);
        }
        else {
            return this;
        }
    }
    withFragment(fragment) {
        return FileUri.createFileUri(this._filePath, this._query, fragment, undefined, this._isCaseSensitive);
    }
    withQuery(query) {
        return FileUri.createFileUri(this._filePath, query, this._fragment, undefined, this._isCaseSensitive);
    }
    stripExtension() {
        const stripped = (0, pathUtils_1.stripFileExtension)(this._filePath);
        if (stripped !== this._filePath) {
            return FileUri.createFileUri(stripped, this._query, this._fragment, undefined, this._isCaseSensitive);
        }
        return this;
    }
    stripAllExtensions() {
        const stripped = (0, pathUtils_1.stripFileExtension)(this._filePath, /* multiDotExtension */ true);
        if (stripped !== this._filePath) {
            return FileUri.createFileUri(stripped, this._query, this._fragment, undefined, this._isCaseSensitive);
        }
        return this;
    }
    getPathComponentsImpl() {
        const components = (0, pathUtils_1.getPathComponents)(this._filePath);
        // Remove the first one if it's empty. The new algorithm doesn't
        // expect this to be there.
        if (components.length > 0 && components[0] === '') {
            components.shift();
        }
        return components.map((component) => this.normalizeSlashes(component));
    }
    getRootPath() {
        return this._filePath.slice(0, (0, pathUtils_1.getRootLength)(this._filePath));
    }
    getComparablePath() {
        return this._getNormalizedPath();
    }
    static _createKey(filePath, query, fragment) {
        return `${filePath}${query ? '?' + query : ''}${fragment ? '#' + fragment : ''}`;
    }
    _getNormalizedPath() {
        if (this._normalizedPath === undefined) {
            this._normalizedPath = this.normalizeSlashes(this._filePath);
        }
        return this._normalizedPath;
    }
}
exports.FileUri = FileUri;
FileUri._separator = (0, pathUtils_1.getPathSeparator)('');
__decorate([
    (0, memoization_1.cacheProperty)()
], FileUri.prototype, "fileName", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], FileUri.prototype, "lastExtension", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], FileUri.prototype, "root", null);
__decorate([
    (0, memoization_1.cacheMethodWithNoArgs)()
], FileUri.prototype, "getDirectory", null);
__decorate([
    (0, memoization_1.cacheStaticFunc)()
], FileUri, "createFileUri", null);


/***/ }),

/***/ "../pyright-internal/src/common/uri/memoization.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/common/uri/memoization.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * memoization.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Decorators used to memoize the result of a function call.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cacheStaticFunc = exports.cacheMethodWithNoArgs = exports.cacheProperty = void 0;
// Cache for static method results.
const staticCache = new Map();
// Caches the results of a getter property.
function cacheProperty() {
    return function (target, functionName, descriptor) {
        const originalMethod = descriptor.get;
        descriptor.get = function (...args) {
            // Call the function once to get the result.
            const result = originalMethod.apply(this, args);
            // Then we replace the original function with one that just returns the result.
            Object.defineProperty(this, functionName, {
                get() {
                    return result;
                },
            });
            return result;
        };
        return descriptor;
    };
}
exports.cacheProperty = cacheProperty;
// Caches the results of method that takes no args.
// This situation can be optimized because the parameters are always the same.
function cacheMethodWithNoArgs() {
    return function (target, functionName, descriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = function (...args) {
            // Call the function once to get the result.
            const result = originalMethod.apply(this, args);
            // Then we replace the original function with one that just returns the result.
            this[functionName] = () => {
                // Note that this poses a risk. The result is passed by reference, so if the caller
                // modifies the result, it will modify the cached result.
                return result;
            };
            return result;
        };
        return descriptor;
    };
}
exports.cacheMethodWithNoArgs = cacheMethodWithNoArgs;
// Create a decorator to cache the results of a static method.
function cacheStaticFunc() {
    return function cacheStaticFunc_Fast(target, functionName, descriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = function (...args) {
            const key = `${functionName}+${args === null || args === void 0 ? void 0 : args.map((a) => a === null || a === void 0 ? void 0 : a.toString()).join(',')}`;
            let cachedResult;
            if (!staticCache.has(key)) {
                cachedResult = originalMethod.apply(this, args);
                staticCache.set(key, cachedResult);
            }
            else {
                cachedResult = staticCache.get(key);
            }
            return cachedResult;
        };
        return descriptor;
    };
}
exports.cacheStaticFunc = cacheStaticFunc;


/***/ }),

/***/ "../pyright-internal/src/common/uri/uri.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/common/uri/uri.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * uri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * URI namespace for storing and manipulating URIs.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Uri = void 0;
const vscode_uri_1 = __webpack_require__(/*! vscode-uri */ "../pyright-internal/node_modules/vscode-uri/lib/umd/index.js");
const caseSensitivityDetector_1 = __webpack_require__(/*! ../caseSensitivityDetector */ "../pyright-internal/src/common/caseSensitivityDetector.ts");
const pathUtils_1 = __webpack_require__(/*! ../pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const fileUri_1 = __webpack_require__(/*! ./fileUri */ "../pyright-internal/src/common/uri/fileUri.ts");
const webUri_1 = __webpack_require__(/*! ./webUri */ "../pyright-internal/src/common/uri/webUri.ts");
const emptyUri_1 = __webpack_require__(/*! ./emptyUri */ "../pyright-internal/src/common/uri/emptyUri.ts");
const core_1 = __webpack_require__(/*! ../core */ "../pyright-internal/src/common/core.ts");
const serviceKeys_1 = __webpack_require__(/*! ../serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const constantUri_1 = __webpack_require__(/*! ./constantUri */ "../pyright-internal/src/common/uri/constantUri.ts");
// Returns just the fsPath path portion of a vscode URI.
function getFilePath(uri) {
    let filePath;
    // Compute the file path ourselves. The vscode.URI class doesn't
    // treat UNC shares with a single slash as UNC paths.
    // https://github.com/microsoft/vscode-uri/blob/53e4ca6263f2e4ddc35f5360c62bc1b1d30f27dd/src/uri.ts#L567
    if (uri.authority && uri.path[0] === '/' && uri.path.length === 1) {
        filePath = `//${uri.authority}${uri.path}`;
    }
    else {
        // Otherwise use the vscode.URI version
        filePath = uri.fsPath;
    }
    // If this is a DOS-style path with a drive letter, remove
    // the leading slash.
    if (filePath.match(/^\/[a-zA-Z]:\//)) {
        filePath = filePath.slice(1);
    }
    // vscode.URI normalizes the path to use the correct path separators.
    // We need to do the same.
    if ((process === null || process === void 0 ? void 0 : process.platform) === 'win32') {
        filePath = filePath.replace(/\//g, '\\');
    }
    return filePath;
}
// Function called to normalize input URIs. This gets rid of '..' and '.' in the path.
// It also removes any '/' on the end of the path.
// This is slow but should only be called when the URI is first created.
function normalizeUri(uri) {
    // Make sure the drive letter is lower case. This
    // is consistent with what VS code does for URIs.
    const parsed = vscode_uri_1.URI.isUri(uri) ? uri : vscode_uri_1.URI.parse(uri);
    // Original URI may not have resolved all the `..` in the path, so remove them.
    // Note: this also has the effect of removing any trailing slashes.
    const finalURI = parsed.path.length > 0 ? vscode_uri_1.Utils.resolvePath(parsed) : parsed;
    const finalString = finalURI.toString();
    return { uri: finalURI, str: finalString };
}
var Uri;
(function (Uri) {
    function file(path, arg, checkRelative = false) {
        arg = caseSensitivityDetector_1.CaseSensitivityDetector.is(arg) ? arg : arg.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
        // Fix path if we're checking for relative paths and this is not a rooted path.
        path = checkRelative && !(0, pathUtils_1.isRootedDiskPath)(path) ? (0, pathUtils_1.combinePaths)(process.cwd(), path) : path;
        // If this already starts with 'file:', then we can
        // parse it normally. It's actually a uri string. Otherwise parse it as a file path.
        const normalized = path.startsWith('file:')
            ? normalizeUri(path)
            : normalizeUri(vscode_uri_1.URI.file((0, pathUtils_1.normalizeSlashes)(path)));
        // Turn the path into a file URI.
        return fileUri_1.FileUri.createFileUri(getFilePath(normalized.uri), normalized.uri.query, normalized.uri.fragment, normalized.str, arg.isCaseSensitive(normalized.str));
    }
    Uri.file = file;
    function parse(value, arg) {
        if (!value) {
            return Uri.empty();
        }
        arg = caseSensitivityDetector_1.CaseSensitivityDetector.is(arg) ? arg : arg.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
        // Normalize the value here. This gets rid of '..' and '.' in the path. It also removes any
        // '/' on the end of the path.
        const normalized = normalizeUri(value);
        if (normalized.uri.scheme === fileUri_1.FileUriSchema) {
            return fileUri_1.FileUri.createFileUri(getFilePath(normalized.uri), normalized.uri.query, normalized.uri.fragment, normalized.str, arg.isCaseSensitive(normalized.str));
        }
        // Web URIs are always case sensitive.
        return webUri_1.WebUri.createWebUri(normalized.uri.scheme, normalized.uri.authority, normalized.uri.path, normalized.uri.query, normalized.uri.fragment, normalized.str);
    }
    Uri.parse = parse;
    function constant(markerName) {
        return new constantUri_1.ConstantUri(markerName);
    }
    Uri.constant = constant;
    function empty() {
        return emptyUri_1.EmptyUri.instance;
    }
    Uri.empty = empty;
    function fromJsonObj(jsonObj) {
        if ((0, core_1.isArray)(jsonObj)) {
            // Currently only file uri supports SerializedType.
            switch (jsonObj[0]) {
                case 0 /* UriKinds.file */:
                    return fileUri_1.FileUri.fromJsonObj(jsonObj);
            }
        }
        if (fileUri_1.FileUri.isFileUri(jsonObj)) {
            return fileUri_1.FileUri.fromJsonObj(jsonObj);
        }
        if (webUri_1.WebUri.isWebUri(jsonObj)) {
            return webUri_1.WebUri.fromJsonObj(jsonObj);
        }
        if (emptyUri_1.EmptyUri.isEmptyUri(jsonObj)) {
            return emptyUri_1.EmptyUri.instance;
        }
        return jsonObj;
    }
    Uri.fromJsonObj = fromJsonObj;
    function is(thing) {
        return !!thing && typeof thing._key === 'string';
    }
    Uri.is = is;
})(Uri || (exports.Uri = Uri = {}));


/***/ }),

/***/ "../pyright-internal/src/common/uri/uriUtils.ts":
/*!******************************************************!*\
  !*** ../pyright-internal/src/common/uri/uriUtils.ts ***!
  \******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * uriUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Utility functions for manipulating URIs.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UriEx = exports.encodeUri = exports.getRootUri = exports.deduplicateFolders = exports.getDirectoryChangeKind = exports.getFileSpec = exports.hasPythonExtension = exports.getWildcardRoot = exports.getWildcardRegexPattern = exports.getFileSystemEntriesFromDirEntries = exports.getFileSystemEntries = exports.tryRealpath = exports.tryStat = exports.isFile = exports.isDirectory = exports.directoryExists = exports.fileExists = exports.getFileSize = exports.makeDirectories = exports.forEachAncestorDirectory = exports.FileSpec = void 0;
const pathUtils_1 = __webpack_require__(/*! ../pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const uri_1 = __webpack_require__(/*! ./uri */ "../pyright-internal/src/common/uri/uri.ts");
const serviceKeys_1 = __webpack_require__(/*! ../serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const caseSensitivityDetector_1 = __webpack_require__(/*! ../caseSensitivityDetector */ "../pyright-internal/src/common/caseSensitivityDetector.ts");
const _includeFileRegex = /\.pyi?$/;
var FileSpec;
(function (FileSpec) {
    function is(value) {
        const candidate = value;
        return candidate && !!candidate.wildcardRoot && !!candidate.regExp;
    }
    FileSpec.is = is;
    function isInPath(uri, paths) {
        return !!paths.find((p) => uri.matchesRegex(p.regExp));
    }
    FileSpec.isInPath = isInPath;
    function matchesIncludeFileRegex(uri, isFile = true) {
        return isFile ? uri.matchesRegex(_includeFileRegex) : true;
    }
    FileSpec.matchesIncludeFileRegex = matchesIncludeFileRegex;
    function matchIncludeFileSpec(includeRegExp, exclude, uri, isFile = true) {
        if (uri.matchesRegex(includeRegExp)) {
            if (!FileSpec.isInPath(uri, exclude) && FileSpec.matchesIncludeFileRegex(uri, isFile)) {
                return true;
            }
        }
        return false;
    }
    FileSpec.matchIncludeFileSpec = matchIncludeFileSpec;
})(FileSpec || (exports.FileSpec = FileSpec = {}));
function forEachAncestorDirectory(directory, callback) {
    while (true) {
        const result = callback(directory);
        if (result !== undefined) {
            return result;
        }
        const parentPath = directory.getDirectory();
        if (parentPath.equals(directory)) {
            return undefined;
        }
        directory = parentPath;
    }
}
exports.forEachAncestorDirectory = forEachAncestorDirectory;
// Creates a directory hierarchy for a path, starting from some ancestor path.
function makeDirectories(fs, dir, startingFrom) {
    if (!dir.startsWith(startingFrom)) {
        return;
    }
    const pathComponents = dir.getPathComponents();
    const relativeToComponents = startingFrom.getPathComponents();
    let curPath = startingFrom;
    for (let i = relativeToComponents.length; i < pathComponents.length; i++) {
        curPath = curPath.combinePaths(pathComponents[i]);
        if (!fs.existsSync(curPath)) {
            fs.mkdirSync(curPath);
        }
    }
}
exports.makeDirectories = makeDirectories;
function getFileSize(fs, uri) {
    const stat = tryStat(fs, uri);
    if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
        return stat.size;
    }
    return 0;
}
exports.getFileSize = getFileSize;
function fileExists(fs, uri) {
    return fileSystemEntryExists(fs, uri, 0 /* FileSystemEntryKind.File */);
}
exports.fileExists = fileExists;
function directoryExists(fs, uri) {
    return fileSystemEntryExists(fs, uri, 1 /* FileSystemEntryKind.Directory */);
}
exports.directoryExists = directoryExists;
function isDirectory(fs, uri) {
    var _a, _b;
    return (_b = (_a = tryStat(fs, uri)) === null || _a === void 0 ? void 0 : _a.isDirectory()) !== null && _b !== void 0 ? _b : false;
}
exports.isDirectory = isDirectory;
function isFile(fs, uri, treatZipDirectoryAsFile = false) {
    var _a, _b;
    const stats = tryStat(fs, uri);
    if (stats === null || stats === void 0 ? void 0 : stats.isFile()) {
        return true;
    }
    if (!treatZipDirectoryAsFile) {
        return false;
    }
    return (_b = (_a = stats === null || stats === void 0 ? void 0 : stats.isZipDirectory) === null || _a === void 0 ? void 0 : _a.call(stats)) !== null && _b !== void 0 ? _b : false;
}
exports.isFile = isFile;
function tryStat(fs, uri) {
    try {
        if (fs.existsSync(uri)) {
            return fs.statSync(uri);
        }
    }
    catch (e) {
        return undefined;
    }
    return undefined;
}
exports.tryStat = tryStat;
function tryRealpath(fs, uri) {
    try {
        return fs.realCasePath(uri);
    }
    catch (e) {
        return undefined;
    }
}
exports.tryRealpath = tryRealpath;
function getFileSystemEntries(fs, uri) {
    try {
        return getFileSystemEntriesFromDirEntries(fs.readdirEntriesSync(uri), fs, uri);
    }
    catch (e) {
        return { files: [], directories: [] };
    }
}
exports.getFileSystemEntries = getFileSystemEntries;
// Sorts the entires into files and directories, including any symbolic links.
function getFileSystemEntriesFromDirEntries(dirEntries, fs, uri) {
    const entries = dirEntries.sort((a, b) => {
        if (a.name < b.name) {
            return -1;
        }
        else if (a.name > b.name) {
            return 1;
        }
        else {
            return 0;
        }
    });
    const files = [];
    const directories = [];
    for (const entry of entries) {
        // This is necessary because on some file system node fails to exclude
        // "." and "..". See https://github.com/nodejs/node/issues/4002
        if (entry.name === '.' || entry.name === '..') {
            continue;
        }
        const entryUri = uri.combinePaths(entry.name);
        if (entry.isFile()) {
            files.push(entryUri);
        }
        else if (entry.isDirectory()) {
            directories.push(entryUri);
        }
        else if (entry.isSymbolicLink()) {
            const stat = tryStat(fs, entryUri);
            if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
                files.push(entryUri);
            }
            else if (stat === null || stat === void 0 ? void 0 : stat.isDirectory()) {
                directories.push(entryUri);
            }
        }
    }
    return { files, directories };
}
exports.getFileSystemEntriesFromDirEntries = getFileSystemEntriesFromDirEntries;
// Transforms a relative file spec (one that potentially contains
// escape characters **, * or ?) and returns a regular expression
// that can be used for matching against.
function getWildcardRegexPattern(root, fileSpec) {
    const absolutePath = root.resolvePaths(fileSpec);
    const pathComponents = Array.from(absolutePath.getPathComponents());
    const escapedSeparator = (0, pathUtils_1.getRegexEscapedSeparator)('/');
    const doubleAsteriskRegexFragment = `(${escapedSeparator}[^${escapedSeparator}][^${escapedSeparator}]*)*?`;
    const reservedCharacterPattern = new RegExp(`[^\\w\\s${escapedSeparator}]`, 'g');
    // Strip the directory separator from the root component.
    if (pathComponents.length > 0) {
        pathComponents[0] = (0, pathUtils_1.stripTrailingDirectorySeparator)(pathComponents[0]);
    }
    let regExPattern = '';
    let firstComponent = true;
    for (let component of pathComponents) {
        if (component === '**') {
            regExPattern += doubleAsteriskRegexFragment;
        }
        else {
            if (!firstComponent) {
                component = escapedSeparator + component;
            }
            regExPattern += component.replace(reservedCharacterPattern, (match) => {
                if (match === '*') {
                    return `[^${escapedSeparator}]*`;
                }
                else if (match === '?') {
                    return `[^${escapedSeparator}]`;
                }
                else {
                    // escaping anything that is not reserved characters - word/space/separator
                    return '\\' + match;
                }
            });
            firstComponent = false;
        }
    }
    return regExPattern;
}
exports.getWildcardRegexPattern = getWildcardRegexPattern;
// Returns the topmost path that contains no wildcard characters.
function getWildcardRoot(root, fileSpec) {
    const absolutePath = root.resolvePaths(fileSpec);
    // make a copy of the path components so we can modify them.
    const pathComponents = Array.from(absolutePath.getPathComponents());
    let wildcardRoot = absolutePath.root;
    // Remove the root component.
    if (pathComponents.length > 0) {
        pathComponents.shift();
    }
    for (const component of pathComponents) {
        if (component === '**') {
            break;
        }
        else {
            if (/[*?]/.test(component)) {
                break;
            }
            wildcardRoot = wildcardRoot.resolvePaths(component);
        }
    }
    return wildcardRoot;
}
exports.getWildcardRoot = getWildcardRoot;
function hasPythonExtension(uri) {
    return uri.hasExtension('.py') || uri.hasExtension('.pyi');
}
exports.hasPythonExtension = hasPythonExtension;
function getFileSpec(root, fileSpec) {
    let regExPattern = getWildcardRegexPattern(root, fileSpec);
    const escapedSeparator = (0, pathUtils_1.getRegexEscapedSeparator)('/');
    regExPattern = `^(${regExPattern})($|${escapedSeparator})`;
    const regExp = new RegExp(regExPattern, root.isCaseSensitive ? undefined : 'i');
    const wildcardRoot = getWildcardRoot(root, fileSpec);
    const hasDirectoryWildcard = (0, pathUtils_1.isDirectoryWildcardPatternPresent)(fileSpec);
    return {
        wildcardRoot,
        regExp,
        hasDirectoryWildcard,
    };
}
exports.getFileSpec = getFileSpec;
function fileSystemEntryExists(fs, uri, entryKind) {
    try {
        const stat = fs.statSync(uri);
        switch (entryKind) {
            case 0 /* FileSystemEntryKind.File */:
                return stat.isFile();
            case 1 /* FileSystemEntryKind.Directory */:
                return stat.isDirectory();
            default:
                return false;
        }
    }
    catch (e) {
        return false;
    }
}
function getDirectoryChangeKind(fs, oldDirectory, newDirectory) {
    if (oldDirectory.equals(newDirectory)) {
        return 'Same';
    }
    const relativePaths = oldDirectory.getRelativePathComponents(newDirectory);
    // 2 means only last folder name has changed.
    if (relativePaths.length === 2 && relativePaths[0] === '..' && relativePaths[1] !== '..') {
        return 'Renamed';
    }
    return 'Moved';
}
exports.getDirectoryChangeKind = getDirectoryChangeKind;
function deduplicateFolders(listOfFolders) {
    const foldersToWatch = new Map();
    listOfFolders.forEach((folders) => {
        folders.forEach((p) => {
            if (foldersToWatch.has(p.key)) {
                // Bail out on exact match.
                return;
            }
            for (const existing of foldersToWatch) {
                // ex) p: "/user/test" existing: "/user"
                if (p.startsWith(existing[1])) {
                    // We already have the parent folder in the watch list
                    return;
                }
                // ex) p: "/user" folderToWatch: "/user/test"
                if (existing[1].startsWith(p)) {
                    // We found better one to watch. replace.
                    foldersToWatch.delete(existing[0]);
                    foldersToWatch.set(p.key, p);
                    return;
                }
            }
            foldersToWatch.set(p.key, p);
        });
    });
    return [...foldersToWatch.values()];
}
exports.deduplicateFolders = deduplicateFolders;
function getRootUri(csdOrSp) {
    csdOrSp = caseSensitivityDetector_1.CaseSensitivityDetector.is(csdOrSp) ? csdOrSp : csdOrSp.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
    if (global.__rootDirectory) {
        return uri_1.Uri.file(global.__rootDirectory, csdOrSp);
    }
    return undefined;
}
exports.getRootUri = getRootUri;
function encodeUri(fs, uri) {
    // Convert to a URI string that the LSP client understands (mapped files are only local to the server).
    return fs.getOriginalUri(uri).toString();
}
exports.encodeUri = encodeUri;
var UriEx;
(function (UriEx) {
    function file(path, arg, checkRelative) {
        const caseDetector = _getCaseSensitivityDetector(arg);
        return uri_1.Uri.file(path, caseDetector, checkRelative);
    }
    UriEx.file = file;
    function parse(value, arg) {
        const caseDetector = _getCaseSensitivityDetector(arg);
        return uri_1.Uri.parse(value, caseDetector);
    }
    UriEx.parse = parse;
    const caseSensitivityDetector = {
        isCaseSensitive: () => true,
    };
    const caseInsensitivityDetector = {
        isCaseSensitive: () => false,
    };
    function _getCaseSensitivityDetector(arg) {
        if (arg === undefined) {
            return caseSensitivityDetector;
        }
        return arg ? caseSensitivityDetector : caseInsensitivityDetector;
    }
})(UriEx || (exports.UriEx = UriEx = {}));


/***/ }),

/***/ "../pyright-internal/src/common/uri/webUri.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/common/uri/webUri.ts ***!
  \****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * webUri.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * URI class that represents a URI that isn't 'file' schemed.
 * This can be URIs like:
 * - http://www.microsoft.com/file.txt
 * - untitled:Untitled-1
 * - vscode:extension/ms-python.python
 * - vscode-vfs://github.com/microsoft/debugpy/debugpy/launcher/debugAdapter.py
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WebUri = void 0;
const pathUtils_1 = __webpack_require__(/*! ../pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const baseUri_1 = __webpack_require__(/*! ./baseUri */ "../pyright-internal/src/common/uri/baseUri.ts");
const memoization_1 = __webpack_require__(/*! ./memoization */ "../pyright-internal/src/common/uri/memoization.ts");
const vscode_uri_1 = __webpack_require__(/*! vscode-uri */ "../pyright-internal/node_modules/vscode-uri/lib/umd/index.js");
class WebUri extends baseUri_1.BaseUri {
    constructor(key, _scheme, _authority, _path, _query, _fragment, _originalString) {
        super(key);
        this._scheme = _scheme;
        this._authority = _authority;
        this._path = _path;
        this._query = _query;
        this._fragment = _fragment;
        this._originalString = _originalString;
    }
    get scheme() {
        return this._scheme;
    }
    get isCaseSensitive() {
        // Web URIs are always case sensitive
        return true;
    }
    get fragment() {
        return this._fragment;
    }
    get query() {
        return this._query;
    }
    get root() {
        const rootPath = this.getRootPath();
        if (rootPath !== this._path) {
            return WebUri.createWebUri(this._scheme, this._authority, rootPath, '', '', undefined);
        }
        return this;
    }
    get fileName() {
        // Path should already be normalized, just get the last on a split of '/'.
        const components = this._path.split('/');
        return components[components.length - 1];
    }
    get lastExtension() {
        const basename = this.fileName;
        const index = basename.lastIndexOf('.');
        if (index >= 0) {
            return basename.slice(index);
        }
        return '';
    }
    static createWebUri(scheme, authority, path, query, fragment, originalString) {
        const key = WebUri._createKey(scheme, authority, path, query, fragment);
        return new WebUri(key, scheme, authority, path, query, fragment, originalString);
    }
    toString() {
        if (!this._originalString) {
            const vscodeUri = vscode_uri_1.URI.revive({
                scheme: this._scheme,
                authority: this._authority,
                path: this._path,
                query: this._query,
                fragment: this._fragment,
            });
            this._originalString = vscodeUri.toString();
        }
        return this._originalString;
    }
    toUserVisibleString() {
        return this.toString();
    }
    static isWebUri(uri) {
        return (uri === null || uri === void 0 ? void 0 : uri._scheme) !== undefined && (uri === null || uri === void 0 ? void 0 : uri._key) !== undefined;
    }
    static fromJsonObj(obj) {
        return WebUri.createWebUri(obj._scheme, obj._authority, obj._path, obj._query, obj._fragment, obj._originalString);
    }
    toJsonObj() {
        return {
            _scheme: this._scheme,
            _authority: this._authority,
            _path: this._path,
            _query: this._query,
            _fragment: this._fragment,
            _originalString: this._originalString,
            _key: this.key,
        };
    }
    matchesRegex(regex) {
        return regex.test(this._path);
    }
    addPath(extra) {
        const newPath = this._path + extra;
        return WebUri.createWebUri(this._scheme, this._authority, newPath, this._query, this._fragment, undefined);
    }
    isRoot() {
        return this._path === this.getRootPath() && this._path.length > 0;
    }
    isChild(parent) {
        if (!WebUri.isWebUri(parent)) {
            return false;
        }
        return parent._path.length < this._path.length && this.startsWith(parent);
    }
    isLocal() {
        return false;
    }
    startsWith(other) {
        if ((other === null || other === void 0 ? void 0 : other.scheme) !== this.scheme) {
            return false;
        }
        const otherWebUri = other;
        if (this._path.length >= otherWebUri._path.length) {
            // Make sure the other ends with a / when comparing longer paths, otherwise we might
            // say that /a/food is a child of /a/foo.
            const otherPath = this._path.length > otherWebUri._path.length && !(0, pathUtils_1.hasTrailingDirectorySeparator)(otherWebUri._path)
                ? `${otherWebUri._path}/`
                : otherWebUri._path;
            return this._path.startsWith(otherPath);
        }
        return false;
    }
    getPathLength() {
        return this._path.length;
    }
    getPath() {
        return this._path;
    }
    getFilePath() {
        return ''; // Web URIs don't have file paths so this is always empty.
    }
    resolvePaths(...paths) {
        // Resolve and combine paths, never want URIs with '..' in the middle.
        let combined = this.normalizeSlashes((0, pathUtils_1.resolvePaths)(this._path, ...paths));
        // Make sure to remove any trailing directory chars.
        if ((0, pathUtils_1.hasTrailingDirectorySeparator)(combined) && combined.length > 1) {
            combined = combined.slice(0, combined.length - 1);
        }
        if (combined !== this._path) {
            return WebUri.createWebUri(this._scheme, this._authority, combined, '', '', undefined);
        }
        return this;
    }
    combinePaths(...paths) {
        if (paths.some((p) => p.includes('..') || p.includes('/') || p === '.')) {
            // This is a slow path that handles paths that contain '..' or '.'.
            return this.resolvePaths(...paths);
        }
        // Paths don't have any thing special that needs to be combined differently, so just
        // use the quick method.
        return this.combinePathsUnsafe(...paths);
    }
    combinePathsUnsafe(...paths) {
        // Combine paths using the quick path implementation.
        const combined = baseUri_1.BaseUri.combinePathElements(this._path, '/', ...paths);
        if (combined !== this._path) {
            return WebUri.createWebUri(this._scheme, this._authority, combined, '', '', undefined);
        }
        return this;
    }
    getDirectory() {
        if (this._path.length === 0) {
            return this;
        }
        const index = this._path.lastIndexOf('/');
        const newPath = index > 0 ? this._path.slice(0, index) : index === 0 ? '/' : '';
        return WebUri.createWebUri(this._scheme, this._authority, newPath, this._query, this._fragment, undefined);
    }
    withFragment(fragment) {
        return WebUri.createWebUri(this._scheme, this._authority, this._path, this._query, fragment, undefined);
    }
    withQuery(query) {
        return WebUri.createWebUri(this._scheme, this._authority, this._path, query, this._fragment, undefined);
    }
    stripExtension() {
        const path = this._path;
        const index = path.lastIndexOf('.');
        if (index > 0) {
            return WebUri.createWebUri(this._scheme, this._authority, path.slice(0, index), this._query, this._fragment, undefined);
        }
        return this;
    }
    stripAllExtensions() {
        const path = this._path;
        const sepIndex = path.lastIndexOf('/');
        const index = path.indexOf('.', sepIndex > 0 ? sepIndex : 0);
        if (index > 0) {
            return WebUri.createWebUri(this._scheme, this._authority, path.slice(0, index), this._query, this._fragment, undefined);
        }
        return this;
    }
    getPathComponentsImpl() {
        // Get the root path and the rest of the path components.
        const rootPath = this.getRootPath();
        const otherPaths = this._path.slice(rootPath.length).split('/');
        return this.reducePathComponents([rootPath, ...otherPaths]).map((component) => this.normalizeSlashes(component));
    }
    getRootPath() {
        const rootLength = (0, pathUtils_1.getRootLength)(this._path, '/');
        return this._path.slice(0, rootLength);
    }
    getComparablePath() {
        return this._path; // Should already have the correct '/'
    }
    static _createKey(scheme, authority, path, query, fragment) {
        return `${scheme}:${authority}${path}${query ? '?' + query : ''}${fragment ? '#' + fragment : ''}`;
    }
}
exports.WebUri = WebUri;
__decorate([
    (0, memoization_1.cacheProperty)()
], WebUri.prototype, "root", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], WebUri.prototype, "fileName", null);
__decorate([
    (0, memoization_1.cacheProperty)()
], WebUri.prototype, "lastExtension", null);
__decorate([
    (0, memoization_1.cacheMethodWithNoArgs)()
], WebUri.prototype, "getDirectory", null);
__decorate([
    (0, memoization_1.cacheStaticFunc)()
], WebUri, "createWebUri", null);


/***/ }),

/***/ "../pyright-internal/src/common/workspaceEditUtils.ts":
/*!************************************************************!*\
  !*** ../pyright-internal/src/common/workspaceEditUtils.ts ***!
  \************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * workspaceEditUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Convert pyright's FileEditActions to LanguageServer's WorkspaceEdits.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.generateWorkspaceEdit = exports.applyDocumentChanges = exports.applyWorkspaceEdit = exports.applyTextEditsToString = exports.appendToWorkspaceEdit = exports.convertToWorkspaceEdit = exports.convertToFileTextEdits = exports.convertToTextEditActions = exports.convertToTextEdits = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const vscode_languageserver_textdocument_1 = __webpack_require__(/*! vscode-languageserver-textdocument */ "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/main.js");
const collectionUtils_1 = __webpack_require__(/*! ./collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ./core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ./debug */ "../pyright-internal/src/common/debug.ts");
const positionUtils_1 = __webpack_require__(/*! ./positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ./textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ./uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
function convertToTextEdits(editActions) {
    return editActions.map((editAction) => ({
        range: editAction.range,
        newText: editAction.replacementText,
    }));
}
exports.convertToTextEdits = convertToTextEdits;
const convertToTextEditActions = (textEdits) => textEdits.map((editAction) => ({
    range: editAction.range,
    replacementText: editAction.newText,
}));
exports.convertToTextEditActions = convertToTextEditActions;
function convertToFileTextEdits(fileUri, editActions) {
    return editActions.map((a) => ({ fileUri, ...a }));
}
exports.convertToFileTextEdits = convertToFileTextEdits;
function convertToWorkspaceEdit(fs, edits, changeAnnotations, defaultAnnotationId = 'default') {
    if ((0, core_1.isArray)(edits)) {
        return _convertToWorkspaceEditWithChanges(fs, edits);
    }
    return _convertToWorkspaceEditWithDocumentChanges(fs, edits, changeAnnotations, defaultAnnotationId);
}
exports.convertToWorkspaceEdit = convertToWorkspaceEdit;
function appendToWorkspaceEdit(fs, edits, workspaceEdit) {
    edits.forEach((edit) => {
        const uri = (0, uriUtils_1.encodeUri)(fs, edit.fileUri);
        workspaceEdit.changes[uri] = workspaceEdit.changes[uri] || [];
        workspaceEdit.changes[uri].push({ range: edit.range, newText: edit.replacementText });
    });
}
exports.appendToWorkspaceEdit = appendToWorkspaceEdit;
function applyTextEditsToString(edits, lines, originalText) {
    const editsWithOffset = edits
        .map((e) => {
        var _a;
        return ({
            range: (_a = (0, positionUtils_1.convertRangeToTextRange)(e.range, lines)) !== null && _a !== void 0 ? _a : { start: originalText.length, length: 0 },
            text: e.replacementText,
        });
    })
        .sort((e1, e2) => {
        const result = e2.range.start - e1.range.start;
        if (result !== 0) {
            return result;
        }
        return textRange_1.TextRange.getEnd(e2.range) - textRange_1.TextRange.getEnd(e1.range);
    });
    // Apply change in reverse order.
    let current = originalText;
    for (const change of editsWithOffset) {
        current = current.substr(0, change.range.start) + change.text + current.substr(textRange_1.TextRange.getEnd(change.range));
    }
    return current;
}
exports.applyTextEditsToString = applyTextEditsToString;
function applyWorkspaceEdit(program, edits, filesChanged) {
    if (edits.changes) {
        for (const kv of Object.entries(edits.changes)) {
            const fileUri = uri_1.Uri.parse(kv[0], program.serviceProvider);
            const fileInfo = program.getSourceFileInfo(fileUri);
            if (!fileInfo || !fileInfo.isTracked) {
                // We don't allow non user file being modified.
                continue;
            }
            applyDocumentChanges(program, fileInfo, kv[1]);
            filesChanged.set(fileUri.key, fileUri);
        }
    }
    // For now, we don't support annotations.
    if (edits.documentChanges) {
        for (const change of edits.documentChanges) {
            if (vscode_languageserver_1.TextDocumentEdit.is(change)) {
                const fileUri = uri_1.Uri.parse(change.textDocument.uri, program.serviceProvider);
                const fileInfo = program.getSourceFileInfo(fileUri);
                if (!fileInfo || !fileInfo.isTracked) {
                    // We don't allow non user file being modified.
                    continue;
                }
                applyDocumentChanges(program, fileInfo, change.edits.filter((e) => vscode_languageserver_1.TextEdit.is(e)));
                filesChanged.set(fileUri.key, fileUri);
            }
            // For now, we don't support other kinds of text changes.
            // But if we want to add support for those in future, we should add them here.
        }
    }
}
exports.applyWorkspaceEdit = applyWorkspaceEdit;
function applyDocumentChanges(program, fileInfo, edits) {
    var _a, _b, _c, _d;
    if (!fileInfo.isOpenByClient) {
        const fileContent = fileInfo.sourceFile.getFileContent();
        program.setFileOpened(fileInfo.sourceFile.getUri(), 0, fileContent !== null && fileContent !== void 0 ? fileContent : '', {
            isTracked: fileInfo.isTracked,
            ipythonMode: fileInfo.sourceFile.getIPythonMode(),
            chainedFileUri: (_a = fileInfo.chainedSourceFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getUri(),
        });
    }
    const version = (_b = fileInfo.sourceFile.getClientVersion()) !== null && _b !== void 0 ? _b : 0;
    const fileUri = fileInfo.sourceFile.getUri();
    const filePath = fileUri.getFilePath();
    const sourceDoc = vscode_languageserver_textdocument_1.TextDocument.create(filePath, 'python', version, (_c = fileInfo.sourceFile.getOpenFileContents()) !== null && _c !== void 0 ? _c : '');
    program.setFileOpened(fileUri, version + 1, vscode_languageserver_textdocument_1.TextDocument.applyEdits(sourceDoc, edits), {
        isTracked: fileInfo.isTracked,
        ipythonMode: fileInfo.sourceFile.getIPythonMode(),
        chainedFileUri: (_d = fileInfo.chainedSourceFile) === null || _d === void 0 ? void 0 : _d.sourceFile.getUri(),
    });
}
exports.applyDocumentChanges = applyDocumentChanges;
function generateWorkspaceEdit(fs, originalService, clonedService, filesChanged) {
    var _a;
    // For now, we won't do text diff to find out minimal text changes. instead, we will
    // consider whole text of the files are changed. In future, we could consider
    // doing minimal changes using vscode's differ (https://github.com/microsoft/vscode/blob/main/src/vs/base/common/diff/diff.ts)
    // to support annotation.
    const edits = { changes: {} };
    for (const uri of filesChanged.values()) {
        const original = originalService.backgroundAnalysisProgram.program.getBoundSourceFile(uri);
        const final = clonedService.backgroundAnalysisProgram.program.getBoundSourceFile(uri);
        if (!original || !final) {
            // Both must exist.
            continue;
        }
        const parseResults = original.getParseResults();
        if (!parseResults) {
            continue;
        }
        edits.changes[(0, uriUtils_1.encodeUri)(fs, uri)] = [
            {
                range: (0, positionUtils_1.convertTextRangeToRange)(parseResults.parserOutput.parseTree, parseResults.tokenizerOutput.lines),
                newText: (_a = final.getFileContent()) !== null && _a !== void 0 ? _a : '',
            },
        ];
    }
    return edits;
}
exports.generateWorkspaceEdit = generateWorkspaceEdit;
function _convertToWorkspaceEditWithChanges(fs, edits) {
    const workspaceEdit = {
        changes: {},
    };
    appendToWorkspaceEdit(fs, edits, workspaceEdit);
    return workspaceEdit;
}
function _convertToWorkspaceEditWithDocumentChanges(fs, editActions, changeAnnotations, defaultAnnotationId = 'default') {
    const workspaceEdit = {
        documentChanges: [],
        changeAnnotations: changeAnnotations,
    };
    // Ordering of documentChanges are important.
    // Make sure create operation happens before edits.
    for (const operation of editActions.fileOperations) {
        switch (operation.kind) {
            case 'create':
                workspaceEdit.documentChanges.push(vscode_languageserver_1.CreateFile.create((0, uriUtils_1.encodeUri)(fs, operation.fileUri), /* options */ undefined, defaultAnnotationId));
                break;
            case 'rename':
            case 'delete':
                break;
            default:
                (0, debug_1.assertNever)(operation);
        }
    }
    // Text edit's file path must refer to original file paths unless it is a new file just created.
    const mapPerFile = (0, collectionUtils_1.createMapFromItems)(editActions.edits, (e) => (0, uriUtils_1.encodeUri)(fs, e.fileUri));
    for (const [uri, value] of mapPerFile) {
        workspaceEdit.documentChanges.push(vscode_languageserver_1.TextDocumentEdit.create({ uri: uri, version: null }, Array.from(value.map((v) => ({
            range: v.range,
            newText: v.replacementText,
            annotationId: defaultAnnotationId,
        })))));
    }
    for (const operation of editActions.fileOperations) {
        switch (operation.kind) {
            case 'create':
                break;
            case 'rename':
                workspaceEdit.documentChanges.push(vscode_languageserver_1.RenameFile.create((0, uriUtils_1.encodeUri)(fs, operation.oldFileUri), (0, uriUtils_1.encodeUri)(fs, operation.newFileUri), 
                /* options */ undefined, defaultAnnotationId));
                break;
            case 'delete':
                workspaceEdit.documentChanges.push(vscode_languageserver_1.DeleteFile.create((0, uriUtils_1.encodeUri)(fs, operation.fileUri), /* options */ undefined, defaultAnnotationId));
                break;
            default:
                (0, debug_1.assertNever)(operation);
        }
    }
    return workspaceEdit;
}


/***/ }),

/***/ "../pyright-internal/src/constants.ts":
/*!********************************************!*\
  !*** ../pyright-internal/src/constants.ts ***!
  \********************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.githubRepo = exports.toolName = void 0;
exports.toolName = 'basedpyright';
exports.githubRepo = `https://github.com/detachhead/${exports.toolName}`;


/***/ }),

/***/ "../pyright-internal/src/languageServerBase.ts":
/*!*****************************************************!*\
  !*** ../pyright-internal/src/languageServerBase.ts ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * languageServerBase.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements common language server functionality.
 * This is split out as a base class to allow for
 * different language server variants to be created
 * from the same core functionality.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LanguageServerBase = exports.VSDiagnosticRank = exports.VSDiagnosticTag = void 0;
__webpack_require__(/*! ./common/extensions */ "../pyright-internal/src/common/extensions.ts");
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const progress_1 = __webpack_require__(/*! vscode-languageserver/lib/common/progress */ "../pyright-internal/node_modules/vscode-languageserver/lib/common/progress.js");
const vscode_languageserver_textdocument_1 = __webpack_require__(/*! vscode-languageserver-textdocument */ "../pyright-internal/node_modules/vscode-languageserver-textdocument/lib/umd/main.js");
const backgroundAnalysisProgram_1 = __webpack_require__(/*! ./analyzer/backgroundAnalysisProgram */ "../pyright-internal/src/analyzer/backgroundAnalysisProgram.ts");
const service_1 = __webpack_require__(/*! ./analyzer/service */ "../pyright-internal/src/analyzer/service.ts");
const sourceFile_1 = __webpack_require__(/*! ./analyzer/sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const commandResult_1 = __webpack_require__(/*! ./commands/commandResult */ "../pyright-internal/src/commands/commandResult.ts");
const cancellationUtils_1 = __webpack_require__(/*! ./common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ./common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const commandLineOptions_1 = __webpack_require__(/*! ./common/commandLineOptions */ "../pyright-internal/src/common/commandLineOptions.ts");
const configOptions_1 = __webpack_require__(/*! ./common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ./common/console */ "../pyright-internal/src/common/console.ts");
const diagnostic_1 = __webpack_require__(/*! ./common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const lspUtils_1 = __webpack_require__(/*! ./common/lspUtils */ "../pyright-internal/src/common/lspUtils.ts");
const progressReporter_1 = __webpack_require__(/*! ./common/progressReporter */ "../pyright-internal/src/common/progressReporter.ts");
const serviceKeys_1 = __webpack_require__(/*! ./common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const uri_1 = __webpack_require__(/*! ./common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const analyzerServiceExecutor_1 = __webpack_require__(/*! ./languageService/analyzerServiceExecutor */ "../pyright-internal/src/languageService/analyzerServiceExecutor.ts");
const callHierarchyProvider_1 = __webpack_require__(/*! ./languageService/callHierarchyProvider */ "../pyright-internal/src/languageService/callHierarchyProvider.ts");
const inlayHintsProvider_1 = __webpack_require__(/*! ./languageService/inlayHintsProvider */ "../pyright-internal/src/languageService/inlayHintsProvider.ts");
const completionProvider_1 = __webpack_require__(/*! ./languageService/completionProvider */ "../pyright-internal/src/languageService/completionProvider.ts");
const definitionProvider_1 = __webpack_require__(/*! ./languageService/definitionProvider */ "../pyright-internal/src/languageService/definitionProvider.ts");
const documentHighlightProvider_1 = __webpack_require__(/*! ./languageService/documentHighlightProvider */ "../pyright-internal/src/languageService/documentHighlightProvider.ts");
const documentSymbolProvider_1 = __webpack_require__(/*! ./languageService/documentSymbolProvider */ "../pyright-internal/src/languageService/documentSymbolProvider.ts");
const hoverProvider_1 = __webpack_require__(/*! ./languageService/hoverProvider */ "../pyright-internal/src/languageService/hoverProvider.ts");
const navigationUtils_1 = __webpack_require__(/*! ./languageService/navigationUtils */ "../pyright-internal/src/languageService/navigationUtils.ts");
const referencesProvider_1 = __webpack_require__(/*! ./languageService/referencesProvider */ "../pyright-internal/src/languageService/referencesProvider.ts");
const renameProvider_1 = __webpack_require__(/*! ./languageService/renameProvider */ "../pyright-internal/src/languageService/renameProvider.ts");
const signatureHelpProvider_1 = __webpack_require__(/*! ./languageService/signatureHelpProvider */ "../pyright-internal/src/languageService/signatureHelpProvider.ts");
const workspaceSymbolProvider_1 = __webpack_require__(/*! ./languageService/workspaceSymbolProvider */ "../pyright-internal/src/languageService/workspaceSymbolProvider.ts");
const localize_1 = __webpack_require__(/*! ./localization/localize */ "../pyright-internal/src/localization/localize.ts");
const workspaceFactory_1 = __webpack_require__(/*! ./workspaceFactory */ "../pyright-internal/src/workspaceFactory.ts");
const constants_1 = __webpack_require__(/*! ./constants */ "../pyright-internal/src/constants.ts");
const semanticTokensProvider_1 = __webpack_require__(/*! ./languageService/semanticTokensProvider */ "../pyright-internal/src/languageService/semanticTokensProvider.ts");
const nullProgressReporter = (0, progress_1.attachWorkDone)(undefined, /* params */ undefined);
/*
 * Additional DiagnosticTag values that are specific to Visual Studio.
 * These must match the values in https://dev.azure.com/devdiv/DevDiv/_git/vslanguageserverclient?path=%2Fsrc%2Fproduct%2FProtocol%2FLanguageServer.Protocol.Extensions%2FVSDiagnosticTags.cs&version=GBdevelop&_a=contents
 */
var VSDiagnosticTag;
(function (VSDiagnosticTag) {
    /**
     * A diagnostic entry generated by the build.
     */
    VSDiagnosticTag.BuildError = -1;
    /**
     * A diagnostic entry generated by Intellisense.
     */
    VSDiagnosticTag.IntellisenseError = -2;
    /**
     * A diagnostic entry that could be generated from both builds and Intellisense.
     *
     * Diagnostic entries tagged with PotentialDuplicate will be hidden
     * in the error list if the error list is displaying build and intellisense errors.
     */
    VSDiagnosticTag.PotentialDuplicate = -3;
    /**
     * A diagnostic entry that is never displayed in the error list.
     */
    VSDiagnosticTag.HiddenInErrorList = -4;
    /**
     * A diagnostic entry that is always displayed in the error list.
     */
    VSDiagnosticTag.VisibleInErrorList = -5;
    /**
     * A diagnostic entry that is never displayed in the editor.
     */
    VSDiagnosticTag.HiddenInEditor = -6;
    /**
     * No tooltip is shown for the Diagnostic entry in the editor.
     */
    VSDiagnosticTag.SuppressEditorToolTip = -7;
    /**
     * A diagnostic entry that is represented in the editor as an Edit and Continue error.
     */
    VSDiagnosticTag.EditAndContinueError = -8;
    /**
     * A diagnostic entry that is represented in the editor as a Task List item (View -> Task List)
     */
    VSDiagnosticTag.TaskItem = -9;
})(VSDiagnosticTag || (exports.VSDiagnosticTag = VSDiagnosticTag = {}));
/*
 * DiagnosticRank values that are specific to Visual Studio.
 * These must match the values in https://dev.azure.com/devdiv/DevDiv/_git/vslanguageserverclient?path=/src/product/Protocol/LanguageServer.Protocol.Extensions/VSDiagnosticRank.cs&version=GBdevelop&_a=contents
 */
var VSDiagnosticRank;
(function (VSDiagnosticRank) {
    VSDiagnosticRank.Highest = 100;
    VSDiagnosticRank.High = 200;
    VSDiagnosticRank.Default = 300;
    VSDiagnosticRank.Low = 400;
    VSDiagnosticRank.Lowest = 500;
})(VSDiagnosticRank || (exports.VSDiagnosticRank = VSDiagnosticRank = {}));
class LanguageServerBase {
    constructor(serverOptions, connection) {
        var _a, _b;
        this.serverOptions = serverOptions;
        this.connection = connection;
        this._lastTriggerKind = vscode_languageserver_1.CompletionTriggerKind.Invoked;
        this._initialized = false;
        this.client = {
            hasConfigurationCapability: false,
            hasVisualStudioExtensionsCapability: false,
            hasWorkspaceFoldersCapability: false,
            hasWatchFileCapability: false,
            hasWatchFileRelativePathCapability: false,
            hasActiveParameterCapability: false,
            hasSignatureLabelOffsetCapability: false,
            hasHierarchicalDocumentSymbolCapability: false,
            hasWindowProgressCapability: false,
            hasGoToDeclarationCapability: false,
            hasDocumentChangeCapability: false,
            hasDocumentAnnotationCapability: false,
            hasCompletionCommitCharCapability: false,
            hoverContentFormat: vscode_languageserver_1.MarkupKind.PlainText,
            completionDocFormat: vscode_languageserver_1.MarkupKind.PlainText,
            completionSupportsSnippet: false,
            signatureDocFormat: vscode_languageserver_1.MarkupKind.PlainText,
            supportsDeprecatedDiagnosticTag: false,
            supportsUnnecessaryDiagnosticTag: false,
            supportsTaskItemDiagnosticTag: false,
            completionItemResolveSupportsAdditionalTextEdits: false,
        };
        this.openFileMap = new Map();
        // The URIs for which diagnostics are reported
        this.documentsWithDiagnostics = new Set();
        // Stash the base directory into a global variable.
        // This must happen before fs.getModulePath().
        global.__rootDirectory = serverOptions.rootDirectory.getFilePath();
        this.console.info(`${serverOptions.productName} language server ${serverOptions.version && serverOptions.version + ' '}starting`);
        this.console.info(`Server root directory: ${serverOptions.rootDirectory}`);
        this.fs = this.serverOptions.serviceProvider.fs();
        this.caseSensitiveDetector = this.serverOptions.serviceProvider.get(serviceKeys_1.ServiceKeys.caseSensitivityDetector);
        this.workspaceFactory = new workspaceFactory_1.WorkspaceFactory(this.console, 
        /* isWeb */ false, this.createAnalyzerServiceForWorkspace.bind(this), this.isPythonPathImmutable.bind(this), this.onWorkspaceCreated.bind(this), this.onWorkspaceRemoved.bind(this), this.serviceProvider);
        // Set the working directory to a known location within
        // the extension directory. Otherwise the execution of
        // python can have unintended and surprising results.
        const moduleDirectory = this.fs.getModulePath();
        if (moduleDirectory && this.fs.existsSync(moduleDirectory)) {
            this.fs.chdir(moduleDirectory);
        }
        // Set up callbacks.
        this.setupConnection((_a = serverOptions.supportedCommands) !== null && _a !== void 0 ? _a : [], (_b = serverOptions.supportedCodeActions) !== null && _b !== void 0 ? _b : []);
        this._progressReporter = new progressReporter_1.ProgressReportTracker(this.createProgressReporter());
        // Listen on the connection.
        this.connection.listen();
    }
    get console() {
        return this.serverOptions.serviceProvider.console();
    }
    // Provides access to the client's window.
    get window() {
        return this.connection.window;
    }
    get supportAdvancedEdits() {
        return this.client.hasDocumentChangeCapability && this.client.hasDocumentAnnotationCapability;
    }
    get serviceProvider() {
        return this.serverOptions.serviceProvider;
    }
    dispose() {
        var _a;
        this.workspaceFactory.clear();
        this.openFileMap.clear();
        (_a = this._workspaceFoldersChangedDisposable) === null || _a === void 0 ? void 0 : _a.dispose();
    }
    // Creates a service instance that's used for analyzing a
    // program within a workspace.
    createAnalyzerService(name, services, libraryReanalysisTimeProvider) {
        var _a;
        this.console.info(`Starting service instance "${name}"`);
        const serviceId = (0, service_1.getNextServiceId)(name);
        const service = new service_1.AnalyzerService(name, this.serverOptions.serviceProvider, {
            console: this.console,
            hostFactory: this.createHost.bind(this),
            importResolverFactory: this.createImportResolver.bind(this),
            backgroundAnalysis: services ? services.backgroundAnalysis : this.createBackgroundAnalysis(serviceId),
            maxAnalysisTime: this.serverOptions.maxAnalysisTimeInForeground,
            backgroundAnalysisProgramFactory: this.createBackgroundAnalysisProgram.bind(this),
            cancellationProvider: this.serverOptions.cancellationProvider,
            libraryReanalysisTimeProvider,
            serviceId,
            fileSystem: (_a = services === null || services === void 0 ? void 0 : services.fs) !== null && _a !== void 0 ? _a : this.serverOptions.serviceProvider.fs(),
        });
        service.setCompletionCallback((results) => this.onAnalysisCompletedHandler(service.fs, results));
        return service;
    }
    async getWorkspaces() {
        const workspaces = [...this.workspaceFactory.items()];
        for (const workspace of workspaces) {
            await workspace.isInitialized.promise;
        }
        return workspaces;
    }
    async getWorkspaceForFile(fileUri, pythonPath) {
        return this.workspaceFactory.getWorkspaceForFile(fileUri, pythonPath);
    }
    async getContainingWorkspacesForFile(fileUri) {
        return this.workspaceFactory.getContainingWorkspacesForFile(fileUri);
    }
    reanalyze() {
        this.workspaceFactory.items().forEach((workspace) => {
            workspace.service.invalidateAndForceReanalysis(backgroundAnalysisProgram_1.InvalidatedReason.Reanalyzed);
        });
    }
    restart() {
        this.workspaceFactory.items().forEach((workspace) => {
            workspace.service.restart();
        });
    }
    updateSettingsForAllWorkspaces() {
        const tasks = [];
        this.workspaceFactory.items().forEach((workspace) => {
            // Updating settings can change workspace's file ownership. Make workspace uninitialized so that
            // features can wait until workspace gets new settings.
            // the file's ownership can also changed by `pyrightconfig.json` changes, but those are synchronous
            // operation, so it won't affect this.
            workspace.isInitialized = workspace.isInitialized.reset();
            tasks.push(this.updateSettingsForWorkspace(workspace, workspace.isInitialized));
        });
        Promise.all(tasks).then(() => {
            this._setupFileWatcher();
        });
    }
    async updateSettingsForWorkspace(workspace, status, serverSettings) {
        var _a;
        status === null || status === void 0 ? void 0 : status.markCalled();
        serverSettings = serverSettings !== null && serverSettings !== void 0 ? serverSettings : (await this.getSettings(workspace));
        // Set logging level first.
        this.console.level = (_a = serverSettings.logLevel) !== null && _a !== void 0 ? _a : console_1.LogLevel.Info;
        // Apply the new path to the workspace (before restarting the service).
        serverSettings.pythonPath = this.workspaceFactory.applyPythonPath(workspace, serverSettings.pythonPath ? serverSettings.pythonPath : undefined);
        // Then use the updated settings to restart the service.
        this.updateOptionsAndRestartService(workspace, serverSettings);
        workspace.disableLanguageServices = !!serverSettings.disableLanguageServices;
        workspace.disableTaggedHints = !!serverSettings.disableTaggedHints;
        workspace.disableOrganizeImports = !!serverSettings.disableOrganizeImports;
        // Don't use workspace.isInitialized directly since it might have been
        // reset due to pending config change event.
        // The workspace is now open for business.
        status === null || status === void 0 ? void 0 : status.resolve();
    }
    updateOptionsAndRestartService(workspace, serverSettings, typeStubTargetImportName) {
        var _a;
        analyzerServiceExecutor_1.AnalyzerServiceExecutor.runWithOptions(workspace, serverSettings, typeStubTargetImportName);
        workspace.searchPathsToWatch = (_a = workspace.service.librarySearchUrisToWatch) !== null && _a !== void 0 ? _a : [];
    }
    isPythonPathImmutable(fileUri) {
        // This function is called to determine if the file is using
        // a special pythonPath separate from a workspace or not.
        // The default is no.
        return false;
    }
    async getConfiguration(scopeUri, section) {
        if (this.client.hasConfigurationCapability) {
            const item = {};
            if (scopeUri !== undefined) {
                item.scopeUri = scopeUri.toString();
            }
            if (section !== undefined) {
                item.section = section;
            }
            return this.connection.workspace.getConfiguration(item);
        }
        if (this.defaultClientConfig) {
            return (0, collectionUtils_1.getNestedProperty)(this.defaultClientConfig, section);
        }
        return undefined;
    }
    isOpenFilesOnly(diagnosticMode) {
        return diagnosticMode !== 'workspace';
    }
    getSeverityOverrides(value) {
        const enumValue = (0, configOptions_1.parseDiagLevel)(value);
        if (!enumValue) {
            return undefined;
        }
        if ((0, commandLineOptions_1.getDiagnosticSeverityOverrides)().includes(enumValue)) {
            return enumValue;
        }
        return undefined;
    }
    getDiagnosticRuleName(value) {
        const enumValue = value;
        if ((0, configOptions_1.getDiagLevelDiagnosticRules)().includes(enumValue)) {
            return enumValue;
        }
        return undefined;
    }
    createBackgroundAnalysisProgram(serviceId, serviceProvider, configOptions, importResolver, backgroundAnalysis, maxAnalysisTime) {
        return new backgroundAnalysisProgram_1.BackgroundAnalysisProgram(serviceId, serviceProvider, configOptions, importResolver, backgroundAnalysis, maxAnalysisTime, 
        /* disableChecker */ undefined);
    }
    setupConnection(supportedCommands, supportedCodeActions) {
        // After the server has started the client sends an initialize request. The server receives
        // in the passed params the rootPath of the workspace plus the client capabilities.
        this.connection.onInitialize((params) => this.initialize(params, supportedCommands, supportedCodeActions));
        this.connection.onInitialized(() => this.onInitialized());
        this.connection.onDidChangeConfiguration((params) => this.onDidChangeConfiguration(params));
        this.connection.onCodeAction((params, token) => this.executeCodeAction(params, token));
        this.connection.onDefinition(async (params, token) => this.onDefinition(params, token));
        this.connection.onDeclaration(async (params, token) => this.onDeclaration(params, token));
        this.connection.onTypeDefinition(async (params, token) => this.onTypeDefinition(params, token));
        this.connection.onReferences(async (params, token, workDoneReporter, resultReporter) => this.onReferences(params, token, workDoneReporter, resultReporter));
        this.connection.onDocumentSymbol(async (params, token) => this.onDocumentSymbol(params, token));
        this.connection.onWorkspaceSymbol(async (params, token, _, resultReporter) => this.onWorkspaceSymbol(params, token, resultReporter));
        this.connection.onHover(async (params, token) => this.onHover(params, token));
        this.connection.onDocumentHighlight(async (params, token) => this.onDocumentHighlight(params, token));
        this.connection.onSignatureHelp(async (params, token) => this.onSignatureHelp(params, token));
        this.connection.onCompletion((params, token) => this.onCompletion(params, token));
        this.connection.onCompletionResolve(async (params, token) => this.onCompletionResolve(params, token));
        this.connection.onPrepareRename(async (params, token) => this.onPrepareRenameRequest(params, token));
        this.connection.onRenameRequest(async (params, token) => this.onRenameRequest(params, token));
        const callHierarchy = this.connection.languages.callHierarchy;
        callHierarchy.onPrepare(async (params, token) => this.onCallHierarchyPrepare(params, token));
        callHierarchy.onIncomingCalls(async (params, token) => this.onCallHierarchyIncomingCalls(params, token));
        callHierarchy.onOutgoingCalls(async (params, token) => this.onCallHierarchyOutgoingCalls(params, token));
        const inlayHints = this.connection.languages.inlayHint;
        inlayHints.on(async (params, token) => this.onInlayHints(params, token));
        const semanticTokens = this.connection.languages.semanticTokens;
        semanticTokens.on(async (params, token) => this.onSemanticTokens(params, token));
        this.connection.onDidOpenTextDocument(async (params) => this.onDidOpenTextDocument(params));
        this.connection.onDidChangeTextDocument(async (params) => this.onDidChangeTextDocument(params));
        this.connection.onDidCloseTextDocument(async (params) => this.onDidCloseTextDocument(params));
        this.connection.onDidChangeWatchedFiles((params) => this.onDidChangeWatchedFiles(params));
        this.connection.onExecuteCommand(async (params, token, reporter) => this.onExecuteCommand(params, token, reporter));
        this.connection.onShutdown(async (token) => this.onShutdown(token));
    }
    initialize(params, supportedCommands, supportedCodeActions) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19;
        if (params.locale) {
            (0, localize_1.setLocaleOverride)(params.locale);
        }
        const capabilities = params.capabilities;
        this.client.hasConfigurationCapability = !!((_a = capabilities.workspace) === null || _a === void 0 ? void 0 : _a.configuration);
        this.client.hasWatchFileCapability = !!((_c = (_b = capabilities.workspace) === null || _b === void 0 ? void 0 : _b.didChangeWatchedFiles) === null || _c === void 0 ? void 0 : _c.dynamicRegistration);
        this.client.hasWatchFileRelativePathCapability =
            !!((_e = (_d = capabilities.workspace) === null || _d === void 0 ? void 0 : _d.didChangeWatchedFiles) === null || _e === void 0 ? void 0 : _e.relativePatternSupport);
        this.client.hasWorkspaceFoldersCapability = !!((_f = capabilities.workspace) === null || _f === void 0 ? void 0 : _f.workspaceFolders);
        this.client.hasVisualStudioExtensionsCapability = !!capabilities._vs_supportsVisualStudioExtensions;
        this.client.hasActiveParameterCapability =
            !!((_j = (_h = (_g = capabilities.textDocument) === null || _g === void 0 ? void 0 : _g.signatureHelp) === null || _h === void 0 ? void 0 : _h.signatureInformation) === null || _j === void 0 ? void 0 : _j.activeParameterSupport);
        this.client.hasSignatureLabelOffsetCapability =
            !!((_o = (_m = (_l = (_k = capabilities.textDocument) === null || _k === void 0 ? void 0 : _k.signatureHelp) === null || _l === void 0 ? void 0 : _l.signatureInformation) === null || _m === void 0 ? void 0 : _m.parameterInformation) === null || _o === void 0 ? void 0 : _o.labelOffsetSupport);
        this.client.hasHierarchicalDocumentSymbolCapability =
            !!((_q = (_p = capabilities.textDocument) === null || _p === void 0 ? void 0 : _p.documentSymbol) === null || _q === void 0 ? void 0 : _q.hierarchicalDocumentSymbolSupport);
        this.client.hasDocumentChangeCapability =
            !!((_s = (_r = capabilities.workspace) === null || _r === void 0 ? void 0 : _r.workspaceEdit) === null || _s === void 0 ? void 0 : _s.documentChanges) &&
                !!((_t = capabilities.workspace.workspaceEdit) === null || _t === void 0 ? void 0 : _t.resourceOperations);
        this.client.hasDocumentAnnotationCapability = !!((_v = (_u = capabilities.workspace) === null || _u === void 0 ? void 0 : _u.workspaceEdit) === null || _v === void 0 ? void 0 : _v.changeAnnotationSupport);
        this.client.hasCompletionCommitCharCapability =
            !!((_y = (_x = (_w = capabilities.textDocument) === null || _w === void 0 ? void 0 : _w.completion) === null || _x === void 0 ? void 0 : _x.completionList) === null || _y === void 0 ? void 0 : _y.itemDefaults) &&
                !!((_z = capabilities.textDocument.completion.completionItem) === null || _z === void 0 ? void 0 : _z.commitCharactersSupport);
        this.client.hoverContentFormat = this._getCompatibleMarkupKind((_1 = (_0 = capabilities.textDocument) === null || _0 === void 0 ? void 0 : _0.hover) === null || _1 === void 0 ? void 0 : _1.contentFormat);
        this.client.completionDocFormat = this._getCompatibleMarkupKind((_4 = (_3 = (_2 = capabilities.textDocument) === null || _2 === void 0 ? void 0 : _2.completion) === null || _3 === void 0 ? void 0 : _3.completionItem) === null || _4 === void 0 ? void 0 : _4.documentationFormat);
        this.client.completionSupportsSnippet = !!((_7 = (_6 = (_5 = capabilities.textDocument) === null || _5 === void 0 ? void 0 : _5.completion) === null || _6 === void 0 ? void 0 : _6.completionItem) === null || _7 === void 0 ? void 0 : _7.snippetSupport);
        this.client.signatureDocFormat = this._getCompatibleMarkupKind((_10 = (_9 = (_8 = capabilities.textDocument) === null || _8 === void 0 ? void 0 : _8.signatureHelp) === null || _9 === void 0 ? void 0 : _9.signatureInformation) === null || _10 === void 0 ? void 0 : _10.documentationFormat);
        const supportedDiagnosticTags = ((_13 = (_12 = (_11 = capabilities.textDocument) === null || _11 === void 0 ? void 0 : _11.publishDiagnostics) === null || _12 === void 0 ? void 0 : _12.tagSupport) === null || _13 === void 0 ? void 0 : _13.valueSet) || [];
        this.client.supportsUnnecessaryDiagnosticTag = supportedDiagnosticTags.some((tag) => tag === vscode_languageserver_1.DiagnosticTag.Unnecessary);
        this.client.supportsDeprecatedDiagnosticTag = supportedDiagnosticTags.some((tag) => tag === vscode_languageserver_1.DiagnosticTag.Deprecated);
        // if the client is running in VS, it always supports task item diagnostics
        this.client.supportsTaskItemDiagnosticTag = this.client.hasVisualStudioExtensionsCapability;
        this.client.hasWindowProgressCapability = !!((_14 = capabilities.window) === null || _14 === void 0 ? void 0 : _14.workDoneProgress);
        this.client.hasGoToDeclarationCapability = !!((_15 = capabilities.textDocument) === null || _15 === void 0 ? void 0 : _15.declaration);
        this.client.completionItemResolveSupportsAdditionalTextEdits =
            !!((_19 = (_18 = (_17 = (_16 = capabilities.textDocument) === null || _16 === void 0 ? void 0 : _16.completion) === null || _17 === void 0 ? void 0 : _17.completionItem) === null || _18 === void 0 ? void 0 : _18.resolveSupport) === null || _19 === void 0 ? void 0 : _19.properties.some((p) => p === 'additionalTextEdits'));
        // Create a service instance for each of the workspace folders.
        this.workspaceFactory.handleInitialize(params);
        const result = {
            capabilities: {
                textDocumentSync: vscode_languageserver_1.TextDocumentSyncKind.Incremental,
                definitionProvider: { workDoneProgress: true },
                declarationProvider: { workDoneProgress: true },
                typeDefinitionProvider: { workDoneProgress: true },
                referencesProvider: { workDoneProgress: true },
                documentSymbolProvider: { workDoneProgress: true },
                workspaceSymbolProvider: { workDoneProgress: true },
                hoverProvider: { workDoneProgress: true },
                documentHighlightProvider: { workDoneProgress: true },
                renameProvider: { prepareProvider: true, workDoneProgress: true },
                completionProvider: {
                    triggerCharacters: this.client.hasVisualStudioExtensionsCapability
                        ? ['.', '[', '@', '"', "'"]
                        : ['.', '[', '"', "'"],
                    resolveProvider: true,
                    workDoneProgress: true,
                    completionItem: {
                        labelDetailsSupport: true,
                    },
                },
                signatureHelpProvider: {
                    triggerCharacters: ['(', ',', ')'],
                    workDoneProgress: true,
                },
                codeActionProvider: {
                    codeActionKinds: supportedCodeActions,
                    workDoneProgress: true,
                },
                executeCommandProvider: {
                    commands: supportedCommands,
                    workDoneProgress: true,
                },
                callHierarchyProvider: true,
                inlayHintProvider: true,
                semanticTokensProvider: {
                    legend: semanticTokensProvider_1.SemanticTokensProviderLegend,
                    full: true,
                },
                workspace: {
                    workspaceFolders: {
                        supported: true,
                        changeNotifications: true,
                    },
                },
            },
        };
        return result;
    }
    onInitialized() {
        // Mark as initialized. We need this to make sure to
        // not send config updates before this point.
        this._initialized = true;
        if (!this.client.hasWorkspaceFoldersCapability) {
            // If folder capability is not supported, initialize ones given by onInitialize.
            this.updateSettingsForAllWorkspaces();
            return;
        }
        this._workspaceFoldersChangedDisposable = this.connection.workspace.onDidChangeWorkspaceFolders((event) => {
            this.workspaceFactory.handleWorkspaceFoldersChanged(event);
            this._setupFileWatcher();
        });
        this._setupFileWatcher();
    }
    onDidChangeConfiguration(params) {
        this.console.log(`Received updated settings`);
        if (params === null || params === void 0 ? void 0 : params.settings) {
            this.defaultClientConfig = params === null || params === void 0 ? void 0 : params.settings;
        }
        this.updateSettingsForAllWorkspaces();
    }
    async onDefinition(params, token) {
        return this.getDefinitions(params, token, this.client.hasGoToDeclarationCapability ? definitionProvider_1.DefinitionFilter.PreferSource : definitionProvider_1.DefinitionFilter.All, (workspace, filePath, position, filter, token) => workspace.service.run((program) => {
            return new definitionProvider_1.DefinitionProvider(program, filePath, position, filter, token).getDefinitions();
        }, token));
    }
    async onDeclaration(params, token) {
        return this.getDefinitions(params, token, this.client.hasGoToDeclarationCapability ? definitionProvider_1.DefinitionFilter.PreferStubs : definitionProvider_1.DefinitionFilter.All, (workspace, filePath, position, filter, token) => workspace.service.run((program) => {
            return new definitionProvider_1.DefinitionProvider(program, filePath, position, filter, token).getDefinitions();
        }, token));
    }
    async onTypeDefinition(params, token) {
        return this.getDefinitions(params, token, definitionProvider_1.DefinitionFilter.All, (workspace, filePath, position, _, token) => workspace.service.run((program) => {
            return new definitionProvider_1.TypeDefinitionProvider(program, filePath, position, token).getDefinitions();
        }, token));
    }
    async getDefinitions(params, token, filter, getDefinitionsFunc) {
        this.recordUserInteractionTime();
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return undefined;
        }
        const locations = getDefinitionsFunc(workspace, uri, params.position, filter, token);
        if (!locations) {
            return undefined;
        }
        return locations
            .filter((loc) => this.canNavigateToFile(loc.uri, workspace.service.fs))
            .map((loc) => vscode_languageserver_1.Location.create((0, uriUtils_1.encodeUri)(workspace.service.fs, loc.uri), loc.range));
    }
    async onReferences(params, token, workDoneReporter, resultReporter, createDocumentRange, convertToLocation) {
        if (this._pendingFindAllRefsCancellationSource) {
            this._pendingFindAllRefsCancellationSource.cancel();
            this._pendingFindAllRefsCancellationSource = undefined;
        }
        // VS Code doesn't support cancellation of "find all references".
        // We provide a progress bar a cancellation button so the user can cancel
        // any long-running actions.
        const progress = await this.getProgressReporter(workDoneReporter, localize_1.Localizer.CodeAction.findingReferences(), token);
        const source = progress.source;
        this._pendingFindAllRefsCancellationSource = source;
        try {
            const uri = this.decodeUri(params.textDocument.uri);
            const workspace = await this.getWorkspaceForFile(uri);
            if (workspace.disableLanguageServices) {
                return;
            }
            return workspace.service.run((program) => {
                return new referencesProvider_1.ReferencesProvider(program, source.token, createDocumentRange, convertToLocation).reportReferences(uri, params.position, params.context.includeDeclaration, resultReporter);
            }, token);
        }
        finally {
            progress.reporter.done();
            source.dispose();
        }
    }
    async onDocumentSymbol(params, token) {
        this.recordUserInteractionTime();
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return undefined;
        }
        return workspace.service.run((program) => {
            return new documentSymbolProvider_1.DocumentSymbolProvider(program, uri, this.client.hasHierarchicalDocumentSymbolCapability, { includeAliases: false }, token).getSymbols();
        }, token);
    }
    onWorkspaceSymbol(params, token, resultReporter) {
        const result = new workspaceSymbolProvider_1.WorkspaceSymbolProvider(this.workspaceFactory.items(), resultReporter, params.query, token).reportSymbols();
        return Promise.resolve(result);
    }
    async onHover(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return;
        }
        return workspace.service.run((program) => {
            return new hoverProvider_1.HoverProvider(program, uri, params.position, this.client.hoverContentFormat, token).getHover();
        }, token);
    }
    async onDocumentHighlight(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        return workspace.service.run((program) => {
            return new documentHighlightProvider_1.DocumentHighlightProvider(program, uri, params.position, token).getDocumentHighlight();
        }, token);
    }
    async onSignatureHelp(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return;
        }
        return workspace.service.run((program) => {
            return new signatureHelpProvider_1.SignatureHelpProvider(program, uri, params.position, this.client.signatureDocFormat, this.client.hasSignatureLabelOffsetCapability, this.client.hasActiveParameterCapability, params.context, token).getSignatureHelp();
        }, token);
    }
    setCompletionIncomplete(params, completions) {
        var _a, _b;
        // We set completion incomplete for the first invocation and next consecutive call,
        // but after that we mark it as completed so the client doesn't repeatedly call back.
        // We mark the first one as incomplete because completion could be invoked without
        // any meaningful character provided, such as an explicit completion invocation (ctrl+space)
        // or a period. That might cause us to not include some items (e.g., auto-imports).
        // The next consecutive call provides some characters to help us to pick
        // better completion items. After that, we are not going to introduce new items,
        // so we can let the client to do the filtering and caching.
        const completionIncomplete = this._lastTriggerKind !== vscode_languageserver_1.CompletionTriggerKind.TriggerForIncompleteCompletions ||
            ((_a = params.context) === null || _a === void 0 ? void 0 : _a.triggerKind) !== vscode_languageserver_1.CompletionTriggerKind.TriggerForIncompleteCompletions;
        this._lastTriggerKind = (_b = params.context) === null || _b === void 0 ? void 0 : _b.triggerKind;
        if (completions) {
            completions.isIncomplete = completionIncomplete;
        }
    }
    async onCompletion(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            var _a;
            const completions = new completionProvider_1.CompletionProvider(program, uri, params.position, {
                format: this.client.completionDocFormat,
                snippet: this.client.completionSupportsSnippet,
                lazyEdit: false,
                triggerCharacter: (_a = params === null || params === void 0 ? void 0 : params.context) === null || _a === void 0 ? void 0 : _a.triggerCharacter,
            }, token).getCompletions();
            this.setCompletionIncomplete(params, completions);
            return completions;
        }, token);
    }
    // Cancellation bugs in vscode and LSP:
    // https://github.com/microsoft/vscode-languageserver-node/issues/615
    // https://github.com/microsoft/vscode/issues/95485
    //
    // If resolver throws cancellation exception, LSP and VSCode
    // cache that result and never call us back.
    async onCompletionResolve(params, token) {
        const completionItemData = (0, lspUtils_1.fromLSPAny)(params.data);
        if (completionItemData && completionItemData.uri) {
            const uri = this.decodeUri(completionItemData.uri);
            const workspace = await this.getWorkspaceForFile(uri);
            workspace.service.run((program) => {
                return new completionProvider_1.CompletionProvider(program, uri, completionItemData.position, {
                    format: this.client.completionDocFormat,
                    snippet: this.client.completionSupportsSnippet,
                    lazyEdit: false,
                }, token).resolveCompletionItem(params);
            }, token);
        }
        return params;
    }
    async onPrepareRenameRequest(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const isUntitled = uri.isUntitled();
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            return new renameProvider_1.RenameProvider(program, uri, params.position, token).canRenameSymbol(workspace.kinds.includes(workspaceFactory_1.WellKnownWorkspaceKinds.Default), isUntitled);
        }, token);
    }
    async onRenameRequest(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const isUntitled = uri.isUntitled();
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return;
        }
        return workspace.service.run((program) => {
            return new renameProvider_1.RenameProvider(program, uri, params.position, token).renameSymbol(params.newName, workspace.kinds.includes(workspaceFactory_1.WellKnownWorkspaceKinds.Default), isUntitled);
        }, token);
    }
    async onInlayHints(params, token) {
        const uri = uri_1.Uri.parse(params.textDocument.uri, this.serviceProvider);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            return new inlayHintsProvider_1.InlayHintsProvider(program, uri, params.range).onInlayHints();
        }, token);
    }
    async onSemanticTokens(params, token) {
        const uri = uri_1.Uri.parse(params.textDocument.uri, this.serviceProvider);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return {
                resultId: undefined,
                data: [],
            };
        }
        return workspace.service.run((program) => {
            return new semanticTokensProvider_1.SemanticTokensProvider(program, uri, token).onSemanticTokens();
        }, token);
    }
    async onCallHierarchyPrepare(params, token) {
        const uri = this.decodeUri(params.textDocument.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            return new callHierarchyProvider_1.CallHierarchyProvider(program, uri, params.position, token).onPrepare();
        }, token);
    }
    async onCallHierarchyIncomingCalls(params, token) {
        const uri = this.decodeUri(params.item.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            return new callHierarchyProvider_1.CallHierarchyProvider(program, uri, params.item.range.start, token).getIncomingCalls();
        }, token);
    }
    async onCallHierarchyOutgoingCalls(params, token) {
        const uri = this.decodeUri(params.item.uri);
        const workspace = await this.getWorkspaceForFile(uri);
        if (workspace.disableLanguageServices) {
            return null;
        }
        return workspace.service.run((program) => {
            return new callHierarchyProvider_1.CallHierarchyProvider(program, uri, params.item.range.start, token).getOutgoingCalls();
        }, token);
    }
    async onDidOpenTextDocument(params, ipythonMode = sourceFile_1.IPythonMode.None) {
        const uri = this.decodeUri(params.textDocument.uri);
        let doc = this.openFileMap.get(uri.key);
        if (doc) {
            // We shouldn't get an open text document request for an already-opened doc.
            this.console.error(`Received redundant open text document command for ${uri}`);
            vscode_languageserver_textdocument_1.TextDocument.update(doc, [{ text: params.textDocument.text }], params.textDocument.version);
        }
        else {
            doc = vscode_languageserver_textdocument_1.TextDocument.create(params.textDocument.uri, 'python', params.textDocument.version, params.textDocument.text);
        }
        this.openFileMap.set(uri.key, doc);
        // Send this open to all the workspaces that might contain this file.
        const workspaces = await this.getContainingWorkspacesForFile(uri);
        workspaces.forEach((w) => {
            w.service.setFileOpened(uri, params.textDocument.version, params.textDocument.text, ipythonMode);
        });
    }
    async onDidChangeTextDocument(params, ipythonMode = sourceFile_1.IPythonMode.None) {
        this.recordUserInteractionTime();
        const uri = this.decodeUri(params.textDocument.uri);
        const doc = this.openFileMap.get(uri.key);
        if (!doc) {
            // We shouldn't get a change text request for a closed doc.
            this.console.error(`Received change text document command for closed file ${uri}`);
            return;
        }
        vscode_languageserver_textdocument_1.TextDocument.update(doc, params.contentChanges, params.textDocument.version);
        const newContents = doc.getText();
        // Send this change to all the workspaces that might contain this file.
        const workspaces = await this.getContainingWorkspacesForFile(uri);
        workspaces.forEach((w) => {
            w.service.updateOpenFileContents(uri, params.textDocument.version, newContents, ipythonMode);
        });
    }
    async onDidCloseTextDocument(params) {
        const uri = this.decodeUri(params.textDocument.uri);
        // Send this close to all the workspaces that might contain this file.
        const workspaces = await this.getContainingWorkspacesForFile(uri);
        workspaces.forEach((w) => {
            w.service.setFileClosed(uri);
        });
        this.openFileMap.delete(uri.key);
    }
    onDidChangeWatchedFiles(params) {
        params.changes.forEach((change) => {
            const filePath = this.fs.realCasePath(this.decodeUri(change.uri));
            const eventType = change.type === 1 ? 'add' : 'change';
            this.serverOptions.fileWatcherHandler.onFileChange(eventType, filePath);
        });
    }
    async onExecuteCommand(params, token, reporter) {
        // Cancel running command if there is one.
        if (this._pendingCommandCancellationSource) {
            this._pendingCommandCancellationSource.cancel();
            this._pendingCommandCancellationSource = undefined;
        }
        const executeCommand = async (token) => {
            const result = await this.executeCommand(params, token);
            if (vscode_languageserver_1.WorkspaceEdit.is(result)) {
                // Tell client to apply edits.
                // Do not await; the client isn't expecting a result.
                this.connection.workspace.applyEdit({
                    label: `Command '${params.command}'`,
                    edit: result,
                    metadata: { isRefactoring: this.isRefactoringCommand(params.command) },
                });
            }
            if (commandResult_1.CommandResult.is(result)) {
                // Tell client to apply edits.
                // Await so that we return after the edit is complete.
                await this.connection.workspace.applyEdit({
                    label: result.label,
                    edit: result.edits,
                    metadata: { isRefactoring: this.isRefactoringCommand(params.command) },
                });
            }
            return result;
        };
        if (this.isLongRunningCommand(params.command)) {
            // Create a progress dialog for long-running commands.
            const progress = await this.getProgressReporter(reporter, localize_1.Localizer.CodeAction.executingCommand(), token);
            const source = progress.source;
            this._pendingCommandCancellationSource = source;
            try {
                const result = await executeCommand(source.token);
                return result;
            }
            finally {
                progress.reporter.done();
                source.dispose();
            }
        }
        else {
            const result = await executeCommand(token);
            return result;
        }
    }
    onShutdown(token) {
        // Shutdown remaining workspaces.
        this.workspaceFactory.clear();
        // Stop tracking all open files.
        this.openFileMap.clear();
        return Promise.resolve();
    }
    convertDiagnostics(fs, fileDiagnostics) {
        return [
            {
                uri: (0, uriUtils_1.encodeUri)(fs, fileDiagnostics.fileUri),
                version: fileDiagnostics.version,
                diagnostics: this._convertDiagnostics(fs, fileDiagnostics.diagnostics),
            },
        ];
    }
    getDiagCode(_diag, rule) {
        return rule;
    }
    onAnalysisCompletedHandler(fs, results) {
        // Send the computed diagnostics to the client.
        results.diagnostics.forEach((fileDiag) => {
            if (!this.canNavigateToFile(fileDiag.fileUri, fs)) {
                return;
            }
            this.sendDiagnostics(this.convertDiagnostics(fs, fileDiag));
        });
        if (!this._progressReporter.isEnabled(results)) {
            // Make sure to disable progress bar if it is currently active.
            // This can happen if a user changes typeCheckingMode in the middle
            // of analysis.
            // end() is noop if there is no active progress bar.
            this._progressReporter.end();
            return;
        }
        // Update progress.
        if (results.filesRequiringAnalysis > 0) {
            this._progressReporter.begin();
            const progressMessage = results.filesRequiringAnalysis === 1
                ? localize_1.Localizer.CodeAction.filesToAnalyzeOne()
                : localize_1.Localizer.CodeAction.filesToAnalyzeCount().format({
                    count: results.filesRequiringAnalysis,
                });
            this._progressReporter.report(progressMessage);
        }
        else {
            this._progressReporter.end();
        }
    }
    onWorkspaceCreated(workspace) {
        // Update settings on this workspace (but only if initialize has happened)
        if (this._initialized) {
            this.updateSettingsForWorkspace(workspace, workspace.isInitialized).ignoreErrors();
        }
        // Otherwise the initialize completion should cause settings to be updated on all workspaces.
    }
    onWorkspaceRemoved(workspace) {
        const documentsWithDiagnosticsList = [...this.documentsWithDiagnostics];
        const otherWorkspaces = this.workspaceFactory.items().filter((w) => w !== workspace);
        for (const uri of documentsWithDiagnosticsList) {
            const fileUri = this.decodeUri(uri);
            if (workspace.service.isTracked(fileUri)) {
                // Do not clean up diagnostics for files tracked by multiple workspaces
                if (otherWorkspaces.some((w) => w.service.isTracked(fileUri))) {
                    continue;
                }
                this.sendDiagnostics([
                    {
                        uri: uri,
                        diagnostics: [],
                    },
                ]);
            }
        }
    }
    createAnalyzerServiceForWorkspace(name, uri, kinds, services) {
        // 5 seconds default
        const defaultBackOffTime = 5 * 1000;
        return this.createAnalyzerService(name, services, () => defaultBackOffTime);
    }
    recordUserInteractionTime() {
        // Tell all of the services that the user is actively
        // interacting with one or more editors, so they should
        // back off from performing any work.
        this.workspaceFactory.items().forEach((workspace) => {
            workspace.service.recordUserInteractionTime();
        });
    }
    getDocumentationUrlForDiagnostic(diag) {
        const rule = diag.getRule();
        if (rule) {
            // Configuration.md is configured to have a link for every rule name.
            return `${constants_1.githubRepo}/blob/main/docs/configuration.md#${rule}`;
        }
        return undefined;
    }
    canNavigateToFile(path, fs) {
        return (0, navigationUtils_1.canNavigateToFile)(fs, path);
    }
    async getProgressReporter(reporter, title, token) {
        // This is a bit ugly, but we need to determine whether the provided reporter
        // is an actual client-side progress reporter or a dummy (null) progress reporter
        // created by the LSP library. If it's the latter, we'll create a server-initiated
        // progress reporter.
        if (reporter.constructor !== nullProgressReporter.constructor) {
            return { reporter: reporter, source: (0, cancellationUtils_1.CancelAfter)(this.serverOptions.cancellationProvider, token) };
        }
        const serverInitiatedReporter = await this.connection.window.createWorkDoneProgress();
        serverInitiatedReporter.begin(title, 
        /* percentage */ undefined, 
        /* message */ undefined, 
        /* cancellable */ true);
        return {
            reporter: serverInitiatedReporter,
            source: (0, cancellationUtils_1.CancelAfter)(this.serverOptions.cancellationProvider, token, serverInitiatedReporter.token),
        };
    }
    sendDiagnostics(params) {
        for (const param of params) {
            if (param.diagnostics.length === 0) {
                this.documentsWithDiagnostics.delete(param.uri);
            }
            else {
                this.documentsWithDiagnostics.add(param.uri);
            }
            this.connection.sendDiagnostics(param);
        }
    }
    decodeUri(uri) {
        return uri_1.Uri.parse(uri, this.serverOptions.serviceProvider);
    }
    _setupFileWatcher() {
        if (!this.client.hasWatchFileCapability) {
            return;
        }
        const watchKind = vscode_languageserver_1.WatchKind.Create | vscode_languageserver_1.WatchKind.Change | vscode_languageserver_1.WatchKind.Delete;
        // Set default (config files and all workspace files) first.
        const watchers = [
            ...service_1.configFileNames.map((fileName) => ({ globPattern: `**/${fileName}`, kind: watchKind })),
            { globPattern: '**', kind: watchKind },
        ];
        // Add all python search paths to watch list
        if (this.client.hasWatchFileRelativePathCapability) {
            // Dedup search paths from all workspaces.
            // Get rid of any search path under workspace root since it is already watched by
            // "**" above.
            const foldersToWatch = (0, uriUtils_1.deduplicateFolders)(this.workspaceFactory
                .getNonDefaultWorkspaces()
                .map((w) => w.searchPathsToWatch.filter((p) => !p.startsWith(w.rootUri))));
            foldersToWatch.forEach((p) => {
                const globPattern = (0, uriUtils_1.isFile)(this.fs, p, /* treatZipDirectoryAsFile */ true)
                    ? { baseUri: p.getDirectory().toString(), pattern: p.fileName }
                    : { baseUri: p.toString(), pattern: '**' };
                watchers.push({ globPattern, kind: watchKind });
            });
        }
        // Dispose all existing file watchers and create new ones.
        this.connection.client.register(vscode_languageserver_1.DidChangeWatchedFilesNotification.type, { watchers }).then((d) => {
            if (this._lastFileWatcherRegistration) {
                this._lastFileWatcherRegistration.dispose();
            }
            this._lastFileWatcherRegistration = d;
        });
    }
    _getCompatibleMarkupKind(clientSupportedFormats) {
        const serverSupportedFormats = [vscode_languageserver_1.MarkupKind.PlainText, vscode_languageserver_1.MarkupKind.Markdown];
        for (const format of clientSupportedFormats !== null && clientSupportedFormats !== void 0 ? clientSupportedFormats : []) {
            if (serverSupportedFormats.includes(format)) {
                return format;
            }
        }
        return vscode_languageserver_1.MarkupKind.PlainText;
    }
    _convertDiagnostics(fs, diags) {
        const convertedDiags = [];
        diags.forEach((diag) => {
            const severity = convertCategoryToSeverity(diag.category);
            const rule = diag.getRule();
            const code = this.getDiagCode(diag, rule);
            const vsDiag = vscode_languageserver_1.Diagnostic.create(diag.range, diag.message, severity, code, this.serverOptions.productName);
            if (diag.category === 3 /* DiagnosticCategory.UnusedCode */ ||
                diag.category === 4 /* DiagnosticCategory.UnreachableCode */) {
                vsDiag.tags = [vscode_languageserver_1.DiagnosticTag.Unnecessary];
                vsDiag.severity = vscode_languageserver_1.DiagnosticSeverity.Hint;
                // If the client doesn't support "unnecessary" tags, don't report unused code.
                if (!this.client.supportsUnnecessaryDiagnosticTag) {
                    return;
                }
            }
            else if (diag.category === 5 /* DiagnosticCategory.Deprecated */) {
                vsDiag.tags = [vscode_languageserver_1.DiagnosticTag.Deprecated];
                vsDiag.severity = vscode_languageserver_1.DiagnosticSeverity.Hint;
                // If the client doesn't support "deprecated" tags, don't report.
                if (!this.client.supportsDeprecatedDiagnosticTag) {
                    return;
                }
            }
            else if (diag.category === 6 /* DiagnosticCategory.TaskItem */) {
                vsDiag.tags = [VSDiagnosticTag.TaskItem];
                // Map the task item priority to a value VS will understand
                // and store it in the diagnostic.
                // The Diagnostic type is defined in a protocol that we can't change,
                // so we just dynamically create the vsDiag._vs_diagnosticRank property at runtime,
                // which is what VS is looking for.
                switch (diag.priority) {
                    case diagnostic_1.TaskListPriority.High:
                        vsDiag._vs_diagnosticRank = VSDiagnosticRank.High;
                        break;
                    case diagnostic_1.TaskListPriority.Normal:
                        vsDiag._vs_diagnosticRank = VSDiagnosticRank.Default;
                        break;
                    case diagnostic_1.TaskListPriority.Low:
                        vsDiag._vs_diagnosticRank = VSDiagnosticRank.Low;
                        break;
                }
                // if the client doesn't support "task item" tags, don't report.
                if (!this.client.supportsTaskItemDiagnosticTag) {
                    return;
                }
            }
            if (rule) {
                const ruleDocUrl = this.getDocumentationUrlForDiagnostic(diag);
                if (ruleDocUrl) {
                    vsDiag.codeDescription = {
                        href: ruleDocUrl,
                    };
                }
            }
            const relatedInfo = diag.getRelatedInfo();
            if (relatedInfo.length > 0) {
                vsDiag.relatedInformation = relatedInfo
                    .filter((info) => this.canNavigateToFile(info.uri, fs))
                    .map((info) => vscode_languageserver_1.DiagnosticRelatedInformation.create(vscode_languageserver_1.Location.create((0, uriUtils_1.encodeUri)(fs, info.uri), info.range), info.message));
            }
            convertedDiags.push(vsDiag);
        });
        function convertCategoryToSeverity(category) {
            switch (category) {
                case 0 /* DiagnosticCategory.Error */:
                    return vscode_languageserver_1.DiagnosticSeverity.Error;
                case 1 /* DiagnosticCategory.Warning */:
                    return vscode_languageserver_1.DiagnosticSeverity.Warning;
                case 2 /* DiagnosticCategory.Information */:
                case 6 /* DiagnosticCategory.TaskItem */: // task items only show up in the task list if they are information or above.
                    return vscode_languageserver_1.DiagnosticSeverity.Information;
                case 3 /* DiagnosticCategory.UnusedCode */:
                case 4 /* DiagnosticCategory.UnreachableCode */:
                case 5 /* DiagnosticCategory.Deprecated */:
                    return vscode_languageserver_1.DiagnosticSeverity.Hint;
            }
        }
        return convertedDiags;
    }
}
exports.LanguageServerBase = LanguageServerBase;


/***/ }),

/***/ "../pyright-internal/src/languageService/analyzerServiceExecutor.ts":
/*!**************************************************************************!*\
  !*** ../pyright-internal/src/languageService/analyzerServiceExecutor.ts ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * analyzerServiceExecutor.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Runs the analyzer service of a given workspace service instance
 * with a specified set of options.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AnalyzerServiceExecutor = void 0;
const pythonPathUtils_1 = __webpack_require__(/*! ../analyzer/pythonPathUtils */ "../pyright-internal/src/analyzer/pythonPathUtils.ts");
const service_1 = __webpack_require__(/*! ../analyzer/service */ "../pyright-internal/src/analyzer/service.ts");
const commandLineOptions_1 = __webpack_require__(/*! ../common/commandLineOptions */ "../pyright-internal/src/common/commandLineOptions.ts");
const console_1 = __webpack_require__(/*! ../common/console */ "../pyright-internal/src/common/console.ts");
const workspaceFactory_1 = __webpack_require__(/*! ../workspaceFactory */ "../pyright-internal/src/workspaceFactory.ts");
class AnalyzerServiceExecutor {
    static runWithOptions(workspace, serverSettings, typeStubTargetImportName, trackFiles = true) {
        const commandLineOptions = getEffectiveCommandLineOptions(workspace.rootUri, serverSettings, trackFiles, typeStubTargetImportName, workspace.pythonEnvironmentName);
        // Setting options causes the analyzer service to re-analyze everything.
        workspace.service.setOptions(commandLineOptions);
    }
    static async cloneService(ls, workspace, options) {
        // Allocate a temporary pseudo-workspace to perform this job.
        const instanceName = 'cloned service';
        const serviceId = (0, service_1.getNextServiceId)(instanceName);
        options = options !== null && options !== void 0 ? options : {};
        const tempWorkspace = {
            ...workspace,
            workspaceName: `temp workspace for cloned service`,
            rootUri: workspace.rootUri,
            pythonPath: workspace.pythonPath,
            pythonPathKind: workspace.pythonPathKind,
            kinds: [...workspace.kinds, workspaceFactory_1.WellKnownWorkspaceKinds.Cloned],
            service: workspace.service.clone(instanceName, serviceId, options.useBackgroundAnalysis ? ls.createBackgroundAnalysis(serviceId) : undefined, options.fileSystem),
            disableLanguageServices: true,
            disableTaggedHints: true,
            disableOrganizeImports: true,
            disableWorkspaceSymbol: true,
            isInitialized: (0, workspaceFactory_1.createInitStatus)(),
            searchPathsToWatch: [],
        };
        const serverSettings = await ls.getSettings(workspace);
        AnalyzerServiceExecutor.runWithOptions(tempWorkspace, serverSettings, options.typeStubTargetImportName, 
        /* trackFiles */ false);
        return tempWorkspace.service;
    }
}
exports.AnalyzerServiceExecutor = AnalyzerServiceExecutor;
function getEffectiveCommandLineOptions(workspaceRootUri, serverSettings, trackFiles, typeStubTargetImportName, pythonEnvironmentName) {
    var _a, _b, _c, _d, _e, _f, _g;
    const commandLineOptions = new commandLineOptions_1.CommandLineOptions(workspaceRootUri, true);
    commandLineOptions.checkOnlyOpenFiles = serverSettings.openFilesOnly;
    commandLineOptions.useLibraryCodeForTypes = serverSettings.useLibraryCodeForTypes;
    commandLineOptions.typeCheckingMode = serverSettings.typeCheckingMode;
    commandLineOptions.autoImportCompletions = serverSettings.autoImportCompletions;
    commandLineOptions.indexing = serverSettings.indexing;
    commandLineOptions.taskListTokens = serverSettings.taskListTokens;
    commandLineOptions.logTypeEvaluationTime = (_a = serverSettings.logTypeEvaluationTime) !== null && _a !== void 0 ? _a : false;
    commandLineOptions.typeEvaluationTimeThreshold = (_b = serverSettings.typeEvaluationTimeThreshold) !== null && _b !== void 0 ? _b : 50;
    commandLineOptions.enableAmbientAnalysis = trackFiles;
    commandLineOptions.pythonEnvironmentName = pythonEnvironmentName;
    commandLineOptions.disableTaggedHints = serverSettings.disableTaggedHints;
    if (!trackFiles) {
        commandLineOptions.watchForSourceChanges = false;
        commandLineOptions.watchForLibraryChanges = false;
        commandLineOptions.watchForConfigChanges = false;
    }
    else {
        commandLineOptions.watchForSourceChanges = serverSettings.watchForSourceChanges;
        commandLineOptions.watchForLibraryChanges = serverSettings.watchForLibraryChanges;
        commandLineOptions.watchForConfigChanges = serverSettings.watchForConfigChanges;
    }
    if (serverSettings.venvPath) {
        commandLineOptions.venvPath = serverSettings.venvPath.getFilePath();
    }
    if (serverSettings.pythonPath) {
        // The Python VS Code extension treats the value "python" specially. This means
        // the local python interpreter should be used rather than interpreting the
        // setting value as a path to the interpreter. We'll simply ignore it in this case.
        if (!(0, pythonPathUtils_1.isPythonBinary)(serverSettings.pythonPath.getFilePath())) {
            commandLineOptions.pythonPath = serverSettings.pythonPath.getFilePath();
        }
    }
    if (serverSettings.typeshedPath) {
        // Pyright supports only one typeshed path currently, whereas the
        // official VS Code Python extension supports multiple typeshed paths.
        // We'll use the first one specified and ignore the rest.
        commandLineOptions.typeshedPath = serverSettings.typeshedPath.getFilePath();
    }
    if (serverSettings.stubPath) {
        commandLineOptions.stubPath = serverSettings.stubPath.getFilePath();
    }
    if (serverSettings.logLevel === console_1.LogLevel.Log) {
        // When logLevel is "Trace", turn on verboseOutput as well
        // so we can get detailed log from analysis service.
        commandLineOptions.verboseOutput = true;
    }
    if (typeStubTargetImportName) {
        commandLineOptions.typeStubTargetImportName = typeStubTargetImportName;
    }
    commandLineOptions.autoSearchPaths = serverSettings.autoSearchPaths;
    commandLineOptions.extraPaths = (_d = (_c = serverSettings.extraPaths) === null || _c === void 0 ? void 0 : _c.map((e) => e.getFilePath())) !== null && _d !== void 0 ? _d : [];
    commandLineOptions.diagnosticSeverityOverrides = serverSettings.diagnosticSeverityOverrides;
    commandLineOptions.includeFileSpecs = (_e = serverSettings.includeFileSpecs) !== null && _e !== void 0 ? _e : [];
    commandLineOptions.excludeFileSpecs = (_f = serverSettings.excludeFileSpecs) !== null && _f !== void 0 ? _f : [];
    commandLineOptions.ignoreFileSpecs = (_g = serverSettings.ignoreFileSpecs) !== null && _g !== void 0 ? _g : [];
    return commandLineOptions;
}


/***/ }),

/***/ "../pyright-internal/src/languageService/autoImporter.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/languageService/autoImporter.ts ***!
  \***************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * autoImporter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Logic for performing auto-import completions.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertSymbolKindToCompletionItemKind = exports.AutoImporter = exports.addModuleSymbolsMap = exports.buildModuleSymbolsMap = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const importStatementUtils_1 = __webpack_require__(/*! ../analyzer/importStatementUtils */ "../pyright-internal/src/analyzer/importStatementUtils.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const SymbolNameUtils = __importStar(__webpack_require__(/*! ../analyzer/symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
const symbolUtils_1 = __webpack_require__(/*! ../analyzer/symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const pathUtils_1 = __webpack_require__(/*! ../common/pathUtils */ "../pyright-internal/src/common/pathUtils.ts");
const StringUtils = __importStar(__webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts"));
const completionProvider_1 = __webpack_require__(/*! ./completionProvider */ "../pyright-internal/src/languageService/completionProvider.ts");
// Build a map of all modules within this program and the module-
// level scope that contains the symbol table for the module.
function buildModuleSymbolsMap(files) {
    const map = new Map();
    addModuleSymbolsMap(files, map);
    return map;
}
exports.buildModuleSymbolsMap = buildModuleSymbolsMap;
function addModuleSymbolsMap(files, moduleSymbolMap) {
    files.forEach((file) => {
        if (file.shadows.length > 0) {
            // There is corresponding stub file. Don't add
            // duplicated files in the map.
            return;
        }
        const uri = file.sourceFile.getUri();
        const symbolTable = file.sourceFile.getModuleSymbolTable();
        if (!symbolTable) {
            return;
        }
        const fileName = (0, pathUtils_1.stripFileExtension)(uri.fileName);
        // Don't offer imports from files that are named with private
        // naming semantics like "_ast.py".
        if (SymbolNameUtils.isPrivateOrProtectedName(fileName)) {
            return;
        }
        moduleSymbolMap.set(uri.key, {
            uri,
            forEach(callbackfn) {
                symbolTable.forEach((symbol, name) => {
                    if (!(0, symbolUtils_1.isVisibleExternally)(symbol)) {
                        return;
                    }
                    const declarations = symbol.getDeclarations();
                    if (!declarations || declarations.length === 0) {
                        return;
                    }
                    const declaration = declarations[0];
                    if (!declaration) {
                        return;
                    }
                    if (declaration.type === 8 /* DeclarationType.Alias */ && (0, sourceFileInfoUtils_1.isUserCode)(file)) {
                        // We don't include import alias in auto import
                        // for workspace files.
                        return;
                    }
                    const variableKind = declaration.type === 1 /* DeclarationType.Variable */ && !declaration.isConstant && !declaration.isFinal
                        ? vscode_languageserver_1.SymbolKind.Variable
                        : undefined;
                    callbackfn({ symbol, kind: variableKind }, name, /* library */ !(0, sourceFileInfoUtils_1.isUserCode)(file));
                });
            },
        });
        return;
    });
}
exports.addModuleSymbolsMap = addModuleSymbolsMap;
class AutoImporter {
    constructor(execEnvironment, importResolver, parseResults, _invocationPosition, _excludes, moduleSymbolMap, options) {
        this.execEnvironment = execEnvironment;
        this.importResolver = importResolver;
        this.parseResults = parseResults;
        this._invocationPosition = _invocationPosition;
        this._excludes = _excludes;
        this.moduleSymbolMap = moduleSymbolMap;
        this.options = options;
        this._importStatements = (0, importStatementUtils_1.getTopLevelImports)(this.parseResults.parserOutput.parseTree, 
        /* includeImplicitImports */ true);
    }
    getAutoImportCandidates(word, similarityLimit, abbrFromUsers, token) {
        const results = [];
        const map = this.getCandidates(word, similarityLimit, abbrFromUsers, token);
        map.forEach((v) => (0, collectionUtils_1.appendArray)(results, v));
        return results;
    }
    getCandidates(word, similarityLimit, abbrFromUsers, token) {
        const resultMap = new Map();
        const importAliasMap = new Map();
        this.addImportsFromModuleMap(word, similarityLimit, abbrFromUsers, importAliasMap, resultMap, token);
        this.addImportsFromImportAliasMap(importAliasMap, abbrFromUsers, resultMap, token);
        return resultMap;
    }
    addImportsFromModuleMap(word, similarityLimit, abbrFromUsers, aliasMap, results, token) {
        this.moduleSymbolMap.forEach((topLevelSymbols, key) => {
            // See if this file should be offered as an implicit import.
            const isStubFileOrHasInit = this.isStubFileOrHasInit(this.moduleSymbolMap, topLevelSymbols.uri);
            this.processModuleSymbolTable(topLevelSymbols, topLevelSymbols.uri, word, similarityLimit, isStubFileOrHasInit, abbrFromUsers, aliasMap, results, token);
        });
    }
    addImportsFromImportAliasMap(importAliasMap, abbrFromUsers, results, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        importAliasMap.forEach((mapPerSymbolName) => {
            mapPerSymbolName.forEach((importAliasData, originalName) => {
                var _a, _b;
                if (abbrFromUsers) {
                    // When alias name is used, our regular exclude mechanism would not work. we need to check
                    // whether import, the alias is referring to, already exists.
                    // ex) import numpy
                    //     np| <= auto-import here.
                    // or
                    //     from scipy import io as spio
                    //     io| <= auto-import here
                    // If import statement for the module already exist, then bail out.
                    // ex) import module[.submodule] or from module[.submodule] import symbol
                    if (this._importStatements.mapByFilePath.has(importAliasData.importParts.fileUri.key)) {
                        return;
                    }
                    // If it is the module itself that got imported, make sure we don't import it again.
                    // ex) from module import submodule as ss
                    //     submodule <= auto-import here
                    if (importAliasData.importParts.importFrom) {
                        const imported = this._importStatements.orderedImports.find((i) => i.moduleName === importAliasData.importParts.importFrom);
                        if (imported &&
                            imported.node.nodeType === 22 /* ParseNodeType.ImportFrom */ &&
                            imported.node.imports.some((i) => i.name.value === importAliasData.importParts.symbolName)) {
                            return;
                        }
                    }
                }
                const alreadyIncluded = this._containsName(importAliasData.importParts.importName, importAliasData.importParts.importFrom, results);
                if (alreadyIncluded) {
                    return;
                }
                const autoImportTextEdits = this._getTextEditsForAutoImportByFilePath({ name: importAliasData.importParts.symbolName, alias: abbrFromUsers }, {
                    name: (_a = importAliasData.importParts.importFrom) !== null && _a !== void 0 ? _a : importAliasData.importParts.importName,
                }, importAliasData.importParts.importName, importAliasData.importGroup, importAliasData.importParts.fileUri);
                this._addResult(results, {
                    name: importAliasData.importParts.importName,
                    alias: abbrFromUsers,
                    symbol: importAliasData.symbol,
                    kind: (_b = importAliasData.itemKind) !== null && _b !== void 0 ? _b : convertSymbolKindToCompletionItemKind(importAliasData.kind),
                    source: importAliasData.importParts.importFrom,
                    insertionText: autoImportTextEdits.insertionText,
                    edits: autoImportTextEdits.edits,
                    declUri: importAliasData.importParts.fileUri,
                    originalName,
                    originalDeclUri: importAliasData.fileUri,
                });
            });
        });
    }
    processModuleSymbolTable(topLevelSymbols, moduleUri, word, similarityLimit, isStubOrHasInit, abbrFromUsers, importAliasMap, results, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const [importSource, importGroup, moduleNameAndType] = this._getImportPartsForSymbols(moduleUri);
        if (!importSource) {
            return;
        }
        const dotCount = StringUtils.getCharacterCount(importSource, '.');
        topLevelSymbols.forEach((autoImportSymbol, name, library) => {
            var _a;
            if (!this._shouldIncludeVariable(autoImportSymbol, name, isStubOrHasInit.isStub, library)) {
                return;
            }
            // For very short matching strings, we will require an exact match. Otherwise
            // we will tend to return a list that's too long. Once we get beyond two
            // characters, we can do a fuzzy match.
            const isSimilar = this._isSimilar(word, name, similarityLimit);
            if (!isSimilar) {
                return;
            }
            const alreadyIncluded = this._containsName(name, importSource, results);
            if (alreadyIncluded) {
                return;
            }
            // We will collect all aliases and then process it later
            if (autoImportSymbol.importAlias) {
                this._addToImportAliasMap(autoImportSymbol.importAlias, {
                    importParts: {
                        symbolName: name,
                        importName: name,
                        importFrom: importSource,
                        fileUri: moduleUri,
                        dotCount,
                        moduleNameAndType,
                    },
                    importGroup,
                    symbol: autoImportSymbol.symbol,
                    kind: autoImportSymbol.importAlias.kind,
                    itemKind: autoImportSymbol.importAlias.itemKind,
                    fileUri: autoImportSymbol.importAlias.moduleUri,
                }, importAliasMap);
                return;
            }
            const nameForImportFrom = this.getNameForImportFrom(library, moduleUri);
            const autoImportTextEdits = this._getTextEditsForAutoImportByFilePath({ name, alias: abbrFromUsers }, { name: importSource, nameForImportFrom }, name, importGroup, moduleUri);
            this._addResult(results, {
                name,
                alias: abbrFromUsers,
                symbol: autoImportSymbol.symbol,
                source: importSource,
                kind: (_a = autoImportSymbol.itemKind) !== null && _a !== void 0 ? _a : convertSymbolKindToCompletionItemKind(autoImportSymbol.kind),
                insertionText: autoImportTextEdits.insertionText,
                edits: autoImportTextEdits.edits,
                declUri: moduleUri,
                originalName: name,
                originalDeclUri: moduleUri,
            });
        });
        // If the current file is in a directory that also contains an "__init__.py[i]"
        // file, we can use that directory name as an implicit import target.
        // Or if the file is a stub file, we can use it as import target.
        if (!isStubOrHasInit.isStub && !isStubOrHasInit.hasInit) {
            return;
        }
        const importParts = this._getImportParts(moduleUri);
        if (!importParts) {
            return;
        }
        const isSimilar = this._isSimilar(word, importParts.importName, similarityLimit);
        if (!isSimilar) {
            return;
        }
        const alreadyIncluded = this._containsName(importParts.importName, importParts.importFrom, results);
        if (alreadyIncluded) {
            return;
        }
        this._addToImportAliasMap({
            moduleUri,
            originalName: importParts.importName,
            kind: vscode_languageserver_1.SymbolKind.Module,
            itemKind: vscode_languageserver_1.CompletionItemKind.Module,
        }, {
            importParts,
            importGroup,
            kind: vscode_languageserver_1.SymbolKind.Module,
            itemKind: vscode_languageserver_1.CompletionItemKind.Module,
            fileUri: moduleUri,
        }, importAliasMap);
    }
    getNameForImportFrom(library, moduleUri) {
        return undefined;
    }
    isStubFileOrHasInit(map, uri) {
        const fileDir = uri.getDirectory();
        const initPathPy = fileDir.initPyUri;
        const initPathPyi = fileDir.initPyiUri;
        const isStub = uri.hasExtension('.pyi');
        const hasInit = map.has(initPathPy.key) || map.has(initPathPyi.key);
        return { isStub, hasInit };
    }
    _shouldIncludeVariable(autoImportSymbol, name, isStub, library) {
        var _a;
        // If it is not a stub file and symbol is Variable, we only include it if
        // name is public constant or type alias unless it is in __all__ for user files.
        if (isStub || autoImportSymbol.kind !== vscode_languageserver_1.SymbolKind.Variable) {
            return true;
        }
        if (this.options.allowVariableInAll && !library && ((_a = autoImportSymbol.symbol) === null || _a === void 0 ? void 0 : _a.isInDunderAll())) {
            return true;
        }
        return SymbolNameUtils.isPublicConstantOrTypeAlias(name);
    }
    _addToImportAliasMap(alias, data, importAliasMap) {
        // Since we don't resolve alias declaration using type evaluator, there is still a chance
        // where we show multiple aliases for same symbols. but this should still reduce number of
        // such cases.
        if (!importAliasMap.has(alias.moduleUri.key)) {
            const map = new Map();
            map.set(alias.originalName, data);
            importAliasMap.set(alias.moduleUri.key, map);
            return;
        }
        const map = importAliasMap.get(alias.moduleUri.key);
        if (!map.has(alias.originalName)) {
            map.set(alias.originalName, data);
            return;
        }
        const existingData = map.get(alias.originalName);
        const comparison = this._compareImportAliasData(existingData, data);
        if (comparison <= 0) {
            // Existing data is better than new one.
            return;
        }
        // Keep the new data.
        map.set(alias.originalName, data);
    }
    _compareImportAliasData(left, right) {
        const groupComparison = left.importGroup - right.importGroup;
        if (groupComparison !== 0) {
            return groupComparison;
        }
        const dotComparison = left.importParts.dotCount - right.importParts.dotCount;
        if (dotComparison !== 0) {
            return dotComparison;
        }
        if (left.symbol && !right.symbol) {
            return -1;
        }
        if (!left.symbol && right.symbol) {
            return 1;
        }
        return StringUtils.getStringComparer()(left.importParts.importName, right.importParts.importName);
    }
    _getImportPartsForSymbols(uri) {
        const localImport = this._importStatements.mapByFilePath.get(uri.key);
        if (localImport) {
            return [
                localImport.moduleName,
                (0, importStatementUtils_1.getImportGroup)(localImport),
                {
                    importType: 2 /* ImportType.Local */,
                    isLocalTypingsFile: false,
                    moduleName: localImport.moduleName,
                },
            ];
        }
        else {
            const moduleNameAndType = this._getModuleNameAndTypeFromFilePath(uri);
            return [
                moduleNameAndType.moduleName,
                (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(moduleNameAndType),
                moduleNameAndType,
            ];
        }
    }
    _getImportParts(uri) {
        const name = (0, pathUtils_1.stripFileExtension)(uri.fileName);
        // See if we can import module as "import xxx"
        if (name === '__init__') {
            return createImportParts(this._getModuleNameAndTypeFromFilePath(uri.getDirectory()));
        }
        return createImportParts(this._getModuleNameAndTypeFromFilePath(uri));
        function createImportParts(module) {
            const moduleName = module.moduleName;
            if (!moduleName) {
                return undefined;
            }
            const index = moduleName.lastIndexOf('.');
            const importNamePart = index > 0 ? moduleName.substring(index + 1) : undefined;
            const importFrom = index > 0 ? moduleName.substring(0, index) : undefined;
            return {
                symbolName: importNamePart,
                importName: importNamePart !== null && importNamePart !== void 0 ? importNamePart : moduleName,
                importFrom,
                fileUri: uri,
                dotCount: StringUtils.getCharacterCount(moduleName, '.'),
                moduleNameAndType: module,
            };
        }
    }
    _isSimilar(word, name, similarityLimit) {
        if (similarityLimit === 1) {
            return word === name;
        }
        if (word.length <= 0 || name.length <= 0) {
            return false;
        }
        if (!this.options.patternMatcher) {
            const index = word[0] !== '_' && name[0] === '_' && name.length > 1 ? 1 : 0;
            if (word[0].toLocaleLowerCase() !== name[index].toLocaleLowerCase()) {
                return false;
            }
            return StringUtils.isPatternInSymbol(word, name);
        }
        return this.options.patternMatcher(word, name);
    }
    _shouldExclude(name) {
        return this._excludes.has(name, completionProvider_1.CompletionMap.labelOnlyIgnoringAutoImports);
    }
    _containsName(name, source, results) {
        if (this._shouldExclude(name)) {
            return true;
        }
        const match = results.get(name);
        if (match === null || match === void 0 ? void 0 : match.some((r) => r.source === source)) {
            return true;
        }
        return false;
    }
    // Given the file path of a module that we want to import,
    // convert to a module name that can be used in an
    // 'import from' statement.
    _getModuleNameAndTypeFromFilePath(uri) {
        return this.importResolver.getModuleNameForImport(uri, this.execEnvironment);
    }
    _getTextEditsForAutoImportByFilePath(importNameInfo, moduleNameInfo, insertionText, importGroup, fileUri) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        // If there is no symbolName, there can't be existing import statement.
        const importStatement = this._importStatements.mapByFilePath.get(fileUri.key);
        if (importStatement) {
            // Found import for given module. See whether we can use the module as it is.
            if (importStatement.node.nodeType === 20 /* ParseNodeType.Import */) {
                // For now, we don't check whether alias or moduleName got overwritten at
                // given position
                const importAlias = (_b = (_a = importStatement.subnode) === null || _a === void 0 ? void 0 : _a.alias) === null || _b === void 0 ? void 0 : _b.value;
                if (importNameInfo.name) {
                    // ex) import module
                    //     method | <= auto-import
                    return {
                        insertionText: `${importAlias !== null && importAlias !== void 0 ? importAlias : importStatement.moduleName}.${importNameInfo.name}`,
                        edits: [],
                    };
                }
                else if (importAlias) {
                    // ex) import module as m
                    //     m | <= auto-import
                    return {
                        insertionText: `${importAlias}`,
                        edits: [],
                    };
                }
            }
            // Does an 'import from' statement already exist?
            if (importNameInfo.name &&
                importStatement.node.nodeType === 22 /* ParseNodeType.ImportFrom */ &&
                !importStatement.node.isWildcardImport) {
                // If so, see whether what we want already exist.
                const importNode = importStatement.node.imports.find((i) => i.name.value === importNameInfo.name);
                if (importNode) {
                    // For now, we don't check whether alias or moduleName got overwritten at
                    // given position
                    const importAlias = (_c = importNode.alias) === null || _c === void 0 ? void 0 : _c.value;
                    return {
                        insertionText: `${importAlias !== null && importAlias !== void 0 ? importAlias : importNameInfo.name}`,
                        edits: [],
                    };
                }
                // If not, add what we want at the existing 'import from' statement as long as
                // what is imported is not module itself.
                // ex) don't add "path" to existing "from os.path import dirname" statement.
                if (moduleNameInfo.name === importStatement.moduleName) {
                    return {
                        insertionText: (_d = importNameInfo.alias) !== null && _d !== void 0 ? _d : insertionText,
                        edits: this.options.lazyEdit
                            ? undefined
                            : (0, importStatementUtils_1.getTextEditsForAutoImportSymbolAddition)(importNameInfo, importStatement, this.parseResults),
                    };
                }
            }
        }
        else if (importNameInfo.name) {
            // If it is the module itself that got imported, make sure we don't import it again.
            // ex) from module import submodule
            const imported = this._importStatements.orderedImports.find((i) => i.moduleName === moduleNameInfo.name);
            if (imported && imported.node.nodeType === 22 /* ParseNodeType.ImportFrom */ && !imported.node.isWildcardImport) {
                const importFrom = imported.node.imports.find((i) => i.name.value === importNameInfo.name);
                if (importFrom) {
                    // For now, we don't check whether alias or moduleName got overwritten at
                    // given position. only move to alias, but not the other way around
                    const importAlias = (_e = importFrom.alias) === null || _e === void 0 ? void 0 : _e.value;
                    if (importAlias) {
                        return {
                            insertionText: `${importAlias}`,
                            edits: [],
                        };
                    }
                }
                else {
                    // If not, add what we want at the existing import from statement.
                    return {
                        insertionText: (_f = importNameInfo.alias) !== null && _f !== void 0 ? _f : insertionText,
                        edits: this.options.lazyEdit
                            ? undefined
                            : (0, importStatementUtils_1.getTextEditsForAutoImportSymbolAddition)(importNameInfo, imported, this.parseResults),
                    };
                }
            }
            // Check whether it is one of implicit imports
            const importFrom = (_g = this._importStatements.implicitImports) === null || _g === void 0 ? void 0 : _g.get(fileUri.key);
            if (importFrom) {
                // For now, we don't check whether alias or moduleName got overwritten at
                // given position
                const importAlias = (_h = importFrom.alias) === null || _h === void 0 ? void 0 : _h.value;
                return {
                    insertionText: `${importAlias !== null && importAlias !== void 0 ? importAlias : importFrom.name.value}.${importNameInfo.name}`,
                    edits: [],
                };
            }
        }
        return {
            insertionText: (_j = importNameInfo.alias) !== null && _j !== void 0 ? _j : insertionText,
            edits: this.options.lazyEdit
                ? undefined
                : (0, importStatementUtils_1.getTextEditsForAutoImportInsertion)(importNameInfo, moduleNameInfo, this._importStatements, importGroup, this.parseResults, this._invocationPosition),
        };
    }
    _addResult(results, result) {
        let entries = results.get(result.name);
        if (!entries) {
            entries = [];
            results.set(result.name, entries);
        }
        entries.push(result);
    }
}
exports.AutoImporter = AutoImporter;
function convertSymbolKindToCompletionItemKind(kind) {
    switch (kind) {
        case vscode_languageserver_1.SymbolKind.File:
            return vscode_languageserver_1.CompletionItemKind.File;
        case vscode_languageserver_1.SymbolKind.Module:
        case vscode_languageserver_1.SymbolKind.Namespace:
            return vscode_languageserver_1.CompletionItemKind.Module;
        case vscode_languageserver_1.SymbolKind.Package:
            return vscode_languageserver_1.CompletionItemKind.Folder;
        case vscode_languageserver_1.SymbolKind.Class:
            return vscode_languageserver_1.CompletionItemKind.Class;
        case vscode_languageserver_1.SymbolKind.Method:
            return vscode_languageserver_1.CompletionItemKind.Method;
        case vscode_languageserver_1.SymbolKind.Property:
            return vscode_languageserver_1.CompletionItemKind.Property;
        case vscode_languageserver_1.SymbolKind.Field:
            return vscode_languageserver_1.CompletionItemKind.Field;
        case vscode_languageserver_1.SymbolKind.Constructor:
            return vscode_languageserver_1.CompletionItemKind.Constructor;
        case vscode_languageserver_1.SymbolKind.Enum:
            return vscode_languageserver_1.CompletionItemKind.Enum;
        case vscode_languageserver_1.SymbolKind.Interface:
            return vscode_languageserver_1.CompletionItemKind.Interface;
        case vscode_languageserver_1.SymbolKind.Function:
            return vscode_languageserver_1.CompletionItemKind.Function;
        case vscode_languageserver_1.SymbolKind.Variable:
        case vscode_languageserver_1.SymbolKind.Array:
            return vscode_languageserver_1.CompletionItemKind.Variable;
        case vscode_languageserver_1.SymbolKind.String:
            return vscode_languageserver_1.CompletionItemKind.Constant;
        case vscode_languageserver_1.SymbolKind.Number:
        case vscode_languageserver_1.SymbolKind.Boolean:
            return vscode_languageserver_1.CompletionItemKind.Value;
        case vscode_languageserver_1.SymbolKind.Constant:
        case vscode_languageserver_1.SymbolKind.Null:
            return vscode_languageserver_1.CompletionItemKind.Constant;
        case vscode_languageserver_1.SymbolKind.Object:
        case vscode_languageserver_1.SymbolKind.Key:
            return vscode_languageserver_1.CompletionItemKind.Value;
        case vscode_languageserver_1.SymbolKind.EnumMember:
            return vscode_languageserver_1.CompletionItemKind.EnumMember;
        case vscode_languageserver_1.SymbolKind.Struct:
            return vscode_languageserver_1.CompletionItemKind.Struct;
        case vscode_languageserver_1.SymbolKind.Event:
            return vscode_languageserver_1.CompletionItemKind.Event;
        case vscode_languageserver_1.SymbolKind.Operator:
            return vscode_languageserver_1.CompletionItemKind.Operator;
        case vscode_languageserver_1.SymbolKind.TypeParameter:
            return vscode_languageserver_1.CompletionItemKind.TypeParameter;
        default:
            return undefined;
    }
}
exports.convertSymbolKindToCompletionItemKind = convertSymbolKindToCompletionItemKind;


/***/ }),

/***/ "../pyright-internal/src/languageService/callHierarchyProvider.ts":
/*!************************************************************************!*\
  !*** ../pyright-internal/src/languageService/callHierarchyProvider.ts ***!
  \************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * callHierarchyProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that provides a list of callers or callees associated with
 * a position.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallHierarchyProvider = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const DeclarationUtils = __importStar(__webpack_require__(/*! ../analyzer/declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts"));
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeWalker_1 = __webpack_require__(/*! ../analyzer/parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const extensibility_1 = __webpack_require__(/*! ../common/extensibility */ "../pyright-internal/src/common/extensibility.ts");
const lspUtils_1 = __webpack_require__(/*! ../common/lspUtils */ "../pyright-internal/src/common/lspUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const referencesProvider_1 = __webpack_require__(/*! ../languageService/referencesProvider */ "../pyright-internal/src/languageService/referencesProvider.ts");
const documentSymbolCollector_1 = __webpack_require__(/*! ./documentSymbolCollector */ "../pyright-internal/src/languageService/documentSymbolCollector.ts");
const navigationUtils_1 = __webpack_require__(/*! ./navigationUtils */ "../pyright-internal/src/languageService/navigationUtils.ts");
class CallHierarchyProvider {
    constructor(_program, _fileUri, _position, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._position = _position;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
    }
    onPrepare() {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const referencesResult = this._getDeclaration();
        if (!referencesResult || referencesResult.declarations.length === 0) {
            return null;
        }
        const { targetDecl, callItemUri, symbolName } = this._getTargetDeclaration(referencesResult);
        if (targetDecl.type !== 5 /* DeclarationType.Function */ &&
            targetDecl.type !== 6 /* DeclarationType.Class */ &&
            targetDecl.type !== 8 /* DeclarationType.Alias */) {
            return null;
        }
        // make sure the alias is resolved to class or function
        if (targetDecl.type === 8 /* DeclarationType.Alias */) {
            const resolvedDecl = this._evaluator.resolveAliasDeclaration(targetDecl, true);
            if (!resolvedDecl) {
                return null;
            }
            if (resolvedDecl.type !== 5 /* DeclarationType.Function */ && resolvedDecl.type !== 6 /* DeclarationType.Class */) {
                return null;
            }
        }
        const callItem = {
            name: symbolName,
            kind: (_a = (0, lspUtils_1.getSymbolKind)(targetDecl, this._evaluator, symbolName)) !== null && _a !== void 0 ? _a : vscode_languageserver_1.SymbolKind.Module,
            uri: (0, uriUtils_1.encodeUri)(this._program.fileSystem, callItemUri),
            range: targetDecl.range,
            selectionRange: targetDecl.range,
        };
        if (!(0, navigationUtils_1.canNavigateToFile)(this._program.fileSystem, uri_1.Uri.parse(callItem.uri, this._program.serviceProvider))) {
            return null;
        }
        return [callItem];
    }
    getIncomingCalls() {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const referencesResult = this._getDeclaration();
        if (!referencesResult || referencesResult.declarations.length === 0) {
            return null;
        }
        const { targetDecl, symbolName } = this._getTargetDeclaration(referencesResult);
        const items = [];
        const sourceFiles = targetDecl.type === 8 /* DeclarationType.Alias */
            ? [this._program.getSourceFileInfo(this._fileUri)]
            : this._program.getSourceFileInfoList();
        for (const curSourceFileInfo of sourceFiles) {
            if ((0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo) || curSourceFileInfo.isOpenByClient) {
                const filePath = curSourceFileInfo.sourceFile.getUri();
                const itemsToAdd = this._getIncomingCallsForDeclaration(filePath, symbolName, targetDecl);
                if (itemsToAdd) {
                    (0, collectionUtils_1.appendArray)(items, itemsToAdd);
                }
                // This operation can consume significant memory, so check
                // for situations where we need to discard the type cache.
                this._program.handleMemoryHighUsage();
            }
        }
        if (items.length === 0) {
            return null;
        }
        return items.filter((item) => (0, navigationUtils_1.canNavigateToFile)(this._program.fileSystem, uri_1.Uri.parse(item.from.uri, this._program.serviceProvider)));
    }
    getOutgoingCalls() {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const referencesResult = this._getDeclaration();
        if (!referencesResult || referencesResult.declarations.length === 0) {
            return null;
        }
        const { targetDecl } = this._getTargetDeclaration(referencesResult);
        // Find the parse node root corresponding to the function or class.
        let parseRoot;
        const resolvedDecl = this._evaluator.resolveAliasDeclaration(targetDecl, /* resolveLocalNames */ true);
        if (!resolvedDecl) {
            return null;
        }
        if (resolvedDecl.type === 5 /* DeclarationType.Function */) {
            parseRoot = resolvedDecl.node;
        }
        else if (resolvedDecl.type === 6 /* DeclarationType.Class */) {
            // Look up the __init__ method for this class.
            const classType = (_a = this._evaluator.getTypeForDeclaration(resolvedDecl)) === null || _a === void 0 ? void 0 : _a.type;
            if (classType && (0, types_1.isInstantiableClass)(classType)) {
                // Don't perform a recursive search of parent classes in this
                // case because we don't want to find an inherited __init__
                // method defined in a different module.
                const initMethodMember = (0, typeUtils_1.lookUpClassMember)(classType, '__init__', 16 /* MemberAccessFlags.SkipInstanceMembers */ |
                    4 /* MemberAccessFlags.SkipObjectBaseClass */ |
                    2 /* MemberAccessFlags.SkipBaseClasses */);
                if (initMethodMember) {
                    const initMethodType = this._evaluator.getTypeOfMember(initMethodMember);
                    if (initMethodType && (0, types_1.isFunction)(initMethodType)) {
                        const initDecls = initMethodMember.symbol.getDeclarations();
                        if (initDecls && initDecls.length > 0) {
                            const primaryInitDecl = initDecls[0];
                            if (primaryInitDecl.type === 5 /* DeclarationType.Function */) {
                                parseRoot = primaryInitDecl.node;
                            }
                        }
                    }
                }
            }
        }
        if (!parseRoot) {
            return null;
        }
        const callFinder = new FindOutgoingCallTreeWalker(this._program.fileSystem, parseRoot, this._parseResults, this._evaluator, this._token);
        const outgoingCalls = callFinder.findCalls();
        if (outgoingCalls.length === 0) {
            return null;
        }
        return outgoingCalls.filter((item) => (0, navigationUtils_1.canNavigateToFile)(this._program.fileSystem, uri_1.Uri.parse(item.to.uri, this._program.serviceProvider)));
    }
    get _evaluator() {
        return this._program.evaluator;
    }
    _getTargetDeclaration(referencesResult) {
        // If there's more than one declaration, pick the target one.
        // We'll always prefer one with a declared type, and we'll always
        // prefer later declarations.
        const declarations = referencesResult.declarations;
        const node = referencesResult.nodeAtOffset;
        let targetDecl = declarations[0];
        for (const decl of declarations) {
            if (DeclarationUtils.hasTypeForDeclaration(decl) || !DeclarationUtils.hasTypeForDeclaration(targetDecl)) {
                if (decl.type === 5 /* DeclarationType.Function */ || decl.type === 6 /* DeclarationType.Class */) {
                    targetDecl = decl;
                    // If the specified node is an exact match, use this declaration
                    // as the primary even if it's not the last.
                    if (decl.node === node) {
                        break;
                    }
                }
            }
        }
        let symbolName;
        // Although the LSP specification requires a URI, we are using a file path
        // here because it is converted to the proper URI by the caller.
        // This simplifies our code and ensures compatibility with the LSP specification.
        let callItemUri;
        if (targetDecl.type === 8 /* DeclarationType.Alias */) {
            symbolName = referencesResult.nodeAtOffset.value;
            callItemUri = this._fileUri;
        }
        else {
            symbolName = DeclarationUtils.getNameFromDeclaration(targetDecl) || referencesResult.symbolNames[0];
            callItemUri = targetDecl.uri;
        }
        return { targetDecl, callItemUri, symbolName };
    }
    _getIncomingCallsForDeclaration(fileUri, symbolName, declaration) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        const callFinder = new FindIncomingCallTreeWalker(this._program, fileUri, symbolName, declaration, this._token);
        const incomingCalls = callFinder.findCalls();
        return incomingCalls.length > 0 ? incomingCalls : undefined;
    }
    _getDeclaration() {
        return referencesProvider_1.ReferencesProvider.getDeclarationForPosition(this._program, this._fileUri, this._position, 
        /* reporter */ undefined, extensibility_1.ReferenceUseCase.References, this._token);
    }
}
exports.CallHierarchyProvider = CallHierarchyProvider;
class FindOutgoingCallTreeWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_fs, _parseRoot, _parseResults, _evaluator, _cancellationToken) {
        super();
        this._fs = _fs;
        this._parseRoot = _parseRoot;
        this._parseResults = _parseResults;
        this._evaluator = _evaluator;
        this._cancellationToken = _cancellationToken;
        this._outgoingCalls = [];
    }
    findCalls() {
        this.walk(this._parseRoot);
        return this._outgoingCalls;
    }
    visitCall(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        let nameNode;
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
            nameNode = node.leftExpression;
        }
        else if (node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            nameNode = node.leftExpression.memberName;
        }
        if (nameNode) {
            const declarations = this._evaluator.getDeclarationsForNameNode(nameNode);
            if (declarations) {
                // TODO - it would be better if we could match the call to the
                // specific declaration (e.g. a specific overload of a property
                // setter vs getter). For now, add callees for all declarations.
                declarations.forEach((decl) => {
                    this._addOutgoingCallForDeclaration(nameNode, decl);
                });
            }
        }
        return true;
    }
    visitMemberAccess(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        // Determine whether the member corresponds to a property.
        // If so, we'll treat it as a function call for purposes of
        // finding outgoing calls.
        const leftHandType = this._evaluator.getType(node.leftExpression);
        if (leftHandType) {
            (0, typeUtils_1.doForEachSubtype)(leftHandType, (subtype) => {
                let baseType = subtype;
                // This could be a bound TypeVar (e.g. used for "self" and "cls").
                baseType = this._evaluator.makeTopLevelTypeVarsConcrete(baseType);
                if (!(0, types_1.isClassInstance)(baseType)) {
                    return;
                }
                const memberInfo = (0, typeUtils_1.lookUpObjectMember)(baseType, node.memberName.value);
                if (!memberInfo) {
                    return;
                }
                const memberType = this._evaluator.getTypeOfMember(memberInfo);
                const propertyDecls = memberInfo.symbol.getDeclarations();
                if (!memberType) {
                    return;
                }
                if ((0, types_1.isClassInstance)(memberType) && types_1.ClassType.isPropertyClass(memberType)) {
                    propertyDecls.forEach((decl) => {
                        this._addOutgoingCallForDeclaration(node.memberName, decl);
                    });
                }
            });
        }
        return true;
    }
    _addOutgoingCallForDeclaration(nameNode, declaration) {
        var _a, _b;
        const resolvedDecl = this._evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ true);
        if (!resolvedDecl) {
            return;
        }
        if (resolvedDecl.type !== 5 /* DeclarationType.Function */ && resolvedDecl.type !== 6 /* DeclarationType.Class */) {
            return;
        }
        const callDest = {
            name: nameNode.value,
            kind: (_a = (0, lspUtils_1.getSymbolKind)(resolvedDecl, this._evaluator, nameNode.value)) !== null && _a !== void 0 ? _a : vscode_languageserver_1.SymbolKind.Module,
            uri: (0, uriUtils_1.encodeUri)(this._fs, resolvedDecl.uri),
            range: resolvedDecl.range,
            selectionRange: resolvedDecl.range,
        };
        // Is there already a call recorded for this destination? If so,
        // we'll simply add a new range. Otherwise, we'll create a new entry.
        let outgoingCall = this._outgoingCalls.find((outgoing) => outgoing.to.uri === callDest.uri && (0, textRange_1.rangesAreEqual)(outgoing.to.range, callDest.range));
        if (!outgoingCall) {
            outgoingCall = {
                to: callDest,
                fromRanges: [],
            };
            this._outgoingCalls.push(outgoingCall);
        }
        if (outgoingCall && outgoingCall.to.name !== nameNode.value) {
            // If both the function and its alias are called in the same function,
            // the name of the call item will be the resolved declaration name, not the alias.
            outgoingCall.to.name = (_b = DeclarationUtils.getNameFromDeclaration(resolvedDecl)) !== null && _b !== void 0 ? _b : nameNode.value;
        }
        const fromRange = (0, positionUtils_1.convertOffsetsToRange)(nameNode.start, nameNode.start + nameNode.length, this._parseResults.tokenizerOutput.lines);
        outgoingCall.fromRanges.push(fromRange);
    }
}
class FindIncomingCallTreeWalker extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_program, _fileUri, _symbolName, _targetDeclaration, _cancellationToken) {
        var _a;
        super();
        this._program = _program;
        this._fileUri = _fileUri;
        this._symbolName = _symbolName;
        this._targetDeclaration = _targetDeclaration;
        this._cancellationToken = _cancellationToken;
        this._incomingCalls = [];
        this._declarations = [];
        this._parseResults = this._program.getParseResults(this._fileUri);
        this._usageProviders = ((_a = this._program.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.symbolUsageProviderFactory)) !== null && _a !== void 0 ? _a : [])
            .map((f) => f.tryCreateProvider(extensibility_1.ReferenceUseCase.References, [this._targetDeclaration], this._cancellationToken))
            .filter(core_1.isDefined);
        this._declarations.push(this._targetDeclaration);
        this._usageProviders.forEach((p) => p.appendDeclarationsTo(this._declarations));
    }
    findCalls() {
        this.walk(this._parseResults.parserOutput.parseTree);
        return this._incomingCalls;
    }
    visitCall(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        let nameNode;
        if (node.leftExpression.nodeType === 38 /* ParseNodeType.Name */) {
            nameNode = node.leftExpression;
        }
        else if (node.leftExpression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            nameNode = node.leftExpression.memberName;
        }
        // Don't bother doing any more work if the name doesn't match.
        if (nameNode && nameNode.value === this._symbolName) {
            const declarations = this._getDeclarations(nameNode);
            if (declarations) {
                if (this._targetDeclaration.type === 8 /* DeclarationType.Alias */) {
                    const resolvedCurDecls = this._evaluator.resolveAliasDeclaration(this._targetDeclaration, 
                    /* resolveLocalNames */ true);
                    if (resolvedCurDecls &&
                        declarations.some((decl) => DeclarationUtils.areDeclarationsSame(decl, resolvedCurDecls))) {
                        this._addIncomingCallForDeclaration(nameNode);
                    }
                }
                else if (declarations.some((decl) => this._declarations.some((t) => DeclarationUtils.areDeclarationsSame(decl, t)))) {
                    this._addIncomingCallForDeclaration(nameNode);
                }
            }
        }
        return true;
    }
    visitMemberAccess(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        if (node.memberName.value === this._symbolName) {
            // Determine whether the member corresponds to a property.
            // If so, we'll treat it as a function call for purposes of
            // finding outgoing calls.
            const leftHandType = this._evaluator.getType(node.leftExpression);
            if (leftHandType) {
                (0, typeUtils_1.doForEachSubtype)(leftHandType, (subtype) => {
                    let baseType = subtype;
                    // This could be a bound TypeVar (e.g. used for "self" and "cls").
                    baseType = this._evaluator.makeTopLevelTypeVarsConcrete(baseType);
                    if (!(0, types_1.isClassInstance)(baseType)) {
                        return;
                    }
                    const memberInfo = (0, typeUtils_1.lookUpObjectMember)(baseType, node.memberName.value);
                    if (!memberInfo) {
                        return;
                    }
                    const memberType = this._evaluator.getTypeOfMember(memberInfo);
                    const propertyDecls = memberInfo.symbol.getDeclarations();
                    if (!memberType) {
                        return;
                    }
                    if (propertyDecls.some((decl) => DeclarationUtils.areDeclarationsSame(decl, this._targetDeclaration))) {
                        this._addIncomingCallForDeclaration(node.memberName);
                    }
                });
            }
        }
        return true;
    }
    get _evaluator() {
        return this._program.evaluator;
    }
    _getDeclarations(node) {
        const declarations = documentSymbolCollector_1.DocumentSymbolCollector.getDeclarationsForNode(this._program, node, 
        /* resolveLocalName */ true, this._cancellationToken);
        const results = [...declarations];
        this._usageProviders.forEach((p) => p.appendDeclarationsAt(node, declarations, results));
        return results;
    }
    _addIncomingCallForDeclaration(nameNode) {
        const executionNode = ParseTreeUtils.getExecutionScopeNode(nameNode);
        if (!executionNode) {
            return;
        }
        let callSource;
        if (executionNode.nodeType === 36 /* ParseNodeType.Module */) {
            const moduleRange = (0, positionUtils_1.convertOffsetsToRange)(0, 0, this._parseResults.tokenizerOutput.lines);
            const fileName = this._fileUri.fileName;
            callSource = {
                name: `(module) ${fileName}`,
                kind: vscode_languageserver_1.SymbolKind.Module,
                uri: (0, uriUtils_1.encodeUri)(this._program.fileSystem, this._fileUri),
                range: moduleRange,
                selectionRange: moduleRange,
            };
        }
        else if (executionNode.nodeType === 30 /* ParseNodeType.Lambda */) {
            const lambdaRange = (0, positionUtils_1.convertOffsetsToRange)(executionNode.start, executionNode.start + executionNode.length, this._parseResults.tokenizerOutput.lines);
            callSource = {
                name: '(lambda)',
                kind: vscode_languageserver_1.SymbolKind.Function,
                uri: (0, uriUtils_1.encodeUri)(this._program.fileSystem, this._fileUri),
                range: lambdaRange,
                selectionRange: lambdaRange,
            };
        }
        else {
            const functionRange = (0, positionUtils_1.convertOffsetsToRange)(executionNode.name.start, executionNode.name.start + executionNode.name.length, this._parseResults.tokenizerOutput.lines);
            callSource = {
                name: executionNode.name.value,
                kind: vscode_languageserver_1.SymbolKind.Function,
                uri: (0, uriUtils_1.encodeUri)(this._program.fileSystem, this._fileUri),
                range: functionRange,
                selectionRange: functionRange,
            };
        }
        // Is there already a call recorded for this caller? If so,
        // we'll simply add a new range. Otherwise, we'll create a new entry.
        let incomingCall = this._incomingCalls.find((incoming) => incoming.from.uri === callSource.uri && (0, textRange_1.rangesAreEqual)(incoming.from.range, callSource.range));
        if (!incomingCall) {
            incomingCall = {
                from: callSource,
                fromRanges: [],
            };
            this._incomingCalls.push(incomingCall);
        }
        const fromRange = (0, positionUtils_1.convertOffsetsToRange)(nameNode.start, nameNode.start + nameNode.length, this._parseResults.tokenizerOutput.lines);
        incomingCall.fromRanges.push(fromRange);
    }
}


/***/ }),

/***/ "../pyright-internal/src/languageService/codeActionProvider.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/languageService/codeActionProvider.ts ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * codeActionProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Handles 'code actions' requests from the client.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CodeActionProvider = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const commandUtils_1 = __webpack_require__(/*! ../common/commandUtils */ "../pyright-internal/src/common/commandUtils.ts");
const workspaceEditUtils_1 = __webpack_require__(/*! ../common/workspaceEditUtils */ "../pyright-internal/src/common/workspaceEditUtils.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const completionProvider_1 = __webpack_require__(/*! ./completionProvider */ "../pyright-internal/src/languageService/completionProvider.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
class CodeActionProvider {
    static mightSupport(kinds) {
        if (!kinds || kinds.length === 0) {
            return true;
        }
        // Only support quick fix actions
        return kinds.some((s) => s.startsWith(vscode_languageserver_1.CodeActionKind.QuickFix));
    }
    static async getCodeActionsForPosition(workspace, fileUri, range, kinds, token) {
        var _a, _b, _c;
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const codeActions = [];
        if (!workspace.rootUri || workspace.disableLanguageServices) {
            return codeActions;
        }
        if (!this.mightSupport(kinds)) {
            // Early exit if code actions are going to be filtered anyway.
            return codeActions;
        }
        const diags = await workspace.service.getDiagnosticsForRange(fileUri, range, token);
        const typeStubDiag = diags.find((d) => {
            const actions = d.getActions();
            return actions && actions.find((a) => a.action === "basedpyright.createtypestub" /* Commands.createTypeStub */);
        });
        if (typeStubDiag) {
            const action = typeStubDiag
                .getActions()
                .find((a) => a.action === "basedpyright.createtypestub" /* Commands.createTypeStub */);
            if (action) {
                const createTypeStubAction = vscode_languageserver_1.CodeAction.create(localize_1.Localizer.CodeAction.createTypeStubFor().format({ moduleName: action.moduleName }), (0, commandUtils_1.createCommand)(localize_1.Localizer.CodeAction.createTypeStub(), "basedpyright.createtypestub" /* Commands.createTypeStub */, workspace.rootUri.toString(), action.moduleName, fileUri.toString()), vscode_languageserver_1.CodeActionKind.QuickFix);
                codeActions.push(createTypeStubAction);
            }
        }
        const renameShadowed = diags.find((d) => {
            const actions = d.getActions();
            return actions && actions.find((a) => a.action === "renameShadowedFile" /* ActionKind.RenameShadowedFileAction */);
        });
        if (renameShadowed) {
            const action = renameShadowed
                .getActions()
                .find((a) => a.action === "renameShadowedFile" /* ActionKind.RenameShadowedFileAction */);
            if (action) {
                const title = localize_1.Localizer.CodeAction.renameShadowedFile().format({
                    oldFile: action.oldUri.getShortenedFileName(),
                    newFile: action.newUri.getShortenedFileName(),
                });
                const editActions = {
                    edits: [],
                    fileOperations: [
                        {
                            kind: 'rename',
                            oldFileUri: action.oldUri,
                            newFileUri: action.newUri,
                        },
                    ],
                };
                const workspaceEdit = (0, workspaceEditUtils_1.convertToWorkspaceEdit)(workspace.service.fs, editActions);
                const renameAction = vscode_languageserver_1.CodeAction.create(title, workspaceEdit, vscode_languageserver_1.CodeActionKind.QuickFix);
                codeActions.push(renameAction);
            }
        }
        if ((_a = diags.find((d) => { var _a; return (_a = d.getActions()) === null || _a === void 0 ? void 0 : _a.some((action) => action.action === "basedpyright.import" /* Commands.import */); })) === null || _a === void 0 ? void 0 : _a.getActions()) {
            const parseResults = workspace.service.backgroundAnalysisProgram.program.getParseResults(fileUri);
            const lines = parseResults.tokenizerOutput.lines;
            const offset = (0, positionUtils_1.convertPositionToOffset)(range.start, lines);
            if (offset === undefined) {
                return [];
            }
            const node = (0, parseTreeUtils_1.findNodeByOffset)(parseResults.parserOutput.parseTree, offset);
            if (node === undefined) {
                return [];
            }
            const completer = new completionProvider_1.CompletionProvider(workspace.service.backgroundAnalysisProgram.program, fileUri, (0, positionUtils_1.convertOffsetToPosition)(node.start + node.length, lines), {
                format: 'plaintext',
                lazyEdit: false,
                snippet: false,
            }, token);
            for (const suggestedImport of (_c = (_b = completer.getCompletions()) === null || _b === void 0 ? void 0 : _b.items) !== null && _c !== void 0 ? _c : []) {
                if (!suggestedImport.data) {
                    continue;
                }
                completer.resolveCompletionItem(suggestedImport);
                if (!completer.itemToResolve) {
                    continue;
                }
                let textEdits = [];
                if (completer.itemToResolve.textEdit && 'range' in completer.itemToResolve.textEdit) {
                    textEdits.push(completer.itemToResolve.textEdit);
                }
                if (completer.itemToResolve.additionalTextEdits) {
                    textEdits = textEdits.concat(completer.itemToResolve.additionalTextEdits);
                }
                if (textEdits.length === 0) {
                    continue;
                }
                const workspaceEdit = (0, workspaceEditUtils_1.convertToWorkspaceEdit)(completer.importResolver.fileSystem, (0, workspaceEditUtils_1.convertToFileTextEdits)(fileUri, (0, workspaceEditUtils_1.convertToTextEditActions)(textEdits)));
                codeActions.push(vscode_languageserver_1.CodeAction.create(suggestedImport.data.autoImportText.trim(), workspaceEdit, vscode_languageserver_1.CodeActionKind.QuickFix));
            }
        }
        return codeActions;
    }
}
exports.CodeActionProvider = CodeActionProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/completionProvider.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/languageService/completionProvider.ts ***!
  \*********************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * completionProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that maps a position within a Python program file into
 * a list of zero or more text completions that apply in the context.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CompletionMap = exports.CompletionProvider = exports.indexValueDetail = exports.autoImportDetail = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const declarationUtils_1 = __webpack_require__(/*! ../analyzer/declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
const docStringConversion_1 = __webpack_require__(/*! ../analyzer/docStringConversion */ "../pyright-internal/src/analyzer/docStringConversion.ts");
const importResolver_1 = __webpack_require__(/*! ../analyzer/importResolver */ "../pyright-internal/src/analyzer/importResolver.ts");
const parameterUtils_1 = __webpack_require__(/*! ../analyzer/parameterUtils */ "../pyright-internal/src/analyzer/parameterUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const scopeUtils_1 = __webpack_require__(/*! ../analyzer/scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts");
const sourceMapper_1 = __webpack_require__(/*! ../analyzer/sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const SymbolNameUtils = __importStar(__webpack_require__(/*! ../analyzer/symbolNameUtils */ "../pyright-internal/src/analyzer/symbolNameUtils.ts"));
const symbolUtils_1 = __webpack_require__(/*! ../analyzer/symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const typedDicts_1 = __webpack_require__(/*! ../analyzer/typedDicts */ "../pyright-internal/src/analyzer/typedDicts.ts");
const typeDocStringUtils_1 = __webpack_require__(/*! ../analyzer/typeDocStringUtils */ "../pyright-internal/src/analyzer/typeDocStringUtils.ts");
const typePrinter_1 = __webpack_require__(/*! ../analyzer/typePrinter */ "../pyright-internal/src/analyzer/typePrinter.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug = __importStar(__webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts"));
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const lspUtils_1 = __webpack_require__(/*! ../common/lspUtils */ "../pyright-internal/src/common/lspUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const StringUtils = __importStar(__webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts"));
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const uri_1 = __webpack_require__(/*! ../common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const workspaceEditUtils_1 = __webpack_require__(/*! ../common/workspaceEditUtils */ "../pyright-internal/src/common/workspaceEditUtils.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const parseNodes_1 = __webpack_require__(/*! ../parser/parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const autoImporter_1 = __webpack_require__(/*! ./autoImporter */ "../pyright-internal/src/languageService/autoImporter.ts");
const completionProviderUtils_1 = __webpack_require__(/*! ./completionProviderUtils */ "../pyright-internal/src/languageService/completionProviderUtils.ts");
const documentSymbolCollector_1 = __webpack_require__(/*! ./documentSymbolCollector */ "../pyright-internal/src/languageService/documentSymbolCollector.ts");
const tooltipUtils_1 = __webpack_require__(/*! ./tooltipUtils */ "../pyright-internal/src/languageService/tooltipUtils.ts");
var Keywords;
(function (Keywords) {
    const base = [
        // Expression keywords
        'True',
        'False',
        'None',
        'and',
        'or',
        'not',
        'is',
        'lambda',
        'yield',
        // Statement keywords
        'assert',
        'break',
        'class',
        'continue',
        'def',
        'del',
        'elif',
        'else',
        'except',
        'finally',
        'for',
        'from',
        'global',
        'if',
        'import',
        'in',
        'nonlocal',
        'pass',
        'raise',
        'return',
        'try',
        'type',
        'while',
        'with',
    ];
    const python3_5 = [...base, 'async', 'await'];
    const python3_10 = [...python3_5, 'case', 'match'];
    function forVersion(version) {
        if (version.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_10)) {
            return python3_10;
        }
        if (version.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_5)) {
            return python3_5;
        }
        return base;
    }
    Keywords.forVersion = forVersion;
})(Keywords || (Keywords = {}));
var SortCategory;
(function (SortCategory) {
    // The order of the following is important. We use
    // this to order the completion suggestions.
    // A keyword that must be entered for the syntax to be correct.
    SortCategory[SortCategory["LikelyKeyword"] = 0] = "LikelyKeyword";
    // A module name recently used in an import statement.
    SortCategory[SortCategory["RecentImportModuleName"] = 1] = "RecentImportModuleName";
    // A module name used in an import statement.
    SortCategory[SortCategory["ImportModuleName"] = 2] = "ImportModuleName";
    // A literal string.
    SortCategory[SortCategory["LiteralValue"] = 3] = "LiteralValue";
    // A named parameter in a call expression.
    SortCategory[SortCategory["NamedParameter"] = 4] = "NamedParameter";
    // A keyword or symbol that was recently used for completion.
    SortCategory[SortCategory["RecentKeywordOrSymbol"] = 5] = "RecentKeywordOrSymbol";
    // An auto-import symbol that was recently used for completion.
    SortCategory[SortCategory["RecentAutoImport"] = 6] = "RecentAutoImport";
    // A keyword in the python syntax.
    SortCategory[SortCategory["Keyword"] = 7] = "Keyword";
    // An enum member.
    SortCategory[SortCategory["EnumMember"] = 8] = "EnumMember";
    // A normal symbol.
    SortCategory[SortCategory["NormalSymbol"] = 9] = "NormalSymbol";
    // A symbol that starts with _ or __ (used only when there is
    // no matching filter).
    SortCategory[SortCategory["PrivateSymbol"] = 10] = "PrivateSymbol";
    // A symbol with a dunder name (e.g. __init__).
    SortCategory[SortCategory["DunderSymbol"] = 11] = "DunderSymbol";
    // An auto-import symbol.
    SortCategory[SortCategory["AutoImport"] = 12] = "AutoImport";
})(SortCategory || (SortCategory = {}));
exports.autoImportDetail = localize_1.Localizer.Completion.autoImportDetail();
exports.indexValueDetail = localize_1.Localizer.Completion.indexValueDetail();
// We'll use a somewhat-arbitrary cutoff value here to determine
// whether it's sufficiently similar.
const similarityLimit = 0.25;
// We'll remember this many completions in the MRU list.
const maxRecentCompletions = 128;
class CompletionProvider {
    constructor(program, fileUri, position, options, cancellationToken) {
        this.program = program;
        this.fileUri = fileUri;
        this.position = position;
        this.options = options;
        this.cancellationToken = cancellationToken;
        // Indicates whether invocation position is inside of string literal
        // token or an f-string expression.
        this._stringLiteralContainer = undefined;
        this.execEnv = this.configOptions.findExecEnvironment(this.fileUri);
        this.parseResults = this.program.getParseResults(this.fileUri);
        this.sourceMapper = this.program.getSourceMapper(this.fileUri, this.cancellationToken, /* mapCompiled */ true);
    }
    get importResolver() {
        return this.program.importResolver;
    }
    getCompletions() {
        if (!this.program.getSourceFileInfo(this.fileUri)) {
            return null;
        }
        const completionMap = this._getCompletions();
        return vscode_languageserver_1.CompletionList.create(completionMap === null || completionMap === void 0 ? void 0 : completionMap.toArray());
    }
    // When the user selects a completion, this callback is invoked,
    // allowing us to record what was selected. This allows us to
    // build our MRU cache so we can better predict entries.
    resolveCompletionItem(completionItem) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this.cancellationToken);
        const completionItemData = (0, lspUtils_1.fromLSPAny)(completionItem.data);
        const label = completionItem.label;
        let autoImportText = '';
        if (completionItemData.autoImportText) {
            autoImportText = completionItemData.autoImportText;
        }
        const curIndex = CompletionProvider._mostRecentCompletions.findIndex((item) => item.label === label && item.autoImportText === autoImportText);
        if (curIndex > 0) {
            // If there's an existing entry with the same name that's not at the
            // beginning of the array, remove it.
            CompletionProvider._mostRecentCompletions = CompletionProvider._mostRecentCompletions.splice(curIndex, 1);
        }
        if (curIndex !== 0) {
            // Add to the start of the array.
            CompletionProvider._mostRecentCompletions.unshift({ label, autoImportText });
        }
        if (CompletionProvider._mostRecentCompletions.length > maxRecentCompletions) {
            // Prevent the MRU list from growing indefinitely.
            CompletionProvider._mostRecentCompletions.pop();
        }
        if (!completionItemData.symbolLabel) {
            return;
        }
        if (completionItemData.moduleUri &&
            importResolver_1.ImportResolver.isSupportedImportSourceFile(uri_1.Uri.parse(completionItemData.moduleUri, this.program.serviceProvider))) {
            const documentation = (0, typeDocStringUtils_1.getModuleDocStringFromUris)([uri_1.Uri.parse(completionItemData.moduleUri, this.program.serviceProvider)], this.sourceMapper);
            if (!documentation) {
                return;
            }
            if (this.options.format === vscode_languageserver_1.MarkupKind.Markdown) {
                const markdownString = (0, docStringConversion_1.convertDocStringToMarkdown)(documentation);
                completionItem.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.Markdown,
                    value: markdownString,
                };
            }
            else if (this.options.format === vscode_languageserver_1.MarkupKind.PlainText) {
                const plainTextString = (0, docStringConversion_1.convertDocStringToPlainText)(documentation);
                completionItem.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.PlainText,
                    value: plainTextString,
                };
            }
            return;
        }
        this.itemToResolve = completionItem;
        if (!completionItemData.autoImportText) {
            // Rerun the completion lookup. It will fill in additional information
            // about the item to be resolved. We'll ignore the rest of the returned
            // list. This is a bit wasteful, but all of that information should be
            // cached, so it's not as bad as it might seem.
            this.getCompletions();
        }
        else if (!completionItem.additionalTextEdits) {
            const completionMap = new CompletionMap();
            this.addAutoImportCompletions(completionItemData.symbolLabel, 
            /* similarityLimit */ 1, 
            /* lazyEdit */ false, completionMap);
        }
    }
    get evaluator() {
        return this.program.evaluator;
    }
    get configOptions() {
        return this.program.configOptions;
    }
    getMethodOverrideCompletions(priorWord, partialName, decorators) {
        var _a, _b;
        const enclosingClass = ParseTreeUtils.getEnclosingClass(partialName, /* stopAtFunction */ true);
        if (!enclosingClass) {
            return undefined;
        }
        const classResults = this.evaluator.getTypeOfClass(enclosingClass);
        if (!classResults) {
            return undefined;
        }
        const symbolTable = new Map();
        for (let i = 1; i < classResults.classType.details.mro.length; i++) {
            const mroClass = classResults.classType.details.mro[i];
            if ((0, types_1.isInstantiableClass)(mroClass)) {
                (0, typeUtils_1.getMembersForClass)(mroClass, symbolTable, /* includeInstanceVars */ false);
            }
        }
        const staticmethod = (_a = decorators === null || decorators === void 0 ? void 0 : decorators.some((d) => ParseTreeUtils.checkDecorator(d, 'staticmethod'))) !== null && _a !== void 0 ? _a : false;
        const classmethod = (_b = decorators === null || decorators === void 0 ? void 0 : decorators.some((d) => ParseTreeUtils.checkDecorator(d, 'classmethod'))) !== null && _b !== void 0 ? _b : false;
        const completionMap = new CompletionMap();
        symbolTable.forEach((symbol, name) => {
            var _a;
            let decl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
            if (decl && decl.type === 5 /* DeclarationType.Function */) {
                if (StringUtils.isPatternInSymbol(partialName.value, name)) {
                    const declaredType = (_a = this.evaluator.getTypeForDeclaration(decl)) === null || _a === void 0 ? void 0 : _a.type;
                    if (!declaredType) {
                        return;
                    }
                    let isProperty = (0, types_1.isClassInstance)(declaredType) && types_1.ClassType.isPropertyClass(declaredType);
                    if (SymbolNameUtils.isDunderName(name)) {
                        // Don't offer suggestions for built-in properties like "__class__", etc.
                        isProperty = false;
                    }
                    if (!(0, types_1.isFunction)(declaredType) && !isProperty) {
                        return;
                    }
                    if (isProperty) {
                        // For properties, we should override the "getter", which is typically
                        // the first declaration.
                        const typedDecls = symbol.getTypedDeclarations();
                        if (typedDecls.length > 0 && typedDecls[0].type === 5 /* DeclarationType.Function */) {
                            decl = typedDecls[0];
                        }
                    }
                    const isDeclaredStaticMethod = (0, types_1.isFunction)(declaredType) && types_1.FunctionType.isStaticMethod(declaredType);
                    // Special-case the "__init_subclass__" method because it's an implicit
                    // classmethod that the type evaluator flags as a real classmethod.
                    const isDeclaredClassMethod = (0, types_1.isFunction)(declaredType) &&
                        types_1.FunctionType.isClassMethod(declaredType) &&
                        name !== '__init_subclass__';
                    if (staticmethod !== isDeclaredStaticMethod || classmethod !== isDeclaredClassMethod) {
                        return;
                    }
                    const methodSignature = this._printMethodSignature(classResults.classType, decl);
                    let text;
                    if ((0, sourceMapper_1.isStubFile)(this.fileUri)) {
                        text = `${methodSignature}: ...`;
                    }
                    else {
                        const methodBody = this.printOverriddenMethodBody(classResults.classType, isDeclaredStaticMethod, isProperty, decl, decl.node.isAsync);
                        text = `${methodSignature}:\n${methodBody}`;
                    }
                    const textEdit = this.createReplaceEdits(priorWord, partialName, text);
                    this.addSymbol(name, symbol, partialName.value, completionMap, {
                        // method signature already contains ()
                        funcParensDisabled: true,
                        edits: {
                            format: this.options.snippet ? vscode_languageserver_1.InsertTextFormat.Snippet : undefined,
                            textEdit,
                        },
                    });
                }
            }
        });
        return completionMap;
    }
    printOverriddenMethodBody(classType, isStaticMethod, isProperty, decl, insertAwait) {
        let sb = this.parseResults.tokenizerOutput.predominantTabSequence;
        if (classType.details.baseClasses.length === 1 &&
            (0, types_1.isClass)(classType.details.baseClasses[0]) &&
            classType.details.baseClasses[0].details.fullName === 'builtins.object') {
            sb += this.options.snippet ? '${0:pass}' : 'pass';
            return sb;
        }
        if (decl.node.parameters.length === 0) {
            sb += this.options.snippet ? '${0:pass}' : 'pass';
            return sb;
        }
        const parameters = getParameters(isStaticMethod ? decl.node.parameters : decl.node.parameters.slice(1));
        if (decl.node.name.value !== '__init__') {
            sb += 'return ';
        }
        if (insertAwait) {
            sb += 'await ';
        }
        if (isProperty) {
            return sb + `super().${decl.node.name.value}`;
        }
        return sb + `super().${decl.node.name.value}(${parameters.map(convertToString).join(', ')})`;
        function getParameters(parameters) {
            const results = [];
            let sawKeywordOnlySeparator = false;
            for (const parameter of parameters) {
                if (parameter.name) {
                    results.push([
                        parameter,
                        parameter.category === 0 /* ParameterCategory.Simple */ && !!parameter.name && sawKeywordOnlySeparator,
                    ]);
                }
                // All simple parameters after a `*` or `*args` parameter
                // are considered keyword only.
                if (parameter.category === 1 /* ParameterCategory.ArgsList */) {
                    sawKeywordOnlySeparator = true;
                }
            }
            return results;
        }
        function convertToString(parameter) {
            var _a;
            const name = (_a = parameter[0].name) === null || _a === void 0 ? void 0 : _a.value;
            if (parameter[0].category === 1 /* ParameterCategory.ArgsList */) {
                return `*${name}`;
            }
            if (parameter[0].category === 2 /* ParameterCategory.KwargsDict */) {
                return `**${name}`;
            }
            return parameter[1] ? `${name}=${name}` : name;
        }
    }
    createReplaceEdits(priorWord, node, text) {
        const replaceOrInsertEndChar = (node === null || node === void 0 ? void 0 : node.nodeType) === 38 /* ParseNodeType.Name */
            ? this.position.character - priorWord.length + node.value.length
            : this.position.character;
        const range = {
            start: { line: this.position.line, character: this.position.character - priorWord.length },
            end: { line: this.position.line, character: replaceOrInsertEndChar },
        };
        return vscode_languageserver_1.TextEdit.replace(range, text);
    }
    shouldProcessDeclaration(declaration) {
        // By default, we allow all symbol/decl to be included in the completion.
        return true;
    }
    addSymbol(name, symbol, priorWord, completionMap, detail) {
        var _a, _b, _c, _d;
        // Make sure we don't crash due to OOM.
        this.program.handleMemoryHighUsage();
        let primaryDecl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
        if (!primaryDecl) {
            const declarations = symbol.getDeclarations();
            if (declarations.length > 0) {
                primaryDecl = declarations[declarations.length - 1];
            }
        }
        if (!this.shouldProcessDeclaration(primaryDecl)) {
            return;
        }
        primaryDecl = primaryDecl
            ? (_a = this.evaluator.resolveAliasDeclaration(primaryDecl, /* resolveLocalNames */ true)) !== null && _a !== void 0 ? _a : primaryDecl
            : undefined;
        const autoImportText = detail.autoImportSource
            ? this.getAutoImportText(name, detail.autoImportSource, detail.autoImportAlias)
            : undefined;
        // Are we resolving a completion item? If so, see if this symbol
        // is the one that we're trying to match.
        if (this.itemToResolve) {
            const completionItemData = (0, lspUtils_1.fromLSPAny)(this.itemToResolve.data);
            if (completionItemData.symbolLabel !== name) {
                // It's not what we are looking for.
                return;
            }
            if (this.itemToResolve.additionalTextEdits === undefined &&
                ((_b = detail.edits) === null || _b === void 0 ? void 0 : _b.additionalTextEdits) !== undefined) {
                this.itemToResolve.additionalTextEdits = (0, workspaceEditUtils_1.convertToTextEdits)(detail.edits.additionalTextEdits);
            }
            if (completionItemData.autoImportText) {
                return;
            }
            // This call can be expensive to perform on every completion item
            // that we return, so we do it lazily in the "resolve" callback.
            const type = this.evaluator.getEffectiveTypeOfSymbol(symbol);
            if (!type) {
                // Can't resolve. so bail out.
                return;
            }
            const typeDetail = (0, completionProviderUtils_1.getTypeDetail)(this.evaluator, type, primaryDecl, name, detail, this.configOptions.functionSignatureDisplay);
            const documentation = (0, tooltipUtils_1.getDocumentationPartsForTypeAndDecl)(this.sourceMapper, type, primaryDecl, this.evaluator, {
                name,
                symbol,
                boundObjectOrClass: detail.boundObjectOrClass,
            });
            if (this.options.format === vscode_languageserver_1.MarkupKind.Markdown || this.options.format === vscode_languageserver_1.MarkupKind.PlainText) {
                this.itemToResolve.documentation = (0, completionProviderUtils_1.getCompletionItemDocumentation)(typeDetail, documentation, this.options.format);
            }
            else {
                (0, debug_1.fail)(`Unsupported markup type: ${this.options.format}`);
            }
            // Bail out. We don't need to add items to completion.
            return;
        }
        if (primaryDecl) {
            let itemKind = this._convertDeclarationTypeToItemKind(primaryDecl);
            // Handle enum members specially. Enum members normally look like
            // variables, but the are declared using assignment expressions
            // within an enum class.
            if (primaryDecl.type === 1 /* DeclarationType.Variable */ &&
                detail.boundObjectOrClass &&
                (0, types_1.isInstantiableClass)(detail.boundObjectOrClass) &&
                types_1.ClassType.isEnumClass(detail.boundObjectOrClass) &&
                ((_c = primaryDecl.node.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 3 /* ParseNodeType.Assignment */) {
                itemKind = vscode_languageserver_1.CompletionItemKind.EnumMember;
            }
            this.addNameToCompletions((_d = detail.autoImportAlias) !== null && _d !== void 0 ? _d : name, itemKind, priorWord, completionMap, {
                autoImportText,
                extraCommitChars: detail.extraCommitChars,
                funcParensDisabled: detail.funcParensDisabled,
                edits: detail.edits,
            });
        }
        else {
            // Does the symbol have no declaration but instead has a synthesized type?
            const synthesizedType = symbol.getSynthesizedType();
            if (synthesizedType) {
                const itemKind = this._convertTypeToItemKind(synthesizedType);
                this.addNameToCompletions(name, itemKind, priorWord, completionMap, {
                    extraCommitChars: detail.extraCommitChars,
                    funcParensDisabled: detail.funcParensDisabled,
                    edits: detail.edits,
                });
            }
        }
    }
    getMemberAccessCompletions(leftExprNode, priorWord) {
        const symbolTable = new Map();
        const completionMap = new CompletionMap();
        let leftType = this.evaluator.getType(leftExprNode);
        if (!leftType) {
            return completionMap;
        }
        leftType = this.evaluator.makeTopLevelTypeVarsConcrete(leftType);
        // If this is an unknown type with a "possible type" associated with
        // it, use the possible type.
        if ((0, types_1.isUnknown)(leftType) && leftType.possibleType) {
            leftType = this.evaluator.makeTopLevelTypeVarsConcrete(leftType.possibleType);
        }
        (0, typeUtils_1.doForEachSubtype)(leftType, (subtype) => {
            subtype = this.evaluator.makeTopLevelTypeVarsConcrete(subtype);
            if ((0, types_1.isClass)(subtype)) {
                const instance = types_1.TypeBase.isInstance(subtype);
                if (types_1.ClassType.isEnumClass(subtype) && instance) {
                    // We don't add members for instances of enum members, but do add members of `enum.Enum` itself.
                    // ex) 'MyEnum.member.' <= here
                    const enumType = subtype.details.baseClasses.find((t) => (0, types_1.isClass)(t) && types_1.ClassType.isBuiltIn(t, 'Enum'));
                    if (!enumType) {
                        return;
                    }
                    (0, typeUtils_1.getMembersForClass)(enumType, symbolTable, /* instance */ true);
                }
                else {
                    (0, typeUtils_1.getMembersForClass)(subtype, symbolTable, instance);
                }
            }
            else if ((0, types_1.isModule)(subtype)) {
                (0, typeUtils_1.getMembersForModule)(subtype, symbolTable);
            }
            else if ((0, types_1.isFunction)(subtype) || (0, types_1.isOverloadedFunction)(subtype)) {
                const functionClass = this.evaluator.getBuiltInType(leftExprNode, 'function');
                if (functionClass && (0, types_1.isInstantiableClass)(functionClass)) {
                    (0, typeUtils_1.getMembersForClass)(functionClass, symbolTable, /* includeInstanceVars */ true);
                }
            }
            else if ((0, typeUtils_1.isNoneInstance)(subtype)) {
                const objectClass = this.evaluator.getBuiltInType(leftExprNode, 'object');
                if (objectClass && (0, types_1.isInstantiableClass)(objectClass)) {
                    (0, typeUtils_1.getMembersForClass)(objectClass, symbolTable, types_1.TypeBase.isInstance(subtype));
                }
            }
            this._addSymbolsForSymbolTable(symbolTable, () => true, priorWord, leftExprNode, 
            /* isInImport */ false, (0, types_1.isClass)(subtype) ? subtype : undefined, completionMap);
        });
        return completionMap;
    }
    addAutoImportCompletions(priorWord, similarityLimit, lazyEdit, completionMap) {
        if (!this.configOptions.autoImportCompletions) {
            // If auto import on the server is turned off or this particular invocation
            // is turned off (ex, notebook), don't do any thing.
            return;
        }
        const currentFile = this.program.getSourceFileInfo(this.fileUri);
        const moduleSymbolMap = (0, autoImporter_1.buildModuleSymbolsMap)(this.program.getSourceFileInfoList().filter((s) => s !== currentFile));
        const autoImporter = new autoImporter_1.AutoImporter(this.execEnv, this.importResolver, this.parseResults, this.position, completionMap, moduleSymbolMap, {
            lazyEdit,
        });
        const results = [];
        (0, collectionUtils_1.appendArray)(results, autoImporter.getAutoImportCandidates(priorWord, similarityLimit, 
        /* abbrFromUsers */ undefined, this.cancellationToken));
        this.addImportResults(results, priorWord, completionMap);
    }
    addImportResults(results, priorWord, completionMap) {
        var _a, _b;
        for (const result of results) {
            if (result.symbol) {
                this.addSymbol(result.name, result.symbol, priorWord, completionMap, {
                    extraCommitChars: true,
                    autoImportSource: result.source,
                    autoImportAlias: result.alias,
                    edits: {
                        textEdit: this.createReplaceEdits(priorWord, /* node */ undefined, result.insertionText),
                        additionalTextEdits: result.edits,
                    },
                });
            }
            else {
                this.addNameToCompletions((_a = result.alias) !== null && _a !== void 0 ? _a : result.name, (_b = result.kind) !== null && _b !== void 0 ? _b : vscode_languageserver_1.CompletionItemKind.Module, priorWord, completionMap, {
                    extraCommitChars: true,
                    autoImportText: this.getAutoImportText(result.name, result.source, result.alias),
                    edits: {
                        textEdit: this.createReplaceEdits(priorWord, /* node */ undefined, result.insertionText),
                        additionalTextEdits: result.edits,
                    },
                });
            }
        }
    }
    addExtraCommitChar(item) {
        // extra commit char is not supported.
    }
    addNameToCompletions(name, itemKind, filter, completionMap, detail) {
        var _a, _b, _c, _d;
        // Auto importer already filtered out unnecessary ones. No need to do it again.
        const similarity = (detail === null || detail === void 0 ? void 0 : detail.autoImportText) ? true : StringUtils.isPatternInSymbol(filter, name);
        if (!similarity) {
            return;
        }
        if (completionMap.has(name, CompletionMap.matchKindAndImportText, itemKind, (_a = detail === null || detail === void 0 ? void 0 : detail.autoImportText) === null || _a === void 0 ? void 0 : _a.importText)) {
            return;
        }
        const completionItem = vscode_languageserver_1.CompletionItem.create(name);
        completionItem.kind = itemKind;
        if (detail === null || detail === void 0 ? void 0 : detail.extraCommitChars) {
            this.addExtraCommitChar(completionItem);
        }
        const completionItemData = {
            uri: this.fileUri.toString(),
            position: this.position,
        };
        if ((detail === null || detail === void 0 ? void 0 : detail.funcParensDisabled) || !this.options.snippet) {
            completionItemData.funcParensDisabled = true;
        }
        if (detail === null || detail === void 0 ? void 0 : detail.moduleUri) {
            completionItemData.moduleUri = detail.moduleUri.toString();
        }
        completionItem.data = (0, lspUtils_1.toLSPAny)(completionItemData);
        if ((detail === null || detail === void 0 ? void 0 : detail.sortText) || (detail === null || detail === void 0 ? void 0 : detail.itemDetail)) {
            completionItem.sortText = detail.sortText;
            completionItem.detail = detail.itemDetail;
        }
        else if (detail === null || detail === void 0 ? void 0 : detail.autoImportText) {
            // Force auto-import entries to the end.
            completionItem.sortText = this._makeSortText(SortCategory.AutoImport, `${name}.${this._formatInteger(detail.autoImportText.source.length, 2)}.${detail.autoImportText.source}`, detail.autoImportText.importText);
            completionItemData.autoImportText = detail.autoImportText.importText;
            completionItem.detail = exports.autoImportDetail;
            if (detail.autoImportText.source) {
                completionItem.labelDetails = { description: detail.autoImportText.source };
            }
        }
        else if (itemKind === vscode_languageserver_1.CompletionItemKind.EnumMember) {
            // Handle enum members separately so they are sorted above other symbols.
            completionItem.sortText = this._makeSortText(SortCategory.EnumMember, name);
        }
        else if (SymbolNameUtils.isDunderName(name)) {
            // Force dunder-named symbols to appear after all other symbols.
            completionItem.sortText = this._makeSortText(SortCategory.DunderSymbol, name);
        }
        else if (filter === '' && SymbolNameUtils.isPrivateOrProtectedName(name)) {
            // Distinguish between normal and private symbols only if there is
            // currently no filter text. Once we get a single character to filter
            // upon, we'll no longer differentiate.
            completionItem.sortText = this._makeSortText(SortCategory.PrivateSymbol, name);
        }
        else {
            completionItem.sortText = this._makeSortText(SortCategory.NormalSymbol, name);
        }
        completionItemData.symbolLabel = name;
        if (this.options.format === vscode_languageserver_1.MarkupKind.Markdown) {
            let markdownString = '';
            if (detail === null || detail === void 0 ? void 0 : detail.autoImportText) {
                markdownString += detail.autoImportText.importText;
                if (detail.typeDetail || detail.documentation) {
                    // Micro perf optimization to not create new string from trimEnd.
                    markdownString += '\n\n';
                }
            }
            if (detail === null || detail === void 0 ? void 0 : detail.typeDetail) {
                markdownString += '```python\n' + detail.typeDetail + '\n```\n';
            }
            if (detail === null || detail === void 0 ? void 0 : detail.documentation) {
                markdownString += '---\n';
                markdownString += (0, docStringConversion_1.convertDocStringToMarkdown)(detail.documentation);
            }
            markdownString = markdownString.trimEnd();
            if (markdownString) {
                completionItem.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.Markdown,
                    value: markdownString,
                };
            }
        }
        else if (this.options.format === vscode_languageserver_1.MarkupKind.PlainText) {
            let plainTextString = '';
            if (detail === null || detail === void 0 ? void 0 : detail.autoImportText) {
                plainTextString += detail.autoImportText.importText;
                if (detail.typeDetail || detail.documentation) {
                    // Micro perf optimization to not create new string from trimEnd.
                    plainTextString += '\n\n';
                }
            }
            if (detail === null || detail === void 0 ? void 0 : detail.typeDetail) {
                plainTextString += detail.typeDetail + '\n';
            }
            if (detail === null || detail === void 0 ? void 0 : detail.documentation) {
                plainTextString += '\n' + (0, docStringConversion_1.convertDocStringToPlainText)(detail.documentation);
            }
            plainTextString = plainTextString.trimEnd();
            if (plainTextString) {
                completionItem.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.PlainText,
                    value: plainTextString,
                };
            }
        }
        else {
            (0, debug_1.fail)(`Unsupported markup type: ${this.options.format}`);
        }
        if ((_b = detail === null || detail === void 0 ? void 0 : detail.edits) === null || _b === void 0 ? void 0 : _b.format) {
            completionItem.insertTextFormat = detail.edits.format;
        }
        if ((_c = detail === null || detail === void 0 ? void 0 : detail.edits) === null || _c === void 0 ? void 0 : _c.textEdit) {
            completionItem.textEdit = detail.edits.textEdit;
        }
        if ((_d = detail === null || detail === void 0 ? void 0 : detail.edits) === null || _d === void 0 ? void 0 : _d.additionalTextEdits) {
            completionItem.additionalTextEdits = (0, workspaceEditUtils_1.convertToTextEdits)(detail.edits.additionalTextEdits);
            // This is for auto import entries from indices which skip symbols.
            if (this.itemToResolve) {
                const data = (0, lspUtils_1.fromLSPAny)(this.itemToResolve.data);
                if (data.autoImportText === completionItemData.autoImportText) {
                    this.itemToResolve.additionalTextEdits = completionItem.additionalTextEdits;
                }
            }
        }
        completionMap.set(completionItem);
    }
    getAutoImportText(importName, importFrom, importAlias) {
        const autoImportText = (0, tooltipUtils_1.getAutoImportText)(importName, importFrom, importAlias);
        let importText = '';
        if (this.options.format === vscode_languageserver_1.MarkupKind.Markdown) {
            importText = `\`\`\`\n${autoImportText}\n\`\`\``;
        }
        else if (this.options.format === vscode_languageserver_1.MarkupKind.PlainText) {
            importText = autoImportText;
        }
        else {
            (0, debug_1.fail)(`Unsupported markup type: ${this.options.format}`);
        }
        return {
            source: importFrom !== null && importFrom !== void 0 ? importFrom : '',
            importText,
        };
    }
    get _fileContents() {
        var _a, _b;
        return (_b = (_a = this.parseResults) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '';
    }
    _getCompletions() {
        var _a, _b;
        const offset = (0, positionUtils_1.convertPositionToOffset)(this.position, this.parseResults.tokenizerOutput.lines);
        if (offset === undefined) {
            return undefined;
        }
        let node = ParseTreeUtils.findNodeByOffset(this.parseResults.parserOutput.parseTree, offset);
        // See if we're inside a string literal or an f-string statement.
        const token = ParseTreeUtils.getTokenOverlapping(this.parseResults.tokenizerOutput.tokens, offset);
        if ((token === null || token === void 0 ? void 0 : token.type) === 5 /* TokenType.String */) {
            const stringToken = token;
            this._stringLiteralContainer = textRange_1.TextRange.contains(stringToken, offset)
                ? stringToken
                : stringToken.flags & 65536 /* StringTokenFlags.Unterminated */
                    ? stringToken
                    : undefined;
        }
        else if (node) {
            const fStringContainer = ParseTreeUtils.getParentNodeOfType(node, 27 /* ParseNodeType.FormatString */);
            if (fStringContainer) {
                this._stringLiteralContainer = fStringContainer.token;
            }
        }
        // See if we can get to a "better" node by backing up a few columns.
        // A "better" node is defined as one that's deeper than the current
        // node.
        const initialNode = node;
        const initialDepth = node ? ParseTreeUtils.getNodeDepth(node) : 0;
        if (!initialNode || initialNode.nodeType !== 38 /* ParseNodeType.Name */) {
            let curOffset = offset;
            let sawComma = false;
            while (curOffset >= 0) {
                curOffset--;
                // Stop scanning backward if we hit certain stop characters.
                const curChar = this._fileContents.substr(curOffset, 1);
                if (curChar === '(' || curChar === '\n' || curChar === '}') {
                    break;
                }
                if (curChar === ',') {
                    sawComma = true;
                }
                const curNode = ParseTreeUtils.findNodeByOffset(this.parseResults.parserOutput.parseTree, curOffset);
                if (curNode && curNode !== initialNode) {
                    if (ParseTreeUtils.getNodeDepth(curNode) > initialDepth) {
                        node = curNode;
                        // If we're at the end of a list with a hanging comma, handle the
                        // special case of "from x import y, ".
                        if (sawComma && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 23 /* ParseNodeType.ImportFromAs */) {
                            node = node.parent;
                        }
                    }
                    break;
                }
            }
        }
        if (node === undefined) {
            return undefined;
        }
        // Get the text on that line prior to the insertion point.
        const lineTextRange = this.parseResults.tokenizerOutput.lines.getItemAt(this.position.line);
        const textOnLine = this._fileContents.substr(lineTextRange.start, lineTextRange.length);
        const priorText = textOnLine.substr(0, this.position.character);
        const postText = textOnLine.substr(this.position.character);
        const priorWordIndex = priorText.search(/\w+$/);
        const priorWord = priorWordIndex >= 0 ? priorText.substr(priorWordIndex) : '';
        // Don't offer completions if we're within a comment.
        if (this._isWithinComment(offset)) {
            return undefined;
        }
        // See if the node is part of an error node. If so, that takes
        // precedence.
        let errorNode = node;
        while (errorNode) {
            if (errorNode.nodeType === 0 /* ParseNodeType.Error */) {
                break;
            }
            errorNode = errorNode.parent;
        }
        // Determine the context based on the parse node's type and
        // that of its ancestors.
        let curNode = errorNode || node;
        while (true) {
            (0, cancellationUtils_1.throwIfCancellationRequested)(this.cancellationToken);
            if (curNode.nodeType === 49 /* ParseNodeType.String */) {
                return this._getLiteralCompletions(curNode, offset, priorWord, priorText, postText);
            }
            if (curNode.nodeType === 48 /* ParseNodeType.StringList */ || curNode.nodeType === 27 /* ParseNodeType.FormatString */) {
                return undefined;
            }
            if (curNode.nodeType === 37 /* ParseNodeType.ModuleName */) {
                return this._getImportModuleCompletions(curNode);
            }
            if (curNode.nodeType === 0 /* ParseNodeType.Error */) {
                return this._getExpressionErrorCompletions(curNode, offset, priorWord, priorText, postText);
            }
            if (curNode.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                return this.getMemberAccessCompletions(curNode.leftExpression, priorWord);
            }
            if (curNode.nodeType === 15 /* ParseNodeType.Dictionary */) {
                const completionMap = new CompletionMap();
                if (this._tryAddTypedDictKeysFromDictionary(curNode, 
                /* stringNode */ undefined, priorWord, priorText, postText, completionMap)) {
                    return completionMap;
                }
            }
            const dictionaryEntry = ParseTreeUtils.getFirstAncestorOrSelfOfKind(curNode, 17 /* ParseNodeType.DictionaryKeyEntry */);
            if (dictionaryEntry) {
                if (((_b = dictionaryEntry.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 15 /* ParseNodeType.Dictionary */) {
                    const dictionaryNode = dictionaryEntry.parent;
                    if (dictionaryNode.trailingCommaToken && dictionaryNode.trailingCommaToken.start < offset) {
                        const completionMap = new CompletionMap();
                        if (this._tryAddTypedDictKeysFromDictionary(dictionaryNode, 
                        /* stringNode */ undefined, priorWord, priorText, postText, completionMap)) {
                            return completionMap;
                        }
                    }
                }
            }
            if (curNode.nodeType === 38 /* ParseNodeType.Name */) {
                // This condition is little different than others since it does its own
                // tree walk up to find context and let outer tree walk up to proceed if it can't find
                // one to show completion.
                const result = this._tryGetNameCompletions(curNode, offset, priorWord, priorText, postText);
                if (result || result === undefined) {
                    return result;
                }
            }
            if (curNode.nodeType === 31 /* ParseNodeType.List */ && this.options.triggerCharacter === '[') {
                // If this is an empty list, don't start putting completions up yet.
                return undefined;
            }
            if (curNode.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                return this._getImportFromCompletions(curNode, priorWord);
            }
            if ((0, parseNodes_1.isExpressionNode)(curNode)) {
                return this._getExpressionCompletions(curNode, priorWord, priorText, postText);
            }
            if (curNode.nodeType === 50 /* ParseNodeType.Suite */) {
                if (curNode.parent &&
                    curNode.parent.nodeType === 25 /* ParseNodeType.Except */ &&
                    !curNode.parent.name &&
                    curNode.parent.typeExpression &&
                    textRange_1.TextRange.getEnd(curNode.parent.typeExpression) < offset &&
                    offset <= curNode.parent.exceptSuite.start) {
                    // except Exception as [<empty>]
                    return undefined;
                }
                if (curNode.parent &&
                    curNode.parent.nodeType === 10 /* ParseNodeType.Class */ &&
                    (!curNode.parent.name || !curNode.parent.name.value) &&
                    curNode.parent.arguments.length === 0 &&
                    offset <= curNode.parent.suite.start) {
                    // class [<empty>]
                    return undefined;
                }
                return this._getStatementCompletions(curNode, priorWord, priorText, postText);
            }
            if (curNode.nodeType === 36 /* ParseNodeType.Module */) {
                return this._getStatementCompletions(curNode, priorWord, priorText, postText);
            }
            if (curNode.nodeType === 41 /* ParseNodeType.Parameter */ &&
                curNode.length === 0 &&
                curNode.parent &&
                curNode.parent.nodeType === 30 /* ParseNodeType.Lambda */) {
                // lambda [<empty>] or lambda x, [<empty>]
                return undefined;
            }
            if (!curNode.parent) {
                break;
            }
            curNode = curNode.parent;
        }
        return undefined;
    }
    // This method returns false if it wants the caller to walk up the
    // tree. It returns CompletionResults or undefined if it wants the
    // caller to return.
    _tryGetNameCompletions(curNode, offset, priorWord, priorText, postText) {
        var _a, _b, _c;
        if (!curNode.parent) {
            return false;
        }
        if (curNode.parent.nodeType === 21 /* ParseNodeType.ImportAs */ && curNode.parent.alias === curNode) {
            // Are we within a "import Y as [Z]"?
            return undefined;
        }
        if (curNode.parent.nodeType === 37 /* ParseNodeType.ModuleName */) {
            // Are we within a "import Y as [<empty>]"?
            if (curNode.parent.parent &&
                curNode.parent.parent.nodeType === 21 /* ParseNodeType.ImportAs */ &&
                !curNode.parent.parent.alias &&
                textRange_1.TextRange.getEnd(curNode.parent.parent) < offset) {
                return undefined;
            }
            // Are we within a "from X import Y as Z" statement and
            // more specifically within the "Y"?
            return this._getImportModuleCompletions(curNode.parent);
        }
        if (curNode.parent.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
            if (curNode.parent.alias === curNode) {
                // Are we within a "from X import Y as [Z]"?
                return undefined;
            }
            const parentNode = curNode.parent.parent;
            if (parentNode && parentNode.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                // Are we within a "from X import Y as [<empty>]"?
                if (!curNode.parent.alias && textRange_1.TextRange.getEnd(curNode.parent) < offset) {
                    return undefined;
                }
                if (curNode.parent.name === curNode) {
                    return this._getImportFromCompletions(parentNode, priorWord);
                }
                return this._getImportFromCompletions(parentNode, '');
            }
            return false;
        }
        if (curNode.parent.nodeType === 35 /* ParseNodeType.MemberAccess */ && curNode === curNode.parent.memberName) {
            return this.getMemberAccessCompletions(curNode.parent.leftExpression, priorWord);
        }
        if (curNode.parent.nodeType === 25 /* ParseNodeType.Except */ && curNode === curNode.parent.name) {
            return undefined;
        }
        if (curNode.parent.nodeType === 28 /* ParseNodeType.Function */ && curNode === curNode.parent.name) {
            if ((_a = curNode.parent.decorators) === null || _a === void 0 ? void 0 : _a.some((d) => this._isOverload(d))) {
                return this._getMethodOverloadsCompletions(priorWord, curNode);
            }
            return undefined;
        }
        if (curNode.parent.nodeType === 41 /* ParseNodeType.Parameter */ && curNode === curNode.parent.name) {
            return undefined;
        }
        if (curNode.parent.nodeType === 10 /* ParseNodeType.Class */ && curNode === curNode.parent.name) {
            return undefined;
        }
        if (curNode.parent.nodeType === 26 /* ParseNodeType.For */ &&
            textRange_1.TextRange.contains(curNode.parent.targetExpression, curNode.start)) {
            return undefined;
        }
        if (curNode.parent.nodeType === 33 /* ParseNodeType.ListComprehensionFor */ &&
            textRange_1.TextRange.contains(curNode.parent.targetExpression, curNode.start)) {
            return undefined;
        }
        // For assignments that implicitly declare variables, remove itself (var decl) from completion.
        if (curNode.parent.nodeType === 3 /* ParseNodeType.Assignment */ ||
            curNode.parent.nodeType === 4 /* ParseNodeType.AssignmentExpression */) {
            const leftNode = curNode.parent.nodeType === 4 /* ParseNodeType.AssignmentExpression */
                ? curNode.parent.name
                : curNode.parent.leftExpression;
            if (leftNode !== curNode || priorWord.length === 0) {
                return false;
            }
            const decls = this.evaluator.getDeclarationsForNameNode(curNode);
            if ((decls === null || decls === void 0 ? void 0 : decls.length) !== 1 || !(0, declaration_1.isVariableDeclaration)(decls[0]) || decls[0].node !== curNode) {
                return false;
            }
            const completionMap = this._getExpressionCompletions(curNode, priorWord, priorText, postText);
            if (completionMap) {
                completionMap.delete(curNode.value);
            }
            return completionMap;
        }
        // Defining class variables.
        // ex) class A:
        //         variable = 1
        if (curNode.parent.nodeType === 47 /* ParseNodeType.StatementList */ &&
            ((_b = curNode.parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 50 /* ParseNodeType.Suite */ &&
            ((_c = curNode.parent.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 10 /* ParseNodeType.Class */) {
            const completionList = this._getClassVariableCompletions(curNode);
            if (completionList) {
                return completionList;
            }
        }
        return false;
    }
    _isWithinComment(offset) {
        var _a, _b;
        const token = getTokenAfter(offset, this.parseResults.tokenizerOutput.tokens);
        if (!token) {
            // If we're in the middle of a token, we're not in a comment.
            return false;
        }
        return (_b = (_a = token.comments) === null || _a === void 0 ? void 0 : _a.some((c) => textRange_1.TextRange.overlaps(c, offset))) !== null && _b !== void 0 ? _b : false;
        function getTokenAfter(offset, tokens) {
            const tokenIndex = tokens.getItemAtPosition(offset);
            if (tokenIndex < 0) {
                return undefined;
            }
            let token = tokens.getItemAt(tokenIndex);
            // If we're in the middle of a token, we can't be within a comment.
            if (offset > token.start && offset < token.start + token.length) {
                return undefined;
            }
            // Multiple zero length tokens can occupy same position.
            // But comment is associated with the first one. loop
            // backward to find the first token if position is same.
            for (let i = tokenIndex - 1; i >= 0; i--) {
                const prevToken = tokens.getItemAt(i);
                if (token.start !== prevToken.start) {
                    break;
                }
                token = prevToken;
            }
            if (offset <= token.start) {
                return token;
            }
            // If offset > token.start, tokenIndex + 1 < tokens.length
            // should be always true.
            debug.assert(tokenIndex + 1 < tokens.length);
            return tokens.getItemAt(tokenIndex + 1);
        }
    }
    _getExpressionErrorCompletions(node, offset, priorWord, priorText, postText) {
        var _a;
        // Is the error due to a missing member access name? If so,
        // we can evaluate the left side of the member access expression
        // to determine its type and offer suggestions based on it.
        switch (node.category) {
            case 0 /* ErrorExpressionCategory.MissingIn */: {
                return this._createSingleKeywordCompletion('in');
            }
            case 1 /* ErrorExpressionCategory.MissingElse */: {
                return this._createSingleKeywordCompletion('else');
            }
            case 7 /* ErrorExpressionCategory.MissingMemberAccessName */:
            case 2 /* ErrorExpressionCategory.MissingExpression */: {
                // Don't show completion after random dots.
                const tokenizerOutput = this.parseResults.tokenizerOutput;
                const offset = (0, positionUtils_1.convertPositionToOffset)(this.position, tokenizerOutput.lines);
                const index = ParseTreeUtils.getTokenIndexAtLeft(tokenizerOutput.tokens, offset);
                const token = ParseTreeUtils.getTokenAtIndex(tokenizerOutput.tokens, index);
                const prevToken = ParseTreeUtils.getTokenAtIndex(tokenizerOutput.tokens, index - 1);
                if (node.category === 2 /* ErrorExpressionCategory.MissingExpression */) {
                    // Skip dots on expressions.
                    if ((token === null || token === void 0 ? void 0 : token.type) === 20 /* TokenType.Dot */ || (token === null || token === void 0 ? void 0 : token.type) === 19 /* TokenType.Ellipsis */) {
                        break;
                    }
                    // ex) class MyType:
                    //         def is_str(self): ...
                    //     myType = MyType()
                    //
                    // In incomplete code such as "myType.is" <= "is" will be tokenized as keyword not identifier,
                    // so even if user's intention is writing "is_str", completion after "is" won't include "is_str"
                    // since parser won't see "is" as partially written member name instead it will see it as
                    // expression statement with missing expression after "is" keyword.
                    // In such case, use "MyType." to get completion.
                    if ((token === null || token === void 0 ? void 0 : token.type) !== 8 /* TokenType.Keyword */ || textRange_1.TextRange.getEnd(token) !== offset) {
                        return this._getExpressionCompletions(node, priorWord, priorText, postText);
                    }
                    if ((prevToken === null || prevToken === void 0 ? void 0 : prevToken.type) !== 20 /* TokenType.Dot */) {
                        return this._getExpressionCompletions(node, priorWord, priorText, postText);
                    }
                    const previousOffset = textRange_1.TextRange.getEnd(prevToken);
                    const previousNode = ParseTreeUtils.findNodeByOffset(this.parseResults.parserOutput.parseTree, previousOffset);
                    if ((previousNode === null || previousNode === void 0 ? void 0 : previousNode.nodeType) !== 0 /* ParseNodeType.Error */ ||
                        previousNode.category !== 7 /* ErrorExpressionCategory.MissingMemberAccessName */) {
                        return this._getExpressionCompletions(node, priorWord, priorText, postText);
                    }
                    else {
                        // Update node to previous node so we get the member access completions.
                        node = previousNode;
                    }
                }
                else if (node.category === 7 /* ErrorExpressionCategory.MissingMemberAccessName */) {
                    // Skip double dots on member access.
                    if (((token === null || token === void 0 ? void 0 : token.type) === 20 /* TokenType.Dot */ || (token === null || token === void 0 ? void 0 : token.type) === 19 /* TokenType.Ellipsis */) &&
                        ((prevToken === null || prevToken === void 0 ? void 0 : prevToken.type) === 20 /* TokenType.Dot */ || (prevToken === null || prevToken === void 0 ? void 0 : prevToken.type) === 19 /* TokenType.Ellipsis */)) {
                        return undefined;
                    }
                }
                return this._getMissingMemberAccessNameCompletions(node, priorWord);
            }
            case 4 /* ErrorExpressionCategory.MissingDecoratorCallName */: {
                return this._getExpressionCompletions(node, priorWord, priorText, postText);
            }
            case 11 /* ErrorExpressionCategory.MissingPattern */:
            case 3 /* ErrorExpressionCategory.MissingIndexOrSlice */: {
                let completionResults = this._getLiteralCompletions(node, offset, priorWord, priorText, postText);
                if (!completionResults) {
                    completionResults = this._getExpressionCompletions(node, priorWord, priorText, postText);
                }
                return completionResults;
            }
            case 10 /* ErrorExpressionCategory.MissingFunctionParameterList */: {
                if (node.child && node.child.nodeType === 38 /* ParseNodeType.Name */) {
                    if ((_a = node.decorators) === null || _a === void 0 ? void 0 : _a.some((d) => this._isOverload(d))) {
                        return this._getMethodOverloadsCompletions(priorWord, node.child);
                    }
                    // Determine if the partial name is a method that's overriding
                    // a method in a base class.
                    return this.getMethodOverrideCompletions(priorWord, node.child, node.decorators);
                }
                break;
            }
        }
        return undefined;
    }
    _getMissingMemberAccessNameCompletions(node, priorWord) {
        if (!node.child || !(0, parseNodes_1.isExpressionNode)(node.child)) {
            return undefined;
        }
        return this.getMemberAccessCompletions(node.child, priorWord);
    }
    _isOverload(node) {
        return ParseTreeUtils.checkDecorator(node, 'overload');
    }
    _createSingleKeywordCompletion(keyword) {
        const completionItem = vscode_languageserver_1.CompletionItem.create(keyword);
        completionItem.kind = vscode_languageserver_1.CompletionItemKind.Keyword;
        completionItem.sortText = this._makeSortText(SortCategory.LikelyKeyword, keyword);
        const completionMap = new CompletionMap();
        completionMap.set(completionItem);
        return completionMap;
    }
    _addClassVariableTypeAnnotationCompletions(priorWord, parseNode, completionMap) {
        var _a, _b, _c, _d;
        // class T:
        //    f: |<= here
        const isTypeAnnotationOfClassVariable = ((_a = parseNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 54 /* ParseNodeType.TypeAnnotation */ &&
            parseNode.parent.valueExpression.nodeType === 38 /* ParseNodeType.Name */ &&
            parseNode.parent.typeAnnotation === parseNode &&
            ((_b = parseNode.parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 47 /* ParseNodeType.StatementList */ &&
            ((_c = parseNode.parent.parent.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 50 /* ParseNodeType.Suite */ &&
            ((_d = parseNode.parent.parent.parent.parent) === null || _d === void 0 ? void 0 : _d.nodeType) === 10 /* ParseNodeType.Class */;
        if (!isTypeAnnotationOfClassVariable) {
            return;
        }
        const enclosingClass = ParseTreeUtils.getEnclosingClass(parseNode, false);
        if (!enclosingClass) {
            return;
        }
        const classResults = this.evaluator.getTypeOfClass(enclosingClass);
        if (!classResults) {
            return undefined;
        }
        const classVariableName = parseNode.parent.valueExpression.value;
        const classMember = (0, typeUtils_1.lookUpClassMember)(classResults.classType, classVariableName, 16 /* MemberAccessFlags.SkipInstanceMembers */ | 1 /* MemberAccessFlags.SkipOriginalClass */);
        // First, see whether we can use semantic info to get variable type.
        if (classMember) {
            const memberType = this.evaluator.getTypeOfMember(classMember);
            const text = this.evaluator.printType(memberType, {
                enforcePythonSyntax: true,
                expandTypeAlias: false,
            });
            this.addNameToCompletions(text, vscode_languageserver_1.CompletionItemKind.Reference, priorWord, completionMap, {
                sortText: this._makeSortText(SortCategory.LikelyKeyword, text),
            });
            return;
        }
        // If we can't do that using semantic info, then try syntactic info.
        const symbolTable = new Map();
        for (const mroClass of classResults.classType.details.mro) {
            if (mroClass === classResults.classType) {
                // Ignore current type.
                continue;
            }
            if ((0, types_1.isInstantiableClass)(mroClass)) {
                (0, typeUtils_1.getMembersForClass)(mroClass, symbolTable, /* includeInstanceVars */ false);
            }
        }
        const symbol = symbolTable.get(classVariableName);
        if (!symbol) {
            return;
        }
        const decls = symbol
            .getDeclarations()
            .filter((d) => (0, declaration_1.isVariableDeclaration)(d) && d.moduleName !== 'builtins');
        // Skip any symbols invalid such as defined in the same class.
        if (decls.length === 0 ||
            decls.some((d) => d.node && ParseTreeUtils.getEnclosingClass(d.node, false) === enclosingClass)) {
            return;
        }
        const declWithTypeAnnotations = decls.filter((d) => d.typeAnnotationNode);
        if (declWithTypeAnnotations.length === 0) {
            return;
        }
        const printFlags = (0, sourceMapper_1.isStubFile)(this.fileUri)
            ? 1 /* ParseTreeUtils.PrintExpressionFlags.ForwardDeclarations */ |
                2 /* ParseTreeUtils.PrintExpressionFlags.DoNotLimitStringLength */
            : 2 /* ParseTreeUtils.PrintExpressionFlags.DoNotLimitStringLength */;
        const text = `${ParseTreeUtils.printExpression(declWithTypeAnnotations[declWithTypeAnnotations.length - 1].typeAnnotationNode, printFlags)}`;
        this.addNameToCompletions(text, vscode_languageserver_1.CompletionItemKind.Reference, priorWord, completionMap, {
            sortText: this._makeSortText(SortCategory.LikelyKeyword, text),
        });
    }
    _getClassVariableCompletions(partialName) {
        const enclosingClass = ParseTreeUtils.getEnclosingClass(partialName, false);
        if (!enclosingClass) {
            return undefined;
        }
        const classResults = this.evaluator.getTypeOfClass(enclosingClass);
        if (!classResults) {
            return undefined;
        }
        const symbolTable = new Map();
        for (const mroClass of classResults.classType.details.mro) {
            if ((0, types_1.isInstantiableClass)(mroClass)) {
                (0, typeUtils_1.getMembersForClass)(mroClass, symbolTable, /* includeInstanceVars */ false);
            }
        }
        const completionMap = new CompletionMap();
        symbolTable.forEach((symbol, name) => {
            if (SymbolNameUtils.isPrivateName(name) ||
                symbol.isPrivateMember() ||
                symbol.isExternallyHidden() ||
                !StringUtils.isPatternInSymbol(partialName.value, name)) {
                return;
            }
            const decls = symbol
                .getDeclarations()
                .filter((d) => (0, declaration_1.isVariableDeclaration)(d) && d.moduleName !== 'builtins');
            // Skip any symbols invalid such as defined in the same class.
            if (decls.length === 0 ||
                decls.some((d) => d.node && ParseTreeUtils.getEnclosingClass(d.node, false) === enclosingClass)) {
                return;
            }
            this.addSymbol(name, symbol, partialName.value, completionMap, {});
        });
        return completionMap.size > 0 ? completionMap : undefined;
    }
    _getMethodOverloadsCompletions(priorWord, partialName) {
        var _a;
        const symbolTable = getSymbolTable(this.evaluator, partialName);
        if (!symbolTable) {
            return undefined;
        }
        const funcParensDisabled = ((_a = partialName.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 28 /* ParseNodeType.Function */ ? true : undefined;
        const completionMap = new CompletionMap();
        const enclosingFunc = ParseTreeUtils.getEnclosingFunction(partialName);
        symbolTable.forEach((symbol, name) => {
            const decl = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
            if (!decl || decl.type !== 5 /* DeclarationType.Function */) {
                return;
            }
            if (!decl.node.decorators.some((d) => this._isOverload(d))) {
                // Only consider ones that have overload decorator.
                return;
            }
            const decls = symbol.getDeclarations();
            if (decls.length === 1 && decls.some((d) => d.node === enclosingFunc)) {
                // Don't show itself.
                return;
            }
            if (StringUtils.isPatternInSymbol(partialName.value, name)) {
                const textEdit = this.createReplaceEdits(priorWord, partialName, decl.node.name.value);
                this.addSymbol(name, symbol, partialName.value, completionMap, {
                    funcParensDisabled,
                    edits: { textEdit },
                });
            }
        });
        return completionMap;
        function getSymbolTable(evaluator, partialName) {
            const enclosingClass = ParseTreeUtils.getEnclosingClass(partialName, false);
            if (enclosingClass) {
                const classResults = evaluator.getTypeOfClass(enclosingClass);
                if (!classResults) {
                    return undefined;
                }
                const symbolTable = new Map();
                for (const mroClass of classResults.classType.details.mro) {
                    if ((0, types_1.isInstantiableClass)(mroClass)) {
                        (0, typeUtils_1.getMembersForClass)(mroClass, symbolTable, /* includeInstanceVars */ false);
                    }
                }
                return symbolTable;
            }
            // For function overload, we only care about top level functions
            const moduleNode = ParseTreeUtils.getEnclosingModule(partialName);
            if (moduleNode) {
                const moduleScope = AnalyzerNodeInfo.getScope(moduleNode);
                return moduleScope === null || moduleScope === void 0 ? void 0 : moduleScope.symbolTable;
            }
            return undefined;
        }
    }
    _printMethodSignature(classType, decl) {
        const node = decl.node;
        let ellipsisForDefault;
        if ((0, sourceMapper_1.isStubFile)(this.fileUri)) {
            // In stubs, always use "...".
            ellipsisForDefault = true;
        }
        else if (classType.details.moduleName === decl.moduleName) {
            // In the same file, always print the full default.
            ellipsisForDefault = false;
        }
        const printFlags = (0, sourceMapper_1.isStubFile)(this.fileUri)
            ? 1 /* ParseTreeUtils.PrintExpressionFlags.ForwardDeclarations */ |
                2 /* ParseTreeUtils.PrintExpressionFlags.DoNotLimitStringLength */
            : 2 /* ParseTreeUtils.PrintExpressionFlags.DoNotLimitStringLength */;
        const paramList = node.parameters
            .map((param, index) => {
            let paramString = '';
            if (param.category === 1 /* ParameterCategory.ArgsList */) {
                paramString += '*';
            }
            else if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                paramString += '**';
            }
            if (param.name) {
                paramString += param.name.value;
            }
            // Currently, we don't automatically add import if the type used in the annotation is not imported
            // in current file.
            const paramTypeAnnotation = ParseTreeUtils.getTypeAnnotationForParameter(node, index);
            if (paramTypeAnnotation) {
                paramString += ': ' + ParseTreeUtils.printExpression(paramTypeAnnotation, printFlags);
            }
            if (param.defaultValue) {
                paramString += paramTypeAnnotation ? ' = ' : '=';
                const useEllipsis = ellipsisForDefault !== null && ellipsisForDefault !== void 0 ? ellipsisForDefault : !ParseTreeUtils.isSimpleDefault(param.defaultValue);
                paramString += useEllipsis ? '...' : ParseTreeUtils.printExpression(param.defaultValue, printFlags);
            }
            if (!paramString && !param.name && param.category === 0 /* ParameterCategory.Simple */) {
                return '/';
            }
            return paramString;
        })
            .join(', ');
        let methodSignature = node.name.value + '(' + paramList + ')';
        if (node.returnTypeAnnotation) {
            methodSignature += ' -> ' + ParseTreeUtils.printExpression(node.returnTypeAnnotation, printFlags);
        }
        else if (node.functionAnnotationComment) {
            methodSignature +=
                ' -> ' +
                    ParseTreeUtils.printExpression(node.functionAnnotationComment.returnTypeAnnotation, printFlags);
        }
        return methodSignature;
    }
    _getStatementCompletions(parseNode, priorWord, priorText, postText) {
        // For now, use the same logic for expressions and statements.
        return this._getExpressionCompletions(parseNode, priorWord, priorText, postText);
    }
    _getExpressionCompletions(parseNode, priorWord, priorText, postText) {
        var _a, _b;
        const isIndexArgument = this._isIndexArgument(parseNode);
        // If the user typed a "." as part of a number, don't present
        // any completion options.
        if (!isIndexArgument && parseNode.nodeType === 40 /* ParseNodeType.Number */) {
            return undefined;
        }
        // Are we within a "with Y as []"?
        // Don't add any completion options.
        if (((_a = parseNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 59 /* ParseNodeType.WithItem */ &&
            parseNode.parent === ((_b = parseNode.parent.target) === null || _b === void 0 ? void 0 : _b.parent)) {
            return undefined;
        }
        const completionMap = new CompletionMap();
        // Return empty completionList for Ellipsis
        if (priorText.slice(-2) === '..') {
            return completionMap;
        }
        // Defining type annotation for class variables.
        // ex) class A:
        //         variable: | <= here
        this._addClassVariableTypeAnnotationCompletions(priorWord, parseNode, completionMap);
        // Add call argument completions.
        this._addCallArgumentCompletions(parseNode, priorWord, priorText, postText, 
        /* atArgument */ false, completionMap);
        // Add symbols that are in scope.
        this._addSymbols(parseNode, priorWord, completionMap);
        // Add keywords.
        this._findMatchingKeywords(Keywords.forVersion(this.execEnv.pythonVersion), priorWord).map((keyword) => {
            if (completionMap.has(keyword)) {
                return;
            }
            const completionItem = vscode_languageserver_1.CompletionItem.create(keyword);
            completionItem.kind = vscode_languageserver_1.CompletionItemKind.Keyword;
            completionItem.sortText = this._makeSortText(SortCategory.Keyword, keyword);
            completionMap.set(completionItem);
        });
        // Add auto-import suggestions from other modules.
        // Ignore this check for privates, since they are not imported.
        if (!priorWord.startsWith('_') && !this.itemToResolve) {
            this.addAutoImportCompletions(priorWord, similarityLimit, this.options.lazyEdit, completionMap);
        }
        // Add literal values if appropriate.
        this._tryAddLiterals(parseNode, priorWord, priorText, postText, completionMap);
        return completionMap;
    }
    _isIndexArgument(node) {
        const currentNode = node.parent;
        return (currentNode &&
            currentNode.nodeType === 1 /* ParseNodeType.Argument */ &&
            currentNode.argumentCategory === 0 /* ArgumentCategory.Simple */ &&
            currentNode.parent &&
            currentNode.parent.nodeType === 24 /* ParseNodeType.Index */ &&
            currentNode.parent.baseExpression &&
            currentNode.parent.baseExpression.nodeType === 38 /* ParseNodeType.Name */);
    }
    _addCallArgumentCompletions(parseNode, priorWord, priorText, postText, atArgument, completionMap) {
        // If we're within the argument list of a call, add parameter names.
        const offset = (0, positionUtils_1.convertPositionToOffset)(this.position, this.parseResults.tokenizerOutput.lines);
        const callInfo = (0, parseTreeUtils_1.getCallNodeAndActiveParameterIndex)(parseNode, offset, this.parseResults.tokenizerOutput.tokens);
        if (!callInfo) {
            return;
        }
        const signatureInfo = this.evaluator.getCallSignatureInfo(callInfo.callNode, callInfo.activeIndex, callInfo.activeOrFake);
        if (signatureInfo) {
            // Are we past the call expression and within the argument list?
            const callNameEnd = (0, positionUtils_1.convertOffsetToPosition)(signatureInfo.callNode.leftExpression.start + signatureInfo.callNode.leftExpression.length, this.parseResults.tokenizerOutput.lines);
            if ((0, textRange_1.comparePositions)(this.position, callNameEnd) > 0) {
                if (!atArgument) {
                    this._addNamedParameters(signatureInfo, priorWord, completionMap);
                }
                // Add literals that apply to this parameter.
                this._addLiteralValuesForArgument(signatureInfo, priorWord, priorText, postText, completionMap);
            }
        }
    }
    _addLiteralValuesForArgument(signatureInfo, priorWord, priorText, postText, completionMap) {
        signatureInfo.signatures.forEach((signature) => {
            if (!signature.activeParam) {
                return undefined;
            }
            const type = signature.type;
            const paramIndex = type.details.parameters.indexOf(signature.activeParam);
            if (paramIndex < 0) {
                return undefined;
            }
            const paramType = type.details.parameters[paramIndex].type;
            this._addLiteralValuesForTargetType(paramType, priorWord, priorText, postText, completionMap);
            return undefined;
        });
    }
    _addLiteralValuesForTargetType(type, priorWord, priorText, postText, completionMap) {
        const quoteValue = this._getQuoteInfo(priorWord, priorText);
        this._getSubTypesWithLiteralValues(type).forEach((v) => {
            if (types_1.ClassType.isBuiltIn(v, 'str')) {
                const value = (0, typePrinter_1.printLiteralValue)(v, quoteValue.quoteCharacter);
                if (quoteValue.stringValue === undefined) {
                    this.addNameToCompletions(value, vscode_languageserver_1.CompletionItemKind.Constant, priorWord, completionMap, {
                        sortText: this._makeSortText(SortCategory.LiteralValue, v.literalValue),
                    });
                }
                else {
                    this._addStringLiteralToCompletions(value.substr(1, value.length - 2), quoteValue, postText, completionMap);
                }
            }
        });
    }
    _getDictExpressionStringKeys(parseNode, excludeIds) {
        const node = getDictionaryLikeNode(parseNode);
        if (!node) {
            return [];
        }
        return node.entries.flatMap((entry) => {
            if (entry.nodeType !== 17 /* ParseNodeType.DictionaryKeyEntry */ || (excludeIds === null || excludeIds === void 0 ? void 0 : excludeIds.has(entry.keyExpression.id))) {
                return [];
            }
            if (entry.keyExpression.nodeType === 48 /* ParseNodeType.StringList */) {
                return [entry.keyExpression.strings.map((s) => s.value).join('')];
            }
            return [];
        });
        function getDictionaryLikeNode(parseNode) {
            // this method assumes the given parseNode is either a child of a dictionary or a dictionary itself
            if (parseNode.nodeType === 15 /* ParseNodeType.Dictionary */) {
                return parseNode;
            }
            let curNode = parseNode;
            while (curNode && curNode.nodeType !== 15 /* ParseNodeType.Dictionary */ && curNode.nodeType !== 45 /* ParseNodeType.Set */) {
                curNode = curNode.parent;
                if (!curNode) {
                    return;
                }
            }
            return curNode;
        }
    }
    _getSubTypesWithLiteralValues(type) {
        const values = [];
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if ((0, types_1.isClassInstance)(subtype) && (0, typeUtils_1.isLiteralType)(subtype)) {
                values.push(subtype);
            }
        });
        return values;
    }
    _getIndexKeyType(baseType) {
        // Handle __getitem__.
        const getItemType = this.evaluator.getBoundMagicMethod(baseType, '__getitem__');
        if (getItemType) {
            const typesToCombine = [];
            // Handle both overloaded and non-overloaded functions.
            (0, typeUtils_1.doForEachSignature)(getItemType, (signature) => {
                if (signature.details.parameters.length >= 1 &&
                    signature.details.parameters[0].category === 0 /* ParameterCategory.Simple */) {
                    typesToCombine.push(types_1.FunctionType.getEffectiveParameterType(signature, 0));
                }
            });
            if (typesToCombine.length > 0) {
                return (0, types_1.combineTypes)(typesToCombine);
            }
        }
        return undefined;
    }
    _getIndexKeys(indexNode, invocationNode) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        const baseType = this.evaluator.getType(indexNode.baseExpression);
        if (!baseType || !(0, types_1.isClassInstance)(baseType)) {
            return [];
        }
        // See whether subscript is typed using Literal types. If it is, return those literal keys.
        const subscriptType = this._getIndexKeyType(baseType);
        if (subscriptType) {
            const keys = [];
            this._getSubTypesWithLiteralValues(subscriptType).forEach((v) => {
                if (!types_1.ClassType.isBuiltIn(v, 'str') &&
                    !types_1.ClassType.isBuiltIn(v, 'int') &&
                    !types_1.ClassType.isBuiltIn(v, 'bool') &&
                    !types_1.ClassType.isBuiltIn(v, 'bytes') &&
                    !types_1.ClassType.isEnumClass(v)) {
                    return;
                }
                keys.push((0, typePrinter_1.printLiteralValue)(v, this.parseResults.tokenizerOutput.predominantSingleQuoteCharacter));
            });
            if (keys.length > 0) {
                return keys;
            }
        }
        if (indexNode.baseExpression.nodeType !== 38 /* ParseNodeType.Name */) {
            // This completion only supports simple name case
            return [];
        }
        // Must be local variable/parameter
        const declarations = (_a = this.evaluator.getDeclarationsForNameNode(indexNode.baseExpression)) !== null && _a !== void 0 ? _a : [];
        const declaration = declarations.length > 0 ? declarations[0] : undefined;
        if (!declaration ||
            (declaration.type !== 1 /* DeclarationType.Variable */ && declaration.type !== 2 /* DeclarationType.Parameter */)) {
            return [];
        }
        if (!declaration.uri.equals(this.fileUri)) {
            return [];
        }
        let startingNode = indexNode.baseExpression;
        if (declaration.node) {
            const scopeRoot = ParseTreeUtils.getEvaluationScopeNode(declaration.node);
            // Find the lowest tree to search the symbol.
            if ((_b = ParseTreeUtils.getFileInfoFromNode(startingNode)) === null || _b === void 0 ? void 0 : _b.fileUri.equals((_c = ParseTreeUtils.getFileInfoFromNode(scopeRoot)) === null || _c === void 0 ? void 0 : _c.fileUri)) {
                startingNode = scopeRoot;
            }
        }
        const results = documentSymbolCollector_1.DocumentSymbolCollector.collectFromNode(this.program, indexNode.baseExpression, this.cancellationToken, startingNode);
        const keys = new Set();
        for (const result of results) {
            const node = ((_d = result.node.parent) === null || _d === void 0 ? void 0 : _d.nodeType) === 54 /* ParseNodeType.TypeAnnotation */ ? result.node.parent : result.node;
            if (((_e = node.parent) === null || _e === void 0 ? void 0 : _e.nodeType) === 3 /* ParseNodeType.Assignment */ ||
                ((_f = node.parent) === null || _f === void 0 ? void 0 : _f.nodeType) === 4 /* ParseNodeType.AssignmentExpression */) {
                if (node.parent.rightExpression.nodeType === 15 /* ParseNodeType.Dictionary */) {
                    const dictionary = node.parent.rightExpression;
                    for (const entry of dictionary.entries.filter((e) => e.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */)) {
                        const key = this.parseResults.text
                            .substr(entry.keyExpression.start, entry.keyExpression.length)
                            .trim();
                        if (key.length > 0)
                            keys.add(key);
                    }
                }
                if (node.parent.rightExpression.nodeType === 9 /* ParseNodeType.Call */) {
                    const call = node.parent.rightExpression;
                    const type = this.evaluator.getType(call.leftExpression);
                    if (!type || !(0, types_1.isInstantiableClass)(type) || !types_1.ClassType.isBuiltIn(type, 'dict')) {
                        continue;
                    }
                    for (const arg of call.arguments) {
                        const key = (_h = (_g = arg.name) === null || _g === void 0 ? void 0 : _g.value.trim()) !== null && _h !== void 0 ? _h : '';
                        const quote = this.parseResults.tokenizerOutput.predominantSingleQuoteCharacter;
                        if (key.length > 0) {
                            keys.add(`${quote}${key}${quote}`);
                        }
                    }
                }
            }
            if (((_j = node.parent) === null || _j === void 0 ? void 0 : _j.nodeType) === 24 /* ParseNodeType.Index */ &&
                node.parent.items.length === 1 &&
                node.parent.items[0].valueExpression.nodeType !== 0 /* ParseNodeType.Error */ &&
                !textRange_1.TextRange.containsRange(node.parent, invocationNode)) {
                const indexArgument = node.parent.items[0];
                const key = this.parseResults.text
                    .substr(indexArgument.valueExpression.start, indexArgument.valueExpression.length)
                    .trim();
                if (key.length > 0)
                    keys.add(key);
            }
        }
        return Array.from(keys);
    }
    _getLiteralCompletions(parseNode, offset, priorWord, priorText, postText) {
        if (this.options.triggerCharacter === '"' || this.options.triggerCharacter === "'") {
            if (parseNode.start !== offset - 1) {
                // If completion is triggered by typing " or ', it must be the one that starts a string
                // literal. In another word, it can't be something inside of another string or comment
                return undefined;
            }
        }
        const completionMap = new CompletionMap();
        if (!this._tryAddLiterals(parseNode, priorWord, priorText, postText, completionMap)) {
            return undefined;
        }
        return completionMap;
    }
    _tryAddLiterals(parseNode, priorWord, priorText, postText, completionMap) {
        var _a, _b, _c, _d, _e, _f;
        const parentAndChild = getParentSkippingStringList(parseNode);
        if (!parentAndChild) {
            return false;
        }
        // See if the type evaluator can determine the expected type for this node.
        // ex) a: Literal["str"] = /* here */
        const nodeForExpectedType = parentAndChild.parent.nodeType === 3 /* ParseNodeType.Assignment */
            ? parentAndChild.parent.rightExpression === parentAndChild.child
                ? parentAndChild.child
                : undefined
            : (0, parseNodes_1.isExpressionNode)(parentAndChild.child)
                ? parentAndChild.child
                : undefined;
        if (nodeForExpectedType) {
            const expectedTypeResult = this.evaluator.getExpectedType(nodeForExpectedType);
            if (expectedTypeResult && (0, typeUtils_1.containsLiteralType)(expectedTypeResult.type)) {
                this._addLiteralValuesForTargetType(expectedTypeResult.type, priorWord, priorText, postText, completionMap);
                return true;
            }
        }
        // ex) a: TypedDictType = { "/* here */" } or a: TypedDictType = { A/* here */ }
        const nodeForKey = parentAndChild.parent;
        if (nodeForKey) {
            // If the dictionary is not yet filled in, it will appear as though it's
            // a set initially.
            let dictOrSet;
            if (nodeForKey.nodeType === 17 /* ParseNodeType.DictionaryKeyEntry */ &&
                nodeForKey.keyExpression === parentAndChild.child &&
                ((_a = nodeForKey.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 15 /* ParseNodeType.Dictionary */) {
                dictOrSet = nodeForKey.parent;
            }
            else if ((nodeForKey === null || nodeForKey === void 0 ? void 0 : nodeForKey.nodeType) === 45 /* ParseNodeType.Set */) {
                dictOrSet = nodeForKey;
            }
            if (dictOrSet) {
                if (this._tryAddTypedDictKeysFromDictionary(dictOrSet, parseNode.nodeType === 49 /* ParseNodeType.String */ ? parseNode : undefined, priorWord, priorText, postText, completionMap)) {
                    return true;
                }
            }
        }
        // a: DictType = { .... }
        // a[/* here */] or a['/* here */'] or a[variable/*here*/]
        const argument = parentAndChild.parent;
        if (argument.nodeType === 1 /* ParseNodeType.Argument */ && ((_b = argument.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 24 /* ParseNodeType.Index */) {
            const priorTextInString = parseNode.nodeType === 49 /* ParseNodeType.String */ ? priorText : '';
            if (this._tryAddTypedDictKeysFromIndexer(argument.parent, priorWord, priorTextInString, postText, completionMap)) {
                return true;
            }
            const quoteInfo = this._getQuoteInfo(priorWord, priorTextInString);
            const keys = this._getIndexKeys(argument.parent, parseNode);
            let keyFound = false;
            for (const key of keys) {
                if (completionMap.has(key)) {
                    // Don't add key if it already exists in the completion.
                    // ex) key = "dictKey"
                    //     dict[key] = 1
                    //     print(dict[<key will come from symbol table provider>]))
                    continue;
                }
                const stringLiteral = /^["|'].*["|']$/.test(key);
                if (parseNode.nodeType === 49 /* ParseNodeType.String */ && !stringLiteral) {
                    continue;
                }
                keyFound = true;
                if (stringLiteral) {
                    const keyWithoutQuote = key.substr(1, key.length - 2);
                    this._addStringLiteralToCompletions(keyWithoutQuote, quoteInfo, postText, completionMap, exports.indexValueDetail);
                }
                else {
                    this.addNameToCompletions(key, vscode_languageserver_1.CompletionItemKind.Constant, priorWord, completionMap, {
                        sortText: this._makeSortText(SortCategory.LiteralValue, key),
                        itemDetail: exports.indexValueDetail,
                    });
                }
            }
            if (keyFound) {
                return true;
            }
        }
        // if c == "/* here */"
        const comparison = parentAndChild.parent;
        const supportedOperators = [2 /* OperatorType.Assign */, 12 /* OperatorType.Equals */, 28 /* OperatorType.NotEquals */];
        if (comparison.nodeType === 7 /* ParseNodeType.BinaryOperation */ && supportedOperators.includes(comparison.operator)) {
            const type = this.evaluator.getType(comparison.leftExpression);
            if (type && (0, typeUtils_1.containsLiteralType)(type)) {
                this._addLiteralValuesForTargetType(type, priorWord, priorText, postText, completionMap);
                return true;
            }
        }
        // if c := "/* here */"
        const assignmentExpression = parentAndChild.parent;
        if (assignmentExpression.nodeType === 4 /* ParseNodeType.AssignmentExpression */ &&
            assignmentExpression.rightExpression === parentAndChild.child) {
            const type = this.evaluator.getType(assignmentExpression.name);
            if (type && (0, typeUtils_1.containsLiteralType)(type)) {
                this._addLiteralValuesForTargetType(type, priorWord, priorText, postText, completionMap);
                return true;
            }
        }
        // For now, we only support simple cases. no complex pattern matching.
        // match c:
        //     case /* here */
        const caseNode = parentAndChild.parent;
        if (caseNode.nodeType === 64 /* ParseNodeType.Case */ &&
            caseNode.pattern.nodeType === 0 /* ParseNodeType.Error */ &&
            caseNode.pattern.category === 11 /* ErrorExpressionCategory.MissingPattern */ &&
            caseNode.suite === parentAndChild.child &&
            ((_c = caseNode.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 63 /* ParseNodeType.Match */) {
            const type = this.evaluator.getType(caseNode.parent.subjectExpression);
            if (type && (0, typeUtils_1.containsLiteralType)(type)) {
                this._addLiteralValuesForTargetType(type, priorWord, priorText, postText, completionMap);
                return true;
            }
        }
        // match c:
        //     case "/* here */"
        //     case Sym/*here*/
        const patternLiteral = parentAndChild.parent;
        if ((patternLiteral.nodeType === 67 /* ParseNodeType.PatternLiteral */ ||
            patternLiteral.nodeType === 69 /* ParseNodeType.PatternCapture */) &&
            ((_d = patternLiteral.parent) === null || _d === void 0 ? void 0 : _d.nodeType) === 66 /* ParseNodeType.PatternAs */ &&
            ((_e = patternLiteral.parent.parent) === null || _e === void 0 ? void 0 : _e.nodeType) === 64 /* ParseNodeType.Case */ &&
            ((_f = patternLiteral.parent.parent.parent) === null || _f === void 0 ? void 0 : _f.nodeType) === 63 /* ParseNodeType.Match */) {
            const type = this.evaluator.getType(patternLiteral.parent.parent.parent.subjectExpression);
            if (type && (0, typeUtils_1.containsLiteralType)(type)) {
                this._addLiteralValuesForTargetType(type, priorWord, priorText, postText, completionMap);
                return true;
            }
        }
        if (parseNode.nodeType === 49 /* ParseNodeType.String */) {
            const offset = (0, positionUtils_1.convertPositionToOffset)(this.position, this.parseResults.tokenizerOutput.lines);
            const atArgument = parseNode.parent.start < offset && offset < textRange_1.TextRange.getEnd(parseNode);
            this._addCallArgumentCompletions(parseNode, priorWord, priorText, postText, atArgument, completionMap);
            return true;
        }
        return false;
        function getParentSkippingStringList(node) {
            var _a;
            if (!node.parent) {
                return undefined;
            }
            if (node.nodeType !== 49 /* ParseNodeType.String */) {
                return { parent: node.parent, child: node };
            }
            if (!node.parent.parent) {
                return undefined;
            }
            if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 48 /* ParseNodeType.StringList */ || node.parent.strings.length > 1) {
                return undefined;
            }
            return { parent: node.parent.parent, child: node.parent };
        }
    }
    _tryAddTypedDictKeys(type, existingKeys, priorWord, priorText, postText, completionMap) {
        let typedDicts = [];
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
                typedDicts.push(subtype);
            }
        });
        if (typedDicts.length === 0) {
            return false;
        }
        typedDicts = this._tryNarrowTypedDicts(typedDicts, existingKeys);
        const quoteInfo = this._getQuoteInfo(priorWord, priorText);
        const excludes = new Set(existingKeys);
        typedDicts.forEach((typedDict) => {
            (0, typedDicts_1.getTypedDictMembersForClass)(this.evaluator, typedDict, /* allowNarrowed */ true).knownItems.forEach((_, key) => {
                // Unions of TypedDicts may define the same key.
                if (excludes.has(key) || completionMap.has(key)) {
                    return;
                }
                excludes.add(key);
                this._addStringLiteralToCompletions(key, quoteInfo, postText, completionMap);
            });
        });
        return true;
    }
    _tryAddTypedDictKeysFromDictionary(dictionaryNode, stringNode, priorWord, priorText, postText, completionMap) {
        var _a;
        const expectedTypeResult = this.evaluator.getExpectedType(dictionaryNode);
        if (!expectedTypeResult) {
            return false;
        }
        // If the expected type result is associated with a node above the
        // dictionaryNode in the parse tree, there are no typed dict keys to add.
        if (ParseTreeUtils.getNodeDepth(expectedTypeResult.node) < ParseTreeUtils.getNodeDepth(dictionaryNode)) {
            return false;
        }
        const keys = this._getDictExpressionStringKeys(dictionaryNode, stringNode ? new Set([(_a = stringNode.parent) === null || _a === void 0 ? void 0 : _a.id]) : undefined);
        return this._tryAddTypedDictKeys(expectedTypeResult.type, keys, priorWord, priorText, postText, completionMap);
    }
    _tryNarrowTypedDicts(types, keys) {
        const newTypes = types.flatMap((type) => {
            const entries = (0, typedDicts_1.getTypedDictMembersForClass)(this.evaluator, type, /* allowNarrowed */ true);
            for (let index = 0; index < keys.length; index++) {
                if (!entries.knownItems.has(keys[index])) {
                    return [];
                }
            }
            return [type];
        });
        if (newTypes.length === 0) {
            // Couldn't narrow to any typed dicts. Just include all.
            return types;
        }
        return newTypes;
    }
    // Find quotation and string prefix to use for string literals
    // completion under current context.
    _getQuoteInfo(priorWord, priorText) {
        let filterText = priorWord;
        let stringValue = undefined;
        let quoteCharacter = this.parseResults.tokenizerOutput.predominantSingleQuoteCharacter;
        // If completion is not inside of the existing string literal
        // ex) typedDict[ |<= here
        // use default quotation char without any string prefix.
        if (!this._stringLiteralContainer) {
            return { priorWord, priorText, filterText, stringValue, quoteCharacter };
        }
        const singleQuote = "'";
        const doubleQuote = '"';
        // If completion is inside of string literal and has prior text
        // ex) typedDict["key |<= here
        // find quotation user has used (ex, ") and string prefix (ex, key)
        if (priorText !== undefined) {
            const lastSingleQuote = priorText.lastIndexOf(singleQuote);
            const lastDoubleQuote = priorText.lastIndexOf(doubleQuote);
            if (lastSingleQuote > lastDoubleQuote) {
                stringValue = priorText.substr(lastSingleQuote + 1);
                quoteCharacter = singleQuote;
            }
            else if (lastDoubleQuote > lastSingleQuote) {
                stringValue = priorText.substr(lastDoubleQuote + 1);
                quoteCharacter = doubleQuote;
            }
        }
        // If the invocation position is within an f-string, use a double or
        // single quote that doesn't match the f-string. Prior to Python 3.12,
        // using the same quotation mark nested within an f-string was not
        // permitted. For example, f"..{typedDict[|<= here ]}", we need to use
        // single quotes. Note that this doesn't account for deeper nested
        // f-strings.
        if (this._stringLiteralContainer.flags & 64 /* StringTokenFlags.Format */) {
            quoteCharacter =
                this._stringLiteralContainer.flags & 1 /* StringTokenFlags.SingleQuote */ ? doubleQuote : singleQuote;
        }
        if (stringValue) {
            filterText = stringValue;
        }
        return { priorWord, priorText, filterText, stringValue, quoteCharacter };
    }
    _tryAddTypedDictKeysFromIndexer(indexNode, priorWord, priorText, postText, completionMap) {
        if (!indexNode) {
            return false;
        }
        const baseType = this.evaluator.getType(indexNode.baseExpression);
        if (!baseType) {
            return false;
        }
        return this._tryAddTypedDictKeys(baseType, [], priorWord, priorText, postText, completionMap);
    }
    _addStringLiteralToCompletions(value, quoteInfo, postText, completionMap, detail) {
        if (!StringUtils.isPatternInSymbol(quoteInfo.filterText || '', value)) {
            return;
        }
        const valueWithQuotes = `${quoteInfo.quoteCharacter}${value}${quoteInfo.quoteCharacter}`;
        if (completionMap.has(valueWithQuotes)) {
            return;
        }
        const completionItem = vscode_languageserver_1.CompletionItem.create(valueWithQuotes);
        completionItem.kind = vscode_languageserver_1.CompletionItemKind.Constant;
        completionItem.sortText = this._makeSortText(SortCategory.LiteralValue, valueWithQuotes);
        let rangeStartCol = this.position.character;
        if (quoteInfo.stringValue !== undefined) {
            rangeStartCol -= quoteInfo.stringValue.length + 1;
        }
        else if (quoteInfo.priorWord) {
            rangeStartCol -= quoteInfo.priorWord.length;
        }
        // If the text after the insertion point is the closing quote,
        // replace it.
        let rangeEndCol = this.position.character;
        if (postText !== undefined) {
            if (postText.startsWith(quoteInfo.quoteCharacter)) {
                rangeEndCol++;
            }
        }
        const range = {
            start: { line: this.position.line, character: rangeStartCol },
            end: { line: this.position.line, character: rangeEndCol },
        };
        completionItem.textEdit = vscode_languageserver_1.TextEdit.replace(range, valueWithQuotes);
        completionItem.detail = detail;
        completionMap.set(completionItem);
    }
    _getImportFromCompletions(importFromNode, priorWord) {
        var _a;
        // Don't attempt to provide completions for "from X import *".
        if (importFromNode.isWildcardImport) {
            return undefined;
        }
        // Access the imported module information, which is hanging
        // off the ImportFromNode.
        const importInfo = AnalyzerNodeInfo.getImportInfo(importFromNode.module);
        if (!importInfo) {
            return undefined;
        }
        const completionMap = new CompletionMap();
        const resolvedPath = importInfo.resolvedUris.length > 0
            ? importInfo.resolvedUris[importInfo.resolvedUris.length - 1]
            : uri_1.Uri.empty();
        const parseResults = this.program.getParseResults(resolvedPath);
        if (!parseResults) {
            // Add the implicit imports.
            this._addImplicitImportsToCompletion(importInfo, importFromNode, priorWord, completionMap);
            return completionMap;
        }
        const symbolTable = (_a = AnalyzerNodeInfo.getScope(parseResults.parserOutput.parseTree)) === null || _a === void 0 ? void 0 : _a.symbolTable;
        if (!symbolTable) {
            return completionMap;
        }
        this._addSymbolsForSymbolTable(symbolTable, (symbol, name) => {
            // Don't suggest built in symbols or ones that have already been imported.
            return (symbol.getDeclarations().some((d) => !(0, declaration_1.isIntrinsicDeclaration)(d)) &&
                !importFromNode.imports.find((imp) => imp.name.value === name));
        }, priorWord, importFromNode, 
        /* isInImport */ true, 
        /* boundObject */ undefined, completionMap);
        // Add the implicit imports.
        this._addImplicitImportsToCompletion(importInfo, importFromNode, priorWord, completionMap);
        return completionMap;
    }
    _addImplicitImportsToCompletion(importInfo, importFromNode, priorWord, completionMap) {
        importInfo.implicitImports.forEach((implImport) => {
            if (!importFromNode.imports.find((imp) => imp.name.value === implImport.name)) {
                this.addNameToCompletions(implImport.name, vscode_languageserver_1.CompletionItemKind.Module, priorWord, completionMap, {
                    moduleUri: implImport.uri,
                });
            }
        });
    }
    _findMatchingKeywords(keywordList, partialMatch) {
        return keywordList.filter((keyword) => {
            if (partialMatch) {
                return StringUtils.isPatternInSymbol(partialMatch, keyword);
            }
            else {
                return true;
            }
        });
    }
    _addNamedParameters(signatureInfo, priorWord, completionMap) {
        const argNameSet = new Set();
        signatureInfo.signatures.forEach((signature) => {
            this._addNamedParametersToMap(signature.type, argNameSet);
        });
        // Add keys from typed dict outside signatures.
        signatureInfo.signatures.forEach((signature) => {
            var _a;
            if (signature.type.boundToType) {
                const keys = Array.from(((_a = signature.type.boundToType.details.typedDictEntries) === null || _a === void 0 ? void 0 : _a.knownItems.keys()) || []);
                keys.forEach((key) => argNameSet.add(key));
            }
        });
        // Remove any named parameters that are already provided.
        signatureInfo.callNode.arguments.forEach((arg) => {
            if (arg.name) {
                argNameSet.delete(arg.name.value);
            }
        });
        // Add the remaining unique parameter names to the completion list.
        argNameSet.forEach((argName) => {
            if (StringUtils.isPatternInSymbol(priorWord, argName)) {
                const label = argName + '=';
                if (completionMap.has(label)) {
                    return;
                }
                const completionItem = vscode_languageserver_1.CompletionItem.create(label);
                completionItem.kind = vscode_languageserver_1.CompletionItemKind.Variable;
                const completionItemData = {
                    uri: this.fileUri.toString(),
                    position: this.position,
                };
                completionItem.data = (0, lspUtils_1.toLSPAny)(completionItemData);
                completionItem.sortText = this._makeSortText(SortCategory.NamedParameter, argName);
                completionItem.filterText = argName;
                completionMap.set(completionItem);
            }
        });
    }
    _addNamedParametersToMap(type, names) {
        const paramDetails = (0, parameterUtils_1.getParameterListDetails)(type);
        paramDetails.params.forEach((paramInfo) => {
            if (paramInfo.param.name && paramInfo.source !== parameterUtils_1.ParameterSource.PositionOnly) {
                if (!SymbolNameUtils.isPrivateOrProtectedName(paramInfo.param.name)) {
                    names.add(paramInfo.param.name);
                }
            }
        });
    }
    _addSymbols(node, priorWord, completionMap) {
        let curNode = node;
        while (curNode) {
            // Does this node have a scope associated with it?
            let scope = (0, scopeUtils_1.getScopeForNode)(curNode);
            if (scope) {
                while (scope) {
                    this._addSymbolsForSymbolTable(scope.symbolTable, () => true, priorWord, node, 
                    /* isInImport */ false, 
                    /* boundObject */ undefined, completionMap);
                    scope = scope.parent;
                }
                // If this is a class scope, add symbols from parent classes.
                if (curNode.nodeType === 10 /* ParseNodeType.Class */) {
                    const classType = this.evaluator.getTypeOfClass(curNode);
                    if (classType && (0, types_1.isInstantiableClass)(classType.classType)) {
                        classType.classType.details.mro.forEach((baseClass, index) => {
                            if ((0, types_1.isInstantiableClass)(baseClass)) {
                                this._addSymbolsForSymbolTable(types_1.ClassType.getSymbolTable(baseClass), (symbol) => {
                                    if (!symbol.isClassMember()) {
                                        return false;
                                    }
                                    // Return only variables, not methods or classes.
                                    return symbol
                                        .getDeclarations()
                                        .some((decl) => decl.type === 1 /* DeclarationType.Variable */);
                                }, priorWord, node, 
                                /* isInImport */ false, 
                                /* boundObject */ undefined, completionMap);
                            }
                        });
                    }
                }
                break;
            }
            curNode = curNode.parent;
        }
    }
    _addSymbolsForSymbolTable(symbolTable, includeSymbolCallback, priorWord, node, isInImport, boundObjectOrClass, completionMap) {
        const insideTypeAnnotation = ParseTreeUtils.isWithinAnnotationComment(node) ||
            ParseTreeUtils.isWithinTypeAnnotation(node, /* requireQuotedAnnotation */ false);
        symbolTable.forEach((symbol, name) => {
            // If there are no declarations or the symbol is not
            // exported from this scope, don't include it in the
            // suggestion list unless we are in the same file.
            const hidden = !(0, symbolUtils_1.isVisibleExternally)(symbol) && !symbol.getDeclarations().some((d) => (0, declarationUtils_1.isDefinedInFile)(d, this.fileUri));
            if (!hidden && includeSymbolCallback(symbol, name)) {
                // Don't add a symbol more than once. It may have already been
                // added from an inner scope's symbol table.
                if (!completionMap.has(name)) {
                    // Skip func parens for classes when not a direct assignment or an argument (passed as a value)
                    const skipForClass = !this._shouldShowAutoParensForClass(symbol, node);
                    this.addSymbol(name, symbol, priorWord, completionMap, {
                        boundObjectOrClass,
                        funcParensDisabled: isInImport || insideTypeAnnotation || skipForClass,
                        extraCommitChars: !isInImport && !!priorWord,
                    });
                }
            }
        });
    }
    _shouldShowAutoParensForClass(symbol, node) {
        var _a, _b;
        if (symbol.getDeclarations().every((d) => d.type !== 6 /* DeclarationType.Class */)) {
            // Not actually a class, so yes show parens.
            return true;
        }
        // If an argument then show parens for classes if not a class argument.
        if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 1 /* ParseNodeType.Argument */ && ((_b = node.parent.parent) === null || _b === void 0 ? void 0 : _b.nodeType) !== 10 /* ParseNodeType.Class */) {
            return true;
        }
        // Otherwise only show when the class is being assigned to a variable.
        const nodeIndex = ParseTreeUtils.getTokenIndexAtLeft(this.parseResults.tokenizerOutput.tokens, node.start);
        const prevToken = ParseTreeUtils.getTokenAtIndex(this.parseResults.tokenizerOutput.tokens, nodeIndex);
        return (prevToken &&
            prevToken.type === 9 /* TokenType.Operator */ &&
            prevToken.operatorType === 2 /* OperatorType.Assign */);
    }
    _getRecentListIndex(name, autoImportText) {
        return CompletionProvider._mostRecentCompletions.findIndex((item) => item.label === name && item.autoImportText === autoImportText);
    }
    _makeSortText(sortCategory, name, autoImportText = '') {
        const recentListIndex = this._getRecentListIndex(name, autoImportText);
        // If the label is in the recent list, modify the category
        // so it appears higher in our list.
        if (recentListIndex >= 0) {
            if (sortCategory === SortCategory.AutoImport) {
                sortCategory = SortCategory.RecentAutoImport;
            }
            else if (sortCategory === SortCategory.ImportModuleName) {
                sortCategory = SortCategory.RecentImportModuleName;
            }
            else if (sortCategory === SortCategory.Keyword ||
                sortCategory === SortCategory.NormalSymbol ||
                sortCategory === SortCategory.PrivateSymbol ||
                sortCategory === SortCategory.DunderSymbol) {
                sortCategory = SortCategory.RecentKeywordOrSymbol;
            }
        }
        // Generate a sort string of the format
        //    XX.YYYY.name
        // where XX is the sort category
        // and YYYY is the index of the item in the MRU list
        return this._formatInteger(sortCategory, 2) + '.' + this._formatInteger(recentListIndex, 4) + '.' + name;
    }
    _formatInteger(val, digits) {
        const charCodeZero = '0'.charCodeAt(0);
        let result = '';
        for (let i = 0; i < digits; i++) {
            // Prepend the next digit.
            let digit = Math.floor(val % 10);
            if (digit < 0) {
                digit = 9;
            }
            result = String.fromCharCode(digit + charCodeZero) + result;
            val = Math.floor(val / 10);
        }
        return result;
    }
    _convertDeclarationTypeToItemKind(declaration) {
        const resolvedDeclaration = this.evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ true);
        if (!resolvedDeclaration) {
            return vscode_languageserver_1.CompletionItemKind.Variable;
        }
        switch (resolvedDeclaration.type) {
            case 0 /* DeclarationType.Intrinsic */:
                return resolvedDeclaration.intrinsicType === 'class'
                    ? vscode_languageserver_1.CompletionItemKind.Class
                    : vscode_languageserver_1.CompletionItemKind.Variable;
            case 2 /* DeclarationType.Parameter */:
                return vscode_languageserver_1.CompletionItemKind.Variable;
            case 3 /* DeclarationType.TypeParameter */:
                return vscode_languageserver_1.CompletionItemKind.TypeParameter;
            case 1 /* DeclarationType.Variable */:
                return resolvedDeclaration.isConstant || resolvedDeclaration.isFinal
                    ? vscode_languageserver_1.CompletionItemKind.Constant
                    : vscode_languageserver_1.CompletionItemKind.Variable;
            case 4 /* DeclarationType.TypeAlias */:
                return vscode_languageserver_1.CompletionItemKind.Variable;
            case 5 /* DeclarationType.Function */: {
                if (this._isPossiblePropertyDeclaration(resolvedDeclaration)) {
                    const functionType = this.evaluator.getTypeOfFunction(resolvedDeclaration.node);
                    if (functionType &&
                        (0, typeUtils_1.isMaybeDescriptorInstance)(functionType.decoratedType, /* requireSetter */ false)) {
                        return vscode_languageserver_1.CompletionItemKind.Property;
                    }
                }
                return resolvedDeclaration.isMethod ? vscode_languageserver_1.CompletionItemKind.Method : vscode_languageserver_1.CompletionItemKind.Function;
            }
            case 6 /* DeclarationType.Class */:
            case 7 /* DeclarationType.SpecialBuiltInClass */:
                return vscode_languageserver_1.CompletionItemKind.Class;
            case 8 /* DeclarationType.Alias */:
                return vscode_languageserver_1.CompletionItemKind.Module;
        }
    }
    _convertTypeToItemKind(type) {
        switch (type.category) {
            case 7 /* TypeCategory.Module */:
                return vscode_languageserver_1.CompletionItemKind.Module;
            case 6 /* TypeCategory.Class */:
                return vscode_languageserver_1.CompletionItemKind.Class;
            case 4 /* TypeCategory.Function */:
            case 5 /* TypeCategory.OverloadedFunction */:
                if ((0, typeUtils_1.isMaybeDescriptorInstance)(type, /* requireSetter */ false)) {
                    return vscode_languageserver_1.CompletionItemKind.Property;
                }
                return vscode_languageserver_1.CompletionItemKind.Function;
            case 9 /* TypeCategory.TypeVar */:
                return vscode_languageserver_1.CompletionItemKind.TypeParameter;
            default:
                return vscode_languageserver_1.CompletionItemKind.Variable;
        }
    }
    _getImportModuleCompletions(node) {
        const moduleDescriptor = {
            leadingDots: node.leadingDots,
            hasTrailingDot: node.hasTrailingDot || false,
            nameParts: node.nameParts.map((part) => part.value),
            importedSymbols: new Set(),
        };
        const completions = this.importResolver.getCompletionSuggestions(this.fileUri, this.execEnv, moduleDescriptor);
        const completionMap = new CompletionMap();
        // If we're in the middle of a "from X import Y" statement, offer
        // the "import" keyword as a completion.
        if (!node.hasTrailingDot &&
            node.parent &&
            node.parent.nodeType === 22 /* ParseNodeType.ImportFrom */ &&
            node.parent.missingImportKeyword) {
            const keyword = 'import';
            const completionItem = vscode_languageserver_1.CompletionItem.create(keyword);
            completionItem.kind = vscode_languageserver_1.CompletionItemKind.Keyword;
            completionItem.sortText = this._makeSortText(SortCategory.Keyword, keyword);
            completionMap.set(completionItem);
        }
        completions.forEach((modulePath, completionName) => {
            this.addNameToCompletions(completionName, vscode_languageserver_1.CompletionItemKind.Module, '', completionMap, {
                sortText: this._makeSortText(SortCategory.ImportModuleName, completionName),
                moduleUri: modulePath,
            });
        });
        return completionMap;
    }
    _isPossiblePropertyDeclaration(decl) {
        // Do cheap check using only nodes that will cover 99.9% cases
        // before doing more expensive type evaluation.
        return decl.isMethod && decl.node.decorators.length > 0;
    }
}
exports.CompletionProvider = CompletionProvider;
CompletionProvider._mostRecentCompletions = [];
class CompletionMap {
    constructor() {
        this._completions = new Map();
    }
    get size() {
        return this._completions.size;
    }
    set(value) {
        const existing = this._completions.get(value.label);
        if (!existing) {
            this._completions.set(value.label, value);
        }
        else if (Array.isArray(existing)) {
            existing.push(value);
        }
        else {
            this._completions.set(value.label, [existing, value]);
        }
    }
    get(key) {
        return this._completions.get(key);
    }
    has(label, predicate, kind, autImportText) {
        const existing = this._completions.get(label);
        if (!existing) {
            return false;
        }
        if (predicate) {
            return predicate(existing, kind, autImportText);
        }
        return true;
    }
    clear() {
        this._completions.clear();
    }
    delete(key) {
        return this._completions.delete(key);
    }
    toArray() {
        var _a;
        const items = [];
        (_a = this._completions) === null || _a === void 0 ? void 0 : _a.forEach((value) => {
            if (Array.isArray(value)) {
                value.forEach((item) => {
                    items.push(item);
                });
            }
            else {
                items.push(value);
            }
        });
        return items;
    }
    static matchKindAndImportText(completionItemOrItems, kind, autoImportText) {
        var _a;
        if (!Array.isArray(completionItemOrItems)) {
            return (completionItemOrItems.kind === kind &&
                ((_a = _getCompletionData(completionItemOrItems)) === null || _a === void 0 ? void 0 : _a.autoImportText) === autoImportText);
        }
        else {
            return !!completionItemOrItems.find((c) => { var _a; return c.kind === kind && ((_a = _getCompletionData(c)) === null || _a === void 0 ? void 0 : _a.autoImportText) === autoImportText; });
        }
    }
    static labelOnlyIgnoringAutoImports(completionItemOrItems) {
        var _a;
        if (!Array.isArray(completionItemOrItems)) {
            if (!((_a = _getCompletionData(completionItemOrItems)) === null || _a === void 0 ? void 0 : _a.autoImportText)) {
                return true;
            }
        }
        else {
            if (completionItemOrItems.find((c) => { var _a; return !((_a = _getCompletionData(c)) === null || _a === void 0 ? void 0 : _a.autoImportText); })) {
                return true;
            }
        }
        return false;
    }
}
exports.CompletionMap = CompletionMap;
function _getCompletionData(completionItem) {
    return (0, lspUtils_1.fromLSPAny)(completionItem.data);
}


/***/ }),

/***/ "../pyright-internal/src/languageService/completionProviderUtils.ts":
/*!**************************************************************************!*\
  !*** ../pyright-internal/src/languageService/completionProviderUtils.ts ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * completionProviderUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper functions for providing completions
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getCompletionItemDocumentation = exports.getTypeDetail = void 0;
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
const docStringConversion_1 = __webpack_require__(/*! ../analyzer/docStringConversion */ "../pyright-internal/src/analyzer/docStringConversion.ts");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const tooltipUtils_1 = __webpack_require__(/*! ./tooltipUtils */ "../pyright-internal/src/languageService/tooltipUtils.ts");
function getTypeDetail(evaluator, type, primaryDecl, name, detail, functionSignatureDisplay) {
    if (!primaryDecl) {
        if ((0, types_1.isModule)(type)) {
            // Special casing import modules.
            // submodule imported through `import` statement doesn't have
            // corresponding decls. so use given name as it is.
            //
            // ex) import X.Y
            // X.[Y]
            return name;
        }
        return;
    }
    switch (primaryDecl.type) {
        case 0 /* DeclarationType.Intrinsic */:
        case 1 /* DeclarationType.Variable */:
        case 2 /* DeclarationType.Parameter */:
        case 3 /* DeclarationType.TypeParameter */: {
            let expandTypeAlias = false;
            if (type && types_1.TypeBase.isInstantiable(type)) {
                const typeAliasInfo = (0, types_1.getTypeAliasInfo)(type);
                if (typeAliasInfo) {
                    if (typeAliasInfo.name === name) {
                        expandTypeAlias = true;
                    }
                }
            }
            // Handle the case where type is a function and was assigned to a variable.
            if (type.category === 5 /* TypeCategory.OverloadedFunction */ || type.category === 4 /* TypeCategory.Function */) {
                return (0, tooltipUtils_1.getToolTipForType)(type, 
                /* label */ '', name, evaluator, 
                /* isProperty */ false, functionSignatureDisplay);
            }
            else {
                return name + ': ' + evaluator.printType(type, { expandTypeAlias });
            }
        }
        case 5 /* DeclarationType.Function */: {
            const functionType = (detail === null || detail === void 0 ? void 0 : detail.boundObjectOrClass) && ((0, types_1.isFunction)(type) || (0, types_1.isOverloadedFunction)(type))
                ? evaluator.bindFunctionToClassOrObject(detail.boundObjectOrClass, type)
                : type;
            if (!functionType) {
                return undefined;
            }
            if ((0, typeUtils_1.isProperty)(functionType) && (detail === null || detail === void 0 ? void 0 : detail.boundObjectOrClass) && (0, types_1.isClassInstance)(detail.boundObjectOrClass)) {
                const propertyType = evaluator.getGetterTypeFromProperty(functionType, /* inferTypeIfNeeded */ true) ||
                    types_1.UnknownType.create();
                return name + ': ' + evaluator.printType(propertyType) + ' (property)';
            }
            return (0, tooltipUtils_1.getToolTipForType)(functionType, 
            /* label */ '', name, evaluator, 
            /* isProperty */ false, functionSignatureDisplay);
        }
        case 6 /* DeclarationType.Class */:
        case 7 /* DeclarationType.SpecialBuiltInClass */: {
            return 'class ' + name + '()';
        }
        case 8 /* DeclarationType.Alias */: {
            return name;
        }
        default: {
            return name;
        }
    }
}
exports.getTypeDetail = getTypeDetail;
function getCompletionItemDocumentation(typeDetail, documentation, markupKind) {
    if (markupKind === vscode_languageserver_types_1.MarkupKind.Markdown) {
        let markdownString = '```python\n' + typeDetail + '\n```\n';
        if (documentation) {
            markdownString += '---\n';
            markdownString += (0, docStringConversion_1.convertDocStringToMarkdown)(documentation);
        }
        markdownString = markdownString.trimEnd();
        return {
            kind: vscode_languageserver_types_1.MarkupKind.Markdown,
            value: markdownString,
        };
    }
    else if (markupKind === vscode_languageserver_types_1.MarkupKind.PlainText) {
        let plainTextString = typeDetail + '\n';
        if (documentation) {
            plainTextString += '\n';
            plainTextString += (0, docStringConversion_1.convertDocStringToPlainText)(documentation);
        }
        plainTextString = plainTextString.trimEnd();
        return {
            kind: vscode_languageserver_types_1.MarkupKind.PlainText,
            value: plainTextString,
        };
    }
    return undefined;
}
exports.getCompletionItemDocumentation = getCompletionItemDocumentation;


/***/ }),

/***/ "../pyright-internal/src/languageService/definitionProvider.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/languageService/definitionProvider.ts ***!
  \*********************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * definitionProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that maps a position within a Python program file into
 * a "definition" of the item that is referred to at that position.
 * For example, if the location is within an import name, the
 * definition is the top of the resolved import file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TypeDefinitionProvider = exports.DefinitionProvider = exports.filterDefinitions = exports.addDeclarationsToDefinitions = exports.DefinitionFilter = void 0;
const analyzerNodeInfo_1 = __webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const sourceMapper_1 = __webpack_require__(/*! ../analyzer/sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
var DefinitionFilter;
(function (DefinitionFilter) {
    DefinitionFilter["All"] = "all";
    DefinitionFilter["PreferSource"] = "preferSource";
    DefinitionFilter["PreferStubs"] = "preferStubs";
})(DefinitionFilter || (exports.DefinitionFilter = DefinitionFilter = {}));
function addDeclarationsToDefinitions(evaluator, sourceMapper, declarations, definitions) {
    if (!declarations) {
        return;
    }
    declarations.forEach((decl) => {
        var _a;
        let resolvedDecl = evaluator.resolveAliasDeclaration(decl, /* resolveLocalNames */ true, {
            allowExternallyHiddenAccess: true,
        });
        if (!resolvedDecl || resolvedDecl.uri.isEmpty()) {
            return;
        }
        // If the decl is an unresolved import, skip it.
        if (resolvedDecl.type === 8 /* DeclarationType.Alias */) {
            if (resolvedDecl.isUnresolved || (0, declaration_1.isUnresolvedAliasDeclaration)(resolvedDecl)) {
                return;
            }
        }
        // If the resolved decl is still an alias, it means it
        // resolved to a module. We need to apply loader actions
        // to determine its path.
        if (resolvedDecl.type === 8 /* DeclarationType.Alias */ &&
            resolvedDecl.symbolName &&
            resolvedDecl.submoduleFallback &&
            !resolvedDecl.submoduleFallback.uri.isEmpty()) {
            resolvedDecl = resolvedDecl.submoduleFallback;
        }
        _addIfUnique(definitions, {
            uri: resolvedDecl.uri,
            range: resolvedDecl.range,
        });
        if ((0, declaration_1.isFunctionDeclaration)(resolvedDecl)) {
            // Handle overloaded function case
            const functionType = (_a = evaluator.getTypeForDeclaration(resolvedDecl)) === null || _a === void 0 ? void 0 : _a.type;
            if (functionType && (0, types_1.isOverloadedFunction)(functionType)) {
                for (const overloadDecl of functionType.overloads.map((o) => o.details.declaration).filter(core_1.isDefined)) {
                    _addIfUnique(definitions, {
                        uri: overloadDecl.uri,
                        range: overloadDecl.range,
                    });
                }
            }
        }
        if (!(0, sourceMapper_1.isStubFile)(resolvedDecl.uri)) {
            return;
        }
        if (resolvedDecl.type === 8 /* DeclarationType.Alias */) {
            // Add matching source module
            sourceMapper
                .findModules(resolvedDecl.uri)
                .map((m) => { var _a; return (_a = (0, analyzerNodeInfo_1.getFileInfo)(m)) === null || _a === void 0 ? void 0 : _a.fileUri; })
                .filter(core_1.isDefined)
                .forEach((f) => _addIfUnique(definitions, _createModuleEntry(f)));
            return;
        }
        const implDecls = sourceMapper.findDeclarations(resolvedDecl);
        for (const implDecl of implDecls) {
            if (implDecl && !implDecl.uri.isEmpty()) {
                _addIfUnique(definitions, {
                    uri: implDecl.uri,
                    range: implDecl.range,
                });
            }
        }
    });
}
exports.addDeclarationsToDefinitions = addDeclarationsToDefinitions;
function filterDefinitions(filter, definitions) {
    if (filter === DefinitionFilter.All) {
        return definitions;
    }
    // If go-to-declaration is supported, attempt to only show only pyi files in go-to-declaration
    // and none in go-to-definition, unless filtering would produce an empty list.
    const preferStubs = filter === DefinitionFilter.PreferStubs;
    const wantedFile = (v) => preferStubs === (0, sourceMapper_1.isStubFile)(v.uri);
    if (definitions.find(wantedFile)) {
        return definitions.filter(wantedFile);
    }
    return definitions;
}
exports.filterDefinitions = filterDefinitions;
class DefinitionProviderBase {
    constructor(sourceMapper, evaluator, _serviceProvider, node, offset, _filter, token) {
        this.sourceMapper = sourceMapper;
        this.evaluator = evaluator;
        this._serviceProvider = _serviceProvider;
        this.node = node;
        this.offset = offset;
        this._filter = _filter;
        this.token = token;
    }
    getDefinitionsForNode(node, offset) {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this.token);
        const definitions = [];
        const factories = (_a = this._serviceProvider) === null || _a === void 0 ? void 0 : _a.tryGet(serviceKeys_1.ServiceKeys.symbolDefinitionProvider);
        if (factories) {
            factories.forEach((f) => {
                const declarations = f.tryGetDeclarations(node, offset, this.token);
                this.resolveDeclarations(declarations, definitions);
            });
        }
        // There should be only one 'definition', so only if extensions failed should we try again.
        if (definitions.length === 0) {
            if (node.nodeType === 38 /* ParseNodeType.Name */) {
                const declarations = this.evaluator.getDeclarationsForNameNode(node);
                this.resolveDeclarations(declarations, definitions);
            }
            else if (node.nodeType === 49 /* ParseNodeType.String */) {
                const declarations = this.evaluator.getDeclarationsForStringNode(node);
                this.resolveDeclarations(declarations, definitions);
            }
        }
        if (definitions.length === 0) {
            return undefined;
        }
        return filterDefinitions(this._filter, definitions);
    }
    resolveDeclarations(declarations, definitions) {
        addDeclarationsToDefinitions(this.evaluator, this.sourceMapper, declarations, definitions);
    }
}
class DefinitionProvider extends DefinitionProviderBase {
    constructor(program, fileUri, position, filter, token) {
        const sourceMapper = program.getSourceMapper(fileUri, token);
        const parseResults = program.getParseResults(fileUri);
        const { node, offset } = _tryGetNode(parseResults, position);
        super(sourceMapper, program.evaluator, program.serviceProvider, node, offset, filter, token);
    }
    static getDefinitionsForNode(sourceMapper, evaluator, node, offset, token) {
        const provider = new DefinitionProviderBase(sourceMapper, evaluator, undefined, node, offset, DefinitionFilter.All, token);
        return provider.getDefinitionsForNode(node, offset);
    }
    getDefinitions() {
        if (this.node === undefined) {
            return undefined;
        }
        return this.getDefinitionsForNode(this.node, this.offset);
    }
}
exports.DefinitionProvider = DefinitionProvider;
class TypeDefinitionProvider extends DefinitionProviderBase {
    constructor(program, fileUri, position, token) {
        const sourceMapper = program.getSourceMapper(fileUri, token, /*mapCompiled*/ false, /*preferStubs*/ true);
        const parseResults = program.getParseResults(fileUri);
        const { node, offset } = _tryGetNode(parseResults, position);
        super(sourceMapper, program.evaluator, program.serviceProvider, node, offset, DefinitionFilter.All, token);
        this._fileUri = fileUri;
    }
    getDefinitions() {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this.token);
        if (this.node === undefined) {
            return undefined;
        }
        const definitions = [];
        if (this.node.nodeType === 38 /* ParseNodeType.Name */) {
            const type = this.evaluator.getType(this.node);
            if (type) {
                let declarations = [];
                (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
                    if ((subtype === null || subtype === void 0 ? void 0 : subtype.category) === 6 /* TypeCategory.Class */) {
                        (0, collectionUtils_1.appendArray)(declarations, this.sourceMapper.findClassDeclarationsByType(this._fileUri, subtype));
                    }
                });
                // Fall back to Go To Definition if the type can't be found (ex. Go To Type Definition
                // was executed on a type name)
                if (declarations.length === 0) {
                    declarations = (_a = this.evaluator.getDeclarationsForNameNode(this.node)) !== null && _a !== void 0 ? _a : [];
                }
                this.resolveDeclarations(declarations, definitions);
            }
        }
        else if (this.node.nodeType === 49 /* ParseNodeType.String */) {
            const declarations = this.evaluator.getDeclarationsForStringNode(this.node);
            this.resolveDeclarations(declarations, definitions);
        }
        if (definitions.length === 0) {
            return undefined;
        }
        return definitions;
    }
}
exports.TypeDefinitionProvider = TypeDefinitionProvider;
function _tryGetNode(parseResults, position) {
    if (!parseResults) {
        return { node: undefined, offset: 0 };
    }
    const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
    if (offset === undefined) {
        return { node: undefined, offset: 0 };
    }
    return { node: ParseTreeUtils.findNodeByOffset(parseResults.parserOutput.parseTree, offset), offset };
}
function _createModuleEntry(uri) {
    return {
        uri,
        range: {
            start: { line: 0, character: 0 },
            end: { line: 0, character: 0 },
        },
    };
}
function _addIfUnique(definitions, itemToAdd) {
    for (const def of definitions) {
        if (def.uri.equals(itemToAdd.uri) && (0, textRange_1.rangesAreEqual)(def.range, itemToAdd.range)) {
            return;
        }
    }
    definitions.push(itemToAdd);
}


/***/ }),

/***/ "../pyright-internal/src/languageService/documentHighlightProvider.ts":
/*!****************************************************************************!*\
  !*** ../pyright-internal/src/languageService/documentHighlightProvider.ts ***!
  \****************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * documentHighlightProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that maps a position within a Python program file into
 * one or more highlight types.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DocumentHighlightProvider = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const extensibility_1 = __webpack_require__(/*! ../common/extensibility */ "../pyright-internal/src/common/extensibility.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const documentSymbolCollector_1 = __webpack_require__(/*! ./documentSymbolCollector */ "../pyright-internal/src/languageService/documentSymbolCollector.ts");
class DocumentHighlightProvider {
    constructor(_program, _fileUri, _position, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._position = _position;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
    }
    getDocumentHighlight() {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return undefined;
        }
        const offset = (0, positionUtils_1.convertPositionToOffset)(this._position, this._parseResults.tokenizerOutput.lines);
        if (offset === undefined) {
            return undefined;
        }
        const node = ParseTreeUtils.findNodeByOffset(this._parseResults.parserOutput.parseTree, offset);
        if (node === undefined) {
            return undefined;
        }
        if (node.nodeType !== 38 /* ParseNodeType.Name */) {
            return undefined;
        }
        const results = documentSymbolCollector_1.DocumentSymbolCollector.collectFromNode(this._program, node, this._token, this._parseResults.parserOutput.parseTree, {
            treatModuleInImportAndFromImportSame: true,
            useCase: extensibility_1.ReferenceUseCase.References,
        });
        const lines = this._parseResults.tokenizerOutput.lines;
        return results.map((r) => ({
            kind: r.node.nodeType === 38 /* ParseNodeType.Name */ && ParseTreeUtils.isWriteAccess(r.node)
                ? vscode_languageserver_1.DocumentHighlightKind.Write
                : vscode_languageserver_1.DocumentHighlightKind.Read,
            range: (0, positionUtils_1.convertOffsetsToRange)(r.range.start, textRange_1.TextRange.getEnd(r.range), lines),
        }));
    }
}
exports.DocumentHighlightProvider = DocumentHighlightProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/documentSymbolCollector.ts":
/*!**************************************************************************!*\
  !*** ../pyright-internal/src/languageService/documentSymbolCollector.ts ***!
  \**************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * documentSymbolCollector.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Collects symbols within the given tree that are semantically
 * equivalent to the requested symbol.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.addDeclarationIfUnique = exports.getDeclarationsForNameNode = exports.DocumentSymbolCollector = exports.AliasResolver = void 0;
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const declarationUtils_1 = __webpack_require__(/*! ../analyzer/declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const parseTreeWalker_1 = __webpack_require__(/*! ../analyzer/parseTreeWalker */ "../pyright-internal/src/analyzer/parseTreeWalker.ts");
const ScopeUtils = __importStar(__webpack_require__(/*! ../analyzer/scopeUtils */ "../pyright-internal/src/analyzer/scopeUtils.ts"));
const sourceFile_1 = __webpack_require__(/*! ../analyzer/sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const sourceMapper_1 = __webpack_require__(/*! ../analyzer/sourceMapper */ "../pyright-internal/src/analyzer/sourceMapper.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const extensibility_1 = __webpack_require__(/*! ../common/extensibility */ "../pyright-internal/src/common/extensibility.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
// 99% of time, `find all references` is looking for a symbol imported from the other file to this file.
// By caching the result of `resolveAlias` we only need to resolve it once per a file.
const withLocalNamesCacheIndex = 0;
const withoutLocalNamesCacheIndex = 1;
class AliasResolver {
    constructor(_evaluator) {
        this._evaluator = _evaluator;
        this._caches = [undefined, undefined];
        // Empty
    }
    resolve(declaration, resolveLocalNames) {
        const index = resolveLocalNames ? withLocalNamesCacheIndex : withoutLocalNamesCacheIndex;
        if (this._caches[index] && this._caches[index].original === declaration) {
            return this._caches[index].resolved;
        }
        const resolved = this._evaluator.resolveAliasDeclaration(declaration, resolveLocalNames, {
            allowExternallyHiddenAccess: true,
            skipFileNeededCheck: true,
        });
        this._caches[index] = { original: declaration, resolved };
        return resolved;
    }
}
exports.AliasResolver = AliasResolver;
// This walker looks for symbols that are semantically equivalent
// to the requested symbol.
class DocumentSymbolCollector extends parseTreeWalker_1.ParseTreeWalker {
    constructor(_program, symbolNames, declarations, _startingNode, _cancellationToken, options) {
        var _a, _b, _c, _d, _e;
        super();
        this._program = _program;
        this._startingNode = _startingNode;
        this._cancellationToken = _cancellationToken;
        this._results = [];
        this._dunderAllNameNodes = new Set();
        this._symbolNames = new Set();
        this._declarations = [];
        this._aliasResolver = new AliasResolver(this._program.evaluator);
        // Start with the symbols passed in
        symbolNames.forEach((s) => this._symbolNames.add(s));
        this._declarations.push(...declarations);
        this._treatModuleInImportAndFromImportSame = (_a = options === null || options === void 0 ? void 0 : options.treatModuleInImportAndFromImportSame) !== null && _a !== void 0 ? _a : false;
        this._skipUnreachableCode = (_b = options === null || options === void 0 ? void 0 : options.skipUnreachableCode) !== null && _b !== void 0 ? _b : true;
        this._useCase = (_c = options === null || options === void 0 ? void 0 : options.useCase) !== null && _c !== void 0 ? _c : extensibility_1.ReferenceUseCase.References;
        this._usageProviders =
            (_d = options === null || options === void 0 ? void 0 : options.providers) !== null && _d !== void 0 ? _d : ((_e = this._program.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.symbolUsageProviderFactory)) !== null && _e !== void 0 ? _e : [])
                .map((f) => f.tryCreateProvider(this._useCase, declarations, this._cancellationToken))
                .filter(core_1.isDefined);
        if ((options === null || options === void 0 ? void 0 : options.providers) === undefined) {
            // Check whether we need to add new symbol names and declarations.
            this._usageProviders.forEach((p) => {
                p.appendSymbolNamesTo(this._symbolNames);
                p.appendDeclarationsTo(this._declarations);
            });
        }
        // Don't report strings in __all__ right away, that will
        // break the assumption on the result ordering.
        this._setDunderAllNodes(this._startingNode);
    }
    static collectFromNode(program, node, cancellationToken, startingNode, options) {
        const declarations = this.getDeclarationsForNode(program, node, /* resolveLocalName */ true, cancellationToken);
        startingNode = startingNode !== null && startingNode !== void 0 ? startingNode : (0, parseTreeUtils_1.getModuleNode)(node);
        if (!startingNode) {
            return [];
        }
        const collector = new DocumentSymbolCollector(program, [node.value], declarations, startingNode, cancellationToken, options);
        return collector.collect();
    }
    static getDeclarationsForNode(program, node, resolveLocalName, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const evaluator = program.evaluator;
        if (!evaluator) {
            return [];
        }
        const declarations = getDeclarationsForNameNode(evaluator, node, /* skipUnreachableCode */ false);
        const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
        const fileUri = fileInfo.fileUri;
        const resolvedDeclarations = [];
        const sourceMapper = program.getSourceMapper(fileUri, token);
        declarations.forEach((decl) => {
            const resolvedDecl = evaluator.resolveAliasDeclaration(decl, resolveLocalName);
            if (resolvedDecl) {
                addDeclarationIfUnique(resolvedDeclarations, resolvedDecl);
                if (sourceMapper && (0, sourceMapper_1.isStubFile)(resolvedDecl.uri)) {
                    const implDecls = sourceMapper.findDeclarations(resolvedDecl);
                    for (const implDecl of implDecls) {
                        if (implDecl && !implDecl.uri.isEmpty()) {
                            addDeclarationIfUnique(resolvedDeclarations, implDecl);
                        }
                    }
                }
            }
        });
        const sourceFileInfo = program.getSourceFileInfo(fileUri);
        if (sourceFileInfo && sourceFileInfo.sourceFile.getIPythonMode() === sourceFile_1.IPythonMode.CellDocs) {
            // Add declarations from chained source files
            let builtinsScope = fileInfo.builtinsScope;
            while (builtinsScope && builtinsScope.type === 3 /* ScopeType.Module */) {
                const symbol = builtinsScope === null || builtinsScope === void 0 ? void 0 : builtinsScope.lookUpSymbol(node.value);
                appendSymbolDeclarations(symbol, resolvedDeclarations);
                builtinsScope = builtinsScope === null || builtinsScope === void 0 ? void 0 : builtinsScope.parent;
            }
            // Add declarations from files that implicitly import the target file.
            const implicitlyImportedBy = (0, sourceFileInfoUtils_1.collectImportedByCells)(program, sourceFileInfo);
            implicitlyImportedBy.forEach((implicitImport) => {
                var _a;
                const parseTree = (_a = program.getParseResults(implicitImport.sourceFile.getUri())) === null || _a === void 0 ? void 0 : _a.parserOutput.parseTree;
                if (parseTree) {
                    const scope = AnalyzerNodeInfo.getScope(parseTree);
                    const symbol = scope === null || scope === void 0 ? void 0 : scope.lookUpSymbol(node.value);
                    appendSymbolDeclarations(symbol, resolvedDeclarations);
                }
            });
        }
        return resolvedDeclarations;
        function appendSymbolDeclarations(symbol, declarations) {
            symbol === null || symbol === void 0 ? void 0 : symbol.getDeclarations().filter((d) => !(0, declaration_1.isAliasDeclaration)(d)).forEach((decl) => {
                const resolvedDecl = evaluator.resolveAliasDeclaration(decl, resolveLocalName);
                if (resolvedDecl) {
                    addDeclarationIfUnique(declarations, resolvedDecl);
                }
            });
        }
    }
    collect() {
        this.walk(this._startingNode);
        return this._results;
    }
    walk(node) {
        if (!this._skipUnreachableCode || !AnalyzerNodeInfo.isCodeUnreachable(node)) {
            super.walk(node);
        }
    }
    visitName(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        // No need to do any more work if the symbol name doesn't match.
        if (!this._symbolNames.has(node.value)) {
            return false;
        }
        if (this._declarations.length > 0) {
            const declarations = getDeclarationsForNameNode(this._evaluator, node, this._skipUnreachableCode);
            if (declarations && declarations.length > 0) {
                // Does this name share a declaration with the symbol of interest?
                if (this._resultsContainsDeclaration(node, declarations)) {
                    this._addResult(node);
                }
            }
        }
        else {
            // There were no declarations
            this._addResult(node);
        }
        return false;
    }
    visitStringList(node) {
        // See if we have reference that matches this node.
        if (this._declarations.some((d) => { var _a; return ((_a = d.node) === null || _a === void 0 ? void 0 : _a.id) === node.id; })) {
            // Then the matching string should be included
            const matching = node.strings.find((s) => this._symbolNames.has(s.value));
            if (matching && matching.nodeType === 49 /* ParseNodeType.String */) {
                this._addResult(matching);
            }
        }
        return super.visitStringList(node);
    }
    visitString(node) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        if (this._dunderAllNameNodes.has(node)) {
            this._addResult(node);
        }
        return false;
    }
    get _evaluator() {
        return this._program.evaluator;
    }
    _addResult(node) {
        const range = node.nodeType === 38 /* ParseNodeType.Name */ ? node.token : (0, parseTreeUtils_1.getStringNodeValueRange)(node);
        this._results.push({ node, range });
    }
    _isDeclarationAllowed(resolvedDecl) {
        return this._declarations.some((decl) => (0, declarationUtils_1.areDeclarationsSame)(decl, resolvedDecl, this._treatModuleInImportAndFromImportSame, 
        /* skipRangeForAliases */ true));
    }
    _resultsContainsDeclaration(usage, declarations) {
        const results = [...declarations];
        this._usageProviders.forEach((p) => p.appendDeclarationsAt(usage, declarations, results));
        return results.some((declaration) => {
            // Resolve the declaration.
            const resolvedDecl = this._aliasResolver.resolve(declaration, /* resolveLocalNames */ false);
            if (!resolvedDecl) {
                return false;
            }
            // The reference results declarations are already resolved, so we don't
            // need to call resolveAliasDeclaration on them.
            if (this._isDeclarationAllowed(resolvedDecl)) {
                return true;
            }
            // We didn't find the declaration using local-only alias resolution. Attempt
            // it again by fully resolving the alias.
            const resolvedDeclNonlocal = this._getResolveAliasDeclaration(resolvedDecl);
            if (!resolvedDeclNonlocal || resolvedDeclNonlocal === resolvedDecl) {
                return false;
            }
            return this._isDeclarationAllowed(resolvedDeclNonlocal);
        });
    }
    _getResolveAliasDeclaration(declaration) {
        // TypeEvaluator.resolveAliasDeclaration only resolve alias in AliasDeclaration in the form of
        // "from x import y as [y]" but don't do thing for alias in "import x as [x]"
        // Here, alias should have same name as module name.
        if (isAliasDeclFromImportAsWithAlias(declaration)) {
            return (0, declarationUtils_1.getDeclarationsWithUsesLocalNameRemoved)([declaration])[0];
        }
        const resolvedDecl = this._aliasResolver.resolve(declaration, /* resolveLocalNames */ true);
        return isAliasDeclFromImportAsWithAlias(resolvedDecl)
            ? (0, declarationUtils_1.getDeclarationsWithUsesLocalNameRemoved)([resolvedDecl])[0]
            : resolvedDecl;
        function isAliasDeclFromImportAsWithAlias(decl) {
            return (!!decl &&
                decl.type === 8 /* DeclarationType.Alias */ &&
                decl.node &&
                decl.usesLocalName &&
                decl.node.nodeType === 21 /* ParseNodeType.ImportAs */);
        }
    }
    _setDunderAllNodes(node) {
        if (node.nodeType !== 36 /* ParseNodeType.Module */) {
            return;
        }
        const dunderAllInfo = AnalyzerNodeInfo.getDunderAllInfo(node);
        if (!dunderAllInfo) {
            return;
        }
        const moduleScope = ScopeUtils.getScopeForNode(node);
        if (!moduleScope) {
            return;
        }
        dunderAllInfo.stringNodes.forEach((stringNode) => {
            if (!this._symbolNames.has(stringNode.value)) {
                return;
            }
            const symbolInScope = moduleScope.lookUpSymbolRecursive(stringNode.value);
            if (!symbolInScope) {
                return;
            }
            if (!this._resultsContainsDeclaration(stringNode, symbolInScope.symbol.getDeclarations())) {
                return;
            }
            this._dunderAllNameNodes.add(stringNode);
        });
    }
}
exports.DocumentSymbolCollector = DocumentSymbolCollector;
function getDeclarationsForNameNode(evaluator, node, skipUnreachableCode = true) {
    var _a;
    // This can handle symbols brought in by wildcard (import *) as long as the declarations that the symbol collector
    // compares against point to the actual alias declaration, not one that uses local name (ex, import alias)
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 37 /* ParseNodeType.ModuleName */) {
        return _getDeclarationsForNonModuleNameNode(evaluator, node, skipUnreachableCode);
    }
    return _getDeclarationsForModuleNameNode(evaluator, node);
}
exports.getDeclarationsForNameNode = getDeclarationsForNameNode;
function addDeclarationIfUnique(declarations, itemToAdd) {
    for (const def of declarations) {
        if ((0, declarationUtils_1.areDeclarationsSame)(def, itemToAdd, 
        /* treatModuleInImportAndFromImportSame */ false, 
        /* skipRangeForAliases */ true)) {
            return;
        }
    }
    declarations.push(itemToAdd);
}
exports.addDeclarationIfUnique = addDeclarationIfUnique;
function _getDeclarationsForNonModuleNameNode(evaluator, node, skipUnreachableCode = true) {
    var _a, _b;
    (0, debug_1.assert)(((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 37 /* ParseNodeType.ModuleName */);
    let decls = evaluator.getDeclarationsForNameNode(node, skipUnreachableCode) || [];
    if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 23 /* ParseNodeType.ImportFromAs */) {
        // Make sure we get the decl for this specific "from import" statement
        decls = decls.filter((d) => d.node === node.parent);
    }
    // If we can't get decl, see whether we can get type from the node.
    // Some might have synthesized type for the node such as subModule in import X.Y statement.
    if (decls.length === 0) {
        const type = evaluator.getType(node);
        if ((type === null || type === void 0 ? void 0 : type.category) === 7 /* TypeCategory.Module */) {
            // Synthesize decl for the module.
            return [(0, declarationUtils_1.createSynthesizedAliasDeclaration)(type.fileUri)];
        }
    }
    // We would like to make X in import X and import X.Y as Y to match, but path for
    // X in import X and one in import X.Y as Y might not match since path in X.Y will point
    // to X.Y rather than X if import statement has an alias.
    // so, for such case, we put synthesized one so we can treat X in both statement same.
    for (const aliasDecl of decls.filter((d) => (0, declaration_1.isAliasDeclaration)(d) && !d.loadSymbolsFromPath)) {
        const node = aliasDecl.node;
        if (node.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
            // from ... import X case, decl in the submodule fallback has the path.
            continue;
        }
        (0, collectionUtils_1.appendArray)(decls, evaluator.getDeclarationsForNameNode(node.module.nameParts[0], skipUnreachableCode) || []);
    }
    return decls;
}
function _getDeclarationsForModuleNameNode(evaluator, node) {
    var _a, _b, _c, _d, _e;
    (0, debug_1.assert)(((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 37 /* ParseNodeType.ModuleName */);
    // We don't have symbols corresponding to ModuleName in our system since those
    // are not referenceable. but in "find all reference", we want to match those
    // if it refers to the same module file. Code below handles different kind of
    // ModuleName cases.
    const moduleName = node.parent;
    if (((_b = moduleName.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 21 /* ParseNodeType.ImportAs */ ||
        ((_c = moduleName.parent) === null || _c === void 0 ? void 0 : _c.nodeType) === 22 /* ParseNodeType.ImportFrom */) {
        const index = moduleName.nameParts.findIndex((n) => n === node);
        // Special case, first module name part.
        if (index === 0) {
            // 1. import X or from X import ...
            const decls = [];
            // First, we need to put decls for module names type evaluator synthesized so that
            // we can match both "import X" and "from X import ..."
            (0, collectionUtils_1.appendArray)(decls, ((_d = evaluator.getDeclarationsForNameNode(moduleName.nameParts[0])) === null || _d === void 0 ? void 0 : _d.filter((d) => (0, declaration_1.isAliasDeclaration)(d))) ||
                []);
            if (decls.length === 0 || moduleName.parent.nodeType !== 21 /* ParseNodeType.ImportAs */) {
                return decls;
            }
            // If module name belong to "import xxx" not "from xxx", then see whether
            // we can get regular decls (decls created from binder, not synthesized from type eval)
            // from symbol as well.
            // ex, import X as x
            const isImportAsWithAlias = moduleName.nameParts.length === 1 &&
                moduleName.parent.nodeType === 21 /* ParseNodeType.ImportAs */ &&
                !!moduleName.parent.alias;
            // if "import" has alias, symbol is assigned to alias, not the module.
            const importName = isImportAsWithAlias
                ? moduleName.parent.alias.value
                : moduleName.nameParts[0].value;
            // And we also need to re-use "decls for X" binder has created
            // so that it matches with decls type evaluator returns for "references for X".
            // ex) import X or from .X import ... in init file and etc.
            const symbolWithScope = (_e = ScopeUtils.getScopeForNode(node)) === null || _e === void 0 ? void 0 : _e.lookUpSymbolRecursive(importName);
            if (symbolWithScope && moduleName.nameParts.length === 1) {
                let declsFromSymbol = [];
                (0, collectionUtils_1.appendArray)(declsFromSymbol, symbolWithScope.symbol.getDeclarations().filter((d) => (0, declaration_1.isAliasDeclaration)(d)));
                // If symbols are re-used, then find one that belong to this import statement.
                if (declsFromSymbol.length > 1) {
                    declsFromSymbol = declsFromSymbol.filter((d) => {
                        d = d;
                        if (d.firstNamePart !== undefined) {
                            // For multiple import statements with sub modules, decl can be re-used.
                            // ex) import X.Y and import X.Z or from .X import ... in init file.
                            // Decls for X will be reused for both import statements, and node will point
                            // to first import statement. For those case, use firstNamePart instead to check.
                            return d.firstNamePart === moduleName.nameParts[0].value;
                        }
                        return d.node === moduleName.parent;
                    });
                }
                // ex, import X as x
                // We have decls for the alias "x" not the module name "X". Convert decls for the "X"
                if (isImportAsWithAlias) {
                    declsFromSymbol = (0, declarationUtils_1.getDeclarationsWithUsesLocalNameRemoved)(declsFromSymbol);
                }
                (0, collectionUtils_1.appendArray)(decls, declsFromSymbol);
            }
            return decls;
        }
        if (index > 0) {
            // 2. import X.Y or from X.Y import ....
            // For submodule "Y", we just use synthesized decls from type evaluator.
            // Decls for these sub module don't actually exist in the system. Instead, symbol for Y in
            // "import X.Y" hold onto synthesized module type (without any decl).
            // And "from X.Y import ..." doesn't have any symbol associated module names.
            // they can't be referenced in the module.
            return evaluator.getDeclarationsForNameNode(moduleName.nameParts[index]) || [];
        }
        return [];
    }
    return [];
}


/***/ }),

/***/ "../pyright-internal/src/languageService/documentSymbolProvider.ts":
/*!*************************************************************************!*\
  !*** ../pyright-internal/src/languageService/documentSymbolProvider.ts ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * documentSymbolProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that enumerates all of the symbols within a specified
 * source file document.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DocumentSymbolProvider = exports.convertToFlatSymbols = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const analyzerNodeInfo_1 = __webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const symbolIndexer_1 = __webpack_require__(/*! ./symbolIndexer */ "../pyright-internal/src/languageService/symbolIndexer.ts");
function convertToFlatSymbols(program, uri, symbolList) {
    const flatSymbols = [];
    for (const symbol of symbolList) {
        _appendToFlatSymbolsRecursive(program.fileSystem, flatSymbols, uri, symbol);
    }
    return flatSymbols;
}
exports.convertToFlatSymbols = convertToFlatSymbols;
class DocumentSymbolProvider {
    constructor(program, uri, _supportHierarchicalDocumentSymbol, _indexOptions, _token) {
        this.program = program;
        this.uri = uri;
        this._supportHierarchicalDocumentSymbol = _supportHierarchicalDocumentSymbol;
        this._indexOptions = _indexOptions;
        this._token = _token;
        this._parseResults = this.program.getParseResults(this.uri);
    }
    getSymbols() {
        if (!this._parseResults) {
            return [];
        }
        const symbolList = this.getHierarchicalSymbols();
        if (this._supportHierarchicalDocumentSymbol) {
            return symbolList;
        }
        return convertToFlatSymbols(this.program, this.uri, symbolList);
    }
    getHierarchicalSymbols() {
        const symbolList = [];
        const parseResults = this.program.getParseResults(this.uri);
        if (!parseResults) {
            return symbolList;
        }
        const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parserOutput.parseTree);
        if (!fileInfo) {
            return symbolList;
        }
        const indexSymbolData = symbolIndexer_1.SymbolIndexer.indexSymbols(fileInfo, parseResults, this._indexOptions, this._token);
        this.appendDocumentSymbolsRecursive(indexSymbolData, symbolList);
        return symbolList;
    }
    appendDocumentSymbolsRecursive(indexSymbolData, symbolList) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!indexSymbolData) {
            return;
        }
        for (const symbolData of indexSymbolData) {
            if (symbolData.alias) {
                continue;
            }
            // It's possible for a name to be '' under certain error
            // conditions (such as a decorator with no associated function
            // or class).
            if (!symbolData.name) {
                continue;
            }
            const children = [];
            this.appendDocumentSymbolsRecursive(symbolData.children, children);
            const symbolInfo = {
                name: symbolData.name,
                kind: symbolData.kind,
                range: symbolData.range,
                selectionRange: symbolData.selectionRange,
                children: children,
            };
            symbolList.push(symbolInfo);
        }
    }
}
exports.DocumentSymbolProvider = DocumentSymbolProvider;
function _appendToFlatSymbolsRecursive(fs, flatSymbols, documentUri, symbol, parent) {
    const flatSymbol = {
        name: symbol.name,
        kind: symbol.kind,
        location: vscode_languageserver_1.Location.create((0, uriUtils_1.encodeUri)(fs, documentUri), symbol.range),
    };
    if (symbol.tags) {
        flatSymbol.tags = symbol.tags;
    }
    if (parent) {
        flatSymbol.containerName = parent.name;
    }
    flatSymbols.push(flatSymbol);
    if (symbol.children) {
        for (const child of symbol.children) {
            _appendToFlatSymbolsRecursive(fs, flatSymbols, documentUri, child, symbol);
        }
    }
}


/***/ }),

/***/ "../pyright-internal/src/languageService/hoverProvider.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/languageService/hoverProvider.ts ***!
  \****************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * hoverProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that maps a position within a Python program file into
 * markdown text that is displayed when the user hovers over that
 * position within a smart editor.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.HoverProvider = exports.getVariableTypeText = exports.addDocumentationResultsPart = exports.convertHoverResults = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const docStringConversion_1 = __webpack_require__(/*! ../analyzer/docStringConversion */ "../pyright-internal/src/analyzer/docStringConversion.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const tooltipUtils_1 = __webpack_require__(/*! ./tooltipUtils */ "../pyright-internal/src/languageService/tooltipUtils.ts");
function convertHoverResults(hoverResults, format) {
    if (!hoverResults) {
        return null;
    }
    const markupString = hoverResults.parts
        .map((part) => {
        if (part.python) {
            if (format === vscode_languageserver_1.MarkupKind.Markdown) {
                return '```python\n' + part.text + '\n```\n';
            }
            else if (format === vscode_languageserver_1.MarkupKind.PlainText) {
                return part.text + '\n\n';
            }
            else {
                (0, debug_1.fail)(`Unsupported markup type: ${format}`);
            }
        }
        return part.text;
    })
        .join('')
        .trimEnd();
    return {
        contents: {
            kind: format,
            value: markupString,
        },
        range: hoverResults.range,
    };
}
exports.convertHoverResults = convertHoverResults;
function addDocumentationResultsPart(docString, format, parts) {
    if (!docString) {
        return;
    }
    if (format === vscode_languageserver_1.MarkupKind.Markdown) {
        const markDown = (0, docStringConversion_1.convertDocStringToMarkdown)(docString);
        if (parts.length > 0 && markDown.length > 0) {
            parts.push({ text: '---\n' });
        }
        parts.push({ text: markDown, python: false });
        return;
    }
    if (format === vscode_languageserver_1.MarkupKind.PlainText) {
        parts.push({ text: (0, docStringConversion_1.convertDocStringToPlainText)(docString), python: false });
        return;
    }
    (0, debug_1.fail)(`Unsupported markup type: ${format}`);
}
exports.addDocumentationResultsPart = addDocumentationResultsPart;
function getVariableTypeText(evaluator, declaration, name, type, typeNode, functionSignatureDisplay) {
    let label = declaration.isConstant || evaluator.isFinalVariableDeclaration(declaration) ? 'constant' : 'variable';
    let expandTypeAlias = false;
    let typeVarName;
    if (type.typeAliasInfo && typeNode.nodeType === 38 /* ParseNodeType.Name */) {
        const typeAliasInfo = (0, types_1.getTypeAliasInfo)(type);
        if ((typeAliasInfo === null || typeAliasInfo === void 0 ? void 0 : typeAliasInfo.name) === typeNode.value) {
            if ((0, types_1.isTypeVar)(type)) {
                label = type.details.isParamSpec ? 'param spec' : 'type variable';
                typeVarName = type.details.name;
            }
            else {
                expandTypeAlias = true;
                label = 'type alias';
            }
        }
    }
    // Handle the case where type is a function and was assigned to a variable.
    if (type.category === 4 /* TypeCategory.Function */ || type.category === 5 /* TypeCategory.OverloadedFunction */) {
        return (0, tooltipUtils_1.getToolTipForType)(type, label, name, evaluator, /* isProperty */ false, functionSignatureDisplay);
    }
    const typeText = typeVarName || name + ': ' + evaluator.printType((0, tooltipUtils_1.getTypeForToolTip)(evaluator, typeNode), { expandTypeAlias });
    return `(${label}) ` + typeText;
}
exports.getVariableTypeText = getVariableTypeText;
class HoverProvider {
    constructor(_program, _fileUri, _position, _format, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._position = _position;
        this._format = _format;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
        this._sourceMapper = this._program.getSourceMapper(this._fileUri, this._token, /* mapCompiled */ true);
    }
    getHover() {
        return convertHoverResults(this._getHoverResult(), this._format);
    }
    static getPrimaryDeclaration(declarations) {
        // In most cases, it's best to treat the first declaration as the
        // "primary". This works well for properties that have setters
        // which often have doc strings on the getter but not the setter.
        // The one case where using the first declaration doesn't work as
        // well is the case where an import statement within an __init__.py
        // file uses the form "from .A import A". In this case, if we use
        // the first declaration, it will show up as a module rather than
        // the imported symbol type.
        const primaryDeclaration = declarations[0];
        if (primaryDeclaration.type === 8 /* DeclarationType.Alias */ && declarations.length > 1) {
            return declarations[1];
        }
        else if (primaryDeclaration.type === 1 /* DeclarationType.Variable */ &&
            declarations.length > 1 &&
            primaryDeclaration.isDefinedBySlots) {
            // Slots cannot have docstrings, so pick the secondary.
            return declarations[1];
        }
        return primaryDeclaration;
    }
    get _evaluator() {
        return this._program.evaluator;
    }
    get _functionSignatureDisplay() {
        return this._program.configOptions.functionSignatureDisplay;
    }
    _getHoverResult() {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const offset = (0, positionUtils_1.convertPositionToOffset)(this._position, this._parseResults.tokenizerOutput.lines);
        if (offset === undefined) {
            return null;
        }
        const node = ParseTreeUtils.findNodeByOffset(this._parseResults.parserOutput.parseTree, offset);
        if (node === undefined) {
            return null;
        }
        const results = {
            parts: [],
            range: {
                start: (0, positionUtils_1.convertOffsetToPosition)(node.start, this._parseResults.tokenizerOutput.lines),
                end: (0, positionUtils_1.convertOffsetToPosition)(textRange_1.TextRange.getEnd(node), this._parseResults.tokenizerOutput.lines),
            },
        };
        if (node.nodeType === 38 /* ParseNodeType.Name */) {
            const declarations = this._evaluator.getDeclarationsForNameNode(node);
            if (declarations && declarations.length > 0) {
                const primaryDeclaration = HoverProvider.getPrimaryDeclaration(declarations);
                this._addResultsForDeclaration(results.parts, primaryDeclaration, node);
            }
            else if (!node.parent || node.parent.nodeType !== 37 /* ParseNodeType.ModuleName */) {
                // If we had no declaration, see if we can provide a minimal tooltip. We'll skip
                // this if it's part of a module name, since a module name part with no declaration
                // is a directory (a namespace package), and we don't want to provide any hover
                // information in that case.
                if (results.parts.length === 0) {
                    const type = this._getType(node);
                    let typeText;
                    if ((0, types_1.isModule)(type)) {
                        // Handle modules specially because submodules aren't associated with
                        // declarations, but we want them to be presented in the same way as
                        // the top-level module, which does have a declaration.
                        typeText = '(module) ' + node.value;
                    }
                    else {
                        let label = 'function';
                        let isProperty = false;
                        if ((0, typeUtils_1.isMaybeDescriptorInstance)(type, /* requireSetter */ false)) {
                            isProperty = true;
                            label = 'property';
                        }
                        typeText = (0, tooltipUtils_1.getToolTipForType)(type, label, node.value, this._evaluator, isProperty, this._functionSignatureDisplay);
                    }
                    this._addResultsPart(results.parts, typeText, /* python */ true);
                    this._addDocumentationPart(results.parts, node, /* resolvedDecl */ undefined);
                }
            }
        }
        else if (node.nodeType === 49 /* ParseNodeType.String */) {
            const type = (_a = this._evaluator.getExpectedType(node)) === null || _a === void 0 ? void 0 : _a.type;
            if (type !== undefined) {
                this._tryAddPartsForTypedDictKey(node, type, results.parts);
            }
        }
        return results.parts.length > 0 ? results : null;
    }
    _addResultsForDeclaration(parts, declaration, node) {
        var _a, _b, _c;
        const resolvedDecl = this._evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ true);
        if (!resolvedDecl || (0, declaration_1.isUnresolvedAliasDeclaration)(resolvedDecl)) {
            this._addResultsPart(parts, `(import) ` + node.value + this._getTypeText(node), /* python */ true);
            return;
        }
        switch (resolvedDecl.type) {
            case 0 /* DeclarationType.Intrinsic */: {
                this._addResultsPart(parts, node.value + this._getTypeText(node), /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 1 /* DeclarationType.Variable */: {
                // If the named node is an aliased import symbol, we can't call
                // getType on the original name because it's not in the symbol
                // table. Instead, use the node from the resolved alias.
                let typeNode = node;
                if (declaration.node.nodeType === 21 /* ParseNodeType.ImportAs */ ||
                    declaration.node.nodeType === 23 /* ParseNodeType.ImportFromAs */) {
                    if (declaration.node.alias && node !== declaration.node.alias) {
                        if (resolvedDecl.node.nodeType === 38 /* ParseNodeType.Name */) {
                            typeNode = resolvedDecl.node;
                        }
                    }
                }
                else if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 1 /* ParseNodeType.Argument */ && node.parent.name === node) {
                    // If this is a named argument, we would normally have received a Parameter declaration
                    // rather than a variable declaration, but we can get here in the case of a dataclass.
                    // Replace the typeNode with the node of the variable declaration.
                    if (declaration.node.nodeType === 38 /* ParseNodeType.Name */) {
                        typeNode = declaration.node;
                    }
                }
                // Determine if this identifier is a type alias. If so, expand
                // the type alias when printing the type information.
                const type = this._getType(typeNode);
                const typeText = getVariableTypeText(this._evaluator, resolvedDecl, node.value, type, typeNode, this._functionSignatureDisplay);
                this._addResultsPart(parts, typeText, /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 2 /* DeclarationType.Parameter */: {
                this._addResultsPart(parts, '(parameter) ' + node.value + this._getTypeText(node), /* python */ true);
                if (resolvedDecl.docString) {
                    this._addResultsPart(parts, resolvedDecl.docString);
                }
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 3 /* DeclarationType.TypeParameter */: {
                // If the user is hovering over a type parameter name in a class type parameter
                // list, display the computed variance of the type param.
                const typeParamListNode = ParseTreeUtils.getParentNodeOfType(node, 76 /* ParseNodeType.TypeParameterList */);
                const printTypeVarVariance = ((_b = typeParamListNode === null || typeParamListNode === void 0 ? void 0 : typeParamListNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 10 /* ParseNodeType.Class */;
                this._addResultsPart(parts, '(type parameter) ' + node.value + this._getTypeText(node, { printTypeVarVariance }), 
                /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 6 /* DeclarationType.Class */:
            case 7 /* DeclarationType.SpecialBuiltInClass */: {
                if (this._addInitOrNewMethodInsteadIfCallNode(node, parts, resolvedDecl)) {
                    return;
                }
                const nameNode = resolvedDecl.type === 6 /* DeclarationType.Class */ ? resolvedDecl.node.name : node;
                this._addResultsPart(parts, '(class) ' + nameNode.value, /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 5 /* DeclarationType.Function */: {
                let label = 'function';
                let isProperty = false;
                if (resolvedDecl.isMethod) {
                    const declaredType = (_c = this._evaluator.getTypeForDeclaration(resolvedDecl)) === null || _c === void 0 ? void 0 : _c.type;
                    isProperty = !!declaredType && (0, typeUtils_1.isMaybeDescriptorInstance)(declaredType, /* requireSetter */ false);
                    label = isProperty ? 'property' : 'method';
                }
                let type = this._getType(node);
                const resolvedType = this._getType(resolvedDecl.node.name);
                type = (0, types_1.isAnyOrUnknown)(type) ? resolvedType : type;
                const signatureString = (0, tooltipUtils_1.getToolTipForType)(type, label, node.value, this._evaluator, isProperty, this._functionSignatureDisplay);
                this._addResultsPart(parts, signatureString, /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 8 /* DeclarationType.Alias */: {
                // First the 'module' header.
                this._addResultsPart(parts, '(module) ' + node.value, /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            case 4 /* DeclarationType.TypeAlias */: {
                const typeText = node.value + this._getTypeText(node, { expandTypeAlias: true });
                this._addResultsPart(parts, `(type alias) ${typeText}`, /* python */ true);
                this._addDocumentationPart(parts, node, resolvedDecl);
                break;
            }
            default:
                (0, debug_1.assertNever)(resolvedDecl);
        }
    }
    _tryAddPartsForTypedDictKey(node, type, parts) {
        // If the expected type is a TypedDict and the current node is a key entry then we can provide a tooltip
        // with the type of the TypedDict key and its docstring, if available.
        (0, typeUtils_1.doForEachSubtype)(type, (subtype) => {
            var _a, _b;
            if ((0, types_1.isClassInstance)(subtype) && types_1.ClassType.isTypedDictClass(subtype)) {
                const entry = (_a = subtype.details.typedDictEntries) === null || _a === void 0 ? void 0 : _a.knownItems.get(node.value);
                if (entry) {
                    // If we have already added parts for another declaration (e.g. for a union of TypedDicts that share the same key)
                    // then we need to add a separator to prevent a visual bug.
                    if (parts.length > 0) {
                        parts.push({ text: '\n\n---\n' });
                    }
                    // e.g. (key) name: str
                    const text = '(key) ' + node.value + ': ' + this._evaluator.printType(entry.valueType);
                    this._addResultsPart(parts, text, /* python */ true);
                    const declarations = (_b = types_1.ClassType.getSymbolTable(subtype).get(node.value)) === null || _b === void 0 ? void 0 : _b.getDeclarations();
                    if (declarations !== undefined && (declarations === null || declarations === void 0 ? void 0 : declarations.length) !== 0) {
                        // As we are just interested in the docString we don't have to worry about
                        // anything other than the first declaration. There also shouldn't be more
                        // than one declaration for a TypedDict key variable.
                        const declaration = declarations[0];
                        if (declaration.type === 1 /* DeclarationType.Variable */ && declaration.docString !== undefined) {
                            this._addDocumentationPartForType(parts, subtype, declaration);
                        }
                    }
                }
            }
        });
    }
    _addInitOrNewMethodInsteadIfCallNode(node, parts, declaration) {
        const result = (0, tooltipUtils_1.getClassAndConstructorTypes)(node, this._evaluator);
        if (!result) {
            return false;
        }
        if (result.methodType && ((0, types_1.isFunction)(result.methodType) || (0, types_1.isOverloadedFunction)(result.methodType))) {
            this._addResultsPart(parts, (0, tooltipUtils_1.getConstructorTooltip)(node.value, result.methodType, this._evaluator, this._functionSignatureDisplay), 
            /* python */ true);
            const addedDoc = this._addDocumentationPartForType(parts, result.methodType, declaration);
            if (!addedDoc) {
                this._addDocumentationPartForType(parts, result.classType, declaration);
            }
            return true;
        }
        return false;
    }
    _getType(node) {
        // It does common work necessary for hover for a type we got
        // from raw type evaluator.
        return (0, tooltipUtils_1.getTypeForToolTip)(this._evaluator, node);
    }
    _getTypeText(node, options) {
        const type = this._getType(node);
        return ': ' + this._evaluator.printType(type, options);
    }
    _addDocumentationPart(parts, node, resolvedDecl) {
        const type = this._getType(node);
        this._addDocumentationPartForType(parts, type, resolvedDecl, node.value);
    }
    _addDocumentationPartForType(parts, type, resolvedDecl, name) {
        const docString = (0, tooltipUtils_1.getDocumentationPartsForTypeAndDecl)(this._sourceMapper, type, resolvedDecl, this._evaluator, {
            name,
        });
        addDocumentationResultsPart(docString, this._format, parts);
        return !!docString;
    }
    _addResultsPart(parts, text, python = false) {
        parts.push({
            python,
            text,
        });
    }
}
exports.HoverProvider = HoverProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/importSorter.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/languageService/importSorter.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * importSorter.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides code that sorts and formats import statements within a
 * Python source file.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ImportSorter = void 0;
const importStatementUtils_1 = __webpack_require__(/*! ../analyzer/importStatementUtils */ "../pyright-internal/src/analyzer/importStatementUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
// We choose a line length that matches the default for the popular
// "black" formatter used in many Python projects.
const _maxLineLength = 88;
class ImportSorter {
    constructor(_parseResults, _cancellationToken) {
        this._parseResults = _parseResults;
        this._cancellationToken = _cancellationToken;
    }
    sort() {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._cancellationToken);
        const actions = [];
        const importStatements = (0, importStatementUtils_1.getTopLevelImports)(this._parseResults.parserOutput.parseTree);
        const sortedStatements = importStatements.orderedImports
            .map((s) => s)
            .sort((a, b) => {
            return (0, importStatementUtils_1.compareImportStatements)(a, b);
        });
        if (sortedStatements.length === 0) {
            // Nothing to do.
            return [];
        }
        const primaryRange = this._getPrimaryReplacementRange(importStatements.orderedImports);
        actions.push({
            range: primaryRange,
            replacementText: this._generateSortedImportText(sortedStatements),
        });
        this._addSecondaryReplacementRanges(importStatements.orderedImports, actions);
        return actions;
    }
    // Determines the text range for the existing primary block of import statements.
    // If there are other blocks of import statements separated by other statements,
    // we'll ignore these other blocks for now.
    _getPrimaryReplacementRange(statements) {
        let statementLimit = statements.findIndex((s) => s.followsNonImportStatement);
        if (statementLimit < 0) {
            statementLimit = statements.length;
        }
        const lastStatement = statements[statementLimit - 1].node;
        return {
            start: (0, positionUtils_1.convertOffsetToPosition)(statements[0].node.start, this._parseResults.tokenizerOutput.lines),
            end: (0, positionUtils_1.convertOffsetToPosition)(textRange_1.TextRange.getEnd(lastStatement), this._parseResults.tokenizerOutput.lines),
        };
    }
    // If import statements are separated by other statements, we will remove the old
    // secondary blocks.
    _addSecondaryReplacementRanges(statements, actions) {
        let secondaryBlockStart = statements.findIndex((s) => s.followsNonImportStatement);
        if (secondaryBlockStart < 0) {
            return;
        }
        while (true) {
            let secondaryBlockLimit = statements.findIndex((s, index) => index > secondaryBlockStart && s.followsNonImportStatement);
            if (secondaryBlockLimit < 0) {
                secondaryBlockLimit = statements.length;
            }
            actions.push({
                range: {
                    start: (0, positionUtils_1.convertOffsetToPosition)(statements[secondaryBlockStart].node.start, this._parseResults.tokenizerOutput.lines),
                    end: (0, positionUtils_1.convertOffsetToPosition)(textRange_1.TextRange.getEnd(statements[secondaryBlockLimit - 1].node), this._parseResults.tokenizerOutput.lines),
                },
                replacementText: '',
            });
            secondaryBlockStart = secondaryBlockLimit;
            if (secondaryBlockStart >= statements.length) {
                break;
            }
        }
    }
    _generateSortedImportText(sortedStatements) {
        let importText = '';
        let prevImportGroup = (0, importStatementUtils_1.getImportGroup)(sortedStatements[0]);
        for (const statement of sortedStatements) {
            // Insert a blank space between import type groups.
            const curImportType = (0, importStatementUtils_1.getImportGroup)(statement);
            if (prevImportGroup !== curImportType) {
                importText += this._parseResults.tokenizerOutput.predominantEndOfLineSequence;
                prevImportGroup = curImportType;
            }
            let importLine;
            if (statement.node.nodeType === 20 /* ParseNodeType.Import */) {
                importLine = this._formatImportNode(statement.subnode, statement.moduleName);
            }
            else {
                importLine = this._formatImportFromNode(statement.node, statement.moduleName);
            }
            // If this isn't the last statement, add a newline.
            if (statement !== sortedStatements[sortedStatements.length - 1]) {
                importLine += this._parseResults.tokenizerOutput.predominantEndOfLineSequence;
            }
            importText += importLine;
        }
        return importText;
    }
    _formatImportNode(subnode, moduleName) {
        let importText = `import ${moduleName}`;
        if (subnode.alias) {
            importText += ` as ${subnode.alias.value}`;
        }
        return importText;
    }
    _formatImportFromNode(node, moduleName) {
        const symbols = node.imports
            .sort((a, b) => this._compareSymbols(a, b))
            .map((symbol) => {
            let symbolText = symbol.name.value;
            if (symbol.alias) {
                symbolText += ` as ${symbol.alias.value}`;
            }
            return symbolText;
        });
        let cumulativeText = `from ${moduleName} import `;
        if (node.isWildcardImport) {
            return cumulativeText + '*';
        }
        const symbolText = symbols.join(', ');
        if (cumulativeText.length + symbolText.length <= _maxLineLength) {
            return cumulativeText + symbolText;
        }
        // We need to split across multiple lines with parens.
        cumulativeText += '(' + this._parseResults.tokenizerOutput.predominantEndOfLineSequence;
        for (const symbol of symbols) {
            cumulativeText +=
                this._parseResults.tokenizerOutput.predominantTabSequence +
                    symbol +
                    ',' +
                    this._parseResults.tokenizerOutput.predominantEndOfLineSequence;
        }
        cumulativeText += ')';
        return cumulativeText;
    }
    _compareSymbols(a, b) {
        return a.name.value < b.name.value ? -1 : 1;
    }
}
exports.ImportSorter = ImportSorter;


/***/ }),

/***/ "../pyright-internal/src/languageService/inlayHintsProvider.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/languageService/inlayHintsProvider.ts ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InlayHintsProvider = void 0;
const vscode_languageserver_protocol_1 = __webpack_require__(/*! vscode-languageserver-protocol */ "../pyright-internal/node_modules/vscode-languageserver-protocol/lib/node/main.js");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const typeInlayHintsWalker_1 = __webpack_require__(/*! ../analyzer/typeInlayHintsWalker */ "../pyright-internal/src/analyzer/typeInlayHintsWalker.ts");
class InlayHintsProvider {
    constructor(_program, fileUri, range) {
        this._program = _program;
        this._walker = new typeInlayHintsWalker_1.TypeInlayHintsWalker(this._program, fileUri, range);
    }
    async onInlayHints() {
        if (!this._walker.parseResults) {
            return null;
        }
        this._walker.walk(this._walker.parseResults.parserOutput.parseTree);
        return this._walker.featureItems.map((item) => ({
            label: [vscode_languageserver_protocol_1.InlayHintLabelPart.create(item.value)],
            position: (0, positionUtils_1.convertOffsetToPosition)(item.position, this._walker.lines),
            paddingLeft: item.inlayHintType === 'functionReturn',
            kind: item.inlayHintType === 'parameter' ? vscode_languageserver_protocol_1.InlayHintKind.Parameter : vscode_languageserver_protocol_1.InlayHintKind.Type,
        }));
    }
}
exports.InlayHintsProvider = InlayHintsProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/navigationUtils.ts":
/*!******************************************************************!*\
  !*** ../pyright-internal/src/languageService/navigationUtils.ts ***!
  \******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertDocumentRangeToLocation = exports.convertDocumentRangesToLocation = exports.canNavigateToFile = void 0;
/*
 * navigationUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Helper functions for navigating files.
 */
const vscode_languageserver_types_1 = __webpack_require__(/*! vscode-languageserver-types */ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js");
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
function canNavigateToFile(fs, path) {
    return !fs.isInZip(path);
}
exports.canNavigateToFile = canNavigateToFile;
function convertDocumentRangesToLocation(fs, ranges, converter = convertDocumentRangeToLocation) {
    return ranges.map((range) => converter(fs, range)).filter((loc) => !!loc);
}
exports.convertDocumentRangesToLocation = convertDocumentRangesToLocation;
function convertDocumentRangeToLocation(fs, range) {
    if (!canNavigateToFile(fs, range.uri)) {
        return undefined;
    }
    return vscode_languageserver_types_1.Location.create((0, uriUtils_1.encodeUri)(fs, range.uri), range.range);
}
exports.convertDocumentRangeToLocation = convertDocumentRangeToLocation;


/***/ }),

/***/ "../pyright-internal/src/languageService/quickActions.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/languageService/quickActions.ts ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * quickActions.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Provides support for miscellaneous quick actions.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.performQuickAction = void 0;
const importSorter_1 = __webpack_require__(/*! ./importSorter */ "../pyright-internal/src/languageService/importSorter.ts");
function performQuickAction(programView, uri, command, args, token) {
    const sourceFileInfo = programView.getSourceFileInfo(uri);
    // This command should be called only for open files, in which
    // case we should have the file contents already loaded.
    if (!sourceFileInfo || !sourceFileInfo.isOpenByClient) {
        return [];
    }
    // If we have no completed analysis job, there's nothing to do.
    const parseResults = programView.getParseResults(uri);
    if (!parseResults) {
        return [];
    }
    if (command === "basedpyright.organizeimports" /* Commands.orderImports */) {
        const importSorter = new importSorter_1.ImportSorter(parseResults, token);
        return importSorter.sort();
    }
    return [];
}
exports.performQuickAction = performQuickAction;


/***/ }),

/***/ "../pyright-internal/src/languageService/referencesProvider.ts":
/*!*********************************************************************!*\
  !*** ../pyright-internal/src/languageService/referencesProvider.ts ***!
  \*********************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * referencesProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that finds all of the references to a symbol specified
 * by a location within a file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReferencesProvider = exports.FindReferencesTreeWalker = exports.ReferencesResult = void 0;
const declaration_1 = __webpack_require__(/*! ../analyzer/declaration */ "../pyright-internal/src/analyzer/declaration.ts");
const declarationUtils_1 = __webpack_require__(/*! ../analyzer/declarationUtils */ "../pyright-internal/src/analyzer/declarationUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const symbolUtils_1 = __webpack_require__(/*! ../analyzer/symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const extensibility_1 = __webpack_require__(/*! ../common/extensibility */ "../pyright-internal/src/common/extensibility.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const serviceKeys_1 = __webpack_require__(/*! ../common/serviceKeys */ "../pyright-internal/src/common/serviceKeys.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const documentSymbolCollector_1 = __webpack_require__(/*! ./documentSymbolCollector */ "../pyright-internal/src/languageService/documentSymbolCollector.ts");
const navigationUtils_1 = __webpack_require__(/*! ./navigationUtils */ "../pyright-internal/src/languageService/navigationUtils.ts");
class ReferencesResult {
    constructor(requiresGlobalSearch, nodeAtOffset, symbolNames, declarations, useCase, providers, _reporter) {
        this.requiresGlobalSearch = requiresGlobalSearch;
        this.nodeAtOffset = nodeAtOffset;
        this.symbolNames = symbolNames;
        this.declarations = declarations;
        this.useCase = useCase;
        this.providers = providers;
        this._reporter = _reporter;
        this._locations = [];
        // Filter out any import decls. but leave one with alias.
        this.nonImportDeclarations = declarations.filter((d) => {
            var _a;
            if (!(0, declaration_1.isAliasDeclaration)(d)) {
                return true;
            }
            // We must have alias and decl node that point to import statement.
            if (!d.usesLocalName || !d.node) {
                return false;
            }
            // d.node can't be ImportFrom if usesLocalName is true.
            // but we are doing this for type checker.
            if (d.node.nodeType === 22 /* ParseNodeType.ImportFrom */) {
                return false;
            }
            // Extract alias for comparison (symbolNames.some can't know d is for an Alias).
            const alias = (_a = d.node.alias) === null || _a === void 0 ? void 0 : _a.value;
            // Check alias and what we are renaming is same thing.
            if (!symbolNames.some((s) => s === alias)) {
                return false;
            }
            return true;
        });
    }
    get containsOnlyImportDecls() {
        return this.declarations.length > 0 && this.nonImportDeclarations.length === 0;
    }
    get locations() {
        return this._locations;
    }
    addLocations(...locs) {
        if (locs.length === 0) {
            return;
        }
        if (this._reporter) {
            this._reporter(locs);
        }
        (0, collectionUtils_1.appendArray)(this._locations, locs);
    }
}
exports.ReferencesResult = ReferencesResult;
class FindReferencesTreeWalker {
    constructor(_program, _fileUri, _referencesResult, _includeDeclaration, _cancellationToken, _createDocumentRange = FindReferencesTreeWalker.createDocumentRange) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._referencesResult = _referencesResult;
        this._includeDeclaration = _includeDeclaration;
        this._cancellationToken = _cancellationToken;
        this._createDocumentRange = _createDocumentRange;
        this._parseResults = this._program.getParseResults(this._fileUri);
    }
    findReferences(rootNode) {
        var _a;
        if (rootNode === void 0) { rootNode = (_a = this._parseResults) === null || _a === void 0 ? void 0 : _a.parserOutput.parseTree; }
        const results = [];
        if (!this._parseResults) {
            return results;
        }
        const collector = new documentSymbolCollector_1.DocumentSymbolCollector(this._program, this._referencesResult.symbolNames, this._referencesResult.declarations, rootNode, this._cancellationToken, {
            treatModuleInImportAndFromImportSame: true,
            skipUnreachableCode: false,
            useCase: this._referencesResult.useCase,
            providers: this._referencesResult.providers,
        });
        for (const result of collector.collect()) {
            // Is it the same symbol?
            if (this._includeDeclaration || result.node !== this._referencesResult.nodeAtOffset) {
                results.push(this._createDocumentRange(this._fileUri, result, this._parseResults));
            }
        }
        return results;
    }
    static createDocumentRange(fileUri, result, parseResults) {
        return {
            uri: fileUri,
            range: {
                start: (0, positionUtils_1.convertOffsetToPosition)(result.range.start, parseResults.tokenizerOutput.lines),
                end: (0, positionUtils_1.convertOffsetToPosition)(textRange_1.TextRange.getEnd(result.range), parseResults.tokenizerOutput.lines),
            },
        };
    }
}
exports.FindReferencesTreeWalker = FindReferencesTreeWalker;
class ReferencesProvider {
    constructor(_program, _token, _createDocumentRange, _convertToLocation) {
        this._program = _program;
        this._token = _token;
        this._createDocumentRange = _createDocumentRange;
        this._convertToLocation = _convertToLocation;
        // empty
    }
    reportReferences(fileUri, position, includeDeclaration, resultReporter) {
        const sourceFileInfo = this._program.getSourceFileInfo(fileUri);
        if (!sourceFileInfo) {
            return;
        }
        const parseResults = this._program.getParseResults(fileUri);
        if (!parseResults) {
            return;
        }
        const locations = [];
        const reporter = resultReporter
            ? (range) => resultReporter.report((0, navigationUtils_1.convertDocumentRangesToLocation)(this._program.fileSystem, range, this._convertToLocation))
            : (range) => (0, collectionUtils_1.appendArray)(locations, (0, navigationUtils_1.convertDocumentRangesToLocation)(this._program.fileSystem, range, this._convertToLocation));
        const invokedFromUserFile = (0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo);
        const referencesResult = ReferencesProvider.getDeclarationForPosition(this._program, fileUri, position, reporter, extensibility_1.ReferenceUseCase.References, this._token);
        if (!referencesResult) {
            return;
        }
        // Do we need to do a global search as well?
        if (!referencesResult.requiresGlobalSearch) {
            this.addReferencesToResult(sourceFileInfo.sourceFile.getUri(), includeDeclaration, referencesResult);
        }
        for (const curSourceFileInfo of this._program.getSourceFileInfoList()) {
            (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
            // "Find all references" will only include references from user code
            // unless the file is explicitly opened in the editor or it is invoked from non user files.
            if (curSourceFileInfo.isOpenByClient || !invokedFromUserFile || (0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo)) {
                // See if the reference symbol's string is located somewhere within the file.
                // If not, we can skip additional processing for the file.
                const fileContents = curSourceFileInfo.sourceFile.getFileContent();
                if (!fileContents || referencesResult.symbolNames.some((s) => fileContents.search(s) >= 0)) {
                    this.addReferencesToResult(curSourceFileInfo.sourceFile.getUri(), includeDeclaration, referencesResult);
                }
                // This operation can consume significant memory, so check
                // for situations where we need to discard the type cache.
                this._program.handleMemoryHighUsage();
            }
        }
        // Make sure to include declarations regardless where they are defined
        // if includeDeclaration is set.
        if (includeDeclaration) {
            for (const decl of referencesResult.declarations) {
                (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
                if (referencesResult.locations.some((l) => l.uri.equals(decl.uri))) {
                    // Already included.
                    continue;
                }
                const declFileInfo = this._program.getSourceFileInfo(decl.uri);
                if (!declFileInfo) {
                    // The file the declaration belongs to doesn't belong to the program.
                    continue;
                }
                const tempResult = new ReferencesResult(referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolNames, referencesResult.declarations, referencesResult.useCase, referencesResult.providers);
                this.addReferencesToResult(declFileInfo.sourceFile.getUri(), includeDeclaration, tempResult);
                for (const loc of tempResult.locations) {
                    // Include declarations only. And throw away any references
                    if (loc.uri.equals(decl.uri) && (0, textRange_1.doesRangeContain)(decl.range, loc.range)) {
                        referencesResult.addLocations(loc);
                    }
                }
            }
        }
        // Deduplicate locations before returning them.
        const locationsSet = new Set();
        const dedupedLocations = [];
        for (const loc of locations) {
            const key = `${loc.uri.toString()}:${loc.range.start.line}:${loc.range.start.character}`;
            if (!locationsSet.has(key)) {
                locationsSet.add(key);
                dedupedLocations.push(loc);
            }
        }
        return dedupedLocations;
    }
    addReferencesToResult(fileUri, includeDeclaration, referencesResult) {
        const parseResults = this._program.getParseResults(fileUri);
        if (!parseResults) {
            return;
        }
        const refTreeWalker = new FindReferencesTreeWalker(this._program, fileUri, referencesResult, includeDeclaration, this._token, this._createDocumentRange);
        referencesResult.addLocations(...refTreeWalker.findReferences());
    }
    static getDeclarationForNode(program, fileUri, node, reporter, useCase, token) {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const declarations = documentSymbolCollector_1.DocumentSymbolCollector.getDeclarationsForNode(program, node, 
        /* resolveLocalNames */ false, token);
        if (declarations.length === 0) {
            return undefined;
        }
        const requiresGlobalSearch = isVisibleOutside(program.evaluator, fileUri, node, declarations);
        const symbolNames = new Set(declarations.map((d) => (0, declarationUtils_1.getNameFromDeclaration)(d)).filter((n) => !!n));
        symbolNames.add(node.value);
        const providers = ((_a = program.serviceProvider.tryGet(serviceKeys_1.ServiceKeys.symbolUsageProviderFactory)) !== null && _a !== void 0 ? _a : [])
            .map((f) => f.tryCreateProvider(useCase, declarations, token))
            .filter(core_1.isDefined);
        // Check whether we need to add new symbol names and declarations.
        providers.forEach((p) => {
            p.appendSymbolNamesTo(symbolNames);
            p.appendDeclarationsTo(declarations);
        });
        return new ReferencesResult(requiresGlobalSearch, node, Array.from(symbolNames.values()), declarations, useCase, providers, reporter);
    }
    static getDeclarationForPosition(program, fileUri, position, reporter, useCase, token) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(token);
        const parseResults = program.getParseResults(fileUri);
        if (!parseResults) {
            return undefined;
        }
        const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
        if (offset === undefined) {
            return undefined;
        }
        const node = ParseTreeUtils.findNodeByOffset(parseResults.parserOutput.parseTree, offset);
        if (node === undefined) {
            return undefined;
        }
        // If this isn't a name node, there are no references to be found.
        if (node.nodeType !== 38 /* ParseNodeType.Name */) {
            return undefined;
        }
        return this.getDeclarationForNode(program, fileUri, node, reporter, useCase, token);
    }
}
exports.ReferencesProvider = ReferencesProvider;
function isVisibleOutside(evaluator, currentUri, node, declarations) {
    const result = evaluator.lookUpSymbolRecursive(node, node.value, /* honorCodeFlow */ false);
    if (result && !isExternallyVisible(result.symbol)) {
        return false;
    }
    // A symbol's effective external visibility check is not enough to determine whether
    // the symbol is visible to the outside. Something like the local variable inside
    // a function will still say it is externally visible even if it can't be accessed from another module.
    // So, we also need to determine whether the symbol is declared within an evaluation scope
    // that is within the current file and cannot be imported directly from other modules.
    return declarations.some((decl) => {
        var _a, _b;
        // If the declaration is outside of this file, a global search is needed.
        if (!decl.uri.equals(currentUri)) {
            return true;
        }
        const evalScope = ParseTreeUtils.getEvaluationScopeNode(decl.node);
        // If the declaration is at the module level or a class level, it can be seen
        // outside of the current module, so a global search is needed.
        if (evalScope.nodeType === 36 /* ParseNodeType.Module */ || evalScope.nodeType === 10 /* ParseNodeType.Class */) {
            return true;
        }
        // If the name node is a member variable, we need to do a global search.
        if (((_b = (_a = decl.node) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 35 /* ParseNodeType.MemberAccess */ && decl.node === decl.node.parent.memberName) {
            return true;
        }
        return false;
    });
    // Return true if the symbol is visible outside of current module, false if not.
    function isExternallyVisible(symbol, recursionCount = 0) {
        if (recursionCount > types_1.maxTypeRecursionCount) {
            return false;
        }
        recursionCount++;
        if (!(0, symbolUtils_1.isVisibleExternally)(symbol)) {
            return false;
        }
        return symbol.getDeclarations().reduce((isVisible, decl) => {
            if (!isVisible) {
                return false;
            }
            switch (decl.type) {
                case 8 /* DeclarationType.Alias */:
                case 0 /* DeclarationType.Intrinsic */:
                case 7 /* DeclarationType.SpecialBuiltInClass */:
                    return isVisible;
                case 6 /* DeclarationType.Class */:
                case 5 /* DeclarationType.Function */:
                    return isVisible && isContainerExternallyVisible(decl.node.name, recursionCount);
                case 2 /* DeclarationType.Parameter */:
                    return isVisible && isContainerExternallyVisible(decl.node.name, recursionCount);
                case 3 /* DeclarationType.TypeParameter */:
                    return false;
                case 1 /* DeclarationType.Variable */:
                case 4 /* DeclarationType.TypeAlias */: {
                    if (decl.node.nodeType === 38 /* ParseNodeType.Name */) {
                        return isVisible && isContainerExternallyVisible(decl.node, recursionCount);
                    }
                    // Symbol without name is not visible outside.
                    return false;
                }
                default:
                    (0, debug_1.assertNever)(decl);
            }
        }, /* visible */ true);
    }
    // Return true if the scope that contains the specified node is visible
    // outside of the current module, false if not.
    function isContainerExternallyVisible(node, recursionCount) {
        const scopingNode = ParseTreeUtils.getEvaluationScopeNode(node);
        switch (scopingNode.nodeType) {
            case 10 /* ParseNodeType.Class */:
            case 28 /* ParseNodeType.Function */: {
                const name = scopingNode.name;
                const result = evaluator.lookUpSymbolRecursive(name, name.value, /* honorCodeFlow */ false);
                return result ? isExternallyVisible(result.symbol, recursionCount) : true;
            }
            case 30 /* ParseNodeType.Lambda */:
            case 32 /* ParseNodeType.ListComprehension */:
                // Symbols in this scope can't be visible outside.
                return false;
            case 36 /* ParseNodeType.Module */:
                return true;
            default:
                (0, debug_1.assertNever)(scopingNode);
        }
    }
}


/***/ }),

/***/ "../pyright-internal/src/languageService/renameProvider.ts":
/*!*****************************************************************!*\
  !*** ../pyright-internal/src/languageService/renameProvider.ts ***!
  \*****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * renameProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that rename identifier on the given position and its references.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RenameProvider = void 0;
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const extensibility_1 = __webpack_require__(/*! ../common/extensibility */ "../pyright-internal/src/common/extensibility.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const workspaceEditUtils_1 = __webpack_require__(/*! ../common/workspaceEditUtils */ "../pyright-internal/src/common/workspaceEditUtils.ts");
const referencesProvider_1 = __webpack_require__(/*! ../languageService/referencesProvider */ "../pyright-internal/src/languageService/referencesProvider.ts");
class RenameProvider {
    constructor(_program, _fileUri, _position, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._position = _position;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
    }
    canRenameSymbol(isDefaultWorkspace, isUntitled) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const referencesResult = this._getReferenceResult();
        if (!referencesResult) {
            return null;
        }
        const renameMode = RenameProvider.getRenameSymbolMode(this._program, this._fileUri, referencesResult, isDefaultWorkspace, isUntitled);
        if (renameMode === 'none') {
            return null;
        }
        // Return the range of the symbol.
        return (0, positionUtils_1.convertTextRangeToRange)(referencesResult.nodeAtOffset, this._parseResults.tokenizerOutput.lines);
    }
    renameSymbol(newName, isDefaultWorkspace, isUntitled) {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return null;
        }
        const referencesResult = this._getReferenceResult();
        if (!referencesResult) {
            return null;
        }
        const referenceProvider = new referencesProvider_1.ReferencesProvider(this._program, this._token);
        const renameMode = RenameProvider.getRenameSymbolMode(this._program, this._fileUri, referencesResult, isDefaultWorkspace, isUntitled);
        switch (renameMode) {
            case 'singleFileMode':
                referenceProvider.addReferencesToResult(this._fileUri, /* includeDeclaration */ true, referencesResult);
                break;
            case 'multiFileMode': {
                for (const curSourceFileInfo of this._program.getSourceFileInfoList()) {
                    // Make sure we only add user code to the references to prevent us
                    // from accidentally changing third party library or type stub.
                    if ((0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo)) {
                        // Make sure searching symbol name exists in the file.
                        const content = (_a = curSourceFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
                        if (!referencesResult.symbolNames.some((s) => content.search(s) >= 0)) {
                            continue;
                        }
                        referenceProvider.addReferencesToResult(curSourceFileInfo.sourceFile.getUri(), 
                        /* includeDeclaration */ true, referencesResult);
                    }
                    // This operation can consume significant memory, so check
                    // for situations where we need to discard the type cache.
                    this._program.handleMemoryHighUsage();
                }
                break;
            }
            case 'none':
                // Rename is not allowed.
                // ex) rename symbols from libraries.
                return null;
            default:
                (0, debug_1.assertNever)(renameMode);
        }
        const edits = [];
        referencesResult.locations.forEach((loc) => {
            edits.push({
                fileUri: loc.uri,
                range: loc.range,
                replacementText: newName,
            });
        });
        return (0, workspaceEditUtils_1.convertToWorkspaceEdit)(this._program.fileSystem, { edits, fileOperations: [] });
    }
    static getRenameSymbolMode(program, fileUri, referencesResult, isDefaultWorkspace, isUntitled) {
        const sourceFileInfo = program.getSourceFileInfo(fileUri);
        // We have 2 different cases
        // Single file mode.
        // 1. rename on default workspace (ex, standalone file mode).
        // 2. rename local symbols.
        // 3. rename symbols defined in the non user open file.
        //
        // and Multi file mode.
        // 1. rename public symbols defined in user files on regular workspace (ex, open folder mode).
        const userFile = (0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo);
        if (isDefaultWorkspace ||
            (userFile && !referencesResult.requiresGlobalSearch) ||
            (!userFile &&
                sourceFileInfo.isOpenByClient &&
                referencesResult.declarations.every((d) => program.getSourceFileInfo(d.uri) === sourceFileInfo))) {
            return 'singleFileMode';
        }
        if (referencesResult.declarations.every((d) => (0, sourceFileInfoUtils_1.isUserCode)(program.getSourceFileInfo(d.uri)))) {
            return 'multiFileMode';
        }
        // Rename is not allowed.
        // ex) rename symbols from libraries.
        return 'none';
    }
    _getReferenceResult() {
        const referencesResult = referencesProvider_1.ReferencesProvider.getDeclarationForPosition(this._program, this._fileUri, this._position, 
        /* reporter */ undefined, extensibility_1.ReferenceUseCase.Rename, this._token);
        if (!referencesResult) {
            return undefined;
        }
        if (referencesResult.containsOnlyImportDecls) {
            return undefined;
        }
        if (referencesResult.nonImportDeclarations.length === 0) {
            // There is no symbol we can rename.
            return undefined;
        }
        // Use declarations that doesn't contain import decls.
        return new referencesProvider_1.ReferencesResult(referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolNames, referencesResult.nonImportDeclarations, referencesResult.useCase, referencesResult.providers);
    }
}
exports.RenameProvider = RenameProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/semanticTokensProvider.ts":
/*!*************************************************************************!*\
  !*** ../pyright-internal/src/languageService/semanticTokensProvider.ts ***!
  \*************************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SemanticTokensProvider = exports.SemanticTokensProviderLegend = exports.tokenModifiers = exports.tokenTypes = exports.CustomSemanticTokenModifiers = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const semanticTokensWalker_1 = __webpack_require__(/*! ../analyzer/semanticTokensWalker */ "../pyright-internal/src/analyzer/semanticTokensWalker.ts");
var CustomSemanticTokenModifiers;
(function (CustomSemanticTokenModifiers) {
    CustomSemanticTokenModifiers["builtin"] = "builtin";
})(CustomSemanticTokenModifiers || (exports.CustomSemanticTokenModifiers = CustomSemanticTokenModifiers = {}));
exports.tokenTypes = [
    vscode_languageserver_1.SemanticTokenTypes.class,
    vscode_languageserver_1.SemanticTokenTypes.parameter,
    vscode_languageserver_1.SemanticTokenTypes.typeParameter,
    vscode_languageserver_1.SemanticTokenTypes.function,
    vscode_languageserver_1.SemanticTokenTypes.method,
    vscode_languageserver_1.SemanticTokenTypes.decorator,
    vscode_languageserver_1.SemanticTokenTypes.property,
    vscode_languageserver_1.SemanticTokenTypes.namespace,
    vscode_languageserver_1.SemanticTokenTypes.variable,
    vscode_languageserver_1.SemanticTokenTypes.type,
    vscode_languageserver_1.SemanticTokenTypes.keyword,
];
exports.tokenModifiers = [
    vscode_languageserver_1.SemanticTokenModifiers.definition,
    vscode_languageserver_1.SemanticTokenModifiers.declaration,
    vscode_languageserver_1.SemanticTokenModifiers.async,
    vscode_languageserver_1.SemanticTokenModifiers.readonly,
    vscode_languageserver_1.SemanticTokenModifiers.defaultLibrary,
    CustomSemanticTokenModifiers.builtin,
];
exports.SemanticTokensProviderLegend = {
    tokenTypes: exports.tokenTypes,
    tokenModifiers: exports.tokenModifiers,
};
function encodeTokenType(type) {
    const idx = exports.tokenTypes.indexOf(type);
    if (idx === -1) {
        throw new Error(`Unknown token type: ${type}`);
    }
    return idx;
}
function encodeTokenModifiers(modifiers) {
    let data = 0;
    for (const t of modifiers) {
        const idx = exports.tokenModifiers.indexOf(t);
        if (idx === undefined) {
            continue;
        }
        data |= 1 << idx;
    }
    return data;
}
class SemanticTokensProvider {
    constructor(_program, _fileUri, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
    }
    onSemanticTokens() {
        const builder = new vscode_languageserver_1.SemanticTokensBuilder();
        if (!this._parseResults) {
            return builder.build();
        }
        const walker = new semanticTokensWalker_1.SemanticTokensWalker(this._program.evaluator);
        walker.walk(this._parseResults.parserOutput.parseTree);
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        // seems that tokens are lost if they show up out of order. TODO: figure out if there's a proper way to fix this
        walker.items.sort((a, b) => a.start - b.start);
        for (const item of walker.items) {
            const range = (0, positionUtils_1.convertOffsetsToRange)(item.start, item.start + item.length, this._parseResults.tokenizerOutput.lines);
            builder.push(range.start.line, range.start.character, item.length, encodeTokenType(item.type), encodeTokenModifiers(item.modifiers));
        }
        return builder.build();
    }
}
exports.SemanticTokensProvider = SemanticTokensProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/signatureHelpProvider.ts":
/*!************************************************************************!*\
  !*** ../pyright-internal/src/languageService/signatureHelpProvider.ts ***!
  \************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * signatureHelpProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Logic that maps a position within a Python call node into info
 * that can be presented to the developer to help fill in the remaining
 * arguments for the call.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SignatureHelpProvider = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const docStringConversion_1 = __webpack_require__(/*! ../analyzer/docStringConversion */ "../pyright-internal/src/analyzer/docStringConversion.ts");
const docStringUtils_1 = __webpack_require__(/*! ../analyzer/docStringUtils */ "../pyright-internal/src/analyzer/docStringUtils.ts");
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const tooltipUtils_1 = __webpack_require__(/*! ./tooltipUtils */ "../pyright-internal/src/languageService/tooltipUtils.ts");
class SignatureHelpProvider {
    constructor(_program, _fileUri, _position, _format, _hasSignatureLabelOffsetCapability, _hasActiveParameterCapability, _context, _token) {
        this._program = _program;
        this._fileUri = _fileUri;
        this._position = _position;
        this._format = _format;
        this._hasSignatureLabelOffsetCapability = _hasSignatureLabelOffsetCapability;
        this._hasActiveParameterCapability = _hasActiveParameterCapability;
        this._context = _context;
        this._token = _token;
        this._parseResults = this._program.getParseResults(this._fileUri);
        this._sourceMapper = this._program.getSourceMapper(this._fileUri, this._token, /* mapCompiled */ true);
    }
    getSignatureHelp() {
        return this._convert(this._getSignatureHelp());
    }
    get _evaluator() {
        return this._program.evaluator;
    }
    _getSignatureHelp() {
        var _a;
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!this._parseResults) {
            return undefined;
        }
        const offset = (0, positionUtils_1.convertPositionToOffset)(this._position, this._parseResults.tokenizerOutput.lines);
        if (offset === undefined) {
            return undefined;
        }
        let node = ParseTreeUtils.findNodeByOffset(this._parseResults.parserOutput.parseTree, offset);
        // See if we can get to a "better" node by backing up a few columns.
        // A "better" node is defined as one that's deeper than the current
        // node.
        const initialNode = node;
        const initialDepth = node ? ParseTreeUtils.getNodeDepth(node) : 0;
        let curOffset = offset - 1;
        while (curOffset >= 0) {
            // Don't scan back across a comma because commas separate
            // arguments, and we don't want to mistakenly think that we're
            // pointing to a previous argument. Don't scan across open parenthesis so that
            // we don't go into the wrong function call
            const ch = this._parseResults.text.substr(curOffset, 1);
            if (ch === ',' || ch === '(') {
                break;
            }
            const curNode = ParseTreeUtils.findNodeByOffset(this._parseResults.parserOutput.parseTree, curOffset);
            if (curNode && curNode !== initialNode) {
                if (ParseTreeUtils.getNodeDepth(curNode) > initialDepth) {
                    node = curNode;
                }
                break;
            }
            curOffset--;
        }
        if (node === undefined) {
            return undefined;
        }
        const callInfo = (0, parseTreeUtils_1.getCallNodeAndActiveParameterIndex)(node, offset, this._parseResults.tokenizerOutput.tokens);
        if (!callInfo) {
            return;
        }
        const callSignatureInfo = this._evaluator.getCallSignatureInfo(callInfo.callNode, callInfo.activeIndex, callInfo.activeOrFake);
        if (!callSignatureInfo) {
            return undefined;
        }
        const signatures = callSignatureInfo.signatures.map((sig) => this._makeSignature(callSignatureInfo.callNode, sig));
        const callHasParameters = !!((_a = callSignatureInfo.callNode.arguments) === null || _a === void 0 ? void 0 : _a.length);
        return {
            signatures,
            callHasParameters,
        };
    }
    _convert(signatureHelpResults) {
        var _a, _b, _c;
        if (!signatureHelpResults) {
            return undefined;
        }
        const signatures = signatureHelpResults.signatures.map((sig) => {
            let paramInfo = [];
            if (sig.parameters) {
                paramInfo = sig.parameters.map((param) => vscode_languageserver_1.ParameterInformation.create(this._hasSignatureLabelOffsetCapability ? [param.startOffset, param.endOffset] : param.text, param.documentation));
            }
            const sigInfo = vscode_languageserver_1.SignatureInformation.create(sig.label, /* documentation */ undefined, ...paramInfo);
            if (sig.documentation !== undefined) {
                sigInfo.documentation = sig.documentation;
            }
            if (sig.activeParameter !== undefined) {
                sigInfo.activeParameter = sig.activeParameter;
            }
            return sigInfo;
        });
        // A signature is active if it contains an active parameter,
        // or if both the signature and its invocation have no parameters.
        const isActive = (sig) => { var _a; return sig.activeParameter !== undefined || (!signatureHelpResults.callHasParameters && !((_a = sig.parameters) === null || _a === void 0 ? void 0 : _a.length)); };
        let activeSignature = signatures.findIndex(isActive);
        if (activeSignature === -1) {
            activeSignature = undefined;
        }
        let activeParameter = activeSignature !== undefined ? signatures[activeSignature].activeParameter : undefined;
        // Check if we should reuse the user's signature selection. If the retrigger was not "invoked"
        // (i.e., the signature help call was automatically generated by the client due to some navigation
        // or text change), check to see if the previous signature is still "active". If so, we mark it as
        // active in our response.
        //
        // This isn't a perfect method. For nested calls, we can't tell when we are moving between them.
        // Ideally, we would include a token in the signature help responses to compare later, allowing us
        // to know when the user's navigated to a nested call (and therefore the old signature's info does
        // not apply), but for now manually retriggering the signature help will work around the issue.
        if (((_a = this._context) === null || _a === void 0 ? void 0 : _a.isRetrigger) && this._context.triggerKind !== vscode_languageserver_1.SignatureHelpTriggerKind.Invoked) {
            const prevActiveSignature = (_b = this._context.activeSignatureHelp) === null || _b === void 0 ? void 0 : _b.activeSignature;
            if (prevActiveSignature !== undefined && prevActiveSignature < signatures.length) {
                const sig = signatures[prevActiveSignature];
                if (isActive(sig)) {
                    activeSignature = prevActiveSignature;
                    activeParameter = (_c = sig.activeParameter) !== null && _c !== void 0 ? _c : undefined;
                }
            }
        }
        if (this._hasActiveParameterCapability || activeSignature === undefined) {
            // If there is no active parameter, then we want the client to not highlight anything.
            // Unfortunately, the LSP spec says that "undefined" or "out of bounds" values should be
            // treated as 0, which is the first parameter. That's not what we want, but thankfully
            // VS Code (and potentially other clients) choose to handle out of bounds values by
            // not highlighting them, which is what we want.
            //
            // The spec defines activeParameter as uinteger, so use the maximum length of any
            // signature's parameter list to ensure that the value is always out of range.
            //
            // We always set this even if some signature has an active parameter, as this
            // value is used as the fallback for signatures that don't explicitly specify an
            // active parameter (and we use "undefined" to mean "no active parameter").
            //
            // We could apply this hack to each individual signature such that they all specify
            // activeParameter, but that would make it more difficult to determine which actually
            // are active when comparing, and we already have to set this for clients which don't
            // support per-signature activeParameter.
            //
            // See:
            //   - https://github.com/microsoft/language-server-protocol/issues/1271
            //   - https://github.com/microsoft/pyright/pull/1783
            activeParameter = Math.max(...signatures.map((s) => { var _a, _b; return (_b = (_a = s.parameters) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; }));
        }
        return { signatures, activeSignature, activeParameter };
    }
    _makeSignature(callNode, signature) {
        var _a;
        const functionType = signature.type;
        const stringParts = this._evaluator.printFunctionParts(functionType, 1024 /* PrintTypeFlags.ExpandTypedDictArgs */);
        const parameters = [];
        const functionDocString = (_a = (0, tooltipUtils_1.getFunctionDocStringFromType)(functionType, this._sourceMapper, this._evaluator)) !== null && _a !== void 0 ? _a : this._getDocStringFromCallNode(callNode);
        let label = '(';
        let activeParameter;
        const params = functionType.details.parameters;
        stringParts[0].forEach((paramString, paramIndex) => {
            let paramName = '';
            if (paramIndex < params.length) {
                paramName = params[paramIndex].name || '';
            }
            else if (params.length > 0) {
                paramName = params[params.length - 1].name || '';
            }
            parameters.push({
                startOffset: label.length,
                endOffset: label.length + paramString.length,
                text: paramString,
                documentation: (0, docStringUtils_1.extractParameterDocumentation)(functionDocString || '', paramName),
            });
            // Name match for active parameter. The set of parameters from the function
            // may not match the actual string output from the typeEvaluator (kwargs for TypedDict is an example).
            if (paramName && signature.activeParam && signature.activeParam.name === paramName) {
                activeParameter = paramIndex;
            }
            label += paramString;
            if (paramIndex < stringParts[0].length - 1) {
                label += ', ';
            }
        });
        label += ') -> ' + stringParts[1];
        if (signature.activeParam && activeParameter === undefined) {
            activeParameter = params.indexOf(signature.activeParam);
            if (activeParameter === -1) {
                activeParameter = undefined;
            }
        }
        const sigInfo = {
            label,
            parameters,
            activeParameter,
        };
        if (functionDocString) {
            if (this._format === vscode_languageserver_1.MarkupKind.Markdown) {
                sigInfo.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.Markdown,
                    value: (0, docStringConversion_1.convertDocStringToMarkdown)(functionDocString),
                };
            }
            else {
                sigInfo.documentation = {
                    kind: vscode_languageserver_1.MarkupKind.PlainText,
                    value: (0, docStringConversion_1.convertDocStringToPlainText)(functionDocString),
                };
            }
        }
        return sigInfo;
    }
    _getDocStringFromCallNode(callNode) {
        var _a;
        // This is a heuristic to see whether we can get some docstring
        // from call node when all other methods failed.
        // It only works if call is off a name node.
        let name;
        const expr = callNode.leftExpression;
        if (expr.nodeType === 38 /* ParseNodeType.Name */) {
            name = expr;
        }
        else if (expr.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            name = expr.memberName;
        }
        if (!name) {
            return undefined;
        }
        for (const decl of (_a = this._evaluator.getDeclarationsForNameNode(name)) !== null && _a !== void 0 ? _a : []) {
            const resolveDecl = this._evaluator.resolveAliasDeclaration(decl, /* resolveLocalNames */ true);
            if (!resolveDecl) {
                continue;
            }
            const type = this._evaluator.getType(name);
            if (!type) {
                continue;
            }
            const part = (0, tooltipUtils_1.getDocumentationPartsForTypeAndDecl)(this._sourceMapper, type, resolveDecl, this._evaluator);
            if (part) {
                return part;
            }
        }
        return undefined;
    }
}
exports.SignatureHelpProvider = SignatureHelpProvider;


/***/ }),

/***/ "../pyright-internal/src/languageService/symbolIndexer.ts":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/languageService/symbolIndexer.ts ***!
  \****************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * symbolIndexer.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Logic that collect all symbol decl information for a specified source file.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SymbolIndexer = void 0;
const AnalyzerNodeInfo = __importStar(__webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts"));
const symbolUtils_1 = __webpack_require__(/*! ../analyzer/symbolUtils */ "../pyright-internal/src/analyzer/symbolUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const lspUtils_1 = __webpack_require__(/*! ../common/lspUtils */ "../pyright-internal/src/common/lspUtils.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const autoImporter_1 = __webpack_require__(/*! ./autoImporter */ "../pyright-internal/src/languageService/autoImporter.ts");
class SymbolIndexer {
    static indexSymbols(fileInfo, parseResults, indexOptions, token) {
        // Here are the rule of what symbols are indexed for a file.
        // 1. If it is a stub file, we index every public symbols defined by "https://www.python.org/dev/peps/pep-0484/#stub-files"
        // 2. If it is a py file and it is py.typed package, we index public symbols
        //    defined by "https://github.com/microsoft/pyright/blob/main/docs/typed-libraries.md#library-interface"
        // 3. If it is a py file and it is not py.typed package, we index only symbols that appear in
        //    __all__ to make sure we don't include too many symbols in the index.
        const indexSymbolData = [];
        collectSymbolIndexData(fileInfo, parseResults, parseResults.parserOutput.parseTree, indexOptions, indexSymbolData, token);
        return indexSymbolData;
    }
}
exports.SymbolIndexer = SymbolIndexer;
function collectSymbolIndexData(fileInfo, parseResults, node, indexOptions, indexSymbolData, token) {
    (0, cancellationUtils_1.throwIfCancellationRequested)(token);
    const scope = AnalyzerNodeInfo.getScope(node);
    if (!scope) {
        return;
    }
    const symbolTable = scope.symbolTable;
    symbolTable.forEach((symbol, name) => {
        if (symbol.isIgnoredForProtocolMatch()) {
            return;
        }
        // Prefer declarations with a defined type.
        let declaration = (0, symbolUtils_1.getLastTypedDeclarationForSymbol)(symbol);
        // Fall back to declarations without a type.
        if (!declaration && symbol.hasDeclarations()) {
            declaration = symbol.getDeclarations()[0];
        }
        if (!declaration) {
            return;
        }
        if (8 /* DeclarationType.Alias */ === declaration.type && !shouldAliasBeIndexed(declaration, indexOptions)) {
            return;
        }
        // We rely on ExternallyHidden flag to determine what
        // symbols should be public (included in the index)
        collectSymbolIndexDataForName(fileInfo, parseResults, declaration, indexOptions, (0, symbolUtils_1.isVisibleExternally)(symbol), name, indexSymbolData, token);
    });
}
function collectSymbolIndexDataForName(fileInfo, parseResults, declaration, indexOptions, externallyVisible, name, indexSymbolData, token) {
    const symbolKind = (0, lspUtils_1.getSymbolKind)(declaration, undefined, name);
    if (symbolKind === undefined) {
        return;
    }
    let selectionRange = declaration.range;
    let range = selectionRange;
    const children = [];
    if (declaration.type === 6 /* DeclarationType.Class */ || declaration.type === 5 /* DeclarationType.Function */) {
        collectSymbolIndexData(fileInfo, parseResults, declaration.node, indexOptions, children, token);
        range = (0, positionUtils_1.convertOffsetsToRange)(declaration.node.start, declaration.node.start + declaration.node.length, parseResults.tokenizerOutput.lines);
    }
    if (8 /* DeclarationType.Alias */ === declaration.type) {
        if (!shouldAliasBeIndexed(declaration, indexOptions)) {
            return;
        }
        // The default range for a module alias is the first character of the module's file.
        // Replace that with the range of the alias token.
        if (declaration.node.nodeType === 21 /* ParseNodeType.ImportAs */ && declaration.node.alias) {
            selectionRange = range = (0, positionUtils_1.convertTextRangeToRange)(declaration.node.alias.token, parseResults.tokenizerOutput.lines);
        }
    }
    const data = {
        name,
        externallyVisible,
        kind: symbolKind,
        itemKind: (0, autoImporter_1.convertSymbolKindToCompletionItemKind)(symbolKind),
        alias: undefined,
        range: range,
        selectionRange: selectionRange,
        children: children,
    };
    indexSymbolData.push(data);
}
function shouldAliasBeIndexed(declaration, indexOptions) {
    if (!indexOptions.includeAliases) {
        return false;
    }
    // Only allow import statements with an alias (`import module as alias` or
    // `from module import symbol as alias`), since the alias is a symbol specific
    // to the importing file.
    return ((declaration.node.nodeType === 21 /* ParseNodeType.ImportAs */ ||
        declaration.node.nodeType === 23 /* ParseNodeType.ImportFromAs */) &&
        declaration.node.alias !== undefined);
}


/***/ }),

/***/ "../pyright-internal/src/languageService/tooltipUtils.ts":
/*!***************************************************************!*\
  !*** ../pyright-internal/src/languageService/tooltipUtils.ts ***!
  \***************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * tooltipUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Helper functions for formatting text that can appear in hover text,
 * completion suggestions, etc.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getTypeForToolTip = exports.limitOverloadBasedOnCall = exports.bindFunctionToClassOrObjectToolTip = exports.getClassAndConstructorTypes = exports.combineExpressionTypes = exports.getAutoImportText = exports.getDocumentationPartsForTypeAndDecl = exports.getOverloadedFunctionDocStringsFromType = exports.getFunctionDocStringFromType = exports.getConstructorTooltip = exports.getFunctionTooltip = exports.getOverloadedFunctionTooltip = exports.getToolTipForType = void 0;
const ParseTreeUtils = __importStar(__webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts"));
const typeDocStringUtils_1 = __webpack_require__(/*! ../analyzer/typeDocStringUtils */ "../pyright-internal/src/analyzer/typeDocStringUtils.ts");
const typeUtils_1 = __webpack_require__(/*! ../analyzer/typeUtils */ "../pyright-internal/src/analyzer/typeUtils.ts");
const types_1 = __webpack_require__(/*! ../analyzer/types */ "../pyright-internal/src/analyzer/types.ts");
const configOptions_1 = __webpack_require__(/*! ../common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const core_1 = __webpack_require__(/*! ../common/core */ "../pyright-internal/src/common/core.ts");
// The number of spaces to indent each parameter, after moving to a newline in tooltips.
const functionParamIndentOffset = 4;
function getToolTipForType(type, label, name, evaluator, isProperty, functionSignatureDisplay) {
    let signatureString = '';
    if ((0, types_1.isOverloadedFunction)(type)) {
        signatureString = label.length > 0 ? `(${label})\n` : '';
        signatureString += `${getOverloadedFunctionTooltip(type, evaluator, functionSignatureDisplay)}`;
    }
    else if ((0, types_1.isFunction)(type)) {
        signatureString = `${getFunctionTooltip(label, name, type, evaluator, isProperty, functionSignatureDisplay)}`;
    }
    else {
        signatureString = label.length > 0 ? `(${label}) ` : '';
        signatureString += `${name}: ${evaluator.printType(type)}`;
    }
    return signatureString;
}
exports.getToolTipForType = getToolTipForType;
// 70 is vscode's default hover width size.
function getOverloadedFunctionTooltip(type, evaluator, functionSignatureDisplay, columnThreshold = 70) {
    let content = '';
    const overloads = types_1.OverloadedFunctionType.getOverloads(type).map((o) => getFunctionTooltip(
    /* label */ '', o.details.name, o, evaluator, 
    /* isProperty */ false, functionSignatureDisplay));
    for (let i = 0; i < overloads.length; i++) {
        if (i !== 0 && overloads[i].length > columnThreshold && overloads[i - 1].length <= columnThreshold) {
            content += '\n';
        }
        content += overloads[i] + `: ...`;
        if (i < overloads.length - 1) {
            content += '\n';
            if (overloads[i].length > columnThreshold) {
                content += '\n';
            }
        }
    }
    return content;
}
exports.getOverloadedFunctionTooltip = getOverloadedFunctionTooltip;
function getFunctionTooltip(label, functionName, type, evaluator, isProperty = false, functionSignatureDisplay) {
    const labelFormatted = label.length === 0 ? '' : `(${label}) `;
    const indentStr = functionSignatureDisplay === configOptions_1.SignatureDisplayType.formatted ? '\n' + ' '.repeat(functionParamIndentOffset) : '';
    const funcParts = evaluator.printFunctionParts(type);
    const paramSignature = `${formatSignature(funcParts, indentStr, functionSignatureDisplay)} -> ${funcParts[1]}`;
    if (types_1.TypeBase.isInstantiable(type)) {
        return `${labelFormatted}${functionName}: type[${paramSignature}]`;
    }
    const sep = isProperty ? ': ' : '';
    let defKeyword = '';
    if (!isProperty) {
        defKeyword = 'def ';
        if (types_1.FunctionType.isAsync(type)) {
            defKeyword = 'async ' + defKeyword;
        }
    }
    return `${labelFormatted}${defKeyword}${functionName}${sep}${paramSignature}`;
}
exports.getFunctionTooltip = getFunctionTooltip;
function getConstructorTooltip(constructorName, type, evaluator, functionSignatureDisplay) {
    const classText = `class `;
    let signature = '';
    if ((0, types_1.isOverloadedFunction)(type)) {
        const overloads = type.overloads.map((overload) => getConstructorTooltip(constructorName, overload, evaluator, functionSignatureDisplay));
        overloads.forEach((overload, index) => {
            signature += overload + ': ...' + '\n\n';
        });
    }
    else if ((0, types_1.isFunction)(type)) {
        const indentStr = functionSignatureDisplay === configOptions_1.SignatureDisplayType.formatted
            ? '\n' + ' '.repeat(functionParamIndentOffset)
            : ' ';
        const funcParts = evaluator.printFunctionParts(type);
        const paramSignature = formatSignature(funcParts, indentStr, functionSignatureDisplay);
        signature += `${classText}${constructorName}${paramSignature}`;
    }
    return signature;
}
exports.getConstructorTooltip = getConstructorTooltip;
// Only formats signature if there is more than one parameter
function formatSignature(funcParts, indentStr, functionSignatureDisplay) {
    return functionSignatureDisplay === configOptions_1.SignatureDisplayType.formatted &&
        funcParts.length > 0 &&
        funcParts[0].length > 1
        ? `(${indentStr}${funcParts[0].join(',' + indentStr)}\n)`
        : `(${funcParts[0].join(', ')})`;
}
function getFunctionDocStringFromType(type, sourceMapper, evaluator) {
    const decl = type.details.declaration;
    const enclosingClass = decl ? ParseTreeUtils.getEnclosingClass(decl.node) : undefined;
    const classResults = enclosingClass ? evaluator.getTypeOfClass(enclosingClass) : undefined;
    return (0, typeDocStringUtils_1.getFunctionDocStringInherited)(type, decl, sourceMapper, classResults === null || classResults === void 0 ? void 0 : classResults.classType);
}
exports.getFunctionDocStringFromType = getFunctionDocStringFromType;
function getOverloadedFunctionDocStringsFromType(type, sourceMapper, evaluator) {
    if (type.overloads.length === 0) {
        return [];
    }
    const decl = type.overloads[0].details.declaration;
    const enclosingClass = decl ? ParseTreeUtils.getEnclosingClass(decl.node) : undefined;
    const classResults = enclosingClass ? evaluator.getTypeOfClass(enclosingClass) : undefined;
    return (0, typeDocStringUtils_1.getOverloadedFunctionDocStringsInherited)(type, type.overloads.map((o) => o.details.declaration).filter(core_1.isDefined), sourceMapper, evaluator, classResults === null || classResults === void 0 ? void 0 : classResults.classType);
}
exports.getOverloadedFunctionDocStringsFromType = getOverloadedFunctionDocStringsFromType;
function getDocumentationPartForTypeAlias(sourceMapper, resolvedDecl, evaluator, symbol) {
    var _a;
    if (!resolvedDecl) {
        return undefined;
    }
    if (resolvedDecl.type === 4 /* DeclarationType.TypeAlias */) {
        return resolvedDecl.docString;
    }
    if (resolvedDecl.type === 1 /* DeclarationType.Variable */) {
        if (resolvedDecl.typeAliasName && resolvedDecl.docString) {
            return resolvedDecl.docString;
        }
        const decl = ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.getDeclarations().find((d) => d.type === 1 /* DeclarationType.Variable */ && !!d.docString)) !== null && _a !== void 0 ? _a : resolvedDecl);
        const doc = (0, typeDocStringUtils_1.getVariableDocString)(decl, sourceMapper);
        if (doc) {
            return doc;
        }
    }
    if (resolvedDecl.type === 5 /* DeclarationType.Function */) {
        // @property functions
        const doc = (0, typeDocStringUtils_1.getPropertyDocStringInherited)(resolvedDecl, sourceMapper, evaluator);
        if (doc) {
            return doc;
        }
    }
    return undefined;
}
function getDocumentationPartForType(sourceMapper, type, resolvedDecl, evaluator, boundObjectOrClass) {
    if ((0, types_1.isModule)(type)) {
        const doc = (0, typeDocStringUtils_1.getModuleDocString)(type, resolvedDecl, sourceMapper);
        if (doc) {
            return doc;
        }
    }
    else if ((0, types_1.isInstantiableClass)(type)) {
        const doc = (0, typeDocStringUtils_1.getClassDocString)(type, resolvedDecl, sourceMapper);
        if (doc) {
            return doc;
        }
    }
    else if ((0, types_1.isFunction)(type)) {
        const functionType = boundObjectOrClass
            ? evaluator.bindFunctionToClassOrObject(boundObjectOrClass, type)
            : type;
        if (functionType && (0, types_1.isFunction)(functionType)) {
            const doc = getFunctionDocStringFromType(functionType, sourceMapper, evaluator);
            if (doc) {
                return doc;
            }
        }
    }
    else if ((0, types_1.isOverloadedFunction)(type)) {
        const functionType = boundObjectOrClass
            ? evaluator.bindFunctionToClassOrObject(boundObjectOrClass, type)
            : type;
        if (functionType && (0, types_1.isOverloadedFunction)(functionType)) {
            const doc = getOverloadedFunctionDocStringsFromType(functionType, sourceMapper, evaluator).find((d) => d);
            if (doc) {
                return doc;
            }
        }
    }
    return undefined;
}
function getDocumentationPartsForTypeAndDecl(sourceMapper, type, resolvedDecl, evaluator, optional) {
    var _a;
    // Get the alias first
    const aliasDoc = getDocumentationPartForTypeAlias(sourceMapper, resolvedDecl, evaluator, optional === null || optional === void 0 ? void 0 : optional.symbol);
    // Combine this with the type doc
    let typeDoc;
    if ((resolvedDecl === null || resolvedDecl === void 0 ? void 0 : resolvedDecl.type) === 8 /* DeclarationType.Alias */) {
        // Handle another alias decl special case.
        // ex) import X.Y
        //     [X].Y
        // Asking decl for X gives us "X.Y" rather than "X" since "X" is not actually a symbol.
        // We need to get corresponding module name to use special code in type eval for this case.
        if (resolvedDecl.type === 8 /* DeclarationType.Alias */ &&
            resolvedDecl.node &&
            resolvedDecl.node.nodeType === 21 /* ParseNodeType.ImportAs */ &&
            !!(optional === null || optional === void 0 ? void 0 : optional.name) &&
            !resolvedDecl.node.alias) {
            const name = resolvedDecl.node.module.nameParts.find((n) => n.value === optional.name);
            if (name) {
                const aliasDecls = (_a = evaluator.getDeclarationsForNameNode(name)) !== null && _a !== void 0 ? _a : [resolvedDecl];
                resolvedDecl = aliasDecls.length > 0 ? aliasDecls[0] : resolvedDecl;
            }
        }
        typeDoc = (0, typeDocStringUtils_1.getModuleDocStringFromUris)([resolvedDecl.uri], sourceMapper);
    }
    typeDoc =
        typeDoc !== null && typeDoc !== void 0 ? typeDoc : (type
            ? getDocumentationPartForType(sourceMapper, type, resolvedDecl, evaluator, optional === null || optional === void 0 ? void 0 : optional.boundObjectOrClass)
            : undefined);
    // Combine with a new line if they both exist
    return aliasDoc && typeDoc && aliasDoc !== typeDoc ? `${aliasDoc}\n\n${typeDoc}` : aliasDoc || typeDoc;
}
exports.getDocumentationPartsForTypeAndDecl = getDocumentationPartsForTypeAndDecl;
function getAutoImportText(name, from, alias) {
    let text;
    if (!from) {
        text = `import ${name}`;
    }
    else {
        text = `from ${from} import ${name}`;
    }
    if (alias) {
        text = `${text} as ${alias}`;
    }
    return text;
}
exports.getAutoImportText = getAutoImportText;
function combineExpressionTypes(typeNodes, evaluator) {
    const typeList = typeNodes.map((n) => evaluator.getType(n) || types_1.UnknownType.create());
    let result = (0, types_1.combineTypes)(typeList);
    // We're expecting a set of types, if there is only one and the outermost type is a list, take its inner type. This
    // is probably an expression that at runtime would turn into a list.
    if (typeList.length === 1 &&
        result.category === 6 /* TypeCategory.Class */ &&
        types_1.ClassType.isBuiltIn(result, 'list') &&
        result.typeArguments) {
        result = result.typeArguments[0];
    }
    else if (typeList.length === 1 &&
        result.category === 6 /* TypeCategory.Class */ &&
        types_1.ClassType.isBuiltIn(result, 'range')) {
        result = evaluator.getBuiltInObject(typeNodes[0], 'int');
    }
    return result;
}
exports.combineExpressionTypes = combineExpressionTypes;
function getClassAndConstructorTypes(node, evaluator) {
    var _a, _b;
    // If the class is used as part of a call (i.e. it is being
    // instantiated), include the constructor arguments within the
    // hover text.
    let callLeftNode = node;
    // Allow the left to be a member access chain (e.g. a.b.c) if the
    // node in question is the last item in the chain.
    if (((_a = callLeftNode === null || callLeftNode === void 0 ? void 0 : callLeftNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 35 /* ParseNodeType.MemberAccess */ && node === callLeftNode.parent.memberName) {
        callLeftNode = node.parent;
        // Allow the left to be a generic class constructor (e.g. foo[int]())
    }
    else if (((_b = callLeftNode === null || callLeftNode === void 0 ? void 0 : callLeftNode.parent) === null || _b === void 0 ? void 0 : _b.nodeType) === 24 /* ParseNodeType.Index */) {
        callLeftNode = node.parent;
    }
    if (!callLeftNode ||
        !callLeftNode.parent ||
        callLeftNode.parent.nodeType !== 9 /* ParseNodeType.Call */ ||
        callLeftNode.parent.leftExpression !== callLeftNode) {
        return;
    }
    // Get the init method for this class.
    const classType = getTypeForToolTip(evaluator, node);
    if (!(0, types_1.isInstantiableClass)(classType)) {
        return;
    }
    const instanceType = getTypeForToolTip(evaluator, callLeftNode.parent);
    if (!(0, types_1.isClassInstance)(instanceType)) {
        return;
    }
    let methodType;
    // Try to get the `__init__` method first because it typically has more type information than `__new__`.
    // Don't exclude `object.__init__` since in the plain case we want to show Foo().
    const initMember = (0, typeUtils_1.lookUpClassMember)(classType, '__init__', 16 /* MemberAccessFlags.SkipInstanceMembers */);
    if (initMember) {
        const functionType = evaluator.getTypeOfMember(initMember);
        if ((0, types_1.isFunction)(functionType) || (0, types_1.isOverloadedFunction)(functionType)) {
            methodType = bindFunctionToClassOrObjectToolTip(evaluator, node, instanceType, functionType);
        }
    }
    // If there was no `__init__`, excluding `object` class `__init__`, or if `__init__` only had default params (*args: Any, **kwargs: Any) or no params (),
    // see if we can find a better `__new__` method.
    if (!methodType ||
        (methodType &&
            (0, types_1.isFunction)(methodType) &&
            (types_1.FunctionType.hasDefaultParameters(methodType) || methodType.details.parameters.length === 0))) {
        const newMember = (0, typeUtils_1.lookUpClassMember)(classType, '__new__', 4 /* MemberAccessFlags.SkipObjectBaseClass */ | 16 /* MemberAccessFlags.SkipInstanceMembers */);
        if (newMember) {
            const newMemberType = evaluator.getTypeOfMember(newMember);
            // Prefer `__new__` if it doesn't have default params (*args: Any, **kwargs: Any) or no params ().
            if ((0, types_1.isFunction)(newMemberType) || (0, types_1.isOverloadedFunction)(newMemberType)) {
                // Set `treatConstructorAsClassMethod` to true to exclude `cls` as a parameter.
                methodType = bindFunctionToClassOrObjectToolTip(evaluator, node, instanceType, newMemberType, 
                /* treatConstructorAsClassMethod */ true);
            }
        }
    }
    return { methodType, classType };
}
exports.getClassAndConstructorTypes = getClassAndConstructorTypes;
function bindFunctionToClassOrObjectToolTip(evaluator, node, baseType, memberType, treatConstructorAsClassMethod) {
    const methodType = evaluator.bindFunctionToClassOrObject(baseType, memberType, 
    /* memberClass */ undefined, treatConstructorAsClassMethod);
    if (!methodType) {
        return undefined;
    }
    return limitOverloadBasedOnCall(evaluator, methodType, node);
}
exports.bindFunctionToClassOrObjectToolTip = bindFunctionToClassOrObjectToolTip;
function limitOverloadBasedOnCall(evaluator, type, node) {
    // If it's an overloaded function, see if it's part of a call expression.
    // If so, we may be able to eliminate some of the overloads based on
    // the overload resolution.
    if (!(0, types_1.isOverloadedFunction)(type) || node.nodeType !== 38 /* ParseNodeType.Name */) {
        return type;
    }
    const callNode = ParseTreeUtils.getCallForName(node);
    if (!callNode) {
        return type;
    }
    const callTypeResult = evaluator.getTypeResult(callNode);
    if (!callTypeResult || !callTypeResult.overloadsUsedForCall || callTypeResult.overloadsUsedForCall.length === 0) {
        return type;
    }
    if (callTypeResult.overloadsUsedForCall.length === 1) {
        return callTypeResult.overloadsUsedForCall[0];
    }
    return types_1.OverloadedFunctionType.create(callTypeResult.overloadsUsedForCall);
}
exports.limitOverloadBasedOnCall = limitOverloadBasedOnCall;
function getTypeForToolTip(evaluator, node) {
    var _a;
    // It does common work necessary for hover for a type we got
    // from raw type evaluator.
    const type = (_a = evaluator.getType(node)) !== null && _a !== void 0 ? _a : types_1.UnknownType.create();
    return limitOverloadBasedOnCall(evaluator, type, node);
}
exports.getTypeForToolTip = getTypeForToolTip;


/***/ }),

/***/ "../pyright-internal/src/languageService/workspaceSymbolProvider.ts":
/*!**************************************************************************!*\
  !*** ../pyright-internal/src/languageService/workspaceSymbolProvider.ts ***!
  \**************************************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * workspaceSymbolProvider.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Provide LSP's workspace symbol functionality.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceSymbolProvider = void 0;
const analyzerNodeInfo_1 = __webpack_require__(/*! ../analyzer/analyzerNodeInfo */ "../pyright-internal/src/analyzer/analyzerNodeInfo.ts");
const sourceFileInfoUtils_1 = __webpack_require__(/*! ../analyzer/sourceFileInfoUtils */ "../pyright-internal/src/analyzer/sourceFileInfoUtils.ts");
const cancellationUtils_1 = __webpack_require__(/*! ../common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const StringUtils = __importStar(__webpack_require__(/*! ../common/stringUtils */ "../pyright-internal/src/common/stringUtils.ts"));
const uriUtils_1 = __webpack_require__(/*! ../common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const symbolIndexer_1 = __webpack_require__(/*! ./symbolIndexer */ "../pyright-internal/src/languageService/symbolIndexer.ts");
class WorkspaceSymbolProvider {
    constructor(_workspaces, resultReporter, _query, _token) {
        this._workspaces = _workspaces;
        this._query = _query;
        this._token = _token;
        this._allSymbols = [];
        this._reporter = resultReporter
            ? (symbols) => resultReporter.report(symbols)
            : (symbols) => (0, collectionUtils_1.appendArray)(this._allSymbols, symbols);
    }
    reportSymbols() {
        for (const workspace of this._workspaces) {
            if (workspace.disableLanguageServices || workspace.disableWorkspaceSymbol) {
                continue;
            }
            if (!workspace.isInitialized.resolved()) {
                // If workspace is not resolved, ignore this workspace and move on.
                // We could wait for the initialization but that cause this to be async
                // so for now, we will just ignore any workspace that is not initialized yet.
                continue;
            }
            workspace.service.run((program) => {
                this._reportSymbolsForProgram(program);
            }, this._token);
        }
        return this._allSymbols;
    }
    getSymbolsForDocument(program, fileUri) {
        const symbolList = [];
        const parseResults = program.getParseResults(fileUri);
        if (!parseResults) {
            return symbolList;
        }
        const fileInfo = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parserOutput.parseTree);
        if (!fileInfo) {
            return symbolList;
        }
        const indexSymbolData = symbolIndexer_1.SymbolIndexer.indexSymbols(fileInfo, parseResults, { includeAliases: false }, this._token);
        this.appendWorkspaceSymbolsRecursive(indexSymbolData, program, fileUri, '', symbolList);
        return symbolList;
    }
    appendWorkspaceSymbolsRecursive(indexSymbolData, program, fileUri, container, symbolList) {
        (0, cancellationUtils_1.throwIfCancellationRequested)(this._token);
        if (!indexSymbolData) {
            return;
        }
        for (const symbolData of indexSymbolData) {
            if (symbolData.alias) {
                continue;
            }
            if (StringUtils.isPatternInSymbol(this._query, symbolData.name)) {
                const location = {
                    uri: (0, uriUtils_1.encodeUri)(program.fileSystem, fileUri),
                    range: symbolData.selectionRange,
                };
                const symbolInfo = {
                    name: symbolData.name,
                    kind: symbolData.kind,
                    location,
                };
                if (container.length) {
                    symbolInfo.containerName = container;
                }
                symbolList.push(symbolInfo);
            }
            this.appendWorkspaceSymbolsRecursive(symbolData.children, program, fileUri, this._getContainerName(container, symbolData.name), symbolList);
        }
    }
    _reportSymbolsForProgram(program) {
        // Don't do a search if the query is empty. We'll return
        // too many results in this case.
        if (!this._query) {
            return;
        }
        // "Workspace symbols" searches symbols only from user code.
        for (const sourceFileInfo of program.getSourceFileInfoList()) {
            if (!(0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo)) {
                continue;
            }
            const symbolList = this.getSymbolsForDocument(program, sourceFileInfo.sourceFile.getUri());
            if (symbolList.length > 0) {
                this._reporter(symbolList);
            }
            // This operation can consume significant memory, so check
            // for situations where we need to discard the type cache.
            program.handleMemoryHighUsage();
        }
    }
    _getContainerName(container, name) {
        if (container.length > 0) {
            return `${container}.${name}`;
        }
        return name;
    }
}
exports.WorkspaceSymbolProvider = WorkspaceSymbolProvider;


/***/ }),

/***/ "../pyright-internal/src/localization/localize.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/localization/localize.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * localize.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Code that localizes user-visible strings.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LocAddendum = exports.LocMessage = exports.Localizer = exports.loadStringsForLocale = exports.getLocaleFromEnv = exports.setLocaleOverride = exports.getRawStringFromMap = exports.setGetRawString = exports.ParameterizedString = void 0;
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const csStrings = __webpack_require__(/*! ./package.nls.cs.json */ "../pyright-internal/src/localization/package.nls.cs.json");
const deStrings = __webpack_require__(/*! ./package.nls.de.json */ "../pyright-internal/src/localization/package.nls.de.json");
const enUsStrings = __webpack_require__(/*! ./package.nls.en-us.json */ "../pyright-internal/src/localization/package.nls.en-us.json");
const esStrings = __webpack_require__(/*! ./package.nls.es.json */ "../pyright-internal/src/localization/package.nls.es.json");
const frStrings = __webpack_require__(/*! ./package.nls.fr.json */ "../pyright-internal/src/localization/package.nls.fr.json");
const itStrings = __webpack_require__(/*! ./package.nls.it.json */ "../pyright-internal/src/localization/package.nls.it.json");
const jaStrings = __webpack_require__(/*! ./package.nls.ja.json */ "../pyright-internal/src/localization/package.nls.ja.json");
const koStrings = __webpack_require__(/*! ./package.nls.ko.json */ "../pyright-internal/src/localization/package.nls.ko.json");
const plStrings = __webpack_require__(/*! ./package.nls.pl.json */ "../pyright-internal/src/localization/package.nls.pl.json");
const ptBrStrings = __webpack_require__(/*! ./package.nls.pt-br.json */ "../pyright-internal/src/localization/package.nls.pt-br.json");
const qpsPlocStrings = __webpack_require__(/*! ./package.nls.qps-ploc.json */ "../pyright-internal/src/localization/package.nls.qps-ploc.json");
const ruStrings = __webpack_require__(/*! ./package.nls.ru.json */ "../pyright-internal/src/localization/package.nls.ru.json");
const trStrings = __webpack_require__(/*! ./package.nls.tr.json */ "../pyright-internal/src/localization/package.nls.tr.json");
const zhCnStrings = __webpack_require__(/*! ./package.nls.zh-cn.json */ "../pyright-internal/src/localization/package.nls.zh-cn.json");
const zhTwStrings = __webpack_require__(/*! ./package.nls.zh-tw.json */ "../pyright-internal/src/localization/package.nls.zh-tw.json");
class ParameterizedString {
    constructor(_formatString) {
        this._formatString = _formatString;
    }
    format(params) {
        let str = this._formatString;
        Object.keys(params).forEach((key) => {
            str = str.replace(new RegExp(`{${key}}`, 'g'), params[key].toString());
        });
        return str;
    }
    getFormatString() {
        return this._formatString;
    }
}
exports.ParameterizedString = ParameterizedString;
const defaultLocale = 'en-us';
const stringMapsByLocale = new Map([
    ['cs', csStrings],
    ['de', deStrings],
    ['en-us', enUsStrings],
    ['en', enUsStrings],
    ['es', esStrings],
    ['fr', frStrings],
    ['it', itStrings],
    ['ja', jaStrings],
    ['ko', koStrings],
    ['pl', plStrings],
    ['pt-br', ptBrStrings],
    ['qps-ploc', qpsPlocStrings],
    ['ru', ruStrings],
    ['tr', trStrings],
    ['zh-cn', zhCnStrings],
    ['zh-tw', zhTwStrings],
]);
let localizedStrings = undefined;
let defaultStrings = {};
function getRawStringDefault(key) {
    if (localizedStrings === undefined) {
        localizedStrings = initialize();
    }
    const keyParts = key.split('.');
    const str = getRawStringFromMap(localizedStrings, keyParts) || getRawStringFromMap(defaultStrings, keyParts);
    if (str) {
        return str;
    }
    (0, debug_1.fail)(`Missing localized string for key "${key}"`);
}
let getRawString = getRawStringDefault;
// Function allowing different strings to be used for messages.
// Returns the previous function used for getting messages.
function setGetRawString(func) {
    const oldLookup = getRawString;
    getRawString = func;
    return oldLookup;
}
exports.setGetRawString = setGetRawString;
function getRawStringFromMap(map, keyParts) {
    let curObj = map;
    for (const keyPart of keyParts) {
        if (!curObj[keyPart]) {
            return undefined;
        }
        curObj = curObj[keyPart];
    }
    return curObj;
}
exports.getRawStringFromMap = getRawStringFromMap;
function initialize() {
    defaultStrings = loadDefaultStrings();
    const currentLocale = getLocaleFromEnv();
    return loadStringsForLocale(currentLocale, stringMapsByLocale);
}
let localeOverride;
function setLocaleOverride(locale) {
    // Force a reload of the localized strings.
    localizedStrings = undefined;
    localeOverride = locale.toLowerCase();
}
exports.setLocaleOverride = setLocaleOverride;
function getLocaleFromEnv() {
    if (localeOverride) {
        return localeOverride;
    }
    try {
        const env = process === null || process === void 0 ? void 0 : process.env;
        // Start with the VSCode environment variables.
        const vscodeConfigString = env === null || env === void 0 ? void 0 : env.VSCODE_NLS_CONFIG;
        if (vscodeConfigString) {
            try {
                return JSON.parse(vscodeConfigString).locale;
            }
            catch {
                // Fall through
            }
        }
        // See if there is a language env variable.
        const localeString = (env === null || env === void 0 ? void 0 : env.LC_ALL) || (env === null || env === void 0 ? void 0 : env.LC_MESSAGES) || (env === null || env === void 0 ? void 0 : env.LANG) || (env === null || env === void 0 ? void 0 : env.LANGUAGE);
        if (localeString) {
            // This string may contain a local followed by an encoding (e.g. "en-us.UTF-8").
            const localeStringSplit = localeString.split('.');
            if (localeStringSplit.length > 0 && localeStringSplit[0]) {
                return localeStringSplit[0];
            }
        }
    }
    catch {
        // Just use the default locale
    }
    // Fall back to the default locale.
    return defaultLocale;
}
exports.getLocaleFromEnv = getLocaleFromEnv;
function loadDefaultStrings() {
    const defaultStrings = stringMapsByLocale.get(defaultLocale);
    if (defaultStrings) {
        return defaultStrings;
    }
    console.error('Could not load default strings');
    return {};
}
function loadStringsForLocale(locale, localeMap) {
    if (locale === defaultLocale) {
        // No need to load override if we're using the default.
        return {};
    }
    let override = localeMap.get(locale);
    if (override !== undefined) {
        return override;
    }
    // If we couldn't find the requested locale, try to fall back on a more
    // general version.
    const localeSplit = locale.split('-');
    if (localeSplit.length > 0 && localeSplit[0]) {
        override = localeMap.get(localeSplit[0]);
        if (override !== undefined) {
            return override;
        }
    }
    return {};
}
exports.loadStringsForLocale = loadStringsForLocale;
var Localizer;
(function (Localizer) {
    let Diagnostic;
    (function (Diagnostic) {
        Diagnostic.abstractMethodInvocation = () => new ParameterizedString(getRawString('Diagnostic.abstractMethodInvocation'));
        Diagnostic.annotatedParamCountMismatch = () => new ParameterizedString(getRawString('Diagnostic.annotatedParamCountMismatch'));
        Diagnostic.annotatedTypeArgMissing = () => getRawString('Diagnostic.annotatedTypeArgMissing');
        Diagnostic.annotationBytesString = () => getRawString('Diagnostic.annotationBytesString');
        Diagnostic.annotationFormatString = () => getRawString('Diagnostic.annotationFormatString');
        Diagnostic.annotationNotSupported = () => getRawString('Diagnostic.annotationNotSupported');
        Diagnostic.annotationRawString = () => getRawString('Diagnostic.annotationRawString');
        Diagnostic.annotationSpansStrings = () => getRawString('Diagnostic.annotationSpansStrings');
        Diagnostic.annotationStringEscape = () => getRawString('Diagnostic.annotationStringEscape');
        Diagnostic.argAssignment = () => new ParameterizedString(getRawString('Diagnostic.argAssignment'));
        Diagnostic.argAssignmentFunction = () => new ParameterizedString(getRawString('Diagnostic.argAssignmentFunction'));
        Diagnostic.argAssignmentParam = () => new ParameterizedString(getRawString('Diagnostic.argAssignmentParam'));
        Diagnostic.argAssignmentParamFunction = () => new ParameterizedString(getRawString('Diagnostic.argAssignmentParamFunction'));
        Diagnostic.argMissingForParam = () => new ParameterizedString(getRawString('Diagnostic.argMissingForParam'));
        Diagnostic.argMissingForParams = () => new ParameterizedString(getRawString('Diagnostic.argMissingForParams'));
        Diagnostic.argMorePositionalExpectedCount = () => new ParameterizedString(getRawString('Diagnostic.argMorePositionalExpectedCount'));
        Diagnostic.argMorePositionalExpectedOne = () => getRawString('Diagnostic.argMorePositionalExpectedOne');
        Diagnostic.argPositional = () => getRawString('Diagnostic.argPositional');
        Diagnostic.argPositionalExpectedCount = () => new ParameterizedString(getRawString('Diagnostic.argPositionalExpectedCount'));
        Diagnostic.argPositionalExpectedOne = () => getRawString('Diagnostic.argPositionalExpectedOne');
        Diagnostic.argTypePartiallyUnknown = () => getRawString('Diagnostic.argTypePartiallyUnknown');
        Diagnostic.argTypeUnknown = () => getRawString('Diagnostic.argTypeUnknown');
        Diagnostic.argTypeAny = () => getRawString('Diagnostic.argTypeAny');
        Diagnostic.assertAlwaysTrue = () => getRawString('Diagnostic.assertAlwaysTrue');
        Diagnostic.assertTypeArgs = () => getRawString('Diagnostic.assertTypeArgs');
        Diagnostic.assertTypeTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.assertTypeTypeMismatch'));
        Diagnostic.assignmentExprContext = () => getRawString('Diagnostic.assignmentExprContext');
        Diagnostic.assignmentExprComprehension = () => new ParameterizedString(getRawString('Diagnostic.assignmentExprComprehension'));
        Diagnostic.assignmentExprInSubscript = () => getRawString('Diagnostic.assignmentExprInSubscript');
        Diagnostic.assignmentInProtocol = () => getRawString('Diagnostic.assignmentInProtocol');
        Diagnostic.assignmentTargetExpr = () => getRawString('Diagnostic.assignmentTargetExpr');
        Diagnostic.asyncNotInAsyncFunction = () => getRawString('Diagnostic.asyncNotInAsyncFunction');
        Diagnostic.awaitIllegal = () => getRawString('Diagnostic.awaitIllegal');
        Diagnostic.awaitNotAllowed = () => getRawString('Diagnostic.awaitNotAllowed');
        Diagnostic.awaitNotInAsync = () => getRawString('Diagnostic.awaitNotInAsync');
        Diagnostic.backticksIllegal = () => getRawString('Diagnostic.backticksIllegal');
        Diagnostic.baseClassCircular = () => getRawString('Diagnostic.baseClassCircular');
        Diagnostic.baseClassFinal = () => new ParameterizedString(getRawString('Diagnostic.baseClassFinal'));
        Diagnostic.baseClassIncompatible = () => new ParameterizedString(getRawString('Diagnostic.baseClassIncompatible'));
        Diagnostic.baseClassInvalid = () => getRawString('Diagnostic.baseClassInvalid');
        Diagnostic.baseClassMethodTypeIncompatible = () => new ParameterizedString(getRawString('Diagnostic.baseClassMethodTypeIncompatible'));
        Diagnostic.baseClassVariableTypeIncompatible = () => new ParameterizedString(getRawString('Diagnostic.baseClassVariableTypeIncompatible'));
        Diagnostic.baseClassUnknown = () => getRawString('Diagnostic.baseClassUnknown');
        Diagnostic.baseClassAny = () => getRawString('Diagnostic.baseClassAny');
        Diagnostic.binaryOperationNotAllowed = () => getRawString('Diagnostic.binaryOperationNotAllowed');
        Diagnostic.bindTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.bindTypeMismatch'));
        Diagnostic.breakOutsideLoop = () => getRawString('Diagnostic.breakOutsideLoop');
        Diagnostic.callableExtraArgs = () => getRawString('Diagnostic.callableExtraArgs');
        Diagnostic.callableFirstArg = () => getRawString('Diagnostic.callableFirstArg');
        Diagnostic.callableNotInstantiable = () => new ParameterizedString(getRawString('Diagnostic.callableNotInstantiable'));
        Diagnostic.callableSecondArg = () => getRawString('Diagnostic.callableSecondArg');
        Diagnostic.casePatternIsIrrefutable = () => getRawString('Diagnostic.casePatternIsIrrefutable');
        Diagnostic.classAlreadySpecialized = () => new ParameterizedString(getRawString('Diagnostic.classAlreadySpecialized'));
        Diagnostic.classDecoratorTypeUnknown = () => getRawString('Diagnostic.classDecoratorTypeUnknown');
        Diagnostic.classDecoratorTypeAny = () => getRawString('Diagnostic.classDecoratorTypeAny');
        Diagnostic.classDefinitionCycle = () => new ParameterizedString(getRawString('Diagnostic.classDefinitionCycle'));
        Diagnostic.classGetItemClsParam = () => getRawString('Diagnostic.classGetItemClsParam');
        Diagnostic.classMethodClsParam = () => getRawString('Diagnostic.classMethodClsParam');
        Diagnostic.classNotRuntimeSubscriptable = () => new ParameterizedString(getRawString('Diagnostic.classNotRuntimeSubscriptable'));
        Diagnostic.classPatternBuiltInArgPositional = () => getRawString('Diagnostic.classPatternBuiltInArgPositional');
        Diagnostic.classPatternPositionalArgCount = () => new ParameterizedString(getRawString('Diagnostic.classPatternPositionalArgCount'));
        Diagnostic.classPatternTypeAlias = () => new ParameterizedString(getRawString('Diagnostic.classPatternTypeAlias'));
        Diagnostic.classPropertyDeprecated = () => getRawString('Diagnostic.classPropertyDeprecated');
        Diagnostic.classTypeParametersIllegal = () => getRawString('Diagnostic.classTypeParametersIllegal');
        Diagnostic.classVarNotAllowed = () => getRawString('Diagnostic.classVarNotAllowed');
        Diagnostic.classVarFirstArgMissing = () => getRawString('Diagnostic.classVarFirstArgMissing');
        Diagnostic.classVarOverridesInstanceVar = () => new ParameterizedString(getRawString('Diagnostic.classVarOverridesInstanceVar'));
        Diagnostic.classVarTooManyArgs = () => getRawString('Diagnostic.classVarTooManyArgs');
        Diagnostic.classVarWithTypeVar = () => getRawString('Diagnostic.classVarWithTypeVar');
        Diagnostic.clsSelfParamTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.clsSelfParamTypeMismatch'));
        Diagnostic.codeTooComplexToAnalyze = () => getRawString('Diagnostic.codeTooComplexToAnalyze');
        Diagnostic.collectionAliasInstantiation = () => new ParameterizedString(getRawString('Diagnostic.collectionAliasInstantiation'));
        Diagnostic.comparisonAlwaysFalse = () => new ParameterizedString(getRawString('Diagnostic.comparisonAlwaysFalse'));
        Diagnostic.comparisonAlwaysTrue = () => new ParameterizedString(getRawString('Diagnostic.comparisonAlwaysTrue'));
        Diagnostic.comprehensionInDict = () => getRawString('Diagnostic.comprehensionInDict');
        Diagnostic.comprehensionInSet = () => getRawString('Diagnostic.comprehensionInSet');
        Diagnostic.concatenateContext = () => getRawString('Diagnostic.concatenateContext');
        Diagnostic.concatenateParamSpecMissing = () => getRawString('Diagnostic.concatenateParamSpecMissing');
        Diagnostic.concatenateTypeArgsMissing = () => getRawString('Diagnostic.concatenateTypeArgsMissing');
        Diagnostic.conditionalOperandInvalid = () => new ParameterizedString(getRawString('Diagnostic.conditionalOperandInvalid'));
        Diagnostic.constantRedefinition = () => new ParameterizedString(getRawString('Diagnostic.constantRedefinition'));
        Diagnostic.constructorNoArgs = () => new ParameterizedString(getRawString('Diagnostic.constructorNoArgs'));
        Diagnostic.coroutineInConditionalExpression = () => getRawString('Diagnostic.coroutineInConditionalExpression');
        Diagnostic.constructorParametersMismatch = () => new ParameterizedString(getRawString('Diagnostic.constructorParametersMismatch'));
        Diagnostic.containmentAlwaysFalse = () => new ParameterizedString(getRawString('Diagnostic.containmentAlwaysFalse'));
        Diagnostic.containmentAlwaysTrue = () => new ParameterizedString(getRawString('Diagnostic.containmentAlwaysTrue'));
        Diagnostic.continueInFinally = () => getRawString('Diagnostic.continueInFinally');
        Diagnostic.continueOutsideLoop = () => getRawString('Diagnostic.continueOutsideLoop');
        Diagnostic.dataClassBaseClassFrozen = () => getRawString('Diagnostic.dataClassBaseClassFrozen');
        Diagnostic.dataClassBaseClassNotFrozen = () => getRawString('Diagnostic.dataClassBaseClassNotFrozen');
        Diagnostic.dataClassConverterFunction = () => new ParameterizedString(getRawString('Diagnostic.dataClassConverterFunction'));
        Diagnostic.dataClassConverterOverloads = () => new ParameterizedString(getRawString('Diagnostic.dataClassConverterOverloads'));
        Diagnostic.dataClassFieldInheritedDefault = () => new ParameterizedString(getRawString('Diagnostic.dataClassFieldInheritedDefault'));
        Diagnostic.dataClassFieldWithDefault = () => getRawString('Diagnostic.dataClassFieldWithDefault');
        Diagnostic.dataClassFieldWithoutAnnotation = () => getRawString('Diagnostic.dataClassFieldWithoutAnnotation');
        Diagnostic.dataClassFieldWithPrivateName = () => getRawString('Diagnostic.dataClassFieldWithPrivateName');
        Diagnostic.dataClassPostInitParamCount = () => new ParameterizedString(getRawString('Diagnostic.dataClassPostInitParamCount'));
        Diagnostic.dataClassPostInitType = () => new ParameterizedString(getRawString('Diagnostic.dataClassPostInitType'));
        Diagnostic.dataClassSlotsOverwrite = () => getRawString('Diagnostic.dataClassSlotsOverwrite');
        Diagnostic.dataClassTransformExpectedBoolLiteral = () => getRawString('Diagnostic.dataClassTransformExpectedBoolLiteral');
        Diagnostic.dataClassTransformFieldSpecifier = () => new ParameterizedString(getRawString('Diagnostic.dataClassTransformFieldSpecifier'));
        Diagnostic.dataClassTransformPositionalParam = () => getRawString('Diagnostic.dataClassTransformPositionalParam');
        Diagnostic.dataClassTransformUnknownArgument = () => new ParameterizedString(getRawString('Diagnostic.dataClassTransformUnknownArgument'));
        Diagnostic.dataProtocolInSubclassCheck = () => getRawString('Diagnostic.dataProtocolInSubclassCheck');
        Diagnostic.declaredReturnTypePartiallyUnknown = () => new ParameterizedString(getRawString('Diagnostic.declaredReturnTypePartiallyUnknown'));
        Diagnostic.declaredReturnTypeUnknown = () => getRawString('Diagnostic.declaredReturnTypeUnknown');
        Diagnostic.defaultValueContainsCall = () => getRawString('Diagnostic.defaultValueContainsCall');
        Diagnostic.defaultValueNotAllowed = () => getRawString('Diagnostic.defaultValueNotAllowed');
        Diagnostic.deprecatedClass = () => new ParameterizedString(getRawString('Diagnostic.deprecatedClass'));
        Diagnostic.deprecatedConstructor = () => new ParameterizedString(getRawString('Diagnostic.deprecatedConstructor'));
        Diagnostic.deprecatedDescriptorDeleter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedDescriptorDeleter'));
        Diagnostic.deprecatedDescriptorGetter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedDescriptorGetter'));
        Diagnostic.deprecatedDescriptorSetter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedDescriptorSetter'));
        Diagnostic.deprecatedFunction = () => new ParameterizedString(getRawString('Diagnostic.deprecatedFunction'));
        Diagnostic.deprecatedMethod = () => new ParameterizedString(getRawString('Diagnostic.deprecatedMethod'));
        Diagnostic.deprecatedPropertyDeleter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedPropertyDeleter'));
        Diagnostic.deprecatedPropertyGetter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedPropertyGetter'));
        Diagnostic.deprecatedPropertySetter = () => new ParameterizedString(getRawString('Diagnostic.deprecatedPropertySetter'));
        Diagnostic.deprecatedType = () => new ParameterizedString(getRawString('Diagnostic.deprecatedType'));
        Diagnostic.dictExpandIllegalInComprehension = () => getRawString('Diagnostic.dictExpandIllegalInComprehension');
        Diagnostic.dictInAnnotation = () => getRawString('Diagnostic.dictInAnnotation');
        Diagnostic.dictKeyValuePairs = () => getRawString('Diagnostic.dictKeyValuePairs');
        Diagnostic.dictUnpackIsNotMapping = () => getRawString('Diagnostic.dictUnpackIsNotMapping');
        Diagnostic.delTargetExpr = () => getRawString('Diagnostic.delTargetExpr');
        Diagnostic.dunderAllSymbolNotPresent = () => new ParameterizedString(getRawString('Diagnostic.dunderAllSymbolNotPresent'));
        Diagnostic.duplicateArgsParam = () => getRawString('Diagnostic.duplicateArgsParam');
        Diagnostic.duplicateBaseClass = () => getRawString('Diagnostic.duplicateBaseClass');
        Diagnostic.duplicateCatchAll = () => getRawString('Diagnostic.duplicateCatchAll');
        Diagnostic.duplicateEnumMember = () => new ParameterizedString(getRawString('Diagnostic.duplicateEnumMember'));
        Diagnostic.duplicateGenericAndProtocolBase = () => getRawString('Diagnostic.duplicateGenericAndProtocolBase');
        Diagnostic.duplicateImport = () => new ParameterizedString(getRawString('Diagnostic.duplicateImport'));
        Diagnostic.duplicateKwargsParam = () => getRawString('Diagnostic.duplicateKwargsParam');
        Diagnostic.duplicateKeywordOnly = () => getRawString('Diagnostic.duplicateKeywordOnly');
        Diagnostic.duplicateParam = () => new ParameterizedString(getRawString('Diagnostic.duplicateParam'));
        Diagnostic.duplicateCapturePatternTarget = () => new ParameterizedString(getRawString('Diagnostic.duplicateCapturePatternTarget'));
        Diagnostic.duplicateStarPattern = () => getRawString('Diagnostic.duplicateStarPattern');
        Diagnostic.duplicateStarStarPattern = () => getRawString('Diagnostic.duplicateStarStarPattern');
        Diagnostic.duplicatePositionOnly = () => getRawString('Diagnostic.duplicatePositionOnly');
        Diagnostic.duplicateUnpack = () => getRawString('Diagnostic.duplicateUnpack');
        Diagnostic.ellipsisAfterUnpacked = () => getRawString('Diagnostic.ellipsisAfterUnpacked');
        Diagnostic.ellipsisContext = () => getRawString('Diagnostic.ellipsisContext');
        Diagnostic.ellipsisSecondArg = () => getRawString('Diagnostic.ellipsisSecondArg');
        Diagnostic.enumClassOverride = () => new ParameterizedString(getRawString('Diagnostic.enumClassOverride'));
        Diagnostic.exceptionGroupIncompatible = () => getRawString('Diagnostic.exceptionGroupIncompatible');
        Diagnostic.exceptionTypeIncorrect = () => new ParameterizedString(getRawString('Diagnostic.exceptionTypeIncorrect'));
        Diagnostic.exceptionTypeNotClass = () => new ParameterizedString(getRawString('Diagnostic.exceptionTypeNotClass'));
        Diagnostic.exceptionTypeNotInstantiable = () => new ParameterizedString(getRawString('Diagnostic.exceptionTypeNotInstantiable'));
        Diagnostic.expectedAfterDecorator = () => getRawString('Diagnostic.expectedAfterDecorator');
        Diagnostic.expectedArrow = () => getRawString('Diagnostic.expectedArrow');
        Diagnostic.expectedAsAfterException = () => getRawString('Diagnostic.expectedAsAfterException');
        Diagnostic.expectedAssignRightHandExpr = () => getRawString('Diagnostic.expectedAssignRightHandExpr');
        Diagnostic.expectedBinaryRightHandExpr = () => getRawString('Diagnostic.expectedBinaryRightHandExpr');
        Diagnostic.expectedBoolLiteral = () => getRawString('Diagnostic.expectedBoolLiteral');
        Diagnostic.expectedCase = () => getRawString('Diagnostic.expectedCase');
        Diagnostic.expectedClassName = () => getRawString('Diagnostic.expectedClassName');
        Diagnostic.expectedCloseBrace = () => getRawString('Diagnostic.expectedCloseBrace');
        Diagnostic.expectedCloseBracket = () => getRawString('Diagnostic.expectedCloseBracket');
        Diagnostic.expectedCloseParen = () => getRawString('Diagnostic.expectedCloseParen');
        Diagnostic.expectedColon = () => getRawString('Diagnostic.expectedColon');
        Diagnostic.expectedComplexNumberLiteral = () => getRawString('Diagnostic.expectedComplexNumberLiteral');
        Diagnostic.expectedDecoratorExpr = () => getRawString('Diagnostic.expectedDecoratorExpr');
        Diagnostic.expectedDecoratorName = () => getRawString('Diagnostic.expectedDecoratorName');
        Diagnostic.expectedDecoratorNewline = () => getRawString('Diagnostic.expectedDecoratorNewline');
        Diagnostic.expectedDelExpr = () => getRawString('Diagnostic.expectedDelExpr');
        Diagnostic.expectedElse = () => getRawString('Diagnostic.expectedElse');
        Diagnostic.expectedEquals = () => getRawString('Diagnostic.expectedEquals');
        Diagnostic.expectedExceptionClass = () => getRawString('Diagnostic.expectedExceptionClass');
        Diagnostic.expectedExceptionObj = () => getRawString('Diagnostic.expectedExceptionObj');
        Diagnostic.expectedExpr = () => getRawString('Diagnostic.expectedExpr');
        Diagnostic.expectedImport = () => getRawString('Diagnostic.expectedImport');
        Diagnostic.expectedImportAlias = () => getRawString('Diagnostic.expectedImportAlias');
        Diagnostic.expectedImportSymbols = () => getRawString('Diagnostic.expectedImportSymbols');
        Diagnostic.expectedIdentifier = () => getRawString('Diagnostic.expectedIdentifier');
        Diagnostic.expectedIndentedBlock = () => getRawString('Diagnostic.expectedIndentedBlock');
        Diagnostic.expectedIn = () => getRawString('Diagnostic.expectedIn');
        Diagnostic.expectedInExpr = () => getRawString('Diagnostic.expectedInExpr');
        Diagnostic.expectedFunctionAfterAsync = () => getRawString('Diagnostic.expectedFunctionAfterAsync');
        Diagnostic.expectedFunctionName = () => getRawString('Diagnostic.expectedFunctionName');
        Diagnostic.expectedMemberName = () => getRawString('Diagnostic.expectedMemberName');
        Diagnostic.expectedModuleName = () => getRawString('Diagnostic.expectedModuleName');
        Diagnostic.expectedNameAfterAs = () => getRawString('Diagnostic.expectedNameAfterAs');
        Diagnostic.expectedNamedParameter = () => getRawString('Diagnostic.expectedNamedParameter');
        Diagnostic.expectedNewline = () => getRawString('Diagnostic.expectedNewline');
        Diagnostic.expectedNewlineOrSemicolon = () => getRawString('Diagnostic.expectedNewlineOrSemicolon');
        Diagnostic.expectedOpenParen = () => getRawString('Diagnostic.expectedOpenParen');
        Diagnostic.expectedParamName = () => getRawString('Diagnostic.expectedParamName');
        Diagnostic.expectedPatternExpr = () => getRawString('Diagnostic.expectedPatternExpr');
        Diagnostic.expectedPatternSubjectExpr = () => getRawString('Diagnostic.expectedPatternSubjectExpr');
        Diagnostic.expectedPatternValue = () => getRawString('Diagnostic.expectedPatternValue');
        Diagnostic.expectedReturnExpr = () => getRawString('Diagnostic.expectedReturnExpr');
        Diagnostic.expectedSliceIndex = () => getRawString('Diagnostic.expectedSliceIndex');
        Diagnostic.expectedTypeNotString = () => getRawString('Diagnostic.expectedTypeNotString');
        Diagnostic.expectedTypeParameterName = () => getRawString('Diagnostic.expectedTypeParameterName');
        Diagnostic.expectedYieldExpr = () => getRawString('Diagnostic.expectedYieldExpr');
        Diagnostic.finalClassIsAbstract = () => new ParameterizedString(getRawString('Diagnostic.finalClassIsAbstract'));
        Diagnostic.finalContext = () => getRawString('Diagnostic.finalContext');
        Diagnostic.finalMethodOverride = () => new ParameterizedString(getRawString('Diagnostic.finalMethodOverride'));
        Diagnostic.finalNonMethod = () => new ParameterizedString(getRawString('Diagnostic.finalNonMethod'));
        Diagnostic.finalReassigned = () => new ParameterizedString(getRawString('Diagnostic.finalReassigned'));
        Diagnostic.finalRedeclaration = () => new ParameterizedString(getRawString('Diagnostic.finalRedeclaration'));
        Diagnostic.finalRedeclarationBySubclass = () => new ParameterizedString(getRawString('Diagnostic.finalRedeclarationBySubclass'));
        Diagnostic.finalTooManyArgs = () => getRawString('Diagnostic.finalTooManyArgs');
        Diagnostic.finalUnassigned = () => new ParameterizedString(getRawString('Diagnostic.finalUnassigned'));
        Diagnostic.formatStringBrace = () => getRawString('Diagnostic.formatStringBrace');
        Diagnostic.formatStringBytes = () => getRawString('Diagnostic.formatStringBytes');
        Diagnostic.formatStringDebuggingIllegal = () => getRawString('Diagnostic.formatStringDebuggingIllegal');
        Diagnostic.formatStringEscape = () => getRawString('Diagnostic.formatStringEscape');
        Diagnostic.formatStringExpectedConversion = () => getRawString('Diagnostic.formatStringExpectedConversion');
        Diagnostic.formatStringInPattern = () => getRawString('Diagnostic.formatStringInPattern');
        Diagnostic.formatStringIllegal = () => getRawString('Diagnostic.formatStringIllegal');
        Diagnostic.formatStringNestedFormatSpecifier = () => getRawString('Diagnostic.formatStringNestedFormatSpecifier');
        Diagnostic.formatStringNestedQuote = () => getRawString('Diagnostic.formatStringNestedQuote');
        Diagnostic.formatStringUnicode = () => getRawString('Diagnostic.formatStringUnicode');
        Diagnostic.formatStringUnterminated = () => getRawString('Diagnostic.formatStringUnterminated');
        Diagnostic.functionDecoratorTypeUnknown = () => getRawString('Diagnostic.functionDecoratorTypeUnknown');
        Diagnostic.functionDecoratorTypeAny = () => getRawString('Diagnostic.functionDecoratorTypeAny');
        Diagnostic.functionInConditionalExpression = () => getRawString('Diagnostic.functionInConditionalExpression');
        Diagnostic.functionTypeParametersIllegal = () => getRawString('Diagnostic.functionTypeParametersIllegal');
        Diagnostic.futureImportLocationNotAllowed = () => getRawString('Diagnostic.futureImportLocationNotAllowed');
        Diagnostic.generatorAsyncReturnType = () => new ParameterizedString(getRawString('Diagnostic.generatorAsyncReturnType'));
        Diagnostic.generatorNotParenthesized = () => getRawString('Diagnostic.generatorNotParenthesized');
        Diagnostic.generatorSyncReturnType = () => new ParameterizedString(getRawString('Diagnostic.generatorSyncReturnType'));
        Diagnostic.genericBaseClassNotAllowed = () => getRawString('Diagnostic.genericBaseClassNotAllowed');
        Diagnostic.genericClassAssigned = () => getRawString('Diagnostic.genericClassAssigned');
        Diagnostic.genericClassDeleted = () => getRawString('Diagnostic.genericClassDeleted');
        Diagnostic.genericInstanceVariableAccess = () => getRawString('Diagnostic.genericInstanceVariableAccess');
        Diagnostic.genericNotAllowed = () => getRawString('Diagnostic.genericNotAllowed');
        Diagnostic.genericTypeAliasBoundTypeVar = () => new ParameterizedString(getRawString('Diagnostic.genericTypeAliasBoundTypeVar'));
        Diagnostic.genericTypeArgMissing = () => getRawString('Diagnostic.genericTypeArgMissing');
        Diagnostic.genericTypeArgTypeVar = () => getRawString('Diagnostic.genericTypeArgTypeVar');
        Diagnostic.genericTypeArgUnique = () => getRawString('Diagnostic.genericTypeArgUnique');
        Diagnostic.globalReassignment = () => new ParameterizedString(getRawString('Diagnostic.globalReassignment'));
        Diagnostic.globalRedefinition = () => new ParameterizedString(getRawString('Diagnostic.globalRedefinition'));
        Diagnostic.implicitStringConcat = () => getRawString('Diagnostic.implicitStringConcat');
        Diagnostic.importCycleDetected = () => getRawString('Diagnostic.importCycleDetected');
        Diagnostic.importDepthExceeded = () => new ParameterizedString(getRawString('Diagnostic.importDepthExceeded'));
        Diagnostic.importResolveFailure = () => new ParameterizedString(getRawString('Diagnostic.importResolveFailure'));
        Diagnostic.importSourceResolveFailure = () => new ParameterizedString(getRawString('Diagnostic.importSourceResolveFailure'));
        Diagnostic.importSymbolUnknown = () => new ParameterizedString(getRawString('Diagnostic.importSymbolUnknown'));
        Diagnostic.incompatibleMethodOverride = () => new ParameterizedString(getRawString('Diagnostic.incompatibleMethodOverride'));
        Diagnostic.inconsistentIndent = () => getRawString('Diagnostic.inconsistentIndent');
        Diagnostic.inconsistentTabs = () => getRawString('Diagnostic.inconsistentTabs');
        Diagnostic.initMethodSelfParamTypeVar = () => getRawString('Diagnostic.initMethodSelfParamTypeVar');
        Diagnostic.initMustReturnNone = () => getRawString('Diagnostic.initMustReturnNone');
        Diagnostic.initSubclassClsParam = () => getRawString('Diagnostic.initSubclassClsParam');
        Diagnostic.initSubclassCallFailed = () => getRawString('Diagnostic.initSubclassCallFailed');
        Diagnostic.initVarNotAllowed = () => getRawString('Diagnostic.initVarNotAllowed');
        Diagnostic.instanceMethodSelfParam = () => getRawString('Diagnostic.instanceMethodSelfParam');
        Diagnostic.instanceVarOverridesClassVar = () => new ParameterizedString(getRawString('Diagnostic.instanceVarOverridesClassVar'));
        Diagnostic.instantiateAbstract = () => new ParameterizedString(getRawString('Diagnostic.instantiateAbstract'));
        Diagnostic.instantiateProtocol = () => new ParameterizedString(getRawString('Diagnostic.instantiateProtocol'));
        Diagnostic.internalBindError = () => new ParameterizedString(getRawString('Diagnostic.internalBindError'));
        Diagnostic.internalParseError = () => new ParameterizedString(getRawString('Diagnostic.internalParseError'));
        Diagnostic.internalTypeCheckingError = () => new ParameterizedString(getRawString('Diagnostic.internalTypeCheckingError'));
        Diagnostic.invalidIdentifierChar = () => getRawString('Diagnostic.invalidIdentifierChar');
        Diagnostic.invalidStubStatement = () => getRawString('Diagnostic.invalidStubStatement');
        Diagnostic.invalidTokenChars = () => new ParameterizedString(getRawString('Diagnostic.invalidTokenChars'));
        Diagnostic.isInstanceInvalidType = () => new ParameterizedString(getRawString('Diagnostic.isInstanceInvalidType'));
        Diagnostic.isSubclassInvalidType = () => new ParameterizedString(getRawString('Diagnostic.isSubclassInvalidType'));
        Diagnostic.keyValueInSet = () => getRawString('Diagnostic.keyValueInSet');
        Diagnostic.keywordArgInTypeArgument = () => getRawString('Diagnostic.keywordArgInTypeArgument');
        Diagnostic.keywordOnlyAfterArgs = () => getRawString('Diagnostic.keywordOnlyAfterArgs');
        Diagnostic.keywordParameterMissing = () => getRawString('Diagnostic.keywordParameterMissing');
        Diagnostic.keywordSubscriptIllegal = () => getRawString('Diagnostic.keywordSubscriptIllegal');
        Diagnostic.lambdaReturnTypeUnknown = () => getRawString('Diagnostic.lambdaReturnTypeUnknown');
        Diagnostic.lambdaReturnTypeAny = () => getRawString('Diagnostic.lambdaReturnTypeAny');
        Diagnostic.lambdaReturnTypePartiallyUnknown = () => new ParameterizedString(getRawString('Diagnostic.lambdaReturnTypePartiallyUnknown'));
        Diagnostic.listAssignmentMismatch = () => new ParameterizedString(getRawString('Diagnostic.listAssignmentMismatch'));
        Diagnostic.listInAnnotation = () => getRawString('Diagnostic.listInAnnotation');
        Diagnostic.literalNamedUnicodeEscape = () => getRawString('Diagnostic.literalNamedUnicodeEscape');
        Diagnostic.literalUnsupportedType = () => getRawString('Diagnostic.literalUnsupportedType');
        Diagnostic.literalEmptyArgs = () => getRawString('Diagnostic.literalEmptyArgs');
        Diagnostic.literalNotAllowed = () => getRawString('Diagnostic.literalNotAllowed');
        Diagnostic.literalNotCallable = () => getRawString('Diagnostic.literalNotCallable');
        Diagnostic.matchIncompatible = () => getRawString('Diagnostic.matchIncompatible');
        Diagnostic.matchIsNotExhaustive = () => getRawString('Diagnostic.matchIsNotExhaustive');
        Diagnostic.maxParseDepthExceeded = () => getRawString('Diagnostic.maxParseDepthExceeded');
        Diagnostic.memberAccess = () => new ParameterizedString(getRawString('Diagnostic.memberAccess'));
        Diagnostic.memberDelete = () => new ParameterizedString(getRawString('Diagnostic.memberDelete'));
        Diagnostic.memberSet = () => new ParameterizedString(getRawString('Diagnostic.memberSet'));
        Diagnostic.metaclassConflict = () => getRawString('Diagnostic.metaclassConflict');
        Diagnostic.metaclassDuplicate = () => getRawString('Diagnostic.metaclassDuplicate');
        Diagnostic.metaclassIsGeneric = () => getRawString('Diagnostic.metaclassIsGeneric');
        Diagnostic.methodNotDefined = () => new ParameterizedString(getRawString('Diagnostic.methodNotDefined'));
        Diagnostic.methodNotDefinedOnType = () => new ParameterizedString(getRawString('Diagnostic.methodNotDefinedOnType'));
        Diagnostic.methodOrdering = () => getRawString('Diagnostic.methodOrdering');
        Diagnostic.methodOverridden = () => new ParameterizedString(getRawString('Diagnostic.methodOverridden'));
        Diagnostic.methodReturnsNonObject = () => new ParameterizedString(getRawString('Diagnostic.methodReturnsNonObject'));
        Diagnostic.missingSuperCall = () => new ParameterizedString(getRawString('Diagnostic.missingSuperCall'));
        Diagnostic.moduleAsType = () => getRawString('Diagnostic.moduleAsType');
        Diagnostic.moduleNotCallable = () => getRawString('Diagnostic.moduleNotCallable');
        Diagnostic.moduleUnknownMember = () => new ParameterizedString(getRawString('Diagnostic.moduleUnknownMember'));
        Diagnostic.namedExceptAfterCatchAll = () => getRawString('Diagnostic.namedExceptAfterCatchAll');
        Diagnostic.namedParamAfterParamSpecArgs = () => new ParameterizedString(getRawString('Diagnostic.namedParamAfterParamSpecArgs'));
        Diagnostic.namedTupleEmptyName = () => getRawString('Diagnostic.namedTupleEmptyName');
        Diagnostic.namedTupleEntryRedeclared = () => new ParameterizedString(getRawString('Diagnostic.namedTupleEntryRedeclared'));
        Diagnostic.namedTupleFirstArg = () => getRawString('Diagnostic.namedTupleFirstArg');
        Diagnostic.namedTupleMultipleInheritance = () => getRawString('Diagnostic.namedTupleMultipleInheritance');
        Diagnostic.namedTupleNameKeyword = () => getRawString('Diagnostic.namedTupleNameKeyword');
        Diagnostic.namedTupleNameType = () => getRawString('Diagnostic.namedTupleNameType');
        Diagnostic.namedTupleNameUnique = () => getRawString('Diagnostic.namedTupleNameUnique');
        Diagnostic.namedTupleNoTypes = () => getRawString('Diagnostic.namedTupleNoTypes');
        Diagnostic.namedTupleSecondArg = () => getRawString('Diagnostic.namedTupleSecondArg');
        Diagnostic.newClsParam = () => getRawString('Diagnostic.newClsParam');
        Diagnostic.newTypeAnyOrUnknown = () => getRawString('Diagnostic.newTypeAnyOrUnknown');
        Diagnostic.newTypeBadName = () => getRawString('Diagnostic.newTypeBadName');
        Diagnostic.newTypeLiteral = () => getRawString('Diagnostic.newTypeLiteral');
        Diagnostic.newTypeNameMismatch = () => getRawString('Diagnostic.newTypeNameMismatch');
        Diagnostic.newTypeNotAClass = () => getRawString('Diagnostic.newTypeNotAClass');
        Diagnostic.newTypeParamCount = () => getRawString('Diagnostic.newTypeParamCount');
        Diagnostic.newTypeProtocolClass = () => getRawString('Diagnostic.newTypeProtocolClass');
        Diagnostic.nonDefaultAfterDefault = () => getRawString('Diagnostic.nonDefaultAfterDefault');
        Diagnostic.noneNotCallable = () => getRawString('Diagnostic.noneNotCallable');
        Diagnostic.noneNotIterable = () => getRawString('Diagnostic.noneNotIterable');
        Diagnostic.noneNotSubscriptable = () => getRawString('Diagnostic.noneNotSubscriptable');
        Diagnostic.noneNotUsableWith = () => getRawString('Diagnostic.noneNotUsableWith');
        Diagnostic.noneOperator = () => new ParameterizedString(getRawString('Diagnostic.noneOperator'));
        Diagnostic.noneUnknownMember = () => new ParameterizedString(getRawString('Diagnostic.noneUnknownMember'));
        Diagnostic.nonLocalNoBinding = () => new ParameterizedString(getRawString('Diagnostic.nonLocalNoBinding'));
        Diagnostic.nonLocalReassignment = () => new ParameterizedString(getRawString('Diagnostic.nonLocalReassignment'));
        Diagnostic.nonLocalRedefinition = () => new ParameterizedString(getRawString('Diagnostic.nonLocalRedefinition'));
        Diagnostic.nonLocalInModule = () => getRawString('Diagnostic.nonLocalInModule');
        Diagnostic.noOverload = () => new ParameterizedString(getRawString('Diagnostic.noOverload'));
        Diagnostic.noReturnContainsReturn = () => getRawString('Diagnostic.noReturnContainsReturn');
        Diagnostic.noReturnContainsYield = () => getRawString('Diagnostic.noReturnContainsYield');
        Diagnostic.noReturnReturnsNone = () => getRawString('Diagnostic.noReturnReturnsNone');
        Diagnostic.notRequiredArgCount = () => getRawString('Diagnostic.notRequiredArgCount');
        Diagnostic.notRequiredNotInTypedDict = () => getRawString('Diagnostic.notRequiredNotInTypedDict');
        Diagnostic.objectNotCallable = () => new ParameterizedString(getRawString('Diagnostic.objectNotCallable'));
        Diagnostic.obscuredClassDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredClassDeclaration'));
        Diagnostic.obscuredFunctionDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredFunctionDeclaration'));
        Diagnostic.obscuredMethodDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredMethodDeclaration'));
        Diagnostic.obscuredParameterDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredParameterDeclaration'));
        Diagnostic.obscuredTypeAliasDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredTypeAliasDeclaration'));
        Diagnostic.obscuredVariableDeclaration = () => new ParameterizedString(getRawString('Diagnostic.obscuredVariableDeclaration'));
        Diagnostic.operatorLessOrGreaterDeprecated = () => getRawString('Diagnostic.operatorLessOrGreaterDeprecated');
        Diagnostic.optionalExtraArgs = () => getRawString('Diagnostic.optionalExtraArgs');
        Diagnostic.orPatternIrrefutable = () => getRawString('Diagnostic.orPatternIrrefutable');
        Diagnostic.orPatternMissingName = () => getRawString('Diagnostic.orPatternMissingName');
        Diagnostic.overlappingKeywordArgs = () => new ParameterizedString(getRawString('Diagnostic.overlappingKeywordArgs'));
        Diagnostic.overlappingOverload = () => new ParameterizedString(getRawString('Diagnostic.overlappingOverload'));
        Diagnostic.overloadAbstractMismatch = () => new ParameterizedString(getRawString('Diagnostic.overloadAbstractMismatch'));
        Diagnostic.overloadClassMethodInconsistent = () => new ParameterizedString(getRawString('Diagnostic.overloadClassMethodInconsistent'));
        Diagnostic.overloadFinalInconsistencyImpl = () => new ParameterizedString(getRawString('Diagnostic.overloadFinalInconsistencyImpl'));
        Diagnostic.overloadFinalInconsistencyNoImpl = () => new ParameterizedString(getRawString('Diagnostic.overloadFinalInconsistencyNoImpl'));
        Diagnostic.overloadImplementationMismatch = () => new ParameterizedString(getRawString('Diagnostic.overloadImplementationMismatch'));
        Diagnostic.overloadReturnTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.overloadReturnTypeMismatch'));
        Diagnostic.overloadStaticMethodInconsistent = () => new ParameterizedString(getRawString('Diagnostic.overloadStaticMethodInconsistent'));
        Diagnostic.overloadWithoutImplementation = () => new ParameterizedString(getRawString('Diagnostic.overloadWithoutImplementation'));
        Diagnostic.overriddenMethodNotFound = () => new ParameterizedString(getRawString('Diagnostic.overriddenMethodNotFound'));
        Diagnostic.overrideDecoratorMissing = () => new ParameterizedString(getRawString('Diagnostic.overrideDecoratorMissing'));
        Diagnostic.paramAfterKwargsParam = () => getRawString('Diagnostic.paramAfterKwargsParam');
        Diagnostic.paramAlreadyAssigned = () => new ParameterizedString(getRawString('Diagnostic.paramAlreadyAssigned'));
        Diagnostic.paramAnnotationMissing = () => new ParameterizedString(getRawString('Diagnostic.paramAnnotationMissing'));
        Diagnostic.paramNameMissing = () => new ParameterizedString(getRawString('Diagnostic.paramNameMissing'));
        Diagnostic.paramSpecArgsKwargsUsage = () => getRawString('Diagnostic.paramSpecArgsKwargsUsage');
        Diagnostic.paramSpecArgsMissing = () => new ParameterizedString(getRawString('Diagnostic.paramSpecArgsMissing'));
        Diagnostic.paramSpecArgsUsage = () => getRawString('Diagnostic.paramSpecArgsUsage');
        Diagnostic.paramSpecAssignedName = () => new ParameterizedString(getRawString('Diagnostic.paramSpecAssignedName'));
        Diagnostic.paramSpecContext = () => getRawString('Diagnostic.paramSpecContext');
        Diagnostic.paramSpecDefaultNotTuple = () => getRawString('Diagnostic.paramSpecDefaultNotTuple');
        Diagnostic.paramSpecFirstArg = () => getRawString('Diagnostic.paramSpecFirstArg');
        Diagnostic.paramSpecKwargsUsage = () => getRawString('Diagnostic.paramSpecKwargsUsage');
        Diagnostic.paramSpecNotUsedByOuterScope = () => new ParameterizedString(getRawString('Diagnostic.paramSpecNotUsedByOuterScope'));
        Diagnostic.paramSpecScopedToReturnType = () => new ParameterizedString(getRawString('Diagnostic.paramSpecScopedToReturnType'));
        Diagnostic.paramSpecUnknownArg = () => getRawString('Diagnostic.paramSpecUnknownArg');
        Diagnostic.paramSpecUnknownMember = () => new ParameterizedString(getRawString('Diagnostic.paramSpecUnknownMember'));
        Diagnostic.paramSpecUnknownParam = () => new ParameterizedString(getRawString('Diagnostic.paramSpecUnknownParam'));
        Diagnostic.paramTypeCovariant = () => getRawString('Diagnostic.paramTypeCovariant');
        Diagnostic.paramTypeUnknown = () => new ParameterizedString(getRawString('Diagnostic.paramTypeUnknown'));
        Diagnostic.paramTypeAny = () => new ParameterizedString(getRawString('Diagnostic.paramTypeAny'));
        Diagnostic.paramAssignmentMismatch = () => new ParameterizedString(getRawString('Diagnostic.paramAssignmentMismatch'));
        Diagnostic.paramTypePartiallyUnknown = () => new ParameterizedString(getRawString('Diagnostic.paramTypePartiallyUnknown'));
        Diagnostic.parenthesizedContextManagerIllegal = () => getRawString('Diagnostic.parenthesizedContextManagerIllegal');
        Diagnostic.patternNeverMatches = () => new ParameterizedString(getRawString('Diagnostic.patternNeverMatches'));
        Diagnostic.positionArgAfterNamedArg = () => getRawString('Diagnostic.positionArgAfterNamedArg');
        Diagnostic.privateImportFromPyTypedModule = () => new ParameterizedString(getRawString('Diagnostic.privateImportFromPyTypedModule'));
        Diagnostic.positionOnlyAfterArgs = () => getRawString('Diagnostic.positionOnlyAfterArgs');
        Diagnostic.positionOnlyAfterKeywordOnly = () => getRawString('Diagnostic.positionOnlyAfterKeywordOnly');
        Diagnostic.positionOnlyAfterNon = () => getRawString('Diagnostic.positionOnlyAfterNon');
        Diagnostic.positionOnlyIncompatible = () => getRawString('Diagnostic.positionOnlyIncompatible');
        Diagnostic.positionOnlyFirstParam = () => getRawString('Diagnostic.positionOnlyFirstParam');
        Diagnostic.privateUsedOutsideOfClass = () => new ParameterizedString(getRawString('Diagnostic.privateUsedOutsideOfClass'));
        Diagnostic.privateUsedOutsideOfModule = () => new ParameterizedString(getRawString('Diagnostic.privateUsedOutsideOfModule'));
        Diagnostic.propertyOverridden = () => new ParameterizedString(getRawString('Diagnostic.propertyOverridden'));
        Diagnostic.propertyStaticMethod = () => getRawString('Diagnostic.propertyStaticMethod');
        Diagnostic.protectedUsedOutsideOfClass = () => new ParameterizedString(getRawString('Diagnostic.protectedUsedOutsideOfClass'));
        Diagnostic.protocolBaseClass = () => new ParameterizedString(getRawString('Diagnostic.protocolBaseClass'));
        Diagnostic.protocolBaseClassWithTypeArgs = () => getRawString('Diagnostic.protocolBaseClassWithTypeArgs');
        Diagnostic.protocolIllegal = () => getRawString('Diagnostic.protocolIllegal');
        Diagnostic.protocolNotAllowed = () => getRawString('Diagnostic.protocolNotAllowed');
        Diagnostic.protocolUnsafeOverlap = () => new ParameterizedString(getRawString('Diagnostic.protocolUnsafeOverlap'));
        Diagnostic.protocolVarianceContravariant = () => new ParameterizedString(getRawString('Diagnostic.protocolVarianceContravariant'));
        Diagnostic.protocolVarianceCovariant = () => new ParameterizedString(getRawString('Diagnostic.protocolVarianceCovariant'));
        Diagnostic.protocolVarianceInvariant = () => new ParameterizedString(getRawString('Diagnostic.protocolVarianceInvariant'));
        Diagnostic.pyrightCommentInvalidDiagnosticBoolValue = () => getRawString('Diagnostic.pyrightCommentInvalidDiagnosticBoolValue');
        Diagnostic.pyrightCommentInvalidDiagnosticSeverityValue = () => getRawString('Diagnostic.pyrightCommentInvalidDiagnosticSeverityValue');
        Diagnostic.pyrightCommentMissingDirective = () => getRawString('Diagnostic.pyrightCommentMissingDirective');
        Diagnostic.pyrightCommentNotOnOwnLine = () => getRawString('Diagnostic.pyrightCommentNotOnOwnLine');
        Diagnostic.pyrightCommentUnknownDirective = () => new ParameterizedString(getRawString('Diagnostic.pyrightCommentUnknownDirective'));
        Diagnostic.pyrightCommentUnknownDiagnosticRule = () => new ParameterizedString(getRawString('Diagnostic.pyrightCommentUnknownDiagnosticRule'));
        Diagnostic.readOnlyArgCount = () => getRawString('Diagnostic.readOnlyArgCount');
        Diagnostic.readOnlyNotInTypedDict = () => getRawString('Diagnostic.readOnlyNotInTypedDict');
        Diagnostic.recursiveDefinition = () => new ParameterizedString(getRawString('Diagnostic.recursiveDefinition'));
        Diagnostic.relativeImportNotAllowed = () => getRawString('Diagnostic.relativeImportNotAllowed');
        Diagnostic.requiredArgCount = () => getRawString('Diagnostic.requiredArgCount');
        Diagnostic.requiredNotInTypedDict = () => getRawString('Diagnostic.requiredNotInTypedDict');
        Diagnostic.returnInAsyncGenerator = () => getRawString('Diagnostic.returnInAsyncGenerator');
        Diagnostic.returnMissing = () => new ParameterizedString(getRawString('Diagnostic.returnMissing'));
        Diagnostic.returnOutsideFunction = () => getRawString('Diagnostic.returnOutsideFunction');
        Diagnostic.returnTypeContravariant = () => getRawString('Diagnostic.returnTypeContravariant');
        Diagnostic.returnTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.returnTypeMismatch'));
        Diagnostic.returnTypeUnknown = () => getRawString('Diagnostic.returnTypeUnknown');
        Diagnostic.returnTypeAny = () => getRawString('Diagnostic.returnTypeAny');
        Diagnostic.returnTypePartiallyUnknown = () => new ParameterizedString(getRawString('Diagnostic.returnTypePartiallyUnknown'));
        Diagnostic.revealLocalsArgs = () => getRawString('Diagnostic.revealLocalsArgs');
        Diagnostic.revealLocalsNone = () => getRawString('Diagnostic.revealLocalsNone');
        Diagnostic.revealTypeArgs = () => getRawString('Diagnostic.revealTypeArgs');
        Diagnostic.revealTypeExpectedTextArg = () => getRawString('Diagnostic.revealTypeExpectedTextArg');
        Diagnostic.revealTypeExpectedTextMismatch = () => new ParameterizedString(getRawString('Diagnostic.revealTypeExpectedTextMismatch'));
        Diagnostic.revealTypeExpectedTypeMismatch = () => new ParameterizedString(getRawString('Diagnostic.revealTypeExpectedTypeMismatch'));
        Diagnostic.selfTypeContext = () => getRawString('Diagnostic.selfTypeContext');
        Diagnostic.selfTypeMetaclass = () => getRawString('Diagnostic.selfTypeMetaclass');
        Diagnostic.selfTypeWithTypedSelfOrCls = () => getRawString('Diagnostic.selfTypeWithTypedSelfOrCls');
        Diagnostic.setterGetterTypeMismatch = () => getRawString('Diagnostic.setterGetterTypeMismatch');
        Diagnostic.starPatternInAsPattern = () => getRawString('Diagnostic.starPatternInAsPattern');
        Diagnostic.starPatternInOrPattern = () => getRawString('Diagnostic.starPatternInOrPattern');
        Diagnostic.singleOverload = () => new ParameterizedString(getRawString('Diagnostic.singleOverload'));
        Diagnostic.slotsAttributeError = () => new ParameterizedString(getRawString('Diagnostic.slotsAttributeError'));
        Diagnostic.slotsClassVarConflict = () => new ParameterizedString(getRawString('Diagnostic.slotsClassVarConflict'));
        Diagnostic.starStarWildcardNotAllowed = () => getRawString('Diagnostic.starStarWildcardNotAllowed');
        Diagnostic.staticClsSelfParam = () => getRawString('Diagnostic.staticClsSelfParam');
        Diagnostic.stdlibModuleOverridden = () => new ParameterizedString(getRawString('Diagnostic.stdlibModuleOverridden'));
        Diagnostic.stringNonAsciiBytes = () => getRawString('Diagnostic.stringNonAsciiBytes');
        Diagnostic.stringNotSubscriptable = () => getRawString('Diagnostic.stringNotSubscriptable');
        Diagnostic.stringUnsupportedEscape = () => getRawString('Diagnostic.stringUnsupportedEscape');
        Diagnostic.stringUnterminated = () => getRawString('Diagnostic.stringUnterminated');
        Diagnostic.stubFileMissing = () => new ParameterizedString(getRawString('Diagnostic.stubFileMissing'));
        Diagnostic.stubUsesGetAttr = () => getRawString('Diagnostic.stubUsesGetAttr');
        Diagnostic.sublistParamsIncompatible = () => getRawString('Diagnostic.sublistParamsIncompatible');
        Diagnostic.superCallArgCount = () => getRawString('Diagnostic.superCallArgCount');
        Diagnostic.superCallFirstArg = () => new ParameterizedString(getRawString('Diagnostic.superCallFirstArg'));
        Diagnostic.superCallSecondArg = () => new ParameterizedString(getRawString('Diagnostic.superCallSecondArg'));
        Diagnostic.superCallZeroArgForm = () => getRawString('Diagnostic.superCallZeroArgForm');
        Diagnostic.superCallZeroArgFormStaticMethod = () => getRawString('Diagnostic.superCallZeroArgFormStaticMethod');
        Diagnostic.symbolIsUnbound = () => new ParameterizedString(getRawString('Diagnostic.symbolIsUnbound'));
        Diagnostic.symbolIsUndefined = () => new ParameterizedString(getRawString('Diagnostic.symbolIsUndefined'));
        Diagnostic.symbolIsPossiblyUnbound = () => new ParameterizedString(getRawString('Diagnostic.symbolIsPossiblyUnbound'));
        Diagnostic.symbolOverridden = () => new ParameterizedString(getRawString('Diagnostic.symbolOverridden'));
        Diagnostic.ternaryNotAllowed = () => getRawString('Diagnostic.ternaryNotAllowed');
        Diagnostic.totalOrderingMissingMethod = () => getRawString('Diagnostic.totalOrderingMissingMethod');
        Diagnostic.trailingCommaInFromImport = () => getRawString('Diagnostic.trailingCommaInFromImport');
        Diagnostic.tryWithoutExcept = () => getRawString('Diagnostic.tryWithoutExcept');
        Diagnostic.tupleAssignmentMismatch = () => new ParameterizedString(getRawString('Diagnostic.tupleAssignmentMismatch'));
        Diagnostic.tupleInAnnotation = () => getRawString('Diagnostic.tupleInAnnotation');
        Diagnostic.tupleIndexOutOfRange = () => new ParameterizedString(getRawString('Diagnostic.tupleIndexOutOfRange'));
        Diagnostic.typeAliasIllegalExpressionForm = () => getRawString('Diagnostic.typeAliasIllegalExpressionForm');
        Diagnostic.typeAliasIsRecursiveDirect = () => new ParameterizedString(getRawString('Diagnostic.typeAliasIsRecursiveDirect'));
        Diagnostic.typeAliasNotInModuleOrClass = () => getRawString('Diagnostic.typeAliasNotInModuleOrClass');
        Diagnostic.typeAliasRedeclared = () => new ParameterizedString(getRawString('Diagnostic.typeAliasRedeclared'));
        Diagnostic.typeAliasStatementIllegal = () => getRawString('Diagnostic.typeAliasStatementIllegal');
        Diagnostic.typeAliasStatementBadScope = () => getRawString('Diagnostic.typeAliasStatementBadScope');
        Diagnostic.typeAliasTypeBaseClass = () => getRawString('Diagnostic.typeAliasTypeBaseClass');
        Diagnostic.typeAliasTypeMustBeAssigned = () => getRawString('Diagnostic.typeAliasTypeMustBeAssigned');
        Diagnostic.typeAliasTypeNameArg = () => getRawString('Diagnostic.typeAliasTypeNameArg');
        Diagnostic.typeAliasTypeNameMismatch = () => getRawString('Diagnostic.typeAliasTypeNameMismatch');
        Diagnostic.typeAliasTypeParamInvalid = () => getRawString('Diagnostic.typeAliasTypeParamInvalid');
        Diagnostic.typeAnnotationCall = () => getRawString('Diagnostic.typeAnnotationCall');
        Diagnostic.typeAnnotationVariable = () => getRawString('Diagnostic.typeAnnotationVariable');
        Diagnostic.typeAnnotationWithCallable = () => getRawString('Diagnostic.typeAnnotationWithCallable');
        Diagnostic.typeArgListExpected = () => getRawString('Diagnostic.typeArgListExpected');
        Diagnostic.typeArgListNotAllowed = () => getRawString('Diagnostic.typeArgListNotAllowed');
        Diagnostic.typeArgsExpectingNone = () => new ParameterizedString(getRawString('Diagnostic.typeArgsExpectingNone'));
        Diagnostic.typeArgsMismatchOne = () => new ParameterizedString(getRawString('Diagnostic.typeArgsMismatchOne'));
        Diagnostic.typeArgsMissingForAlias = () => new ParameterizedString(getRawString('Diagnostic.typeArgsMissingForAlias'));
        Diagnostic.typeArgsMissingForClass = () => new ParameterizedString(getRawString('Diagnostic.typeArgsMissingForClass'));
        Diagnostic.typeArgsTooFew = () => new ParameterizedString(getRawString('Diagnostic.typeArgsTooFew'));
        Diagnostic.typeArgsTooMany = () => new ParameterizedString(getRawString('Diagnostic.typeArgsTooMany'));
        Diagnostic.typeAssignmentMismatch = () => new ParameterizedString(getRawString('Diagnostic.typeAssignmentMismatch'));
        Diagnostic.typeAssignmentMismatchWildcard = () => new ParameterizedString(getRawString('Diagnostic.typeAssignmentMismatchWildcard'));
        Diagnostic.typeCallNotAllowed = () => getRawString('Diagnostic.typeCallNotAllowed');
        Diagnostic.typeCheckOnly = () => new ParameterizedString(getRawString('Diagnostic.typeCheckOnly'));
        Diagnostic.typeCommentDeprecated = () => getRawString('Diagnostic.typeCommentDeprecated');
        Diagnostic.typedDictAccess = () => getRawString('Diagnostic.typedDictAccess');
        Diagnostic.typedDictAssignedName = () => new ParameterizedString(getRawString('Diagnostic.typedDictAssignedName'));
        Diagnostic.typedDictBadVar = () => getRawString('Diagnostic.typedDictBadVar');
        Diagnostic.typedDictBaseClass = () => getRawString('Diagnostic.typedDictBaseClass');
        Diagnostic.typedDictBoolParam = () => new ParameterizedString(getRawString('Diagnostic.typedDictBoolParam'));
        Diagnostic.typedDictClosedExtras = () => new ParameterizedString(getRawString('Diagnostic.typedDictClosedExtras'));
        Diagnostic.typedDictClosedNoExtras = () => new ParameterizedString(getRawString('Diagnostic.typedDictClosedNoExtras'));
        Diagnostic.typedDictDelete = () => getRawString('Diagnostic.typedDictDelete');
        Diagnostic.typedDictEmptyName = () => getRawString('Diagnostic.typedDictEmptyName');
        Diagnostic.typedDictEntryName = () => getRawString('Diagnostic.typedDictEntryName');
        Diagnostic.typedDictEntryUnique = () => getRawString('Diagnostic.typedDictEntryUnique');
        Diagnostic.typedDictExtraArgs = () => getRawString('Diagnostic.typedDictExtraArgs');
        Diagnostic.typedDictFieldNotRequiredRedefinition = () => new ParameterizedString(getRawString('Diagnostic.typedDictFieldNotRequiredRedefinition'));
        Diagnostic.typedDictFieldReadOnlyRedefinition = () => new ParameterizedString(getRawString('Diagnostic.typedDictFieldReadOnlyRedefinition'));
        Diagnostic.typedDictFieldRequiredRedefinition = () => new ParameterizedString(getRawString('Diagnostic.typedDictFieldRequiredRedefinition'));
        Diagnostic.typedDictFirstArg = () => getRawString('Diagnostic.typedDictFirstArg');
        Diagnostic.typedDictInitsubclassParameter = () => new ParameterizedString(getRawString('Diagnostic.typedDictInitsubclassParameter'));
        Diagnostic.typedDictNotAllowed = () => getRawString('Diagnostic.typedDictNotAllowed');
        Diagnostic.typedDictSecondArgDict = () => getRawString('Diagnostic.typedDictSecondArgDict');
        Diagnostic.typedDictSecondArgDictEntry = () => getRawString('Diagnostic.typedDictSecondArgDictEntry');
        Diagnostic.typedDictSet = () => getRawString('Diagnostic.typedDictSet');
        Diagnostic.typeExpectedClass = () => new ParameterizedString(getRawString('Diagnostic.typeExpectedClass'));
        Diagnostic.typeGuardArgCount = () => getRawString('Diagnostic.typeGuardArgCount');
        Diagnostic.typeGuardParamCount = () => getRawString('Diagnostic.typeGuardParamCount');
        Diagnostic.typeIsReturnType = () => new ParameterizedString(getRawString('Diagnostic.typeIsReturnType'));
        Diagnostic.typeNotAwaitable = () => new ParameterizedString(getRawString('Diagnostic.typeNotAwaitable'));
        Diagnostic.typeNotIntantiable = () => new ParameterizedString(getRawString('Diagnostic.typeNotIntantiable'));
        Diagnostic.typeNotIterable = () => new ParameterizedString(getRawString('Diagnostic.typeNotIterable'));
        Diagnostic.typeNotSpecializable = () => new ParameterizedString(getRawString('Diagnostic.typeNotSpecializable'));
        Diagnostic.typeNotSubscriptable = () => new ParameterizedString(getRawString('Diagnostic.typeNotSubscriptable'));
        Diagnostic.typeNotUsableWith = () => new ParameterizedString(getRawString('Diagnostic.typeNotUsableWith'));
        Diagnostic.typeNotSupportBinaryOperator = () => new ParameterizedString(getRawString('Diagnostic.typeNotSupportBinaryOperator'));
        Diagnostic.typeNotSupportBinaryOperatorBidirectional = () => new ParameterizedString(getRawString('Diagnostic.typeNotSupportBinaryOperatorBidirectional'));
        Diagnostic.typeNotSupportUnaryOperator = () => new ParameterizedString(getRawString('Diagnostic.typeNotSupportUnaryOperator'));
        Diagnostic.typeNotSupportUnaryOperatorBidirectional = () => new ParameterizedString(getRawString('Diagnostic.typeNotSupportUnaryOperatorBidirectional'));
        Diagnostic.typeParameterBoundNotAllowed = () => getRawString('Diagnostic.typeParameterBoundNotAllowed');
        Diagnostic.typeParameterConstraintTuple = () => getRawString('Diagnostic.typeParameterConstraintTuple');
        Diagnostic.typeParameterExistingTypeParameter = () => new ParameterizedString(getRawString('Diagnostic.typeParameterExistingTypeParameter'));
        Diagnostic.typeParametersMissing = () => getRawString('Diagnostic.typeParametersMissing');
        Diagnostic.typeParameterNotDeclared = () => new ParameterizedString(getRawString('Diagnostic.typeParameterNotDeclared'));
        Diagnostic.typePartiallyUnknown = () => new ParameterizedString(getRawString('Diagnostic.typePartiallyUnknown'));
        Diagnostic.typeUnknown = () => new ParameterizedString(getRawString('Diagnostic.typeUnknown'));
        Diagnostic.typeAny = () => new ParameterizedString(getRawString('Diagnostic.typeAny'));
        Diagnostic.typeVarAssignedName = () => new ParameterizedString(getRawString('Diagnostic.typeVarAssignedName'));
        Diagnostic.typeVarAssignmentMismatch = () => new ParameterizedString(getRawString('Diagnostic.typeVarAssignmentMismatch'));
        Diagnostic.typeVarBoundAndConstrained = () => getRawString('Diagnostic.typeVarBoundAndConstrained');
        Diagnostic.typeVarBoundGeneric = () => getRawString('Diagnostic.typeVarBoundGeneric');
        Diagnostic.typeVarConstraintGeneric = () => getRawString('Diagnostic.typeVarConstraintGeneric');
        Diagnostic.typeVarDefaultBoundMismatch = () => getRawString('Diagnostic.typeVarDefaultBoundMismatch');
        Diagnostic.typeVarDefaultConstraintMismatch = () => getRawString('Diagnostic.typeVarDefaultConstraintMismatch');
        Diagnostic.typeVarDefaultIllegal = () => getRawString('Diagnostic.typeVarDefaultIllegal');
        Diagnostic.typeVarDefaultInvalidTypeVar = () => new ParameterizedString(getRawString('Diagnostic.typeVarDefaultInvalidTypeVar'));
        Diagnostic.typeVarFirstArg = () => getRawString('Diagnostic.typeVarFirstArg');
        Diagnostic.typeVarNoMember = () => new ParameterizedString(getRawString('Diagnostic.typeVarNoMember'));
        Diagnostic.typeVarNotSubscriptable = () => new ParameterizedString(getRawString('Diagnostic.typeVarNotSubscriptable'));
        Diagnostic.typeVarNotUsedByOuterScope = () => new ParameterizedString(getRawString('Diagnostic.typeVarNotUsedByOuterScope'));
        Diagnostic.typeVarPossiblyUnsolvable = () => new ParameterizedString(getRawString('Diagnostic.typeVarPossiblyUnsolvable'));
        Diagnostic.typeVarScopedToReturnType = () => new ParameterizedString(getRawString('Diagnostic.typeVarScopedToReturnType'));
        Diagnostic.typeVarSingleConstraint = () => getRawString('Diagnostic.typeVarSingleConstraint');
        Diagnostic.typeVarsNotInGenericOrProtocol = () => getRawString('Diagnostic.typeVarsNotInGenericOrProtocol');
        Diagnostic.typeVarTupleContext = () => getRawString('Diagnostic.typeVarTupleContext');
        Diagnostic.typeVarTupleDefaultNotUnpacked = () => getRawString('Diagnostic.typeVarTupleDefaultNotUnpacked');
        Diagnostic.typeVarTupleMustBeUnpacked = () => getRawString('Diagnostic.typeVarTupleMustBeUnpacked');
        Diagnostic.typeVarTupleConstraints = () => getRawString('Diagnostic.typeVarTupleConstraints');
        Diagnostic.typeVarTupleUnknownParam = () => new ParameterizedString(getRawString('Diagnostic.typeVarTupleUnknownParam'));
        Diagnostic.typeVarUnknownParam = () => new ParameterizedString(getRawString('Diagnostic.typeVarUnknownParam'));
        Diagnostic.typeVarUsedByOuterScope = () => new ParameterizedString(getRawString('Diagnostic.typeVarUsedByOuterScope'));
        Diagnostic.typeVarUsedOnlyOnce = () => new ParameterizedString(getRawString('Diagnostic.typeVarUsedOnlyOnce'));
        Diagnostic.typeVarVariance = () => getRawString('Diagnostic.typeVarVariance');
        Diagnostic.typeVarWithDefaultFollowsVariadic = () => new ParameterizedString(getRawString('Diagnostic.typeVarWithDefaultFollowsVariadic'));
        Diagnostic.typeVarWithoutDefault = () => new ParameterizedString(getRawString('Diagnostic.typeVarWithoutDefault'));
        Diagnostic.unaccessedClass = () => new ParameterizedString(getRawString('Diagnostic.unaccessedClass'));
        Diagnostic.unaccessedFunction = () => new ParameterizedString(getRawString('Diagnostic.unaccessedFunction'));
        Diagnostic.unaccessedImport = () => new ParameterizedString(getRawString('Diagnostic.unaccessedImport'));
        Diagnostic.unaccessedSymbol = () => new ParameterizedString(getRawString('Diagnostic.unaccessedSymbol'));
        Diagnostic.unaccessedVariable = () => new ParameterizedString(getRawString('Diagnostic.unaccessedVariable'));
        Diagnostic.unannotatedFunctionSkipped = () => new ParameterizedString(getRawString('Diagnostic.unannotatedFunctionSkipped'));
        Diagnostic.unaryOperationNotAllowed = () => getRawString('Diagnostic.unaryOperationNotAllowed');
        Diagnostic.unexpectedAsyncToken = () => getRawString('Diagnostic.unexpectedAsyncToken');
        Diagnostic.unexpectedExprToken = () => getRawString('Diagnostic.unexpectedExprToken');
        Diagnostic.unexpectedIndent = () => getRawString('Diagnostic.unexpectedIndent');
        Diagnostic.unexpectedUnindent = () => getRawString('Diagnostic.unexpectedUnindent');
        Diagnostic.unhashableDictKey = () => getRawString('Diagnostic.unhashableDictKey');
        Diagnostic.unhashableSetEntry = () => getRawString('Diagnostic.unhashableSetEntry');
        Diagnostic.unionForwardReferenceNotAllowed = () => getRawString('Diagnostic.unionForwardReferenceNotAllowed');
        Diagnostic.unionSyntaxIllegal = () => getRawString('Diagnostic.unionSyntaxIllegal');
        Diagnostic.unionTypeArgCount = () => getRawString('Diagnostic.unionTypeArgCount');
        Diagnostic.uninitializedAbstractVariables = () => new ParameterizedString(getRawString('Diagnostic.uninitializedAbstractVariables'));
        Diagnostic.uninitializedInstanceVariable = () => new ParameterizedString(getRawString('Diagnostic.uninitializedInstanceVariable'));
        Diagnostic.unionUnpackedTuple = () => getRawString('Diagnostic.unionUnpackedTuple');
        Diagnostic.unionUnpackedTypeVarTuple = () => getRawString('Diagnostic.unionUnpackedTypeVarTuple');
        Diagnostic.unnecessaryCast = () => new ParameterizedString(getRawString('Diagnostic.unnecessaryCast'));
        Diagnostic.unnecessaryIsInstanceAlways = () => new ParameterizedString(getRawString('Diagnostic.unnecessaryIsInstanceAlways'));
        Diagnostic.unnecessaryIsSubclassAlways = () => new ParameterizedString(getRawString('Diagnostic.unnecessaryIsSubclassAlways'));
        Diagnostic.unnecessaryPyrightIgnore = () => getRawString('Diagnostic.unnecessaryPyrightIgnore');
        Diagnostic.unnecessaryPyrightIgnoreRule = () => new ParameterizedString(getRawString('Diagnostic.unnecessaryPyrightIgnoreRule'));
        Diagnostic.unnecessaryTypeIgnore = () => getRawString('Diagnostic.unnecessaryTypeIgnore');
        Diagnostic.unpackArgCount = () => getRawString('Diagnostic.unpackArgCount');
        Diagnostic.unpackedArgInTypeArgument = () => getRawString('Diagnostic.unpackedArgInTypeArgument');
        Diagnostic.unpackedArgWithVariadicParam = () => getRawString('Diagnostic.unpackedArgWithVariadicParam');
        Diagnostic.unpackedDictArgumentNotMapping = () => getRawString('Diagnostic.unpackedDictArgumentNotMapping');
        Diagnostic.unpackedDictSubscriptIllegal = () => getRawString('Diagnostic.unpackedDictSubscriptIllegal');
        Diagnostic.unpackedSubscriptIllegal = () => getRawString('Diagnostic.unpackedSubscriptIllegal');
        Diagnostic.unpackedTypedDictArgument = () => getRawString('Diagnostic.unpackedTypedDictArgument');
        Diagnostic.unpackedTypeVarTupleExpected = () => new ParameterizedString(getRawString('Diagnostic.unpackedTypeVarTupleExpected'));
        Diagnostic.unpackExpectedTypedDict = () => getRawString('Diagnostic.unpackExpectedTypedDict');
        Diagnostic.unpackExpectedTypeVarTuple = () => getRawString('Diagnostic.unpackExpectedTypeVarTuple');
        Diagnostic.unpackIllegalInComprehension = () => getRawString('Diagnostic.unpackIllegalInComprehension');
        Diagnostic.unpackInAnnotation = () => getRawString('Diagnostic.unpackInAnnotation');
        Diagnostic.unpackInDict = () => getRawString('Diagnostic.unpackInDict');
        Diagnostic.unpackInSet = () => getRawString('Diagnostic.unpackInSet');
        Diagnostic.unpackNotAllowed = () => getRawString('Diagnostic.unpackNotAllowed');
        Diagnostic.unpackOperatorNotAllowed = () => getRawString('Diagnostic.unpackOperatorNotAllowed');
        Diagnostic.unpackTuplesIllegal = () => getRawString('Diagnostic.unpackTuplesIllegal');
        Diagnostic.unreachableCode = () => getRawString('Diagnostic.unreachableCode');
        Diagnostic.unreachableExcept = () => getRawString('Diagnostic.unreachableExcept');
        Diagnostic.unsupportedDunderAllOperation = () => getRawString('Diagnostic.unsupportedDunderAllOperation');
        Diagnostic.unusedCallResult = () => new ParameterizedString(getRawString('Diagnostic.unusedCallResult'));
        Diagnostic.unusedCoroutine = () => getRawString('Diagnostic.unusedCoroutine');
        Diagnostic.unusedExpression = () => getRawString('Diagnostic.unusedExpression');
        Diagnostic.varAnnotationIllegal = () => getRawString('Diagnostic.varAnnotationIllegal');
        Diagnostic.variableFinalOverride = () => new ParameterizedString(getRawString('Diagnostic.variableFinalOverride'));
        Diagnostic.variadicTypeArgsTooMany = () => getRawString('Diagnostic.variadicTypeArgsTooMany');
        Diagnostic.variadicTypeParamTooManyAlias = () => new ParameterizedString(getRawString('Diagnostic.variadicTypeParamTooManyAlias'));
        Diagnostic.variadicTypeParamTooManyClass = () => new ParameterizedString(getRawString('Diagnostic.variadicTypeParamTooManyClass'));
        Diagnostic.walrusIllegal = () => getRawString('Diagnostic.walrusIllegal');
        Diagnostic.walrusNotAllowed = () => getRawString('Diagnostic.walrusNotAllowed');
        Diagnostic.wildcardInFunction = () => getRawString('Diagnostic.wildcardInFunction');
        Diagnostic.wildcardPatternTypeUnknown = () => getRawString('Diagnostic.wildcardPatternTypeUnknown');
        Diagnostic.wildcardPatternTypeAny = () => getRawString('Diagnostic.wildcardPatternTypeAny');
        Diagnostic.wildcardPatternTypePartiallyUnknown = () => getRawString('Diagnostic.wildcardPatternTypePartiallyUnknown');
        Diagnostic.wildcardLibraryImport = () => getRawString('Diagnostic.wildcardLibraryImport');
        Diagnostic.yieldFromIllegal = () => getRawString('Diagnostic.yieldFromIllegal');
        Diagnostic.yieldFromOutsideAsync = () => getRawString('Diagnostic.yieldFromOutsideAsync');
        Diagnostic.yieldOutsideFunction = () => getRawString('Diagnostic.yieldOutsideFunction');
        Diagnostic.yieldWithinListCompr = () => getRawString('Diagnostic.yieldWithinListCompr');
        Diagnostic.zeroCaseStatementsFound = () => getRawString('Diagnostic.zeroCaseStatementsFound');
        Diagnostic.zeroLengthTupleNotAllowed = () => getRawString('Diagnostic.zeroLengthTupleNotAllowed');
        Diagnostic.pyrightIgnoreCommentWithoutRule = () => getRawString('Diagnostic.pyrightIgnoreCommentWithoutRule');
        Diagnostic.typeIgnoreCommentWithoutRule = () => getRawString('Diagnostic.typeIgnoreCommentWithoutRule');
        Diagnostic.implicitRelativeImport = () => new ParameterizedString(getRawString('Diagnostic.implicitRelativeImport'));
        Diagnostic.invalidCast = () => new ParameterizedString(getRawString('Diagnostic.invalidCast'));
    })(Diagnostic = Localizer.Diagnostic || (Localizer.Diagnostic = {}));
    let DiagnosticAddendum;
    (function (DiagnosticAddendum) {
        DiagnosticAddendum.annotatedNotAllowed = () => getRawString('DiagnosticAddendum.annotatedNotAllowed');
        DiagnosticAddendum.argParam = () => new ParameterizedString(getRawString('DiagnosticAddendum.argParam'));
        DiagnosticAddendum.argParamFunction = () => new ParameterizedString(getRawString('DiagnosticAddendum.argParamFunction'));
        DiagnosticAddendum.argsParamMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.argsParamMissing'));
        DiagnosticAddendum.argsPositionOnly = () => new ParameterizedString(getRawString('DiagnosticAddendum.argsPositionOnly'));
        DiagnosticAddendum.argumentType = () => new ParameterizedString(getRawString('DiagnosticAddendum.argumentType'));
        DiagnosticAddendum.argumentTypes = () => new ParameterizedString(getRawString('DiagnosticAddendum.argumentTypes'));
        DiagnosticAddendum.assignToNone = () => getRawString('DiagnosticAddendum.assignToNone');
        DiagnosticAddendum.asyncHelp = () => getRawString('DiagnosticAddendum.asyncHelp');
        DiagnosticAddendum.baseClassIncompatible = () => new ParameterizedString(getRawString('DiagnosticAddendum.baseClassIncompatible'));
        DiagnosticAddendum.baseClassIncompatibleSubclass = () => new ParameterizedString(getRawString('DiagnosticAddendum.baseClassIncompatibleSubclass'));
        DiagnosticAddendum.baseClassOverriddenType = () => new ParameterizedString(getRawString('DiagnosticAddendum.baseClassOverriddenType'));
        DiagnosticAddendum.baseClassOverridesType = () => new ParameterizedString(getRawString('DiagnosticAddendum.baseClassOverridesType'));
        DiagnosticAddendum.bytesTypePromotions = () => getRawString('DiagnosticAddendum.bytesTypePromotions');
        DiagnosticAddendum.conditionalRequiresBool = () => new ParameterizedString(getRawString('DiagnosticAddendum.conditionalRequiresBool'));
        DiagnosticAddendum.dataClassFrozen = () => new ParameterizedString(getRawString('DiagnosticAddendum.dataClassFrozen'));
        DiagnosticAddendum.dataClassFieldLocation = () => getRawString('DiagnosticAddendum.dataClassFieldLocation');
        DiagnosticAddendum.dataProtocolUnsupported = () => new ParameterizedString(getRawString('DiagnosticAddendum.dataProtocolUnsupported'));
        DiagnosticAddendum.descriptorAccessBindingFailed = () => new ParameterizedString(getRawString('DiagnosticAddendum.descriptorAccessBindingFailed'));
        DiagnosticAddendum.descriptorAccessCallFailed = () => new ParameterizedString(getRawString('DiagnosticAddendum.descriptorAccessCallFailed'));
        DiagnosticAddendum.finalMethod = () => getRawString('DiagnosticAddendum.finalMethod');
        DiagnosticAddendum.functionParamDefaultMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionParamDefaultMissing'));
        DiagnosticAddendum.functionParamName = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionParamName'));
        DiagnosticAddendum.functionParamPositionOnly = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionParamPositionOnly'));
        DiagnosticAddendum.functionReturnTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionReturnTypeMismatch'));
        DiagnosticAddendum.functionTooFewParams = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionTooFewParams'));
        DiagnosticAddendum.genericClassNotAllowed = () => getRawString('DiagnosticAddendum.genericClassNotAllowed');
        DiagnosticAddendum.incompatibleGetter = () => getRawString('DiagnosticAddendum.incompatibleGetter');
        DiagnosticAddendum.incompatibleSetter = () => getRawString('DiagnosticAddendum.incompatibleSetter');
        DiagnosticAddendum.incompatibleDeleter = () => getRawString('DiagnosticAddendum.incompatibleDeleter');
        DiagnosticAddendum.initMethodLocation = () => new ParameterizedString(getRawString('DiagnosticAddendum.initMethodLocation'));
        DiagnosticAddendum.initMethodSignature = () => new ParameterizedString(getRawString('DiagnosticAddendum.initMethodSignature'));
        DiagnosticAddendum.initSubclassLocation = () => new ParameterizedString(getRawString('DiagnosticAddendum.initSubclassLocation'));
        DiagnosticAddendum.invariantSuggestionDict = () => getRawString('DiagnosticAddendum.invariantSuggestionDict');
        DiagnosticAddendum.invariantSuggestionList = () => getRawString('DiagnosticAddendum.invariantSuggestionList');
        DiagnosticAddendum.invariantSuggestionSet = () => getRawString('DiagnosticAddendum.invariantSuggestionSet');
        DiagnosticAddendum.functionTooManyParams = () => new ParameterizedString(getRawString('DiagnosticAddendum.functionTooManyParams'));
        DiagnosticAddendum.keyNotRequired = () => new ParameterizedString(getRawString('DiagnosticAddendum.keyNotRequired'));
        DiagnosticAddendum.keyReadOnly = () => new ParameterizedString(getRawString('DiagnosticAddendum.keyReadOnly'));
        DiagnosticAddendum.keyRequiredDeleted = () => new ParameterizedString(getRawString('DiagnosticAddendum.keyRequiredDeleted'));
        DiagnosticAddendum.keyUndefined = () => new ParameterizedString(getRawString('DiagnosticAddendum.keyUndefined'));
        DiagnosticAddendum.kwargsParamMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.kwargsParamMissing'));
        DiagnosticAddendum.listAssignmentMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.listAssignmentMismatch'));
        DiagnosticAddendum.literalAssignmentMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.literalAssignmentMismatch'));
        DiagnosticAddendum.matchIsNotExhaustiveType = () => new ParameterizedString(getRawString('DiagnosticAddendum.matchIsNotExhaustiveType'));
        DiagnosticAddendum.matchIsNotExhaustiveHint = () => getRawString('DiagnosticAddendum.matchIsNotExhaustiveHint');
        DiagnosticAddendum.memberAssignment = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberAssignment'));
        DiagnosticAddendum.memberIsAbstract = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsAbstract'));
        DiagnosticAddendum.memberIsAbstractMore = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsAbstractMore'));
        DiagnosticAddendum.memberIsClassVarInProtocol = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsClassVarInProtocol'));
        DiagnosticAddendum.memberIsFinalInProtocol = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsFinalInProtocol'));
        DiagnosticAddendum.memberIsInitVar = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsInitVar'));
        DiagnosticAddendum.memberIsInvariant = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsInvariant'));
        DiagnosticAddendum.memberIsNotClassVarInClass = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsNotClassVarInClass'));
        DiagnosticAddendum.memberIsNotClassVarInProtocol = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsNotClassVarInProtocol'));
        DiagnosticAddendum.memberIsNotFinalInProtocol = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsNotFinalInProtocol'));
        DiagnosticAddendum.memberIsWritableInProtocol = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberIsWritableInProtocol'));
        DiagnosticAddendum.memberSetClassVar = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberSetClassVar'));
        DiagnosticAddendum.memberTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberTypeMismatch'));
        DiagnosticAddendum.memberUnknown = () => new ParameterizedString(getRawString('DiagnosticAddendum.memberUnknown'));
        DiagnosticAddendum.metaclassConflict = () => new ParameterizedString(getRawString('DiagnosticAddendum.metaclassConflict'));
        DiagnosticAddendum.missingGetter = () => getRawString('DiagnosticAddendum.missingGetter');
        DiagnosticAddendum.missingSetter = () => getRawString('DiagnosticAddendum.missingSetter');
        DiagnosticAddendum.missingDeleter = () => getRawString('DiagnosticAddendum.missingDeleter');
        DiagnosticAddendum.namedParamMissingInDest = () => new ParameterizedString(getRawString('DiagnosticAddendum.namedParamMissingInDest'));
        DiagnosticAddendum.namedParamMissingInSource = () => new ParameterizedString(getRawString('DiagnosticAddendum.namedParamMissingInSource'));
        DiagnosticAddendum.namedParamTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.namedParamTypeMismatch'));
        DiagnosticAddendum.namedTupleNotAllowed = () => getRawString('DiagnosticAddendum.namedTupleNotAllowed');
        DiagnosticAddendum.newMethodLocation = () => new ParameterizedString(getRawString('DiagnosticAddendum.newMethodLocation'));
        DiagnosticAddendum.newMethodSignature = () => new ParameterizedString(getRawString('DiagnosticAddendum.newMethodSignature'));
        DiagnosticAddendum.noneNotAllowed = () => getRawString('DiagnosticAddendum.noneNotAllowed');
        DiagnosticAddendum.newTypeClassNotAllowed = () => getRawString('DiagnosticAddendum.newTypeClassNotAllowed');
        DiagnosticAddendum.noOverloadAssignable = () => new ParameterizedString(getRawString('DiagnosticAddendum.noOverloadAssignable'));
        DiagnosticAddendum.orPatternMissingName = () => new ParameterizedString(getRawString('DiagnosticAddendum.orPatternMissingName'));
        DiagnosticAddendum.overloadIndex = () => new ParameterizedString(getRawString('DiagnosticAddendum.overloadIndex'));
        DiagnosticAddendum.overloadSignature = () => getRawString('DiagnosticAddendum.overloadSignature');
        DiagnosticAddendum.overloadNotAssignable = () => new ParameterizedString(getRawString('DiagnosticAddendum.overloadNotAssignable'));
        DiagnosticAddendum.overriddenMethod = () => getRawString('DiagnosticAddendum.overriddenMethod');
        DiagnosticAddendum.overriddenSymbol = () => getRawString('DiagnosticAddendum.overriddenSymbol');
        DiagnosticAddendum.overrideIsInvariant = () => getRawString('DiagnosticAddendum.overrideIsInvariant');
        DiagnosticAddendum.overrideInvariantMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideInvariantMismatch'));
        DiagnosticAddendum.overrideNoOverloadMatches = () => getRawString('DiagnosticAddendum.overrideNoOverloadMatches');
        DiagnosticAddendum.overrideNotClassMethod = () => getRawString('DiagnosticAddendum.overrideNotClassMethod');
        DiagnosticAddendum.overrideNotInstanceMethod = () => getRawString('DiagnosticAddendum.overrideNotInstanceMethod');
        DiagnosticAddendum.overrideNotStaticMethod = () => getRawString('DiagnosticAddendum.overrideNotStaticMethod');
        DiagnosticAddendum.overrideOverloadNoMatch = () => getRawString('DiagnosticAddendum.overrideOverloadNoMatch');
        DiagnosticAddendum.overrideOverloadOrder = () => getRawString('DiagnosticAddendum.overrideOverloadOrder');
        DiagnosticAddendum.overrideParamKeywordNoDefault = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamKeywordNoDefault'));
        DiagnosticAddendum.overrideParamKeywordType = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamKeywordType'));
        DiagnosticAddendum.overrideParamName = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamName'));
        DiagnosticAddendum.overrideParamNameExtra = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamNameExtra'));
        DiagnosticAddendum.overrideParamNameMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamNameMissing'));
        DiagnosticAddendum.overrideParamNamePositionOnly = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamNamePositionOnly'));
        DiagnosticAddendum.overrideParamNoDefault = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamNoDefault'));
        DiagnosticAddendum.overrideParamType = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideParamType'));
        DiagnosticAddendum.overridePositionalParamCount = () => new ParameterizedString(getRawString('DiagnosticAddendum.overridePositionalParamCount'));
        DiagnosticAddendum.overrideReturnType = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideReturnType'));
        DiagnosticAddendum.overrideType = () => new ParameterizedString(getRawString('DiagnosticAddendum.overrideType'));
        DiagnosticAddendum.paramAssignment = () => new ParameterizedString(getRawString('DiagnosticAddendum.paramAssignment'));
        DiagnosticAddendum.paramSpecMissingInOverride = () => getRawString('DiagnosticAddendum.paramSpecMissingInOverride');
        DiagnosticAddendum.paramType = () => new ParameterizedString(getRawString('DiagnosticAddendum.paramType'));
        DiagnosticAddendum.privateImportFromPyTypedSource = () => new ParameterizedString(getRawString('DiagnosticAddendum.privateImportFromPyTypedSource'));
        DiagnosticAddendum.propertyAccessFromProtocolClass = () => getRawString('DiagnosticAddendum.propertyAccessFromProtocolClass');
        DiagnosticAddendum.propertyMethodIncompatible = () => new ParameterizedString(getRawString('DiagnosticAddendum.propertyMethodIncompatible'));
        DiagnosticAddendum.propertyMethodMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.propertyMethodMissing'));
        DiagnosticAddendum.propertyMissingDeleter = () => new ParameterizedString(getRawString('DiagnosticAddendum.propertyMissingDeleter'));
        DiagnosticAddendum.propertyMissingSetter = () => new ParameterizedString(getRawString('DiagnosticAddendum.propertyMissingSetter'));
        DiagnosticAddendum.protocolIncompatible = () => new ParameterizedString(getRawString('DiagnosticAddendum.protocolIncompatible'));
        DiagnosticAddendum.protocolMemberMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.protocolMemberMissing'));
        DiagnosticAddendum.protocolRequiresRuntimeCheckable = () => getRawString('DiagnosticAddendum.protocolRequiresRuntimeCheckable');
        DiagnosticAddendum.protocolSourceIsNotConcrete = () => new ParameterizedString(getRawString('DiagnosticAddendum.protocolSourceIsNotConcrete'));
        DiagnosticAddendum.protocolUnsafeOverlap = () => new ParameterizedString(getRawString('DiagnosticAddendum.protocolUnsafeOverlap'));
        DiagnosticAddendum.pyrightCommentIgnoreTip = () => getRawString('DiagnosticAddendum.pyrightCommentIgnoreTip');
        DiagnosticAddendum.readOnlyAttribute = () => new ParameterizedString(getRawString('DiagnosticAddendum.readOnlyAttribute'));
        DiagnosticAddendum.seeDeclaration = () => getRawString('DiagnosticAddendum.seeDeclaration');
        DiagnosticAddendum.seeClassDeclaration = () => getRawString('DiagnosticAddendum.seeClassDeclaration');
        DiagnosticAddendum.seeFunctionDeclaration = () => getRawString('DiagnosticAddendum.seeFunctionDeclaration');
        DiagnosticAddendum.seeMethodDeclaration = () => getRawString('DiagnosticAddendum.seeMethodDeclaration');
        DiagnosticAddendum.seeParameterDeclaration = () => getRawString('DiagnosticAddendum.seeParameterDeclaration');
        DiagnosticAddendum.seeTypeAliasDeclaration = () => getRawString('DiagnosticAddendum.seeTypeAliasDeclaration');
        DiagnosticAddendum.seeVariableDeclaration = () => getRawString('DiagnosticAddendum.seeVariableDeclaration');
        DiagnosticAddendum.tupleEntryTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleEntryTypeMismatch'));
        DiagnosticAddendum.tupleAssignmentMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleAssignmentMismatch'));
        DiagnosticAddendum.tupleSizeIndeterminateSrc = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleSizeIndeterminateSrc'));
        DiagnosticAddendum.tupleSizeIndeterminateSrcDest = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleSizeIndeterminateSrcDest'));
        DiagnosticAddendum.tupleSizeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleSizeMismatch'));
        DiagnosticAddendum.tupleSizeMismatchIndeterminateDest = () => new ParameterizedString(getRawString('DiagnosticAddendum.tupleSizeMismatchIndeterminateDest'));
        DiagnosticAddendum.typeAliasInstanceCheck = () => getRawString('DiagnosticAddendum.typeAliasInstanceCheck');
        DiagnosticAddendum.typeAssignmentMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeAssignmentMismatch'));
        DiagnosticAddendum.typeBound = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeBound'));
        DiagnosticAddendum.typeConstrainedTypeVar = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeConstrainedTypeVar'));
        DiagnosticAddendum.typedDictBaseClass = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictBaseClass'));
        DiagnosticAddendum.typedDictClassNotAllowed = () => getRawString('DiagnosticAddendum.typedDictClassNotAllowed');
        DiagnosticAddendum.typedDictExtraFieldNotAllowed = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictExtraFieldNotAllowed'));
        DiagnosticAddendum.typedDictExtraFieldTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictExtraFieldTypeMismatch'));
        DiagnosticAddendum.typedDictFieldMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldMissing'));
        DiagnosticAddendum.typedDictClosedExtraNotAllowed = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictClosedExtraNotAllowed'));
        DiagnosticAddendum.typedDictClosedExtraTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictClosedExtraTypeMismatch'));
        DiagnosticAddendum.typedDictClosedFieldNotRequired = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictClosedFieldNotRequired'));
        DiagnosticAddendum.typedDictFieldNotReadOnly = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldNotReadOnly'));
        DiagnosticAddendum.typedDictFieldNotRequired = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldNotRequired'));
        DiagnosticAddendum.typedDictFieldRequired = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldRequired'));
        DiagnosticAddendum.typedDictFieldTypeMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldTypeMismatch'));
        DiagnosticAddendum.typedDictFieldUndefined = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFieldUndefined'));
        DiagnosticAddendum.typedDictFinalMismatch = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictFinalMismatch'));
        DiagnosticAddendum.typedDictKeyAccess = () => new ParameterizedString(getRawString('DiagnosticAddendum.typedDictKeyAccess'));
        DiagnosticAddendum.typedDictNotAllowed = () => getRawString('DiagnosticAddendum.typedDictNotAllowed');
        DiagnosticAddendum.typeIncompatible = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeIncompatible'));
        DiagnosticAddendum.typeNotClass = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeNotClass'));
        DiagnosticAddendum.typeParamSpec = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeParamSpec'));
        DiagnosticAddendum.typeNotStringLiteral = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeNotStringLiteral'));
        DiagnosticAddendum.typeOfSymbol = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeOfSymbol'));
        DiagnosticAddendum.typeUnsupported = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeUnsupported'));
        DiagnosticAddendum.typeVarDefaultOutOfScope = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarDefaultOutOfScope'));
        DiagnosticAddendum.typeVarIsContravariant = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarIsContravariant'));
        DiagnosticAddendum.typeVarIsCovariant = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarIsCovariant'));
        DiagnosticAddendum.typeVarIsInvariant = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarIsInvariant'));
        DiagnosticAddendum.typeVarsMissing = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarsMissing'));
        DiagnosticAddendum.typeVarNotAllowed = () => getRawString('DiagnosticAddendum.typeVarNotAllowed');
        DiagnosticAddendum.typeVarTupleRequiresKnownLength = () => getRawString('DiagnosticAddendum.typeVarTupleRequiresKnownLength');
        DiagnosticAddendum.typeVarUnnecessarySuggestion = () => new ParameterizedString(getRawString('DiagnosticAddendum.typeVarUnnecessarySuggestion'));
        DiagnosticAddendum.typeVarUnsolvableRemedy = () => getRawString('DiagnosticAddendum.typeVarUnsolvableRemedy');
        DiagnosticAddendum.unhashableType = () => new ParameterizedString(getRawString('DiagnosticAddendum.unhashableType'));
        DiagnosticAddendum.uninitializedAbstractVariable = () => new ParameterizedString(getRawString('DiagnosticAddendum.uninitializedAbstractVariable'));
        DiagnosticAddendum.unreachableExcept = () => new ParameterizedString(getRawString('DiagnosticAddendum.unreachableExcept'));
        DiagnosticAddendum.useDictInstead = () => getRawString('DiagnosticAddendum.useDictInstead');
        DiagnosticAddendum.useListInstead = () => getRawString('DiagnosticAddendum.useListInstead');
        DiagnosticAddendum.useTupleInstead = () => getRawString('DiagnosticAddendum.useTupleInstead');
        DiagnosticAddendum.useTypeInstead = () => getRawString('DiagnosticAddendum.useTypeInstead');
        DiagnosticAddendum.varianceMismatchForClass = () => new ParameterizedString(getRawString('DiagnosticAddendum.varianceMismatchForClass'));
        DiagnosticAddendum.varianceMismatchForTypeAlias = () => new ParameterizedString(getRawString('DiagnosticAddendum.varianceMismatchForTypeAlias'));
        DiagnosticAddendum.explicitRelativeImportSuggestion = () => new ParameterizedString(getRawString('DiagnosticAddendum.explicitRelativeImportSuggestion'));
        DiagnosticAddendum.fullPathImportSuggestion = () => new ParameterizedString(getRawString('DiagnosticAddendum.fullPathImportSuggestion'));
    })(DiagnosticAddendum = Localizer.DiagnosticAddendum || (Localizer.DiagnosticAddendum = {}));
    let CodeAction;
    (function (CodeAction) {
        CodeAction.createTypeStub = () => getRawString('CodeAction.createTypeStub');
        CodeAction.createTypeStubFor = () => new ParameterizedString(getRawString('CodeAction.createTypeStubFor'));
        CodeAction.executingCommand = () => getRawString('CodeAction.executingCommand');
        CodeAction.filesToAnalyzeOne = () => getRawString('CodeAction.filesToAnalyzeOne');
        CodeAction.filesToAnalyzeCount = () => new ParameterizedString(getRawString('CodeAction.filesToAnalyzeCount'));
        CodeAction.findingReferences = () => getRawString('CodeAction.findingReferences');
        CodeAction.organizeImports = () => getRawString('CodeAction.organizeImports');
        CodeAction.renameShadowedFile = () => new ParameterizedString(getRawString('CodeAction.renameShadowedFile'));
    })(CodeAction = Localizer.CodeAction || (Localizer.CodeAction = {}));
    let Completion;
    (function (Completion) {
        Completion.autoImportDetail = () => getRawString('Completion.autoImportDetail');
        Completion.indexValueDetail = () => getRawString('Completion.indexValueDetail');
    })(Completion = Localizer.Completion || (Localizer.Completion = {}));
})(Localizer || (exports.Localizer = Localizer = {}));
exports.LocMessage = Localizer.Diagnostic;
exports.LocAddendum = Localizer.DiagnosticAddendum;


/***/ }),

/***/ "../pyright-internal/src/nodeMain.ts":
/*!*******************************************!*\
  !*** ../pyright-internal/src/nodeMain.ts ***!
  \*******************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * nodeMain.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Provides the main entrypoint to the server when running in Node.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.main = void 0;
const backgroundAnalysis_1 = __webpack_require__(/*! ./backgroundAnalysis */ "../pyright-internal/src/backgroundAnalysis.ts");
const serviceProvider_1 = __webpack_require__(/*! ./common/serviceProvider */ "../pyright-internal/src/common/serviceProvider.ts");
const nodeServer_1 = __webpack_require__(/*! ./nodeServer */ "../pyright-internal/src/nodeServer.ts");
const server_1 = __webpack_require__(/*! ./server */ "../pyright-internal/src/server.ts");
function main(maxWorkers) {
    (0, nodeServer_1.run)((conn) => new server_1.PyrightServer(conn, maxWorkers), () => {
        const runner = new backgroundAnalysis_1.BackgroundAnalysisRunner(new serviceProvider_1.ServiceProvider());
        runner.start();
    });
}
exports.main = main;


/***/ }),

/***/ "../pyright-internal/src/nodeServer.ts":
/*!*********************************************!*\
  !*** ../pyright-internal/src/nodeServer.ts ***!
  \*********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * nodeServer.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Implements utilities for starting the language server in a node environment.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getConnectionOptions = exports.run = void 0;
const node_1 = __webpack_require__(/*! vscode-languageserver/node */ "../pyright-internal/node_modules/vscode-languageserver/node.js");
const worker_threads_1 = __webpack_require__(/*! worker_threads */ "worker_threads");
const fileBasedCancellationUtils_1 = __webpack_require__(/*! ./common/fileBasedCancellationUtils */ "../pyright-internal/src/common/fileBasedCancellationUtils.ts");
function run(runServer, runBackgroundThread) {
    if (false) {}
    if (worker_threads_1.isMainThread) {
        runServer((0, node_1.createConnection)(getConnectionOptions()));
    }
    else {
        runBackgroundThread();
    }
}
exports.run = run;
function getConnectionOptions() {
    return { cancellationStrategy: (0, fileBasedCancellationUtils_1.getCancellationStrategyFromArgv)(process.argv) };
}
exports.getConnectionOptions = getConnectionOptions;


/***/ }),

/***/ "../pyright-internal/src/parser/characterStream.ts":
/*!*********************************************************!*\
  !*** ../pyright-internal/src/parser/characterStream.ts ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * characterStream.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from vscode-python repository:
 *  https://github.com/Microsoft/vscode-python
 *
 * Class that represents a stream of characters.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CharacterStream = void 0;
const characters_1 = __webpack_require__(/*! ./characters */ "../pyright-internal/src/parser/characters.ts");
class CharacterStream {
    constructor(text) {
        this._text = text;
        this._position = 0;
        this._currentChar = text.length > 0 ? text.charCodeAt(0) : 0;
        this._isEndOfStream = text.length === 0;
    }
    get position() {
        return this._position;
    }
    set position(value) {
        this._position = value;
        this._checkBounds();
    }
    get currentChar() {
        return this._currentChar;
    }
    get nextChar() {
        return this.position + 1 < this._text.length ? this._text.charCodeAt(this.position + 1) : 0;
    }
    get prevChar() {
        return this.position - 1 >= 0 ? this._text.charCodeAt(this.position - 1) : 0;
    }
    get length() {
        return this._text.length;
    }
    getText() {
        return this._text;
    }
    // We also expose a (non-property) method that is
    // the equivalent of currentChar above. This allows
    // us to work around assumptions in the TypeScript
    // compiler that method calls (e.g. moveNext()) don't
    // modify properties.
    getCurrentChar() {
        return this._currentChar;
    }
    isEndOfStream() {
        return this._isEndOfStream;
    }
    lookAhead(offset) {
        const pos = this._position + offset;
        return pos < 0 || pos >= this._text.length ? 0 : this._text.charCodeAt(pos);
    }
    advance(offset) {
        this.position += offset;
    }
    moveNext() {
        if (this._position < this._text.length - 1) {
            // Most common case, no need to check bounds extensively
            this._position += 1;
            this._currentChar = this._text.charCodeAt(this._position);
            return true;
        }
        this.advance(1);
        return !this.isEndOfStream();
    }
    isAtWhiteSpace() {
        return (0, characters_1.isWhiteSpace)(this.currentChar);
    }
    isAtLineBreak() {
        return (0, characters_1.isLineBreak)(this.currentChar);
    }
    skipLineBreak() {
        if (this._currentChar === 13 /* Char.CarriageReturn */) {
            this.moveNext();
            if (this.currentChar === 10 /* Char.LineFeed */) {
                this.moveNext();
            }
        }
        else if (this._currentChar === 10 /* Char.LineFeed */) {
            this.moveNext();
        }
    }
    skipWhitespace() {
        while (!this.isEndOfStream() && this.isAtWhiteSpace()) {
            this.moveNext();
        }
    }
    skipToEol() {
        while (!this.isEndOfStream() && !this.isAtLineBreak()) {
            this.moveNext();
        }
    }
    skipToWhitespace() {
        while (!this.isEndOfStream() && !this.isAtWhiteSpace()) {
            this.moveNext();
        }
    }
    charCodeAt(index) {
        return this._text.charCodeAt(index);
    }
    _checkBounds() {
        if (this._position < 0) {
            this._position = 0;
        }
        this._isEndOfStream = this._position >= this._text.length;
        if (this._isEndOfStream) {
            this._position = this._text.length;
        }
        this._currentChar = this._isEndOfStream ? 0 : this._text.charCodeAt(this._position);
    }
}
exports.CharacterStream = CharacterStream;


/***/ }),

/***/ "../pyright-internal/src/parser/characters.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/parser/characters.ts ***!
  \****************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * characters.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from vscode-python repository:
 *  https://github.com/Microsoft/vscode-python
 *
 * Utility routines used by tokenizer.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isBinary = exports.isOctal = exports.isHex = exports.isDecimal = exports.isNumber = exports.isLineBreak = exports.isWhiteSpace = exports.isSurrogateChar = exports.isIdentifierChar = exports.isIdentifierStartChar = void 0;
const unicode = __importStar(__webpack_require__(/*! ./unicode */ "../pyright-internal/src/parser/unicode.ts"));
var CharCategory;
(function (CharCategory) {
    // Character cannot appear in identifier
    CharCategory[CharCategory["NotIdentifierChar"] = 0] = "NotIdentifierChar";
    // Character can appear at beginning or within identifier
    CharCategory[CharCategory["StartIdentifierChar"] = 1] = "StartIdentifierChar";
    // Character can appear only within identifier, not at beginning
    CharCategory[CharCategory["IdentifierChar"] = 2] = "IdentifierChar";
    // Character is a surrogate, meaning that additional character
    // needs to be consulted.
    CharCategory[CharCategory["SurrogateChar"] = 3] = "SurrogateChar";
})(CharCategory || (CharCategory = {}));
// Table of first 256 character codes (the most common cases).
const _identifierCharFastTableSize = 256;
const _identifierCharFastTable = new Array(_identifierCharFastTableSize);
const _identifierCharMap = {};
// Secondary character map based on the primary (surrogate) character.
const _surrogateCharMap = {};
// We do lazy initialization of this map because it's rarely used.
let _identifierCharMapInitialized = false;
function isIdentifierStartChar(char, nextChar) {
    if (char < _identifierCharFastTableSize) {
        return _identifierCharFastTable[char] === CharCategory.StartIdentifierChar;
    }
    // Lazy initialize the char map. We'll rarely get here.
    if (!_identifierCharMapInitialized) {
        _buildIdentifierLookupTable(false);
        _identifierCharMapInitialized = true;
    }
    let charCategory;
    if (nextChar !== undefined) {
        charCategory = _lookUpSurrogate(char, nextChar);
    }
    else {
        charCategory = _identifierCharMap[char];
    }
    return charCategory === CharCategory.StartIdentifierChar;
}
exports.isIdentifierStartChar = isIdentifierStartChar;
function isIdentifierChar(char, nextChar) {
    if (char < _identifierCharFastTableSize) {
        return (_identifierCharFastTable[char] === CharCategory.StartIdentifierChar ||
            _identifierCharFastTable[char] === CharCategory.IdentifierChar);
    }
    // Lazy initialize the char map. We'll rarely get here.
    if (!_identifierCharMapInitialized) {
        _buildIdentifierLookupTable(false);
        _identifierCharMapInitialized = true;
    }
    if (nextChar !== undefined) {
        return _lookUpSurrogate(char, nextChar);
    }
    return (_identifierCharMap[char] === CharCategory.StartIdentifierChar ||
        _identifierCharMap[char] === CharCategory.IdentifierChar);
}
exports.isIdentifierChar = isIdentifierChar;
function isSurrogateChar(char) {
    if (char < _identifierCharFastTableSize) {
        return false;
    }
    // Lazy initialize the char map. We'll rarely get here.
    if (!_identifierCharMapInitialized) {
        _buildIdentifierLookupTable(false);
        _identifierCharMapInitialized = true;
    }
    return _identifierCharMap[char] === CharCategory.SurrogateChar;
}
exports.isSurrogateChar = isSurrogateChar;
function isWhiteSpace(ch) {
    return ch === 32 /* Char.Space */ || ch === 9 /* Char.Tab */ || ch === 12 /* Char.FormFeed */;
}
exports.isWhiteSpace = isWhiteSpace;
function isLineBreak(ch) {
    return ch === 13 /* Char.CarriageReturn */ || ch === 10 /* Char.LineFeed */;
}
exports.isLineBreak = isLineBreak;
function isNumber(ch) {
    return (ch >= 48 /* Char._0 */ && ch <= 57 /* Char._9 */) || ch === 95 /* Char.Underscore */;
}
exports.isNumber = isNumber;
function isDecimal(ch) {
    return (ch >= 48 /* Char._0 */ && ch <= 57 /* Char._9 */) || ch === 95 /* Char.Underscore */;
}
exports.isDecimal = isDecimal;
function isHex(ch) {
    return isDecimal(ch) || (ch >= 97 /* Char.a */ && ch <= 102 /* Char.f */) || (ch >= 65 /* Char.A */ && ch <= 70 /* Char.F */) || ch === 95 /* Char.Underscore */;
}
exports.isHex = isHex;
function isOctal(ch) {
    return (ch >= 48 /* Char._0 */ && ch <= 55 /* Char._7 */) || ch === 95 /* Char.Underscore */;
}
exports.isOctal = isOctal;
function isBinary(ch) {
    return ch === 48 /* Char._0 */ || ch === 49 /* Char._1 */ || ch === 95 /* Char.Underscore */;
}
exports.isBinary = isBinary;
function _lookUpSurrogate(char, nextChar) {
    if (_identifierCharMap[char] !== CharCategory.SurrogateChar) {
        return CharCategory.NotIdentifierChar;
    }
    const surrogateTable = _surrogateCharMap[char];
    if (!surrogateTable) {
        return CharCategory.NotIdentifierChar;
    }
    return surrogateTable[nextChar];
}
// Underscore is explicitly allowed to start an identifier.
// Characters with the Other_ID_Start property.
const _specialStartIdentifierChars = [
    95 /* Char.Underscore */,
    0x1885,
    0x1886,
    0x2118,
    0x212e,
    0x309b,
    0x309c,
];
const _startIdentifierCharRanges = [
    _specialStartIdentifierChars,
    unicode.unicodeLu,
    unicode.unicodeLl,
    unicode.unicodeLt,
    unicode.unicodeLo,
    unicode.unicodeLm,
    unicode.unicodeNl,
];
const _startCharSurrogateRanges = [
    unicode.unicodeLuSurrogate,
    unicode.unicodeLlSurrogate,
    unicode.unicodeLoSurrogate,
    unicode.unicodeLmSurrogate,
    unicode.unicodeNlSurrogate,
];
// Characters with the Other_ID_Start property.
const _specialIdentifierChars = [
    0x00b7, 0x0387, 0x1369, 0x136a, 0x136b, 0x136c, 0x136d, 0x136e, 0x136f, 0x1370, 0x1371, 0x19da,
];
const _identifierCharRanges = [
    _specialIdentifierChars,
    unicode.unicodeMn,
    unicode.unicodeMc,
    unicode.unicodeNd,
    unicode.unicodePc,
];
const _identifierCharSurrogateRanges = [
    unicode.unicodeMnSurrogate,
    unicode.unicodeMcSurrogate,
    unicode.unicodeNdSurrogate,
];
function _buildIdentifierLookupTableFromUnicodeRangeTable(table, category, fastTableOnly, fastTable, fullTable) {
    for (let entryIndex = 0; entryIndex < table.length; entryIndex++) {
        const entry = table[entryIndex];
        let rangeStart;
        let rangeEnd;
        if (Array.isArray(entry)) {
            rangeStart = entry[0];
            rangeEnd = entry[1];
        }
        else {
            rangeStart = rangeEnd = entry;
        }
        for (let i = rangeStart; i <= rangeEnd; i++) {
            if (i < _identifierCharFastTableSize) {
                fastTable[i] = category;
            }
            else {
                fullTable[i] = category;
            }
        }
        if (fastTableOnly && rangeStart >= _identifierCharFastTableSize) {
            break;
        }
    }
}
function _buildIdentifierLookupTableFromSurrogateRangeTable(surrogateTable, category) {
    for (const surrogateChar in surrogateTable) {
        if (!_surrogateCharMap[surrogateChar]) {
            _surrogateCharMap[surrogateChar] = {};
            _identifierCharMap[surrogateChar] = CharCategory.SurrogateChar;
        }
        _buildIdentifierLookupTableFromUnicodeRangeTable(surrogateTable[surrogateChar], category, 
        /* fastTableOnly */ false, _surrogateCharMap[surrogateChar], _surrogateCharMap[surrogateChar]);
    }
}
// Build a lookup table for to speed up tokenization of identifiers.
function _buildIdentifierLookupTable(fastTableOnly) {
    _identifierCharFastTable.fill(CharCategory.NotIdentifierChar);
    _identifierCharRanges.forEach((table) => {
        _buildIdentifierLookupTableFromUnicodeRangeTable(table, CharCategory.IdentifierChar, fastTableOnly, _identifierCharFastTable, _identifierCharMap);
    });
    _startIdentifierCharRanges.forEach((table) => {
        _buildIdentifierLookupTableFromUnicodeRangeTable(table, CharCategory.StartIdentifierChar, fastTableOnly, _identifierCharFastTable, _identifierCharMap);
    });
    // Populate the surrogate tables for characters that require two
    // character codes.
    if (!fastTableOnly) {
        for (const surrogateTable of _identifierCharSurrogateRanges) {
            _buildIdentifierLookupTableFromSurrogateRangeTable(surrogateTable, CharCategory.IdentifierChar);
        }
        for (const surrogateTable of _startCharSurrogateRanges) {
            _buildIdentifierLookupTableFromSurrogateRangeTable(surrogateTable, CharCategory.StartIdentifierChar);
        }
    }
}
_buildIdentifierLookupTable(true);


/***/ }),

/***/ "../pyright-internal/src/parser/parseNodes.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/parser/parseNodes.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * parseNodes.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Definition of parse nodes that make up the Python abstract
 * syntax tree (AST).
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.StringListNode = exports.FormatStringNode = exports.StringNode = exports.NumberNode = exports.EllipsisNode = exports.ConstantNode = exports.NameNode = exports.LambdaNode = exports.MemberAccessNode = exports.YieldFromNode = exports.YieldNode = exports.SliceNode = exports.IndexNode = exports.ListComprehensionNode = exports.CallNode = exports.TupleNode = exports.UnpackNode = exports.TernaryNode = exports.AwaitNode = exports.AugmentedAssignmentNode = exports.FunctionAnnotationNode = exports.TypeAnnotationNode = exports.TypeAliasNode = exports.TypeParameterListNode = exports.TypeParameterNode = exports.TypeParameterCategory = exports.AssignmentNode = exports.AssignmentExpressionNode = exports.BinaryOperationNode = exports.UnaryOperationNode = exports.ErrorNode = exports.isExpressionNode = exports.StatementListNode = exports.DecoratorNode = exports.WithItemNode = exports.WithNode = exports.ClassNode = exports.ParameterNode = exports.FunctionNode = exports.ExceptNode = exports.TryNode = exports.ListComprehensionIfNode = exports.ListComprehensionForNode = exports.ForNode = exports.WhileNode = exports.IfNode = exports.SuiteNode = exports.ModuleNode = exports.extendRange = exports.getNextNodeId = void 0;
exports.PatternValueNode = exports.PatternMappingExpandEntryNode = exports.PatternMappingKeyEntryNode = exports.PatternMappingNode = exports.PatternCaptureNode = exports.PatternClassArgumentNode = exports.PatternClassNode = exports.PatternLiteralNode = exports.PatternAsNode = exports.PatternSequenceNode = exports.CaseNode = exports.MatchNode = exports.RaiseNode = exports.ReturnNode = exports.ContinueNode = exports.BreakNode = exports.AssertNode = exports.NonlocalNode = exports.GlobalNode = exports.ImportFromAsNode = exports.ImportFromNode = exports.ImportAsNode = exports.ModuleNameNode = exports.ImportNode = exports.PassNode = exports.DelNode = exports.ArgumentNode = exports.ListNode = exports.SetNode = exports.DictionaryExpandEntryNode = exports.DictionaryKeyEntryNode = exports.DictionaryNode = void 0;
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
let _nextNodeId = 1;
function getNextNodeId() {
    return _nextNodeId++;
}
exports.getNextNodeId = getNextNodeId;
function extendRange(node, newRange) {
    const extendedRange = textRange_1.TextRange.extend(node, newRange);
    // Temporarily allow writes to the range fields.
    const mutableNode = node;
    mutableNode.start = extendedRange.start;
    mutableNode.length = extendedRange.length;
}
exports.extendRange = extendRange;
var ModuleNode;
(function (ModuleNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 36 /* ParseNodeType.Module */,
            id: _nextNodeId++,
            statements: [],
        };
        return node;
    }
    ModuleNode.create = create;
})(ModuleNode || (exports.ModuleNode = ModuleNode = {}));
var SuiteNode;
(function (SuiteNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 50 /* ParseNodeType.Suite */,
            id: _nextNodeId++,
            statements: [],
        };
        return node;
    }
    SuiteNode.create = create;
})(SuiteNode || (exports.SuiteNode = SuiteNode = {}));
var IfNode;
(function (IfNode) {
    function create(ifOrElifToken, testExpression, ifSuite, elseSuite) {
        const node = {
            start: ifOrElifToken.start,
            length: ifOrElifToken.length,
            nodeType: 19 /* ParseNodeType.If */,
            id: _nextNodeId++,
            testExpression,
            ifSuite,
            elseSuite,
        };
        testExpression.parent = node;
        ifSuite.parent = node;
        extendRange(node, testExpression);
        extendRange(node, ifSuite);
        if (elseSuite) {
            extendRange(node, elseSuite);
            elseSuite.parent = node;
        }
        return node;
    }
    IfNode.create = create;
})(IfNode || (exports.IfNode = IfNode = {}));
var WhileNode;
(function (WhileNode) {
    function create(whileToken, testExpression, whileSuite) {
        const node = {
            start: whileToken.start,
            length: whileToken.length,
            nodeType: 57 /* ParseNodeType.While */,
            id: _nextNodeId++,
            testExpression,
            whileSuite,
        };
        testExpression.parent = node;
        whileSuite.parent = node;
        extendRange(node, whileSuite);
        return node;
    }
    WhileNode.create = create;
})(WhileNode || (exports.WhileNode = WhileNode = {}));
var ForNode;
(function (ForNode) {
    function create(forToken, targetExpression, iterableExpression, forSuite) {
        const node = {
            start: forToken.start,
            length: forToken.length,
            nodeType: 26 /* ParseNodeType.For */,
            id: _nextNodeId++,
            targetExpression,
            iterableExpression,
            forSuite,
        };
        targetExpression.parent = node;
        iterableExpression.parent = node;
        forSuite.parent = node;
        extendRange(node, forSuite);
        return node;
    }
    ForNode.create = create;
})(ForNode || (exports.ForNode = ForNode = {}));
var ListComprehensionForNode;
(function (ListComprehensionForNode) {
    function create(startToken, targetExpression, iterableExpression) {
        const node = {
            start: startToken.start,
            length: startToken.length,
            nodeType: 33 /* ParseNodeType.ListComprehensionFor */,
            id: _nextNodeId++,
            targetExpression,
            iterableExpression,
        };
        targetExpression.parent = node;
        iterableExpression.parent = node;
        extendRange(node, targetExpression);
        extendRange(node, iterableExpression);
        return node;
    }
    ListComprehensionForNode.create = create;
})(ListComprehensionForNode || (exports.ListComprehensionForNode = ListComprehensionForNode = {}));
var ListComprehensionIfNode;
(function (ListComprehensionIfNode) {
    function create(ifToken, testExpression) {
        const node = {
            start: ifToken.start,
            length: ifToken.length,
            nodeType: 34 /* ParseNodeType.ListComprehensionIf */,
            id: _nextNodeId++,
            testExpression,
        };
        testExpression.parent = node;
        extendRange(node, testExpression);
        return node;
    }
    ListComprehensionIfNode.create = create;
})(ListComprehensionIfNode || (exports.ListComprehensionIfNode = ListComprehensionIfNode = {}));
var TryNode;
(function (TryNode) {
    function create(tryToken, trySuite) {
        const node = {
            start: tryToken.start,
            length: tryToken.length,
            nodeType: 53 /* ParseNodeType.Try */,
            id: _nextNodeId++,
            trySuite,
            exceptClauses: [],
        };
        trySuite.parent = node;
        extendRange(node, trySuite);
        return node;
    }
    TryNode.create = create;
})(TryNode || (exports.TryNode = TryNode = {}));
var ExceptNode;
(function (ExceptNode) {
    function create(exceptToken, exceptSuite, isExceptGroup) {
        const node = {
            start: exceptToken.start,
            length: exceptToken.length,
            nodeType: 25 /* ParseNodeType.Except */,
            id: _nextNodeId++,
            exceptSuite,
            isExceptGroup,
        };
        exceptSuite.parent = node;
        extendRange(node, exceptSuite);
        return node;
    }
    ExceptNode.create = create;
})(ExceptNode || (exports.ExceptNode = ExceptNode = {}));
var FunctionNode;
(function (FunctionNode) {
    function create(defToken, name, suite, typeParameters) {
        const node = {
            start: defToken.start,
            length: defToken.length,
            nodeType: 28 /* ParseNodeType.Function */,
            id: _nextNodeId++,
            decorators: [],
            name,
            typeParameters,
            parameters: [],
            suite,
        };
        name.parent = node;
        suite.parent = node;
        if (typeParameters) {
            typeParameters.parent = node;
        }
        extendRange(node, suite);
        return node;
    }
    FunctionNode.create = create;
})(FunctionNode || (exports.FunctionNode = FunctionNode = {}));
var ParameterNode;
(function (ParameterNode) {
    function create(startToken, paramCategory) {
        const node = {
            start: startToken.start,
            length: startToken.length,
            nodeType: 41 /* ParseNodeType.Parameter */,
            id: _nextNodeId++,
            category: paramCategory,
        };
        return node;
    }
    ParameterNode.create = create;
})(ParameterNode || (exports.ParameterNode = ParameterNode = {}));
var ClassNode;
(function (ClassNode) {
    function create(classToken, name, suite, typeParameters) {
        const node = {
            start: classToken.start,
            length: classToken.length,
            nodeType: 10 /* ParseNodeType.Class */,
            id: _nextNodeId++,
            decorators: [],
            name,
            typeParameters,
            arguments: [],
            suite,
        };
        name.parent = node;
        suite.parent = node;
        if (typeParameters) {
            typeParameters.parent = node;
        }
        extendRange(node, suite);
        return node;
    }
    ClassNode.create = create;
    // This variant is used to create a dummy class
    // when the parser encounters decorators with no
    // function or class declaration.
    function createDummyForDecorators(decorators) {
        const node = {
            start: decorators[0].start,
            length: 0,
            nodeType: 10 /* ParseNodeType.Class */,
            id: _nextNodeId++,
            decorators,
            name: {
                start: decorators[0].start,
                length: 0,
                id: 0,
                nodeType: 38 /* ParseNodeType.Name */,
                token: {
                    type: 7 /* TokenType.Identifier */,
                    start: 0,
                    length: 0,
                    comments: [],
                    value: '',
                },
                value: '',
            },
            arguments: [],
            suite: {
                start: decorators[0].start,
                length: 0,
                id: 0,
                nodeType: 50 /* ParseNodeType.Suite */,
                statements: [],
            },
        };
        decorators.forEach((decorator) => {
            decorator.parent = node;
            extendRange(node, decorator);
        });
        node.name.parent = node;
        node.suite.parent = node;
        return node;
    }
    ClassNode.createDummyForDecorators = createDummyForDecorators;
})(ClassNode || (exports.ClassNode = ClassNode = {}));
var WithNode;
(function (WithNode) {
    function create(withToken, suite) {
        const node = {
            start: withToken.start,
            length: withToken.length,
            nodeType: 58 /* ParseNodeType.With */,
            id: _nextNodeId++,
            withItems: [],
            suite,
        };
        suite.parent = node;
        extendRange(node, suite);
        return node;
    }
    WithNode.create = create;
})(WithNode || (exports.WithNode = WithNode = {}));
var WithItemNode;
(function (WithItemNode) {
    function create(expression) {
        const node = {
            start: expression.start,
            length: expression.length,
            nodeType: 59 /* ParseNodeType.WithItem */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        return node;
    }
    WithItemNode.create = create;
})(WithItemNode || (exports.WithItemNode = WithItemNode = {}));
var DecoratorNode;
(function (DecoratorNode) {
    function create(atToken, expression) {
        const node = {
            start: atToken.start,
            length: atToken.length,
            nodeType: 13 /* ParseNodeType.Decorator */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        extendRange(node, expression);
        return node;
    }
    DecoratorNode.create = create;
})(DecoratorNode || (exports.DecoratorNode = DecoratorNode = {}));
var StatementListNode;
(function (StatementListNode) {
    function create(atToken) {
        const node = {
            start: atToken.start,
            length: atToken.length,
            nodeType: 47 /* ParseNodeType.StatementList */,
            id: _nextNodeId++,
            statements: [],
        };
        return node;
    }
    StatementListNode.create = create;
})(StatementListNode || (exports.StatementListNode = StatementListNode = {}));
function isExpressionNode(node) {
    switch (node.nodeType) {
        case 0 /* ParseNodeType.Error */:
        case 55 /* ParseNodeType.UnaryOperation */:
        case 7 /* ParseNodeType.BinaryOperation */:
        case 4 /* ParseNodeType.AssignmentExpression */:
        case 54 /* ParseNodeType.TypeAnnotation */:
        case 6 /* ParseNodeType.Await */:
        case 51 /* ParseNodeType.Ternary */:
        case 56 /* ParseNodeType.Unpack */:
        case 52 /* ParseNodeType.Tuple */:
        case 9 /* ParseNodeType.Call */:
        case 32 /* ParseNodeType.ListComprehension */:
        case 24 /* ParseNodeType.Index */:
        case 46 /* ParseNodeType.Slice */:
        case 60 /* ParseNodeType.Yield */:
        case 61 /* ParseNodeType.YieldFrom */:
        case 35 /* ParseNodeType.MemberAccess */:
        case 30 /* ParseNodeType.Lambda */:
        case 38 /* ParseNodeType.Name */:
        case 11 /* ParseNodeType.Constant */:
        case 18 /* ParseNodeType.Ellipsis */:
        case 40 /* ParseNodeType.Number */:
        case 49 /* ParseNodeType.String */:
        case 27 /* ParseNodeType.FormatString */:
        case 48 /* ParseNodeType.StringList */:
        case 15 /* ParseNodeType.Dictionary */:
        case 31 /* ParseNodeType.List */:
        case 45 /* ParseNodeType.Set */:
            return true;
        default:
            return false;
    }
}
exports.isExpressionNode = isExpressionNode;
var ErrorNode;
(function (ErrorNode) {
    function create(initialRange, category, child, decorators) {
        const node = {
            start: initialRange.start,
            length: initialRange.length,
            nodeType: 0 /* ParseNodeType.Error */,
            id: _nextNodeId++,
            category,
            child,
            decorators,
        };
        if (child) {
            child.parent = node;
            extendRange(node, child);
        }
        if (decorators) {
            decorators.forEach((decorator) => {
                decorator.parent = node;
            });
            if (decorators.length > 0) {
                extendRange(node, decorators[0]);
            }
        }
        return node;
    }
    ErrorNode.create = create;
})(ErrorNode || (exports.ErrorNode = ErrorNode = {}));
var UnaryOperationNode;
(function (UnaryOperationNode) {
    function create(operatorToken, expression, operator) {
        var _a;
        const node = {
            start: operatorToken.start,
            length: operatorToken.length,
            nodeType: 55 /* ParseNodeType.UnaryOperation */,
            id: _nextNodeId++,
            operator,
            operatorToken,
            expression,
        };
        expression.parent = node;
        node.maxChildDepth = 1 + ((_a = expression.maxChildDepth) !== null && _a !== void 0 ? _a : 0);
        extendRange(node, expression);
        return node;
    }
    UnaryOperationNode.create = create;
})(UnaryOperationNode || (exports.UnaryOperationNode = UnaryOperationNode = {}));
var BinaryOperationNode;
(function (BinaryOperationNode) {
    function create(leftExpression, rightExpression, operatorToken, operator) {
        var _a, _b;
        const node = {
            start: leftExpression.start,
            length: leftExpression.length,
            nodeType: 7 /* ParseNodeType.BinaryOperation */,
            id: _nextNodeId++,
            leftExpression,
            operatorToken,
            operator,
            rightExpression,
        };
        leftExpression.parent = node;
        rightExpression.parent = node;
        node.maxChildDepth = 1 + Math.max((_a = leftExpression.maxChildDepth) !== null && _a !== void 0 ? _a : 0, (_b = rightExpression.maxChildDepth) !== null && _b !== void 0 ? _b : 0);
        extendRange(node, rightExpression);
        return node;
    }
    BinaryOperationNode.create = create;
})(BinaryOperationNode || (exports.BinaryOperationNode = BinaryOperationNode = {}));
var AssignmentExpressionNode;
(function (AssignmentExpressionNode) {
    function create(name, rightExpression) {
        const node = {
            start: name.start,
            length: name.length,
            nodeType: 4 /* ParseNodeType.AssignmentExpression */,
            id: _nextNodeId++,
            name,
            rightExpression,
        };
        name.parent = node;
        rightExpression.parent = node;
        extendRange(node, rightExpression);
        return node;
    }
    AssignmentExpressionNode.create = create;
})(AssignmentExpressionNode || (exports.AssignmentExpressionNode = AssignmentExpressionNode = {}));
var AssignmentNode;
(function (AssignmentNode) {
    function create(leftExpression, rightExpression) {
        const node = {
            start: leftExpression.start,
            length: leftExpression.length,
            nodeType: 3 /* ParseNodeType.Assignment */,
            id: _nextNodeId++,
            leftExpression,
            rightExpression,
        };
        leftExpression.parent = node;
        rightExpression.parent = node;
        extendRange(node, rightExpression);
        return node;
    }
    AssignmentNode.create = create;
})(AssignmentNode || (exports.AssignmentNode = AssignmentNode = {}));
var TypeParameterCategory;
(function (TypeParameterCategory) {
    TypeParameterCategory[TypeParameterCategory["TypeVar"] = 0] = "TypeVar";
    TypeParameterCategory[TypeParameterCategory["TypeVarTuple"] = 1] = "TypeVarTuple";
    TypeParameterCategory[TypeParameterCategory["ParamSpec"] = 2] = "ParamSpec";
})(TypeParameterCategory || (exports.TypeParameterCategory = TypeParameterCategory = {}));
var TypeParameterNode;
(function (TypeParameterNode) {
    function create(name, typeParamCategory, boundExpression, defaultExpression) {
        const node = {
            start: name.start,
            length: name.length,
            nodeType: 75 /* ParseNodeType.TypeParameter */,
            id: _nextNodeId++,
            name,
            typeParamCategory,
            boundExpression,
            defaultExpression,
        };
        name.parent = node;
        if (boundExpression) {
            boundExpression.parent = node;
            extendRange(node, boundExpression);
        }
        if (defaultExpression) {
            defaultExpression.parent = node;
            extendRange(node, defaultExpression);
        }
        return node;
    }
    TypeParameterNode.create = create;
})(TypeParameterNode || (exports.TypeParameterNode = TypeParameterNode = {}));
var TypeParameterListNode;
(function (TypeParameterListNode) {
    function create(startToken, endToken, parameters) {
        const node = {
            start: startToken.start,
            length: startToken.length,
            nodeType: 76 /* ParseNodeType.TypeParameterList */,
            id: _nextNodeId++,
            parameters,
        };
        extendRange(node, endToken);
        parameters.forEach((param) => {
            extendRange(node, param);
            param.parent = node;
        });
        return node;
    }
    TypeParameterListNode.create = create;
})(TypeParameterListNode || (exports.TypeParameterListNode = TypeParameterListNode = {}));
var TypeAliasNode;
(function (TypeAliasNode) {
    function create(typeToken, name, expression, typeParameters) {
        const node = {
            start: typeToken.start,
            length: typeToken.length,
            nodeType: 77 /* ParseNodeType.TypeAlias */,
            id: _nextNodeId++,
            name,
            typeParameters,
            expression,
        };
        name.parent = node;
        expression.parent = node;
        if (typeParameters) {
            typeParameters.parent = node;
        }
        extendRange(node, expression);
        return node;
    }
    TypeAliasNode.create = create;
})(TypeAliasNode || (exports.TypeAliasNode = TypeAliasNode = {}));
var TypeAnnotationNode;
(function (TypeAnnotationNode) {
    function create(valueExpression, typeAnnotation) {
        const node = {
            start: valueExpression.start,
            length: valueExpression.length,
            nodeType: 54 /* ParseNodeType.TypeAnnotation */,
            id: _nextNodeId++,
            valueExpression,
            typeAnnotation,
        };
        valueExpression.parent = node;
        typeAnnotation.parent = node;
        extendRange(node, typeAnnotation);
        return node;
    }
    TypeAnnotationNode.create = create;
})(TypeAnnotationNode || (exports.TypeAnnotationNode = TypeAnnotationNode = {}));
var FunctionAnnotationNode;
(function (FunctionAnnotationNode) {
    function create(openParenToken, isParamListEllipsis, paramTypeAnnotations, returnTypeAnnotation) {
        const node = {
            start: openParenToken.start,
            length: openParenToken.length,
            nodeType: 62 /* ParseNodeType.FunctionAnnotation */,
            id: _nextNodeId++,
            isParamListEllipsis,
            paramTypeAnnotations,
            returnTypeAnnotation,
        };
        paramTypeAnnotations.forEach((p) => {
            p.parent = node;
        });
        returnTypeAnnotation.parent = node;
        extendRange(node, returnTypeAnnotation);
        return node;
    }
    FunctionAnnotationNode.create = create;
})(FunctionAnnotationNode || (exports.FunctionAnnotationNode = FunctionAnnotationNode = {}));
var AugmentedAssignmentNode;
(function (AugmentedAssignmentNode) {
    function create(leftExpression, rightExpression, operator, destExpression) {
        const node = {
            start: leftExpression.start,
            length: leftExpression.length,
            nodeType: 5 /* ParseNodeType.AugmentedAssignment */,
            id: _nextNodeId++,
            leftExpression,
            operator,
            rightExpression,
            destExpression,
        };
        leftExpression.parent = node;
        rightExpression.parent = node;
        destExpression.parent = node;
        extendRange(node, rightExpression);
        return node;
    }
    AugmentedAssignmentNode.create = create;
})(AugmentedAssignmentNode || (exports.AugmentedAssignmentNode = AugmentedAssignmentNode = {}));
var AwaitNode;
(function (AwaitNode) {
    function create(awaitToken, expression) {
        const node = {
            start: awaitToken.start,
            length: awaitToken.length,
            nodeType: 6 /* ParseNodeType.Await */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        extendRange(node, expression);
        return node;
    }
    AwaitNode.create = create;
})(AwaitNode || (exports.AwaitNode = AwaitNode = {}));
var TernaryNode;
(function (TernaryNode) {
    function create(ifExpression, testExpression, elseExpression) {
        const node = {
            start: ifExpression.start,
            length: ifExpression.length,
            nodeType: 51 /* ParseNodeType.Ternary */,
            id: _nextNodeId++,
            ifExpression,
            testExpression,
            elseExpression,
        };
        ifExpression.parent = node;
        testExpression.parent = node;
        elseExpression.parent = node;
        extendRange(node, elseExpression);
        return node;
    }
    TernaryNode.create = create;
})(TernaryNode || (exports.TernaryNode = TernaryNode = {}));
var UnpackNode;
(function (UnpackNode) {
    function create(starToken, expression) {
        const node = {
            starToken,
            start: starToken.start,
            length: starToken.length,
            nodeType: 56 /* ParseNodeType.Unpack */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        extendRange(node, expression);
        return node;
    }
    UnpackNode.create = create;
})(UnpackNode || (exports.UnpackNode = UnpackNode = {}));
var TupleNode;
(function (TupleNode) {
    function create(range, enclosedInParens) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 52 /* ParseNodeType.Tuple */,
            id: _nextNodeId++,
            expressions: [],
            enclosedInParens,
        };
        return node;
    }
    TupleNode.create = create;
})(TupleNode || (exports.TupleNode = TupleNode = {}));
var CallNode;
(function (CallNode) {
    function create(leftExpression, argList, trailingComma) {
        var _a;
        const node = {
            start: leftExpression.start,
            length: leftExpression.length,
            nodeType: 9 /* ParseNodeType.Call */,
            id: _nextNodeId++,
            leftExpression,
            arguments: argList,
            trailingComma,
        };
        leftExpression.parent = node;
        node.maxChildDepth = 1 + ((_a = leftExpression.maxChildDepth) !== null && _a !== void 0 ? _a : 0);
        if (argList.length > 0) {
            argList.forEach((arg) => {
                arg.parent = node;
            });
            extendRange(node, argList[argList.length - 1]);
        }
        return node;
    }
    CallNode.create = create;
})(CallNode || (exports.CallNode = CallNode = {}));
var ListComprehensionNode;
(function (ListComprehensionNode) {
    function create(expression, isGenerator) {
        const node = {
            start: expression.start,
            length: expression.length,
            nodeType: 32 /* ParseNodeType.ListComprehension */,
            id: _nextNodeId++,
            expression,
            forIfNodes: [],
            isGenerator,
        };
        expression.parent = node;
        return node;
    }
    ListComprehensionNode.create = create;
})(ListComprehensionNode || (exports.ListComprehensionNode = ListComprehensionNode = {}));
var IndexNode;
(function (IndexNode) {
    function create(baseExpression, items, trailingComma, closeBracketToken) {
        var _a;
        const node = {
            start: baseExpression.start,
            length: baseExpression.length,
            nodeType: 24 /* ParseNodeType.Index */,
            id: _nextNodeId++,
            baseExpression,
            items,
            trailingComma,
        };
        baseExpression.parent = node;
        items.forEach((item) => {
            item.parent = node;
        });
        extendRange(node, closeBracketToken);
        node.maxChildDepth = 1 + ((_a = baseExpression.maxChildDepth) !== null && _a !== void 0 ? _a : 0);
        return node;
    }
    IndexNode.create = create;
})(IndexNode || (exports.IndexNode = IndexNode = {}));
var SliceNode;
(function (SliceNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 46 /* ParseNodeType.Slice */,
            id: _nextNodeId++,
        };
        return node;
    }
    SliceNode.create = create;
})(SliceNode || (exports.SliceNode = SliceNode = {}));
var YieldNode;
(function (YieldNode) {
    function create(yieldToken, expression) {
        const node = {
            start: yieldToken.start,
            length: yieldToken.length,
            nodeType: 60 /* ParseNodeType.Yield */,
            id: _nextNodeId++,
            expression,
        };
        if (expression) {
            expression.parent = node;
            extendRange(node, expression);
        }
        return node;
    }
    YieldNode.create = create;
})(YieldNode || (exports.YieldNode = YieldNode = {}));
var YieldFromNode;
(function (YieldFromNode) {
    function create(yieldToken, expression) {
        const node = {
            start: yieldToken.start,
            length: yieldToken.length,
            nodeType: 61 /* ParseNodeType.YieldFrom */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        extendRange(node, expression);
        return node;
    }
    YieldFromNode.create = create;
})(YieldFromNode || (exports.YieldFromNode = YieldFromNode = {}));
var MemberAccessNode;
(function (MemberAccessNode) {
    function create(leftExpression, memberName) {
        var _a;
        const node = {
            start: leftExpression.start,
            length: leftExpression.length,
            nodeType: 35 /* ParseNodeType.MemberAccess */,
            id: _nextNodeId++,
            leftExpression,
            memberName,
        };
        leftExpression.parent = node;
        memberName.parent = node;
        extendRange(node, memberName);
        node.maxChildDepth = 1 + ((_a = leftExpression.maxChildDepth) !== null && _a !== void 0 ? _a : 0);
        return node;
    }
    MemberAccessNode.create = create;
})(MemberAccessNode || (exports.MemberAccessNode = MemberAccessNode = {}));
var LambdaNode;
(function (LambdaNode) {
    function create(lambdaToken, expression) {
        const node = {
            start: lambdaToken.start,
            length: lambdaToken.length,
            nodeType: 30 /* ParseNodeType.Lambda */,
            id: _nextNodeId++,
            parameters: [],
            expression,
        };
        expression.parent = node;
        extendRange(node, expression);
        return node;
    }
    LambdaNode.create = create;
})(LambdaNode || (exports.LambdaNode = LambdaNode = {}));
var NameNode;
(function (NameNode) {
    function create(nameToken) {
        const node = {
            start: nameToken.start,
            length: nameToken.length,
            nodeType: 38 /* ParseNodeType.Name */,
            id: _nextNodeId++,
            token: nameToken,
            value: nameToken.value,
        };
        return node;
    }
    NameNode.create = create;
})(NameNode || (exports.NameNode = NameNode = {}));
var ConstantNode;
(function (ConstantNode) {
    function create(token) {
        const node = {
            start: token.start,
            length: token.length,
            nodeType: 11 /* ParseNodeType.Constant */,
            id: _nextNodeId++,
            constType: token.keywordType,
        };
        return node;
    }
    ConstantNode.create = create;
})(ConstantNode || (exports.ConstantNode = ConstantNode = {}));
var EllipsisNode;
(function (EllipsisNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 18 /* ParseNodeType.Ellipsis */,
            id: _nextNodeId++,
        };
        return node;
    }
    EllipsisNode.create = create;
})(EllipsisNode || (exports.EllipsisNode = EllipsisNode = {}));
var NumberNode;
(function (NumberNode) {
    function create(token) {
        const node = {
            start: token.start,
            length: token.length,
            nodeType: 40 /* ParseNodeType.Number */,
            id: _nextNodeId++,
            value: token.value,
            isInteger: token.isInteger,
            isImaginary: token.isImaginary,
        };
        return node;
    }
    NumberNode.create = create;
})(NumberNode || (exports.NumberNode = NumberNode = {}));
var StringNode;
(function (StringNode) {
    function create(token, unescapedValue) {
        const node = {
            start: token.start,
            length: token.length,
            nodeType: 49 /* ParseNodeType.String */,
            id: _nextNodeId++,
            token,
            value: unescapedValue,
        };
        return node;
    }
    StringNode.create = create;
})(StringNode || (exports.StringNode = StringNode = {}));
var FormatStringNode;
(function (FormatStringNode) {
    function create(startToken, endToken, middleTokens, fieldExpressions, formatExpressions) {
        const node = {
            start: startToken.start,
            length: startToken.length,
            nodeType: 27 /* ParseNodeType.FormatString */,
            id: _nextNodeId++,
            token: startToken,
            middleTokens,
            fieldExpressions,
            formatExpressions,
            value: '',
        };
        fieldExpressions.forEach((expr) => {
            expr.parent = node;
            extendRange(node, expr);
        });
        if (formatExpressions) {
            formatExpressions.forEach((expr) => {
                expr.parent = node;
                extendRange(node, expr);
            });
        }
        if (endToken) {
            extendRange(node, endToken);
        }
        return node;
    }
    FormatStringNode.create = create;
})(FormatStringNode || (exports.FormatStringNode = FormatStringNode = {}));
var StringListNode;
(function (StringListNode) {
    function create(strings) {
        const node = {
            start: strings[0].start,
            length: strings[0].length,
            nodeType: 48 /* ParseNodeType.StringList */,
            id: _nextNodeId++,
            strings,
        };
        if (strings.length > 0) {
            strings.forEach((str) => {
                str.parent = node;
            });
            extendRange(node, strings[strings.length - 1]);
        }
        return node;
    }
    StringListNode.create = create;
})(StringListNode || (exports.StringListNode = StringListNode = {}));
var DictionaryNode;
(function (DictionaryNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 15 /* ParseNodeType.Dictionary */,
            id: _nextNodeId++,
            entries: [],
        };
        return node;
    }
    DictionaryNode.create = create;
})(DictionaryNode || (exports.DictionaryNode = DictionaryNode = {}));
var DictionaryKeyEntryNode;
(function (DictionaryKeyEntryNode) {
    function create(keyExpression, valueExpression) {
        const node = {
            start: keyExpression.start,
            length: keyExpression.length,
            nodeType: 17 /* ParseNodeType.DictionaryKeyEntry */,
            id: _nextNodeId++,
            keyExpression,
            valueExpression,
        };
        keyExpression.parent = node;
        valueExpression.parent = node;
        extendRange(node, valueExpression);
        return node;
    }
    DictionaryKeyEntryNode.create = create;
})(DictionaryKeyEntryNode || (exports.DictionaryKeyEntryNode = DictionaryKeyEntryNode = {}));
var DictionaryExpandEntryNode;
(function (DictionaryExpandEntryNode) {
    function create(expandExpression) {
        const node = {
            start: expandExpression.start,
            length: expandExpression.length,
            nodeType: 16 /* ParseNodeType.DictionaryExpandEntry */,
            id: _nextNodeId++,
            expandExpression,
        };
        expandExpression.parent = node;
        return node;
    }
    DictionaryExpandEntryNode.create = create;
})(DictionaryExpandEntryNode || (exports.DictionaryExpandEntryNode = DictionaryExpandEntryNode = {}));
var SetNode;
(function (SetNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 45 /* ParseNodeType.Set */,
            id: _nextNodeId++,
            entries: [],
        };
        return node;
    }
    SetNode.create = create;
})(SetNode || (exports.SetNode = SetNode = {}));
var ListNode;
(function (ListNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 31 /* ParseNodeType.List */,
            id: _nextNodeId++,
            entries: [],
        };
        return node;
    }
    ListNode.create = create;
})(ListNode || (exports.ListNode = ListNode = {}));
var ArgumentNode;
(function (ArgumentNode) {
    function create(startToken, valueExpression, argCategory) {
        const node = {
            start: startToken ? startToken.start : valueExpression.start,
            length: startToken ? startToken.length : valueExpression.length,
            nodeType: 1 /* ParseNodeType.Argument */,
            id: _nextNodeId++,
            valueExpression,
            argumentCategory: argCategory,
        };
        valueExpression.parent = node;
        extendRange(node, valueExpression);
        return node;
    }
    ArgumentNode.create = create;
})(ArgumentNode || (exports.ArgumentNode = ArgumentNode = {}));
var DelNode;
(function (DelNode) {
    function create(delToken) {
        const node = {
            start: delToken.start,
            length: delToken.length,
            nodeType: 14 /* ParseNodeType.Del */,
            id: _nextNodeId++,
            expressions: [],
        };
        return node;
    }
    DelNode.create = create;
})(DelNode || (exports.DelNode = DelNode = {}));
var PassNode;
(function (PassNode) {
    function create(passToken) {
        const node = {
            start: passToken.start,
            length: passToken.length,
            nodeType: 42 /* ParseNodeType.Pass */,
            id: _nextNodeId++,
        };
        return node;
    }
    PassNode.create = create;
})(PassNode || (exports.PassNode = PassNode = {}));
var ImportNode;
(function (ImportNode) {
    function create(passToken) {
        const node = {
            start: passToken.start,
            length: passToken.length,
            nodeType: 20 /* ParseNodeType.Import */,
            id: _nextNodeId++,
            list: [],
        };
        return node;
    }
    ImportNode.create = create;
})(ImportNode || (exports.ImportNode = ImportNode = {}));
var ModuleNameNode;
(function (ModuleNameNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 37 /* ParseNodeType.ModuleName */,
            id: _nextNodeId++,
            leadingDots: 0,
            nameParts: [],
        };
        return node;
    }
    ModuleNameNode.create = create;
})(ModuleNameNode || (exports.ModuleNameNode = ModuleNameNode = {}));
var ImportAsNode;
(function (ImportAsNode) {
    function create(module) {
        const node = {
            start: module.start,
            length: module.length,
            nodeType: 21 /* ParseNodeType.ImportAs */,
            id: _nextNodeId++,
            module,
        };
        module.parent = node;
        return node;
    }
    ImportAsNode.create = create;
})(ImportAsNode || (exports.ImportAsNode = ImportAsNode = {}));
var ImportFromNode;
(function (ImportFromNode) {
    function create(fromToken, module) {
        const node = {
            start: fromToken.start,
            length: fromToken.length,
            nodeType: 22 /* ParseNodeType.ImportFrom */,
            id: _nextNodeId++,
            module,
            imports: [],
            isWildcardImport: false,
            usesParens: false,
        };
        module.parent = node;
        extendRange(node, module);
        return node;
    }
    ImportFromNode.create = create;
})(ImportFromNode || (exports.ImportFromNode = ImportFromNode = {}));
var ImportFromAsNode;
(function (ImportFromAsNode) {
    function create(name) {
        const node = {
            start: name.start,
            length: name.length,
            nodeType: 23 /* ParseNodeType.ImportFromAs */,
            id: _nextNodeId++,
            name,
        };
        name.parent = node;
        return node;
    }
    ImportFromAsNode.create = create;
})(ImportFromAsNode || (exports.ImportFromAsNode = ImportFromAsNode = {}));
var GlobalNode;
(function (GlobalNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 29 /* ParseNodeType.Global */,
            id: _nextNodeId++,
            nameList: [],
        };
        return node;
    }
    GlobalNode.create = create;
})(GlobalNode || (exports.GlobalNode = GlobalNode = {}));
var NonlocalNode;
(function (NonlocalNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 39 /* ParseNodeType.Nonlocal */,
            id: _nextNodeId++,
            nameList: [],
        };
        return node;
    }
    NonlocalNode.create = create;
})(NonlocalNode || (exports.NonlocalNode = NonlocalNode = {}));
var AssertNode;
(function (AssertNode) {
    function create(assertToken, testExpression) {
        const node = {
            start: assertToken.start,
            length: assertToken.length,
            nodeType: 2 /* ParseNodeType.Assert */,
            id: _nextNodeId++,
            testExpression,
        };
        testExpression.parent = node;
        extendRange(node, testExpression);
        return node;
    }
    AssertNode.create = create;
})(AssertNode || (exports.AssertNode = AssertNode = {}));
var BreakNode;
(function (BreakNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 8 /* ParseNodeType.Break */,
            id: _nextNodeId++,
        };
        return node;
    }
    BreakNode.create = create;
})(BreakNode || (exports.BreakNode = BreakNode = {}));
var ContinueNode;
(function (ContinueNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 12 /* ParseNodeType.Continue */,
            id: _nextNodeId++,
        };
        return node;
    }
    ContinueNode.create = create;
})(ContinueNode || (exports.ContinueNode = ContinueNode = {}));
var ReturnNode;
(function (ReturnNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 44 /* ParseNodeType.Return */,
            id: _nextNodeId++,
        };
        return node;
    }
    ReturnNode.create = create;
})(ReturnNode || (exports.ReturnNode = ReturnNode = {}));
var RaiseNode;
(function (RaiseNode) {
    function create(range) {
        const node = {
            start: range.start,
            length: range.length,
            nodeType: 43 /* ParseNodeType.Raise */,
            id: _nextNodeId++,
        };
        return node;
    }
    RaiseNode.create = create;
})(RaiseNode || (exports.RaiseNode = RaiseNode = {}));
var MatchNode;
(function (MatchNode) {
    function create(matchToken, subjectExpression) {
        const node = {
            start: matchToken.start,
            length: matchToken.length,
            nodeType: 63 /* ParseNodeType.Match */,
            id: _nextNodeId++,
            subjectExpression,
            cases: [],
        };
        subjectExpression.parent = node;
        extendRange(node, subjectExpression);
        return node;
    }
    MatchNode.create = create;
})(MatchNode || (exports.MatchNode = MatchNode = {}));
var CaseNode;
(function (CaseNode) {
    function create(caseToken, pattern, isIrrefutable, guardExpression, suite) {
        const node = {
            start: caseToken.start,
            length: caseToken.length,
            nodeType: 64 /* ParseNodeType.Case */,
            id: _nextNodeId++,
            pattern,
            isIrrefutable,
            guardExpression,
            suite,
        };
        extendRange(node, suite);
        pattern.parent = node;
        suite.parent = node;
        if (guardExpression) {
            guardExpression.parent = node;
        }
        return node;
    }
    CaseNode.create = create;
})(CaseNode || (exports.CaseNode = CaseNode = {}));
var PatternSequenceNode;
(function (PatternSequenceNode) {
    function create(firstToken, entries) {
        const starEntryIndex = entries.findIndex((entry) => entry.orPatterns.length === 1 &&
            entry.orPatterns[0].nodeType === 69 /* ParseNodeType.PatternCapture */ &&
            entry.orPatterns[0].isStar);
        const node = {
            start: firstToken.start,
            length: firstToken.length,
            nodeType: 65 /* ParseNodeType.PatternSequence */,
            id: _nextNodeId++,
            entries,
            starEntryIndex: starEntryIndex >= 0 ? starEntryIndex : undefined,
        };
        if (entries.length > 0) {
            extendRange(node, entries[entries.length - 1]);
        }
        entries.forEach((entry) => {
            entry.parent = node;
        });
        return node;
    }
    PatternSequenceNode.create = create;
})(PatternSequenceNode || (exports.PatternSequenceNode = PatternSequenceNode = {}));
var PatternAsNode;
(function (PatternAsNode) {
    function create(orPatterns, target) {
        const node = {
            start: orPatterns[0].start,
            length: orPatterns[0].length,
            nodeType: 66 /* ParseNodeType.PatternAs */,
            id: _nextNodeId++,
            orPatterns,
            target,
        };
        if (orPatterns.length > 1) {
            extendRange(node, orPatterns[orPatterns.length - 1]);
        }
        orPatterns.forEach((pattern) => {
            pattern.parent = node;
        });
        if (target) {
            extendRange(node, target);
            target.parent = node;
        }
        return node;
    }
    PatternAsNode.create = create;
})(PatternAsNode || (exports.PatternAsNode = PatternAsNode = {}));
var PatternLiteralNode;
(function (PatternLiteralNode) {
    function create(expression) {
        const node = {
            start: expression.start,
            length: expression.length,
            nodeType: 67 /* ParseNodeType.PatternLiteral */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        return node;
    }
    PatternLiteralNode.create = create;
})(PatternLiteralNode || (exports.PatternLiteralNode = PatternLiteralNode = {}));
var PatternClassNode;
(function (PatternClassNode) {
    function create(className, args) {
        const node = {
            start: className.start,
            length: className.length,
            nodeType: 68 /* ParseNodeType.PatternClass */,
            id: _nextNodeId++,
            className,
            arguments: args,
        };
        className.parent = node;
        args.forEach((arg) => {
            arg.parent = node;
        });
        if (args.length > 0) {
            extendRange(node, args[args.length - 1]);
        }
        return node;
    }
    PatternClassNode.create = create;
})(PatternClassNode || (exports.PatternClassNode = PatternClassNode = {}));
var PatternClassArgumentNode;
(function (PatternClassArgumentNode) {
    function create(pattern, name) {
        const node = {
            start: pattern.start,
            length: pattern.length,
            nodeType: 74 /* ParseNodeType.PatternClassArgument */,
            id: _nextNodeId++,
            pattern,
            name,
        };
        pattern.parent = node;
        if (name) {
            extendRange(node, name);
            name.parent = node;
        }
        return node;
    }
    PatternClassArgumentNode.create = create;
})(PatternClassArgumentNode || (exports.PatternClassArgumentNode = PatternClassArgumentNode = {}));
var PatternCaptureNode;
(function (PatternCaptureNode) {
    function create(target, starToken) {
        const node = {
            start: target.start,
            length: target.length,
            nodeType: 69 /* ParseNodeType.PatternCapture */,
            id: _nextNodeId++,
            target,
            isStar: starToken !== undefined,
            isWildcard: target.value === '_',
        };
        target.parent = node;
        if (starToken) {
            extendRange(node, starToken);
        }
        return node;
    }
    PatternCaptureNode.create = create;
})(PatternCaptureNode || (exports.PatternCaptureNode = PatternCaptureNode = {}));
var PatternMappingNode;
(function (PatternMappingNode) {
    function create(startToken, entries) {
        const node = {
            start: startToken.start,
            length: startToken.length,
            nodeType: 70 /* ParseNodeType.PatternMapping */,
            id: _nextNodeId++,
            entries,
        };
        if (entries.length > 0) {
            extendRange(node, entries[entries.length - 1]);
        }
        entries.forEach((entry) => {
            entry.parent = node;
        });
        return node;
    }
    PatternMappingNode.create = create;
})(PatternMappingNode || (exports.PatternMappingNode = PatternMappingNode = {}));
var PatternMappingKeyEntryNode;
(function (PatternMappingKeyEntryNode) {
    function create(keyPattern, valuePattern) {
        const node = {
            start: keyPattern.start,
            length: keyPattern.length,
            nodeType: 71 /* ParseNodeType.PatternMappingKeyEntry */,
            id: _nextNodeId++,
            keyPattern,
            valuePattern,
        };
        keyPattern.parent = node;
        valuePattern.parent = node;
        extendRange(node, valuePattern);
        return node;
    }
    PatternMappingKeyEntryNode.create = create;
})(PatternMappingKeyEntryNode || (exports.PatternMappingKeyEntryNode = PatternMappingKeyEntryNode = {}));
var PatternMappingExpandEntryNode;
(function (PatternMappingExpandEntryNode) {
    function create(starStarToken, target) {
        const node = {
            start: starStarToken.start,
            length: starStarToken.length,
            nodeType: 72 /* ParseNodeType.PatternMappingExpandEntry */,
            id: _nextNodeId++,
            target,
        };
        target.parent = node;
        extendRange(node, target);
        return node;
    }
    PatternMappingExpandEntryNode.create = create;
})(PatternMappingExpandEntryNode || (exports.PatternMappingExpandEntryNode = PatternMappingExpandEntryNode = {}));
var PatternValueNode;
(function (PatternValueNode) {
    function create(expression) {
        const node = {
            start: expression.start,
            length: expression.length,
            nodeType: 73 /* ParseNodeType.PatternValue */,
            id: _nextNodeId++,
            expression,
        };
        expression.parent = node;
        return node;
    }
    PatternValueNode.create = create;
})(PatternValueNode || (exports.PatternValueNode = PatternValueNode = {}));


/***/ }),

/***/ "../pyright-internal/src/parser/parser.ts":
/*!************************************************!*\
  !*** ../pyright-internal/src/parser/parser.ts ***!
  \************************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * parser.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from python-language-server repository:
 *  https://github.com/Microsoft/python-language-server
 *
 * Parser for the Python language. Converts a stream of tokens
 * into an abstract syntax tree (AST).
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Parser = exports.ParseOptions = void 0;
const sourceFile_1 = __webpack_require__(/*! ../analyzer/sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const collectionUtils_1 = __webpack_require__(/*! ../common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const debug_1 = __webpack_require__(/*! ../common/debug */ "../pyright-internal/src/common/debug.ts");
const diagnostic_1 = __webpack_require__(/*! ../common/diagnostic */ "../pyright-internal/src/common/diagnostic.ts");
const diagnosticSink_1 = __webpack_require__(/*! ../common/diagnosticSink */ "../pyright-internal/src/common/diagnosticSink.ts");
const positionUtils_1 = __webpack_require__(/*! ../common/positionUtils */ "../pyright-internal/src/common/positionUtils.ts");
const pythonVersion_1 = __webpack_require__(/*! ../common/pythonVersion */ "../pyright-internal/src/common/pythonVersion.ts");
const textRange_1 = __webpack_require__(/*! ../common/textRange */ "../pyright-internal/src/common/textRange.ts");
const timing_1 = __webpack_require__(/*! ../common/timing */ "../pyright-internal/src/common/timing.ts");
const localize_1 = __webpack_require__(/*! ../localization/localize */ "../pyright-internal/src/localization/localize.ts");
const parseNodes_1 = __webpack_require__(/*! ./parseNodes */ "../pyright-internal/src/parser/parseNodes.ts");
const StringTokenUtils = __importStar(__webpack_require__(/*! ./stringTokenUtils */ "../pyright-internal/src/parser/stringTokenUtils.ts"));
const tokenizer_1 = __webpack_require__(/*! ./tokenizer */ "../pyright-internal/src/parser/tokenizer.ts");
const tokenizerTypes_1 = __webpack_require__(/*! ./tokenizerTypes */ "../pyright-internal/src/parser/tokenizerTypes.ts");
class ParseOptions {
    constructor() {
        this.isStubFile = false;
        this.pythonVersion = pythonVersion_1.latestStablePythonVersion;
        this.reportInvalidStringEscapeSequence = false;
        this.skipFunctionAndClassBody = false;
        this.ipythonMode = sourceFile_1.IPythonMode.None;
        this.reportErrorsForParsedStringContents = false;
    }
}
exports.ParseOptions = ParseOptions;
// Limit the max child node depth to prevent stack overflows.
const maxChildNodeDepth = 256;
class Parser {
    constructor() {
        this._tokenIndex = 0;
        this._areErrorsSuppressed = false;
        this._parseOptions = new ParseOptions();
        this._diagSink = new diagnosticSink_1.DiagnosticSink();
        this._isInLoop = false;
        this._isInFunction = false;
        this._isInFinally = false;
        this._isParsingTypeAnnotation = false;
        this._isParsingIndexTrailer = false;
        this._isParsingQuotedText = false;
        this._futureImports = new Set();
        this._importedModules = [];
        this._containsWildcardImport = false;
        this._assignmentExpressionsAllowed = true;
        this._typingImportAliases = [];
        this._typingSymbolAliases = new Map();
    }
    parseSourceFile(fileContents, parseOptions, diagSink) {
        timing_1.timingStats.tokenizeFileTime.timeOperation(() => {
            this._startNewParse(fileContents, 0, fileContents.length, parseOptions, diagSink);
        });
        const moduleNode = parseNodes_1.ModuleNode.create({ start: 0, length: fileContents.length });
        timing_1.timingStats.parseFileTime.timeOperation(() => {
            while (!this._atEof()) {
                if (!this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
                    // Handle a common error case and try to recover.
                    const nextToken = this._peekToken();
                    if (nextToken.type === 3 /* TokenType.Indent */) {
                        this._getNextToken();
                        const indentToken = nextToken;
                        if (indentToken.isIndentAmbiguous) {
                            this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), indentToken);
                        }
                        else {
                            this._addSyntaxError(localize_1.LocMessage.unexpectedIndent(), nextToken);
                        }
                    }
                    const statement = this._parseStatement();
                    if (!statement) {
                        // Perform basic error recovery to get to the next line.
                        this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
                    }
                    else {
                        statement.parent = moduleNode;
                        moduleNode.statements.push(statement);
                    }
                }
            }
        });
        (0, debug_1.assert)(this._tokenizerOutput !== undefined);
        return {
            text: fileContents,
            parserOutput: {
                parseTree: moduleNode,
                importedModules: this._importedModules,
                futureImports: this._futureImports,
                containsWildcardImport: this._containsWildcardImport,
                typingSymbolAliases: this._typingSymbolAliases,
            },
            tokenizerOutput: this._tokenizerOutput,
        };
    }
    parseTextExpression(fileContents, textOffset, textLength, parseOptions, parseTextMode = 0 /* ParseTextMode.Expression */, initialParenDepth = 0, typingSymbolAliases) {
        const diagSink = new diagnosticSink_1.DiagnosticSink();
        this._startNewParse(fileContents, textOffset, textLength, parseOptions, diagSink, initialParenDepth);
        if (typingSymbolAliases) {
            this._typingSymbolAliases = new Map(typingSymbolAliases);
        }
        let parseTree;
        if (parseTextMode === 1 /* ParseTextMode.VariableAnnotation */) {
            this._isParsingQuotedText = true;
            parseTree = this._parseTypeAnnotation();
        }
        else if (parseTextMode === 2 /* ParseTextMode.FunctionAnnotation */) {
            this._isParsingQuotedText = true;
            parseTree = this._parseFunctionTypeAnnotation();
        }
        else {
            const exprListResult = this._parseTestOrStarExpressionList(
            /* allowAssignmentExpression */ false, 
            /* allowMultipleUnpack */ true);
            if (exprListResult.parseError) {
                parseTree = exprListResult.parseError;
            }
            else {
                if (exprListResult.list.length === 0) {
                    this._addSyntaxError(localize_1.LocMessage.expectedExpr(), this._peekToken());
                }
                parseTree = this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ false);
            }
        }
        if (this._peekTokenType() === 2 /* TokenType.NewLine */) {
            this._getNextToken();
        }
        if (!this._atEof()) {
            this._addSyntaxError(localize_1.LocMessage.unexpectedExprToken(), this._peekToken());
        }
        return {
            parseTree,
            lines: this._tokenizerOutput.lines,
            diagnostics: diagSink.fetchAndClear(),
        };
    }
    _startNewParse(fileContents, textOffset, textLength, parseOptions, diagSink, initialParenDepth = 0) {
        this._fileContents = fileContents;
        this._parseOptions = parseOptions;
        this._diagSink = diagSink;
        // Tokenize the file contents.
        const tokenizer = new tokenizer_1.Tokenizer();
        this._tokenizerOutput = tokenizer.tokenize(fileContents, textOffset, textLength, initialParenDepth, this._parseOptions.ipythonMode);
        this._tokenIndex = 0;
    }
    // stmt: simple_stmt | compound_stmt
    // compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt
    //   | funcdef | classdef | decorated | async_stmt
    _parseStatement() {
        // Handle the errant condition of a dedent token here to provide
        // better recovery.
        if (this._consumeTokenIfType(4 /* TokenType.Dedent */)) {
            this._addSyntaxError(localize_1.LocMessage.unexpectedUnindent(), this._peekToken());
        }
        switch (this._peekKeywordType()) {
            case 20 /* KeywordType.If */:
                return this._parseIfStatement();
            case 36 /* KeywordType.While */:
                return this._parseWhileStatement();
            case 17 /* KeywordType.For */:
                return this._parseForStatement();
            case 34 /* KeywordType.Try */:
                return this._parseTryStatement();
            case 37 /* KeywordType.With */:
                return this._parseWithStatement();
            case 10 /* KeywordType.Def */:
                return this._parseFunctionDef();
            case 7 /* KeywordType.Class */:
                return this._parseClassDef();
            case 3 /* KeywordType.Async */:
                return this._parseAsyncStatement();
            case 25 /* KeywordType.Match */: {
                // Match is considered a "soft" keyword, so we will treat
                // it as an identifier if it is followed by an unexpected
                // token.
                const peekToken = this._peekToken(1);
                let isInvalidMatchToken = false;
                if (peekToken.type === 10 /* TokenType.Colon */ ||
                    peekToken.type === 11 /* TokenType.Semicolon */ ||
                    peekToken.type === 12 /* TokenType.Comma */ ||
                    peekToken.type === 20 /* TokenType.Dot */ ||
                    peekToken.type === 2 /* TokenType.NewLine */ ||
                    peekToken.type === 1 /* TokenType.EndOfStream */) {
                    isInvalidMatchToken = true;
                }
                else if (peekToken.type === 9 /* TokenType.Operator */) {
                    const operatorToken = peekToken;
                    if (operatorToken.operatorType !== 26 /* OperatorType.Multiply */ &&
                        operatorToken.operatorType !== 0 /* OperatorType.Add */ &&
                        operatorToken.operatorType !== 5 /* OperatorType.BitwiseInvert */ &&
                        operatorToken.operatorType !== 33 /* OperatorType.Subtract */) {
                        isInvalidMatchToken = true;
                    }
                }
                if (!isInvalidMatchToken) {
                    // Try to parse the match statement. If it doesn't appear to
                    // be a match statement, treat as a non-keyword and reparse.
                    const matchStatement = this._parseMatchStatement();
                    if (matchStatement) {
                        return matchStatement;
                    }
                }
                break;
            }
        }
        if (this._peekOperatorType() === 22 /* OperatorType.MatrixMultiply */) {
            return this._parseDecorated();
        }
        return this._parseSimpleStatement();
    }
    // async_stmt: 'async' (funcdef | with_stmt | for_stmt)
    _parseAsyncStatement() {
        const asyncToken = this._getKeywordToken(3 /* KeywordType.Async */);
        switch (this._peekKeywordType()) {
            case 10 /* KeywordType.Def */:
                return this._parseFunctionDef(asyncToken);
            case 37 /* KeywordType.With */:
                return this._parseWithStatement(asyncToken);
            case 17 /* KeywordType.For */:
                return this._parseForStatement(asyncToken);
        }
        this._addSyntaxError(localize_1.LocMessage.unexpectedAsyncToken(), asyncToken);
        return undefined;
    }
    // type_alias_stmt: "type" name [type_param_seq] = expr
    _parseTypeAliasStatement() {
        const typeToken = this._getKeywordToken(35 /* KeywordType.Type */);
        if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_12)) {
            this._addSyntaxError(localize_1.LocMessage.typeAliasStatementIllegal(), typeToken);
        }
        const nameToken = this._getTokenIfIdentifier();
        (0, debug_1.assert)(nameToken !== undefined);
        const name = parseNodes_1.NameNode.create(nameToken);
        let typeParameters;
        if (this._peekToken().type === 15 /* TokenType.OpenBracket */) {
            typeParameters = this._parseTypeParameterList();
        }
        const assignToken = this._peekToken();
        if (assignToken.type !== 9 /* TokenType.Operator */ ||
            assignToken.operatorType !== 2 /* OperatorType.Assign */) {
            this._addSyntaxError(localize_1.LocMessage.expectedEquals(), assignToken);
        }
        else {
            this._getNextToken();
        }
        const wasParsingTypeAnnotation = this._isParsingTypeAnnotation;
        this._isParsingTypeAnnotation = true;
        const expression = this._parseTestExpression(/* allowAssignmentExpression */ false);
        this._isParsingTypeAnnotation = wasParsingTypeAnnotation;
        return parseNodes_1.TypeAliasNode.create(typeToken, name, expression, typeParameters);
    }
    // type_param_seq: '[' (type_param ',')+ ']'
    _parseTypeParameterList() {
        const typeVariableNodes = [];
        const openBracketToken = this._getNextToken();
        (0, debug_1.assert)(openBracketToken.type === 15 /* TokenType.OpenBracket */);
        while (true) {
            const firstToken = this._peekToken();
            if (firstToken.type === 16 /* TokenType.CloseBracket */) {
                if (typeVariableNodes.length === 0) {
                    this._addSyntaxError(localize_1.LocMessage.typeParametersMissing(), this._peekToken());
                }
                break;
            }
            const typeVarNode = this._parseTypeParameter();
            if (!typeVarNode) {
                break;
            }
            typeVariableNodes.push(typeVarNode);
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
        }
        const closingToken = this._peekToken();
        if (closingToken.type !== 16 /* TokenType.CloseBracket */) {
            this._addSyntaxError(localize_1.LocMessage.expectedCloseBracket(), this._peekToken());
            this._consumeTokensUntilType([2 /* TokenType.NewLine */, 16 /* TokenType.CloseBracket */, 10 /* TokenType.Colon */]);
        }
        else {
            this._getNextToken();
        }
        return parseNodes_1.TypeParameterListNode.create(openBracketToken, closingToken, typeVariableNodes);
    }
    // type_param: ['*' | '**'] NAME [':' bound_expr] ['=' default_expr]
    _parseTypeParameter() {
        let typeParamCategory = parseNodes_1.TypeParameterCategory.TypeVar;
        if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
            typeParamCategory = parseNodes_1.TypeParameterCategory.TypeVarTuple;
        }
        else if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
            typeParamCategory = parseNodes_1.TypeParameterCategory.ParamSpec;
        }
        const nameToken = this._getTokenIfIdentifier();
        if (!nameToken) {
            this._addSyntaxError(localize_1.LocMessage.expectedTypeParameterName(), this._peekToken());
            return undefined;
        }
        const name = parseNodes_1.NameNode.create(nameToken);
        let boundExpression;
        if (this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            boundExpression = this._parseExpression(/* allowUnpack */ false);
            if (typeParamCategory !== parseNodes_1.TypeParameterCategory.TypeVar) {
                this._addSyntaxError(localize_1.LocMessage.typeParameterBoundNotAllowed(), boundExpression);
            }
        }
        let defaultExpression;
        if (this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
            defaultExpression = this._parseExpression(
            /* allowUnpack */ typeParamCategory === parseNodes_1.TypeParameterCategory.TypeVarTuple);
            if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_13)) {
                this._addSyntaxError(localize_1.LocMessage.typeVarDefaultIllegal(), defaultExpression);
            }
        }
        return parseNodes_1.TypeParameterNode.create(name, typeParamCategory, boundExpression, defaultExpression);
    }
    // match_stmt: "match" subject_expr ':' NEWLINE INDENT case_block+ DEDENT
    // subject_expr:
    //     | star_named_expression ',' star_named_expressions?
    //     | named_expression
    _parseMatchStatement() {
        // Parse the subject expression with errors suppressed. If it's not
        // followed by a colon, we'll assume this is not a match statement.
        // We need to do this because "match" is considered a soft keyword,
        // and we need to distinguish between "match(2)" and "match (2):"
        // and between "match[2]" and "match [2]:"
        let smellsLikeMatchStatement = false;
        this._suppressErrors(() => {
            const curTokenIndex = this._tokenIndex;
            this._getKeywordToken(25 /* KeywordType.Match */);
            const expression = this._parseTestOrStarListAsExpression(
            /* allowAssignmentExpression */ true, 
            /* allowMultipleUnpack */ true, 12 /* ErrorExpressionCategory.MissingPatternSubject */, () => localize_1.LocMessage.expectedReturnExpr());
            smellsLikeMatchStatement =
                expression.nodeType !== 0 /* ParseNodeType.Error */ && this._peekToken().type === 10 /* TokenType.Colon */;
            // Set the token index back to the start.
            this._tokenIndex = curTokenIndex;
        });
        if (!smellsLikeMatchStatement) {
            return undefined;
        }
        const matchToken = this._getKeywordToken(25 /* KeywordType.Match */);
        const subjectExpression = this._parseTestOrStarListAsExpression(
        /* allowAssignmentExpression */ true, 
        /* allowMultipleUnpack */ true, 12 /* ErrorExpressionCategory.MissingPatternSubject */, () => localize_1.LocMessage.expectedReturnExpr());
        const matchNode = parseNodes_1.MatchNode.create(matchToken, subjectExpression);
        const nextToken = this._peekToken();
        if (!this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedColon(), nextToken);
            // Try to perform parse recovery by consuming tokens until
            // we find the end of the line.
            if (this._consumeTokensUntilType([2 /* TokenType.NewLine */, 10 /* TokenType.Colon */])) {
                this._getNextToken();
            }
        }
        else {
            (0, parseNodes_1.extendRange)(matchNode, nextToken);
            if (!this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
                this._addSyntaxError(localize_1.LocMessage.expectedNewline(), nextToken);
            }
            else {
                const possibleIndent = this._peekToken();
                if (!this._consumeTokenIfType(3 /* TokenType.Indent */)) {
                    this._addSyntaxError(localize_1.LocMessage.expectedIndentedBlock(), this._peekToken());
                }
                else {
                    const indentToken = possibleIndent;
                    if (indentToken.isIndentAmbiguous) {
                        this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), indentToken);
                    }
                }
                while (true) {
                    // Handle a common error here and see if we can recover.
                    const possibleUnexpectedIndent = this._peekToken();
                    if (possibleUnexpectedIndent.type === 3 /* TokenType.Indent */) {
                        this._getNextToken();
                        const indentToken = possibleUnexpectedIndent;
                        if (indentToken.isIndentAmbiguous) {
                            this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), indentToken);
                        }
                        else {
                            this._addSyntaxError(localize_1.LocMessage.unexpectedIndent(), possibleUnexpectedIndent);
                        }
                    }
                    const caseStatement = this._parseCaseStatement();
                    if (!caseStatement) {
                        // Perform basic error recovery to get to the next line.
                        if (this._consumeTokensUntilType([2 /* TokenType.NewLine */, 10 /* TokenType.Colon */])) {
                            this._getNextToken();
                        }
                    }
                    else {
                        caseStatement.parent = matchNode;
                        matchNode.cases.push(caseStatement);
                    }
                    const dedentToken = this._peekToken();
                    if (this._consumeTokenIfType(4 /* TokenType.Dedent */)) {
                        if (!dedentToken.matchesIndent) {
                            this._addSyntaxError(localize_1.LocMessage.inconsistentIndent(), dedentToken);
                        }
                        if (dedentToken.isDedentAmbiguous) {
                            this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), dedentToken);
                        }
                        break;
                    }
                    if (this._peekTokenType() === 1 /* TokenType.EndOfStream */) {
                        break;
                    }
                }
            }
            if (matchNode.cases.length > 0) {
                (0, parseNodes_1.extendRange)(matchNode, matchNode.cases[matchNode.cases.length - 1]);
            }
            else {
                this._addSyntaxError(localize_1.LocMessage.zeroCaseStatementsFound(), matchToken);
            }
        }
        // This feature requires Python 3.10.
        if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_10)) {
            this._addSyntaxError(localize_1.LocMessage.matchIncompatible(), matchToken);
        }
        // Validate that only the last entry uses an irrefutable pattern.
        for (let i = 0; i < matchNode.cases.length - 1; i++) {
            const caseNode = matchNode.cases[i];
            if (!caseNode.guardExpression && caseNode.isIrrefutable) {
                this._addSyntaxError(localize_1.LocMessage.casePatternIsIrrefutable(), caseNode.pattern);
            }
        }
        return matchNode;
    }
    // case_block: "case" patterns [guard] ':' block
    // patterns: sequence_pattern | as_pattern
    // guard: 'if' named_expression
    _parseCaseStatement() {
        const caseToken = this._peekToken();
        if (!this._consumeTokenIfKeyword(6 /* KeywordType.Case */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedCase(), caseToken);
            return undefined;
        }
        const patternList = this._parsePatternSequence();
        let casePattern;
        if (patternList.parseError) {
            casePattern = patternList.parseError;
        }
        else if (patternList.list.length === 0) {
            this._addSyntaxError(localize_1.LocMessage.expectedPatternExpr(), this._peekToken());
            casePattern = parseNodes_1.ErrorNode.create(caseToken, 11 /* ErrorExpressionCategory.MissingPattern */);
        }
        else if (patternList.list.length === 1 && !patternList.trailingComma) {
            const pattern = patternList.list[0].orPatterns[0];
            if (pattern.nodeType === 69 /* ParseNodeType.PatternCapture */ && pattern.isStar) {
                casePattern = parseNodes_1.PatternSequenceNode.create(patternList.list[0], patternList.list);
            }
            else {
                casePattern = patternList.list[0];
            }
        }
        else {
            casePattern = parseNodes_1.PatternSequenceNode.create(patternList.list[0], patternList.list);
        }
        if (casePattern.nodeType !== 0 /* ParseNodeType.Error */) {
            const globalNameMap = new Map();
            const localNameMap = new Map();
            this._reportDuplicatePatternCaptureTargets(casePattern, globalNameMap, localNameMap);
        }
        let guardExpression;
        if (this._consumeTokenIfKeyword(20 /* KeywordType.If */)) {
            guardExpression = this._parseTestExpression(/* allowAssignmentExpression */ true);
        }
        const suite = this._parseSuite(this._isInFunction);
        return parseNodes_1.CaseNode.create(caseToken, casePattern, this._isPatternIrrefutable(casePattern), guardExpression, suite);
    }
    // PEP 634 defines the concept of an "irrefutable" pattern - a pattern that
    // will always be matched.
    _isPatternIrrefutable(node) {
        if (node.nodeType === 69 /* ParseNodeType.PatternCapture */) {
            return true;
        }
        if (node.nodeType === 66 /* ParseNodeType.PatternAs */) {
            return node.orPatterns.some((pattern) => this._isPatternIrrefutable(pattern));
        }
        return false;
    }
    // Reports any situations where a capture target (a variable that receives part of a pattern)
    // appears twice within the same pattern. This is complicated by the fact that duplicate targets
    // are allowed in separate "or" clauses, so we need to track the targets we've seen globally
    // as well as the targets we've seen locally within the current "or" clause.
    _reportDuplicatePatternCaptureTargets(node, globalNameMap, localNameMap) {
        const reportTargetIfDuplicate = (nameNode) => {
            if (globalNameMap.has(nameNode.value) || localNameMap.has(nameNode.value)) {
                this._addSyntaxError(localize_1.LocMessage.duplicateCapturePatternTarget().format({
                    name: nameNode.value,
                }), nameNode);
            }
            else {
                localNameMap.set(nameNode.value, nameNode);
            }
        };
        switch (node.nodeType) {
            case 65 /* ParseNodeType.PatternSequence */: {
                node.entries.forEach((subpattern) => {
                    this._reportDuplicatePatternCaptureTargets(subpattern, globalNameMap, localNameMap);
                });
                break;
            }
            case 68 /* ParseNodeType.PatternClass */: {
                node.arguments.forEach((arg) => {
                    this._reportDuplicatePatternCaptureTargets(arg.pattern, globalNameMap, localNameMap);
                });
                break;
            }
            case 66 /* ParseNodeType.PatternAs */: {
                if (node.target) {
                    reportTargetIfDuplicate(node.target);
                }
                const orLocalNameMaps = node.orPatterns.map((subpattern) => {
                    const orLocalNameMap = new Map();
                    this._reportDuplicatePatternCaptureTargets(subpattern, localNameMap, orLocalNameMap);
                    return orLocalNameMap;
                });
                const combinedLocalOrNameMap = new Map();
                orLocalNameMaps.forEach((orLocalNameMap) => {
                    orLocalNameMap.forEach((node) => {
                        if (!combinedLocalOrNameMap.has(node.value)) {
                            combinedLocalOrNameMap.set(node.value, node);
                            reportTargetIfDuplicate(node);
                        }
                    });
                });
                break;
            }
            case 69 /* ParseNodeType.PatternCapture */: {
                if (!node.isWildcard) {
                    reportTargetIfDuplicate(node.target);
                }
                break;
            }
            case 70 /* ParseNodeType.PatternMapping */: {
                node.entries.forEach((mapEntry) => {
                    if (mapEntry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */) {
                        reportTargetIfDuplicate(mapEntry.target);
                    }
                    else {
                        this._reportDuplicatePatternCaptureTargets(mapEntry.keyPattern, globalNameMap, localNameMap);
                        this._reportDuplicatePatternCaptureTargets(mapEntry.valuePattern, globalNameMap, localNameMap);
                    }
                });
                break;
            }
            case 67 /* ParseNodeType.PatternLiteral */:
            case 73 /* ParseNodeType.PatternValue */:
            case 0 /* ParseNodeType.Error */: {
                break;
            }
        }
    }
    _getPatternTargetNames(node, nameSet) {
        switch (node.nodeType) {
            case 65 /* ParseNodeType.PatternSequence */: {
                node.entries.forEach((subpattern) => {
                    this._getPatternTargetNames(subpattern, nameSet);
                });
                break;
            }
            case 68 /* ParseNodeType.PatternClass */: {
                node.arguments.forEach((arg) => {
                    this._getPatternTargetNames(arg.pattern, nameSet);
                });
                break;
            }
            case 66 /* ParseNodeType.PatternAs */: {
                if (node.target) {
                    nameSet.add(node.target.value);
                }
                node.orPatterns.forEach((subpattern) => {
                    this._getPatternTargetNames(subpattern, nameSet);
                });
                break;
            }
            case 69 /* ParseNodeType.PatternCapture */: {
                if (!node.isWildcard) {
                    nameSet.add(node.target.value);
                }
                break;
            }
            case 70 /* ParseNodeType.PatternMapping */: {
                node.entries.forEach((mapEntry) => {
                    if (mapEntry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */) {
                        nameSet.add(mapEntry.target.value);
                    }
                    else {
                        this._getPatternTargetNames(mapEntry.keyPattern, nameSet);
                        this._getPatternTargetNames(mapEntry.valuePattern, nameSet);
                    }
                });
                break;
            }
            case 67 /* ParseNodeType.PatternLiteral */:
            case 73 /* ParseNodeType.PatternValue */:
            case 0 /* ParseNodeType.Error */: {
                break;
            }
        }
    }
    _parsePatternSequence() {
        const patternList = this._parseExpressionListGeneric(() => this._parsePatternAs());
        // Check for more than one star entry.
        const starEntries = patternList.list.filter((entry) => entry.orPatterns.length === 1 &&
            entry.orPatterns[0].nodeType === 69 /* ParseNodeType.PatternCapture */ &&
            entry.orPatterns[0].isStar);
        if (starEntries.length > 1) {
            this._addSyntaxError(localize_1.LocMessage.duplicateStarPattern(), starEntries[1].orPatterns[0]);
        }
        return patternList;
    }
    // as_pattern: or_pattern ['as' NAME]
    // or_pattern: '|'.pattern_atom+
    _parsePatternAs() {
        const orPatterns = [];
        while (true) {
            const patternAtom = this._parsePatternAtom();
            orPatterns.push(patternAtom);
            if (!this._consumeTokenIfOperator(6 /* OperatorType.BitwiseOr */)) {
                break;
            }
        }
        if (orPatterns.length > 1) {
            // Star patterns cannot be ORed with other patterns.
            orPatterns.forEach((patternAtom) => {
                if (patternAtom.nodeType === 69 /* ParseNodeType.PatternCapture */ && patternAtom.isStar) {
                    this._addSyntaxError(localize_1.LocMessage.starPatternInOrPattern(), patternAtom);
                }
            });
        }
        let target;
        if (this._consumeTokenIfKeyword(1 /* KeywordType.As */)) {
            const nameToken = this._getTokenIfIdentifier();
            if (nameToken) {
                target = parseNodes_1.NameNode.create(nameToken);
            }
            else {
                this._addSyntaxError(localize_1.LocMessage.expectedNameAfterAs(), this._peekToken());
            }
        }
        // Star patterns cannot be used with AS pattern.
        if (target &&
            orPatterns.length === 1 &&
            orPatterns[0].nodeType === 69 /* ParseNodeType.PatternCapture */ &&
            orPatterns[0].isStar) {
            this._addSyntaxError(localize_1.LocMessage.starPatternInAsPattern(), orPatterns[0]);
        }
        // Validate that irrefutable patterns are not in any entries other than the last.
        orPatterns.forEach((orPattern, index) => {
            if (index < orPatterns.length - 1 && this._isPatternIrrefutable(orPattern)) {
                this._addSyntaxError(localize_1.LocMessage.orPatternIrrefutable(), orPattern);
            }
        });
        // Validate that all bound variables are the same within all or patterns.
        const fullNameSet = new Set();
        orPatterns.forEach((orPattern) => {
            this._getPatternTargetNames(orPattern, fullNameSet);
        });
        orPatterns.forEach((orPattern) => {
            const localNameSet = new Set();
            this._getPatternTargetNames(orPattern, localNameSet);
            if (localNameSet.size < fullNameSet.size) {
                const missingNames = Array.from(fullNameSet.keys()).filter((name) => !localNameSet.has(name));
                const diag = new diagnostic_1.DiagnosticAddendum();
                diag.addMessage(localize_1.LocAddendum.orPatternMissingName().format({
                    name: missingNames.map((name) => `"${name}"`).join(', '),
                }));
                this._addSyntaxError(localize_1.LocMessage.orPatternMissingName() + diag.getString(), orPattern);
            }
        });
        return parseNodes_1.PatternAsNode.create(orPatterns, target);
    }
    // pattern_atom:
    //     | literal_pattern
    //     | name_or_attr
    //     | '(' as_pattern ')'
    //     | '[' [sequence_pattern] ']'
    //     | '(' [sequence_pattern] ')'
    //     | '{' [items_pattern] '}'
    //     | name_or_attr '(' [pattern_arguments ','?] ')'
    // name_or_attr: attr | NAME
    // attr: name_or_attr '.' NAME
    // sequence_pattern: ','.maybe_star_pattern+ ','?
    // maybe_star_pattern: '*' NAME | pattern
    // items_pattern: ','.key_value_pattern+ ','?
    _parsePatternAtom() {
        const patternLiteral = this._parsePatternLiteral();
        if (patternLiteral) {
            return patternLiteral;
        }
        const patternCaptureOrValue = this._parsePatternCaptureOrValue();
        if (patternCaptureOrValue) {
            const openParenToken = this._peekToken();
            if (patternCaptureOrValue.nodeType === 0 /* ParseNodeType.Error */ ||
                !this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */)) {
                return patternCaptureOrValue;
            }
            const args = this._parseClassPatternArgList();
            const classNameExpr = patternCaptureOrValue.nodeType === 69 /* ParseNodeType.PatternCapture */
                ? patternCaptureOrValue.target
                : patternCaptureOrValue.expression;
            const classPattern = parseNodes_1.PatternClassNode.create(classNameExpr, args);
            if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
                this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), openParenToken);
                // Consume the remainder of tokens on the line for error
                // recovery.
                this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
                // Extend the node's range to include the rest of the line.
                // This helps the signatureHelpProvider.
                (0, parseNodes_1.extendRange)(classPattern, this._peekToken());
            }
            return classPattern;
        }
        const nextToken = this._peekToken();
        const nextOperator = this._peekOperatorType();
        if (nextOperator === 26 /* OperatorType.Multiply */) {
            const starToken = this._getNextToken();
            const identifierToken = this._getTokenIfIdentifier();
            if (!identifierToken) {
                this._addSyntaxError(localize_1.LocMessage.expectedIdentifier(), this._peekToken());
                return parseNodes_1.ErrorNode.create(starToken, 2 /* ErrorExpressionCategory.MissingExpression */);
            }
            else {
                return parseNodes_1.PatternCaptureNode.create(parseNodes_1.NameNode.create(identifierToken), starToken);
            }
        }
        if (nextToken.type === 13 /* TokenType.OpenParenthesis */ || nextToken.type === 15 /* TokenType.OpenBracket */) {
            const startToken = this._getNextToken();
            const patternList = this._parsePatternSequence();
            let casePattern;
            if (patternList.parseError) {
                casePattern = patternList.parseError;
            }
            else if (patternList.list.length === 1 &&
                !patternList.trailingComma &&
                startToken.type === 13 /* TokenType.OpenParenthesis */) {
                const pattern = patternList.list[0].orPatterns[0];
                if (pattern.nodeType === 69 /* ParseNodeType.PatternCapture */ && pattern.isStar) {
                    casePattern = parseNodes_1.PatternSequenceNode.create(startToken, patternList.list);
                }
                else {
                    casePattern = patternList.list[0];
                }
                (0, parseNodes_1.extendRange)(casePattern, nextToken);
            }
            else {
                casePattern = parseNodes_1.PatternSequenceNode.create(startToken, patternList.list);
            }
            const endToken = this._peekToken();
            if (this._consumeTokenIfType(nextToken.type === 13 /* TokenType.OpenParenthesis */ ? 14 /* TokenType.CloseParenthesis */ : 16 /* TokenType.CloseBracket */)) {
                (0, parseNodes_1.extendRange)(casePattern, endToken);
            }
            else {
                this._addSyntaxError(nextToken.type === 13 /* TokenType.OpenParenthesis */
                    ? localize_1.LocMessage.expectedCloseParen()
                    : localize_1.LocMessage.expectedCloseBracket(), nextToken);
                this._consumeTokensUntilType([
                    10 /* TokenType.Colon */,
                    nextToken.type === 13 /* TokenType.OpenParenthesis */ ? 14 /* TokenType.CloseParenthesis */ : 16 /* TokenType.CloseBracket */,
                ]);
            }
            return casePattern;
        }
        else if (nextToken.type === 17 /* TokenType.OpenCurlyBrace */) {
            const firstToken = this._getNextToken();
            const mappingPattern = this._parsePatternMapping(firstToken);
            const lastToken = this._peekToken();
            if (this._consumeTokenIfType(18 /* TokenType.CloseCurlyBrace */)) {
                (0, parseNodes_1.extendRange)(mappingPattern, lastToken);
            }
            else {
                this._addSyntaxError(localize_1.LocMessage.expectedCloseBrace(), nextToken);
                this._consumeTokensUntilType([10 /* TokenType.Colon */, 18 /* TokenType.CloseCurlyBrace */]);
            }
            return mappingPattern;
        }
        return this._handleExpressionParseError(11 /* ErrorExpressionCategory.MissingPattern */, localize_1.LocMessage.expectedPatternExpr());
    }
    // pattern_arguments:
    //     | positional_patterns [',' keyword_patterns]
    //     | keyword_patterns
    // positional_patterns: ','.as_pattern+
    // keyword_patterns: ','.keyword_pattern+
    _parseClassPatternArgList() {
        const argList = [];
        let sawKeywordArg = false;
        while (true) {
            const nextTokenType = this._peekTokenType();
            if (nextTokenType === 14 /* TokenType.CloseParenthesis */ ||
                nextTokenType === 2 /* TokenType.NewLine */ ||
                nextTokenType === 1 /* TokenType.EndOfStream */) {
                break;
            }
            const arg = this._parseClassPatternArgument();
            if (arg.name) {
                sawKeywordArg = true;
            }
            else if (sawKeywordArg && !arg.name) {
                this._addSyntaxError(localize_1.LocMessage.positionArgAfterNamedArg(), arg);
            }
            argList.push(arg);
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
        }
        return argList;
    }
    // keyword_pattern: NAME '=' as_pattern
    _parseClassPatternArgument() {
        const firstToken = this._peekToken();
        const secondToken = this._peekToken(1);
        let keywordName;
        if ((firstToken.type === 7 /* TokenType.Identifier */ || firstToken.type === 8 /* TokenType.Keyword */) &&
            secondToken.type === 9 /* TokenType.Operator */ &&
            secondToken.operatorType === 2 /* OperatorType.Assign */) {
            const classNameToken = this._getTokenIfIdentifier();
            if (classNameToken !== undefined) {
                keywordName = parseNodes_1.NameNode.create(classNameToken);
                this._getNextToken();
            }
        }
        const pattern = this._parsePatternAs();
        return parseNodes_1.PatternClassArgumentNode.create(pattern, keywordName);
    }
    // literal_pattern:
    //     | signed_number
    //     | signed_number '+' NUMBER
    //     | signed_number '-' NUMBER
    //     | strings
    //     | 'None'
    //     | 'True'
    //     | 'False'
    _parsePatternLiteral() {
        const nextToken = this._peekToken();
        const nextOperator = this._peekOperatorType();
        if (nextToken.type === 6 /* TokenType.Number */ || nextOperator === 33 /* OperatorType.Subtract */) {
            return this._parsePatternLiteralNumber();
        }
        if (nextToken.type === 5 /* TokenType.String */) {
            const stringList = this._parseAtom();
            (0, debug_1.assert)(stringList.nodeType === 48 /* ParseNodeType.StringList */);
            // Check for f-strings, which are not allowed.
            stringList.strings.forEach((stringAtom) => {
                if (stringAtom.nodeType === 27 /* ParseNodeType.FormatString */) {
                    this._addSyntaxError(localize_1.LocMessage.formatStringInPattern(), stringAtom);
                }
            });
            return parseNodes_1.PatternLiteralNode.create(stringList);
        }
        if (nextToken.type === 8 /* TokenType.Keyword */) {
            const keywordToken = nextToken;
            if (keywordToken.keywordType === 15 /* KeywordType.False */ ||
                keywordToken.keywordType === 33 /* KeywordType.True */ ||
                keywordToken.keywordType === 26 /* KeywordType.None */) {
                return parseNodes_1.PatternLiteralNode.create(this._parseAtom());
            }
        }
        return undefined;
    }
    // signed_number: NUMBER | '-' NUMBER
    _parsePatternLiteralNumber() {
        const expression = this._parseArithmeticExpression();
        let realValue;
        let imagValue;
        if (expression.nodeType === 7 /* ParseNodeType.BinaryOperation */) {
            if (expression.operator === 33 /* OperatorType.Subtract */ || expression.operator === 0 /* OperatorType.Add */) {
                realValue = expression.leftExpression;
                imagValue = expression.rightExpression;
            }
        }
        else {
            realValue = expression;
        }
        if (realValue) {
            if (realValue.nodeType === 55 /* ParseNodeType.UnaryOperation */ && realValue.operator === 33 /* OperatorType.Subtract */) {
                realValue = realValue.expression;
            }
            if (realValue.nodeType !== 40 /* ParseNodeType.Number */ || (imagValue !== undefined && realValue.isImaginary)) {
                this._addSyntaxError(localize_1.LocMessage.expectedComplexNumberLiteral(), expression);
                imagValue = undefined;
            }
        }
        if (imagValue) {
            if (imagValue.nodeType === 55 /* ParseNodeType.UnaryOperation */ && imagValue.operator === 33 /* OperatorType.Subtract */) {
                imagValue = imagValue.expression;
            }
            if (imagValue.nodeType !== 40 /* ParseNodeType.Number */ || !imagValue.isImaginary) {
                this._addSyntaxError(localize_1.LocMessage.expectedComplexNumberLiteral(), expression);
            }
        }
        return parseNodes_1.PatternLiteralNode.create(expression);
    }
    _parsePatternMapping(firstToken) {
        const itemList = this._parseExpressionListGeneric(() => this._parsePatternMappingItem());
        if (itemList.list.length > 0) {
            // Verify there's at most one ** entry.
            const starStarEntries = itemList.list.filter((entry) => entry.nodeType === 72 /* ParseNodeType.PatternMappingExpandEntry */);
            if (starStarEntries.length > 1) {
                this._addSyntaxError(localize_1.LocMessage.duplicateStarStarPattern(), starStarEntries[1]);
            }
            return parseNodes_1.PatternMappingNode.create(firstToken, itemList.list);
        }
        return itemList.parseError || parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
    }
    // key_value_pattern:
    //     | (literal_pattern | attr) ':' as_pattern
    //     | '**' NAME
    _parsePatternMappingItem() {
        let keyExpression;
        const doubleStar = this._peekToken();
        if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
            const identifierToken = this._getTokenIfIdentifier();
            if (!identifierToken) {
                this._addSyntaxError(localize_1.LocMessage.expectedIdentifier(), this._peekToken());
                return parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
            }
            const nameNode = parseNodes_1.NameNode.create(identifierToken);
            if (identifierToken.value === '_') {
                this._addSyntaxError(localize_1.LocMessage.starStarWildcardNotAllowed(), nameNode);
            }
            return parseNodes_1.PatternMappingExpandEntryNode.create(doubleStar, nameNode);
        }
        const patternLiteral = this._parsePatternLiteral();
        if (patternLiteral) {
            keyExpression = patternLiteral;
        }
        else {
            const patternCaptureOrValue = this._parsePatternCaptureOrValue();
            if (patternCaptureOrValue) {
                if (patternCaptureOrValue.nodeType === 73 /* ParseNodeType.PatternValue */) {
                    keyExpression = patternCaptureOrValue;
                }
                else {
                    this._addSyntaxError(localize_1.LocMessage.expectedPatternValue(), patternCaptureOrValue);
                    keyExpression = parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
                }
            }
        }
        if (!keyExpression) {
            this._addSyntaxError(localize_1.LocMessage.expectedPatternExpr(), this._peekToken());
            keyExpression = parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
        }
        let valuePattern;
        if (!this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedColon(), this._peekToken());
            valuePattern = parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
        }
        else {
            valuePattern = this._parsePatternAs();
        }
        return parseNodes_1.PatternMappingKeyEntryNode.create(keyExpression, valuePattern);
    }
    _parsePatternCaptureOrValue() {
        const nextToken = this._peekToken();
        if (nextToken.type === 7 /* TokenType.Identifier */ || nextToken.type === 8 /* TokenType.Keyword */) {
            let nameOrMember;
            while (true) {
                const identifierToken = this._getTokenIfIdentifier();
                if (identifierToken) {
                    const nameNode = parseNodes_1.NameNode.create(identifierToken);
                    nameOrMember = nameOrMember ? parseNodes_1.MemberAccessNode.create(nameOrMember, nameNode) : nameNode;
                }
                else {
                    this._addSyntaxError(localize_1.LocMessage.expectedIdentifier(), this._peekToken());
                    break;
                }
                if (!this._consumeTokenIfType(20 /* TokenType.Dot */)) {
                    break;
                }
            }
            if (!nameOrMember) {
                this._addSyntaxError(localize_1.LocMessage.expectedIdentifier(), this._peekToken());
                return parseNodes_1.ErrorNode.create(this._peekToken(), 11 /* ErrorExpressionCategory.MissingPattern */);
            }
            if (nameOrMember.nodeType === 35 /* ParseNodeType.MemberAccess */) {
                return parseNodes_1.PatternValueNode.create(nameOrMember);
            }
            return parseNodes_1.PatternCaptureNode.create(nameOrMember);
        }
        return undefined;
    }
    // if_stmt: 'if' test_suite ('elif' test_suite)* ['else' suite]
    // test_suite: test suite
    // test: or_test ['if' or_test 'else' test] | lambdef
    _parseIfStatement(keywordType = 20 /* KeywordType.If */) {
        const ifOrElifToken = this._getKeywordToken(keywordType);
        const test = this._parseTestExpression(/* allowAssignmentExpression */ true);
        const suite = this._parseSuite(this._isInFunction);
        const ifNode = parseNodes_1.IfNode.create(ifOrElifToken, test, suite);
        if (this._consumeTokenIfKeyword(13 /* KeywordType.Else */)) {
            ifNode.elseSuite = this._parseSuite(this._isInFunction);
            ifNode.elseSuite.parent = ifNode;
            (0, parseNodes_1.extendRange)(ifNode, ifNode.elseSuite);
        }
        else if (this._peekKeywordType() === 12 /* KeywordType.Elif */) {
            // Recursively handle an "elif" statement.
            ifNode.elseSuite = this._parseIfStatement(12 /* KeywordType.Elif */);
            ifNode.elseSuite.parent = ifNode;
            (0, parseNodes_1.extendRange)(ifNode, ifNode.elseSuite);
        }
        return ifNode;
    }
    _parseLoopSuite() {
        const wasInLoop = this._isInLoop;
        const wasInFinally = this._isInFinally;
        this._isInLoop = true;
        this._isInFinally = false;
        let typeComment;
        const suite = this._parseSuite(this._isInFunction, /* skipBody */ false, () => {
            const comment = this._getTypeAnnotationCommentText();
            if (comment) {
                typeComment = comment;
            }
        });
        this._isInLoop = wasInLoop;
        this._isInFinally = wasInFinally;
        if (typeComment) {
            suite.typeComment = typeComment;
        }
        return suite;
    }
    // suite: ':' (simple_stmt | NEWLINE INDENT stmt+ DEDENT)
    _parseSuite(isFunction = false, skipBody = false, postColonCallback) {
        const nextToken = this._peekToken();
        const suite = parseNodes_1.SuiteNode.create(nextToken);
        if (!this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedColon(), nextToken);
            // Try to perform parse recovery by consuming tokens.
            if (this._consumeTokensUntilType([2 /* TokenType.NewLine */, 10 /* TokenType.Colon */])) {
                if (this._peekTokenType() === 10 /* TokenType.Colon */) {
                    this._getNextToken();
                }
                else if (this._peekToken(1).type !== 3 /* TokenType.Indent */) {
                    // Bail so we resume the at the next statement.
                    // We can't parse as a simple statement as we've skipped all but the newline.
                    this._getNextToken();
                    return suite;
                }
            }
        }
        if (skipBody) {
            if (this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
                let indent = 0;
                while (true) {
                    const nextToken = this._getNextToken();
                    if (nextToken.type === 3 /* TokenType.Indent */) {
                        indent++;
                    }
                    if (nextToken.type === 4 /* TokenType.Dedent */) {
                        if (nextToken.isDedentAmbiguous) {
                            this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), nextToken);
                        }
                        indent--;
                        if (indent === 0) {
                            break;
                        }
                    }
                    if (nextToken.type === 1 /* TokenType.EndOfStream */) {
                        break;
                    }
                }
            }
            else {
                // consume tokens
                this._parseSimpleStatement();
            }
            if (this._tokenIndex > 0) {
                (0, parseNodes_1.extendRange)(suite, this._tokenizerOutput.tokens.getItemAt(this._tokenIndex - 1));
            }
            return suite;
        }
        if (postColonCallback) {
            postColonCallback();
        }
        const wasFunction = this._isInFunction;
        this._isInFunction = isFunction;
        if (this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
            if (postColonCallback) {
                postColonCallback();
            }
            const possibleIndent = this._peekToken();
            if (!this._consumeTokenIfType(3 /* TokenType.Indent */)) {
                this._addSyntaxError(localize_1.LocMessage.expectedIndentedBlock(), this._peekToken());
                return suite;
            }
            const bodyIndentToken = possibleIndent;
            if (bodyIndentToken.isIndentAmbiguous) {
                this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), bodyIndentToken);
            }
            while (true) {
                // Handle a common error here and see if we can recover.
                const nextToken = this._peekToken();
                if (nextToken.type === 3 /* TokenType.Indent */) {
                    this._getNextToken();
                    const indentToken = nextToken;
                    if (indentToken.isIndentAmbiguous) {
                        this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), indentToken);
                    }
                    else {
                        this._addSyntaxError(localize_1.LocMessage.unexpectedIndent(), nextToken);
                    }
                }
                else if (nextToken.type === 4 /* TokenType.Dedent */) {
                    // When we see a dedent, stop before parsing the dedented statement.
                    const dedentToken = nextToken;
                    if (!dedentToken.matchesIndent) {
                        this._addSyntaxError(localize_1.LocMessage.inconsistentIndent(), dedentToken);
                    }
                    if (dedentToken.isDedentAmbiguous) {
                        this._addSyntaxError(localize_1.LocMessage.inconsistentTabs(), dedentToken);
                    }
                    // When the suite is incomplete (no statements), leave the dedent token for
                    // recovery. This allows a single dedent token to cause us to break out of
                    // multiple levels of nested suites. Also extend the suite's range in this
                    // case so it is multi-line as this works better with indentationUtils.
                    if (suite.statements.length > 0) {
                        this._consumeTokenIfType(4 /* TokenType.Dedent */);
                    }
                    else {
                        (0, parseNodes_1.extendRange)(suite, dedentToken);
                    }
                    // Did this dedent take us to an indent amount that is less than the
                    // initial indent of the suite body?
                    if (!bodyIndentToken || dedentToken.indentAmount < bodyIndentToken.indentAmount) {
                        break;
                    }
                    else if (dedentToken.indentAmount === bodyIndentToken.indentAmount) {
                        // If the next token is also a dedent that reduces the indent
                        // level to a less than the initial indent of the suite body, swallow
                        // the extra dedent to help recover the parse.
                        const nextToken = this._peekToken();
                        if (this._consumeTokenIfType(4 /* TokenType.Dedent */)) {
                            (0, parseNodes_1.extendRange)(suite, nextToken);
                            break;
                        }
                    }
                }
                const statement = this._parseStatement();
                if (!statement) {
                    // Perform basic error recovery to get to the next line.
                    this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
                }
                else {
                    statement.parent = suite;
                    suite.statements.push(statement);
                }
                if (this._peekTokenType() === 1 /* TokenType.EndOfStream */) {
                    break;
                }
            }
        }
        else {
            const simpleStatement = this._parseSimpleStatement();
            suite.statements.push(simpleStatement);
            simpleStatement.parent = suite;
        }
        if (suite.statements.length > 0) {
            (0, parseNodes_1.extendRange)(suite, suite.statements[suite.statements.length - 1]);
        }
        this._isInFunction = wasFunction;
        return suite;
    }
    // for_stmt: [async] 'for' exprlist 'in' testlist suite ['else' suite]
    _parseForStatement(asyncToken) {
        const forToken = this._getKeywordToken(17 /* KeywordType.For */);
        const targetExpr = this._parseExpressionListAsPossibleTuple(2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedExpr(), forToken);
        let seqExpr;
        let forSuite;
        let elseSuite;
        if (!this._consumeTokenIfKeyword(22 /* KeywordType.In */)) {
            seqExpr = this._handleExpressionParseError(0 /* ErrorExpressionCategory.MissingIn */, localize_1.LocMessage.expectedIn());
            forSuite = parseNodes_1.SuiteNode.create(this._peekToken());
        }
        else {
            seqExpr = this._parseTestOrStarListAsExpression(
            /* allowAssignmentExpression */ false, 
            /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedInExpr());
            forSuite = this._parseLoopSuite();
            // Versions of Python earlier than 3.9 didn't allow unpack operators if the
            // tuple wasn't enclosed in parentheses.
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_9) && !this._parseOptions.isStubFile) {
                if (seqExpr.nodeType === 52 /* ParseNodeType.Tuple */ && !seqExpr.enclosedInParens) {
                    let sawStar = false;
                    seqExpr.expressions.forEach((expr) => {
                        if (expr.nodeType === 56 /* ParseNodeType.Unpack */ && !sawStar) {
                            this._addSyntaxError(localize_1.LocMessage.unpackOperatorNotAllowed(), expr);
                            sawStar = true;
                        }
                    });
                }
            }
            if (this._consumeTokenIfKeyword(13 /* KeywordType.Else */)) {
                elseSuite = this._parseSuite(this._isInFunction);
            }
        }
        const forNode = parseNodes_1.ForNode.create(forToken, targetExpr, seqExpr, forSuite);
        forNode.elseSuite = elseSuite;
        if (elseSuite) {
            (0, parseNodes_1.extendRange)(forNode, elseSuite);
            elseSuite.parent = forNode;
        }
        if (asyncToken) {
            forNode.isAsync = true;
            forNode.asyncToken = asyncToken;
            (0, parseNodes_1.extendRange)(forNode, asyncToken);
        }
        if (forSuite.typeComment) {
            forNode.typeComment = forSuite.typeComment;
        }
        return forNode;
    }
    // comp_iter: comp_for | comp_if
    _tryParseListComprehension(target, isGenerator) {
        const compFor = this._tryParseCompForStatement();
        if (!compFor) {
            return undefined;
        }
        if (target.nodeType === 56 /* ParseNodeType.Unpack */) {
            this._addSyntaxError(localize_1.LocMessage.unpackIllegalInComprehension(), target);
        }
        else if (target.nodeType === 16 /* ParseNodeType.DictionaryExpandEntry */) {
            this._addSyntaxError(localize_1.LocMessage.dictExpandIllegalInComprehension(), target);
        }
        const listCompNode = parseNodes_1.ListComprehensionNode.create(target, isGenerator);
        const forIfList = [compFor];
        while (true) {
            const compIter = this._tryParseCompForStatement() || this._tryParseCompIfStatement();
            if (!compIter) {
                break;
            }
            compIter.parent = listCompNode;
            forIfList.push(compIter);
        }
        listCompNode.forIfNodes = forIfList;
        if (forIfList.length > 0) {
            forIfList.forEach((comp) => {
                comp.parent = listCompNode;
            });
            (0, parseNodes_1.extendRange)(listCompNode, forIfList[forIfList.length - 1]);
        }
        return listCompNode;
    }
    // comp_for: ['async'] 'for' exprlist 'in' or_test [comp_iter]
    _tryParseCompForStatement() {
        const startTokenKeywordType = this._peekKeywordType();
        if (startTokenKeywordType === 3 /* KeywordType.Async */) {
            const nextToken = this._peekToken(1);
            if (nextToken.type !== 8 /* TokenType.Keyword */ || nextToken.keywordType !== 17 /* KeywordType.For */) {
                return undefined;
            }
        }
        else if (startTokenKeywordType !== 17 /* KeywordType.For */) {
            return undefined;
        }
        let asyncToken;
        if (this._peekKeywordType() === 3 /* KeywordType.Async */) {
            asyncToken = this._getKeywordToken(3 /* KeywordType.Async */);
        }
        const forToken = this._getKeywordToken(17 /* KeywordType.For */);
        const targetExpr = this._parseExpressionListAsPossibleTuple(2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedExpr(), forToken);
        let seqExpr;
        if (!this._consumeTokenIfKeyword(22 /* KeywordType.In */)) {
            seqExpr = this._handleExpressionParseError(0 /* ErrorExpressionCategory.MissingIn */, localize_1.LocMessage.expectedIn());
        }
        else {
            this._disallowAssignmentExpression(() => {
                seqExpr = this._parseOrTest();
            });
        }
        const compForNode = parseNodes_1.ListComprehensionForNode.create(asyncToken || forToken, targetExpr, seqExpr);
        if (asyncToken) {
            compForNode.isAsync = true;
            compForNode.asyncToken = asyncToken;
        }
        return compForNode;
    }
    // comp_if: 'if' test_nocond [comp_iter]
    // comp_iter: comp_for | comp_if
    _tryParseCompIfStatement() {
        if (this._peekKeywordType() !== 20 /* KeywordType.If */) {
            return undefined;
        }
        const ifToken = this._getKeywordToken(20 /* KeywordType.If */);
        const ifExpr = this._tryParseLambdaExpression() ||
            this._parseAssignmentExpression(/* disallowAssignmentExpression */ true);
        const compIfNode = parseNodes_1.ListComprehensionIfNode.create(ifToken, ifExpr);
        return compIfNode;
    }
    // while_stmt: 'while' test suite ['else' suite]
    _parseWhileStatement() {
        const whileToken = this._getKeywordToken(36 /* KeywordType.While */);
        const whileNode = parseNodes_1.WhileNode.create(whileToken, this._parseTestExpression(/* allowAssignmentExpression */ true), this._parseLoopSuite());
        if (this._consumeTokenIfKeyword(13 /* KeywordType.Else */)) {
            whileNode.elseSuite = this._parseSuite(this._isInFunction);
            whileNode.elseSuite.parent = whileNode;
            (0, parseNodes_1.extendRange)(whileNode, whileNode.elseSuite);
        }
        return whileNode;
    }
    // try_stmt: ('try' suite
    //         ((except_clause suite)+
    //             ['else' suite]
    //             ['finally' suite] |
    //         'finally' suite))
    // except_clause: 'except' [test ['as' NAME]]
    _parseTryStatement() {
        const tryToken = this._getKeywordToken(34 /* KeywordType.Try */);
        const trySuite = this._parseSuite(this._isInFunction);
        const tryNode = parseNodes_1.TryNode.create(tryToken, trySuite);
        let sawCatchAllExcept = false;
        while (true) {
            const exceptToken = this._peekToken();
            if (!this._consumeTokenIfKeyword(14 /* KeywordType.Except */)) {
                break;
            }
            // See if this is a Python 3.11 exception group.
            const possibleStarToken = this._peekToken();
            let isExceptGroup = false;
            if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
                if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_11) && !this._parseOptions.isStubFile) {
                    this._addSyntaxError(localize_1.LocMessage.exceptionGroupIncompatible(), possibleStarToken);
                }
                isExceptGroup = true;
            }
            let typeExpr;
            let symbolName;
            if (this._peekTokenType() !== 10 /* TokenType.Colon */) {
                typeExpr = this._parseTestExpression(/* allowAssignmentExpression */ true);
                if (this._consumeTokenIfKeyword(1 /* KeywordType.As */)) {
                    symbolName = this._getTokenIfIdentifier();
                    if (!symbolName) {
                        this._addSyntaxError(localize_1.LocMessage.expectedNameAfterAs(), this._peekToken());
                    }
                }
                else {
                    // Handle the python 2.x syntax in a graceful manner.
                    const peekToken = this._peekToken();
                    if (this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                        this._addSyntaxError(localize_1.LocMessage.expectedAsAfterException(), peekToken);
                        // Parse the expression expected in python 2.x, but discard it.
                        this._parseTestExpression(/* allowAssignmentExpression */ false);
                    }
                }
            }
            if (!typeExpr) {
                if (sawCatchAllExcept) {
                    this._addSyntaxError(localize_1.LocMessage.duplicateCatchAll(), exceptToken);
                }
                sawCatchAllExcept = true;
            }
            else {
                if (sawCatchAllExcept) {
                    this._addSyntaxError(localize_1.LocMessage.namedExceptAfterCatchAll(), typeExpr);
                }
            }
            const exceptSuite = this._parseSuite(this._isInFunction);
            const exceptNode = parseNodes_1.ExceptNode.create(exceptToken, exceptSuite, isExceptGroup);
            if (typeExpr) {
                exceptNode.typeExpression = typeExpr;
                exceptNode.typeExpression.parent = exceptNode;
            }
            if (symbolName) {
                exceptNode.name = parseNodes_1.NameNode.create(symbolName);
                exceptNode.name.parent = exceptNode;
            }
            tryNode.exceptClauses.push(exceptNode);
            exceptNode.parent = tryNode;
        }
        if (tryNode.exceptClauses.length > 0) {
            (0, parseNodes_1.extendRange)(tryNode, tryNode.exceptClauses[tryNode.exceptClauses.length - 1]);
            if (this._consumeTokenIfKeyword(13 /* KeywordType.Else */)) {
                tryNode.elseSuite = this._parseSuite(this._isInFunction);
                tryNode.elseSuite.parent = tryNode;
                (0, parseNodes_1.extendRange)(tryNode, tryNode.elseSuite);
            }
        }
        if (this._consumeTokenIfKeyword(16 /* KeywordType.Finally */)) {
            tryNode.finallySuite = this._parseSuite(this._isInFunction);
            tryNode.finallySuite.parent = tryNode;
            (0, parseNodes_1.extendRange)(tryNode, tryNode.finallySuite);
        }
        if (!tryNode.finallySuite && tryNode.exceptClauses.length === 0) {
            this._addSyntaxError(localize_1.LocMessage.tryWithoutExcept(), tryToken);
        }
        return tryNode;
    }
    // funcdef: 'def' NAME parameters ['->' test] ':' suite
    // parameters: '(' [typedargslist] ')'
    _parseFunctionDef(asyncToken, decorators) {
        const defToken = this._getKeywordToken(10 /* KeywordType.Def */);
        const nameToken = this._getTokenIfIdentifier();
        if (!nameToken) {
            this._addSyntaxError(localize_1.LocMessage.expectedFunctionName(), defToken);
            return parseNodes_1.ErrorNode.create(defToken, 10 /* ErrorExpressionCategory.MissingFunctionParameterList */, undefined, decorators);
        }
        let typeParameters;
        const possibleOpenBracket = this._peekToken();
        if (possibleOpenBracket.type === 15 /* TokenType.OpenBracket */) {
            typeParameters = this._parseTypeParameterList();
            if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_12)) {
                this._addSyntaxError(localize_1.LocMessage.functionTypeParametersIllegal(), typeParameters);
            }
        }
        const openParenToken = this._peekToken();
        if (!this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedOpenParen(), this._peekToken());
            return parseNodes_1.ErrorNode.create(nameToken, 10 /* ErrorExpressionCategory.MissingFunctionParameterList */, parseNodes_1.NameNode.create(nameToken), decorators);
        }
        const paramList = this._parseVarArgsList(14 /* TokenType.CloseParenthesis */, /* allowAnnotations */ true);
        if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), openParenToken);
            this._consumeTokensUntilType([10 /* TokenType.Colon */]);
        }
        let returnType;
        if (this._consumeTokenIfType(21 /* TokenType.Arrow */)) {
            returnType = this._parseTypeAnnotation();
        }
        let functionTypeAnnotationToken;
        const suite = this._parseSuite(/* isFunction */ true, this._parseOptions.skipFunctionAndClassBody, () => {
            if (!functionTypeAnnotationToken) {
                functionTypeAnnotationToken = this._getTypeAnnotationCommentText();
            }
        });
        const functionNode = parseNodes_1.FunctionNode.create(defToken, parseNodes_1.NameNode.create(nameToken), suite, typeParameters);
        if (asyncToken) {
            functionNode.isAsync = true;
            (0, parseNodes_1.extendRange)(functionNode, asyncToken);
        }
        functionNode.parameters = paramList;
        paramList.forEach((param) => {
            param.parent = functionNode;
        });
        if (decorators) {
            functionNode.decorators = decorators;
            decorators.forEach((decorator) => {
                decorator.parent = functionNode;
            });
            if (decorators.length > 0) {
                (0, parseNodes_1.extendRange)(functionNode, decorators[0]);
            }
        }
        if (returnType) {
            functionNode.returnTypeAnnotation = returnType;
            functionNode.returnTypeAnnotation.parent = functionNode;
            (0, parseNodes_1.extendRange)(functionNode, returnType);
        }
        // If there was a type annotation comment for the function,
        // parse it now.
        if (functionTypeAnnotationToken) {
            this._parseFunctionTypeAnnotationComment(functionTypeAnnotationToken, functionNode);
        }
        return functionNode;
    }
    // typedargslist: (
    //   tfpdef ['=' test] (',' tfpdef ['=' test])*
    //      [ ','
    //          [
    //              '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
    //              | '**' tfpdef [',']
    //          ]
    //      ]
    //   | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
    //   | '**' tfpdef [','])
    // tfpdef: NAME [':' test]
    // vfpdef: NAME;
    _parseVarArgsList(terminator, allowAnnotations) {
        const paramMap = new Map();
        const paramList = [];
        let sawDefaultParam = false;
        let reportedNonDefaultParamErr = false;
        let sawKeywordOnlySeparator = false;
        let sawPositionOnlySeparator = false;
        let sawKeywordOnlyParamAfterSeparator = false;
        let sawArgs = false;
        let sawKwArgs = false;
        while (true) {
            if (this._peekTokenType() === terminator) {
                break;
            }
            const param = this._parseParameter(allowAnnotations);
            if (!param) {
                this._consumeTokensUntilType([terminator]);
                break;
            }
            if (param.name) {
                const name = param.name.value;
                if (paramMap.has(name)) {
                    this._addSyntaxError(localize_1.LocMessage.duplicateParam().format({ name }), param.name);
                }
                else {
                    paramMap.set(name, name);
                }
            }
            else if (param.category === 0 /* ParameterCategory.Simple */) {
                if (paramList.length === 0) {
                    this._addSyntaxError(localize_1.LocMessage.positionOnlyFirstParam(), param);
                }
            }
            if (param.category === 0 /* ParameterCategory.Simple */) {
                if (!param.name) {
                    if (sawPositionOnlySeparator) {
                        this._addSyntaxError(localize_1.LocMessage.duplicatePositionOnly(), param);
                    }
                    else if (sawKeywordOnlySeparator) {
                        this._addSyntaxError(localize_1.LocMessage.positionOnlyAfterKeywordOnly(), param);
                    }
                    else if (sawArgs) {
                        this._addSyntaxError(localize_1.LocMessage.positionOnlyAfterArgs(), param);
                    }
                    sawPositionOnlySeparator = true;
                }
                else {
                    if (sawKeywordOnlySeparator) {
                        sawKeywordOnlyParamAfterSeparator = true;
                    }
                    if (param.defaultValue) {
                        sawDefaultParam = true;
                    }
                    else if (sawDefaultParam && !sawKeywordOnlySeparator && !sawArgs) {
                        // Report this error only once.
                        if (!reportedNonDefaultParamErr) {
                            this._addSyntaxError(localize_1.LocMessage.nonDefaultAfterDefault(), param);
                            reportedNonDefaultParamErr = true;
                        }
                    }
                }
            }
            paramList.push(param);
            if (param.category === 1 /* ParameterCategory.ArgsList */) {
                if (!param.name) {
                    if (sawKeywordOnlySeparator) {
                        this._addSyntaxError(localize_1.LocMessage.duplicateKeywordOnly(), param);
                    }
                    else if (sawArgs) {
                        this._addSyntaxError(localize_1.LocMessage.keywordOnlyAfterArgs(), param);
                    }
                    sawKeywordOnlySeparator = true;
                }
                else {
                    if (sawKeywordOnlySeparator || sawArgs) {
                        this._addSyntaxError(localize_1.LocMessage.duplicateArgsParam(), param);
                    }
                    sawArgs = true;
                }
            }
            if (param.category === 2 /* ParameterCategory.KwargsDict */) {
                if (sawKwArgs) {
                    this._addSyntaxError(localize_1.LocMessage.duplicateKwargsParam(), param);
                }
                sawKwArgs = true;
                // A **kwargs cannot immediately follow a keyword-only separator ("*").
                if (sawKeywordOnlySeparator && !sawKeywordOnlyParamAfterSeparator) {
                    this._addSyntaxError(localize_1.LocMessage.keywordParameterMissing(), param);
                }
            }
            else if (sawKwArgs) {
                this._addSyntaxError(localize_1.LocMessage.paramAfterKwargsParam(), param);
            }
            const foundComma = this._consumeTokenIfType(12 /* TokenType.Comma */);
            if (allowAnnotations && !param.typeAnnotation) {
                // Look for a type annotation comment at the end of the line.
                const typeAnnotationComment = this._parseVariableTypeAnnotationComment();
                if (typeAnnotationComment) {
                    param.typeAnnotationComment = typeAnnotationComment;
                    param.typeAnnotationComment.parent = param;
                    (0, parseNodes_1.extendRange)(param, param.typeAnnotationComment);
                }
            }
            if (!foundComma) {
                break;
            }
        }
        if (paramList.length > 0) {
            const lastParam = paramList[paramList.length - 1];
            if (lastParam.category === 1 /* ParameterCategory.ArgsList */ && !lastParam.name) {
                this._addSyntaxError(localize_1.LocMessage.expectedNamedParameter(), lastParam);
            }
        }
        return paramList;
    }
    _parseParameter(allowAnnotations) {
        let starCount = 0;
        let slashCount = 0;
        const firstToken = this._peekToken();
        if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
            starCount = 1;
        }
        else if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
            starCount = 2;
        }
        else if (this._consumeTokenIfOperator(10 /* OperatorType.Divide */)) {
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_8) && !this._parseOptions.isStubFile) {
                this._addSyntaxError(localize_1.LocMessage.positionOnlyIncompatible(), firstToken);
            }
            slashCount = 1;
        }
        const paramName = this._getTokenIfIdentifier();
        if (!paramName) {
            if (starCount === 1) {
                const paramNode = parseNodes_1.ParameterNode.create(firstToken, 1 /* ParameterCategory.ArgsList */);
                return paramNode;
            }
            else if (slashCount === 1) {
                const paramNode = parseNodes_1.ParameterNode.create(firstToken, 0 /* ParameterCategory.Simple */);
                return paramNode;
            }
            // Check for the Python 2.x parameter sublist syntax and handle it gracefully.
            if (this._peekTokenType() === 13 /* TokenType.OpenParenthesis */) {
                const sublistStart = this._getNextToken();
                if (this._consumeTokensUntilType([14 /* TokenType.CloseParenthesis */])) {
                    this._getNextToken();
                }
                this._addSyntaxError(localize_1.LocMessage.sublistParamsIncompatible(), sublistStart);
            }
            else {
                this._addSyntaxError(localize_1.LocMessage.expectedParamName(), this._peekToken());
            }
        }
        let paramType = 0 /* ParameterCategory.Simple */;
        if (starCount === 1) {
            paramType = 1 /* ParameterCategory.ArgsList */;
        }
        else if (starCount === 2) {
            paramType = 2 /* ParameterCategory.KwargsDict */;
        }
        const paramNode = parseNodes_1.ParameterNode.create(firstToken, paramType);
        if (paramName) {
            paramNode.name = parseNodes_1.NameNode.create(paramName);
            paramNode.name.parent = paramNode;
            (0, parseNodes_1.extendRange)(paramNode, paramName);
        }
        if (allowAnnotations && this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            paramNode.typeAnnotation = this._parseTypeAnnotation(paramType === 1 /* ParameterCategory.ArgsList */);
            paramNode.typeAnnotation.parent = paramNode;
            (0, parseNodes_1.extendRange)(paramNode, paramNode.typeAnnotation);
        }
        if (this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
            paramNode.defaultValue = this._parseTestExpression(/* allowAssignmentExpression */ false);
            paramNode.defaultValue.parent = paramNode;
            (0, parseNodes_1.extendRange)(paramNode, paramNode.defaultValue);
            if (starCount > 0) {
                this._addSyntaxError(localize_1.LocMessage.defaultValueNotAllowed(), paramNode.defaultValue);
            }
        }
        return paramNode;
    }
    // with_stmt: 'with' with_item (',' with_item)*  ':' suite
    // Python 3.10 adds support for optional parentheses around
    // with_item list.
    _parseWithStatement(asyncToken) {
        const withToken = this._getKeywordToken(37 /* KeywordType.With */);
        let withItemList = [];
        const possibleParen = this._peekToken();
        // If the expression starts with a paren, parse it as though the
        // paren is enclosing the list of "with items". This is done as a
        // "dry run" to determine whether the entire list of "with items"
        // is enclosed in parentheses.
        let isParenthesizedWithItemList = false;
        if (possibleParen.type === 13 /* TokenType.OpenParenthesis */) {
            const openParenTokenIndex = this._tokenIndex;
            this._suppressErrors(() => {
                this._getNextToken();
                while (true) {
                    withItemList.push(this._parseWithItem());
                    if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                        break;
                    }
                    if (this._peekToken().type === 14 /* TokenType.CloseParenthesis */) {
                        break;
                    }
                }
                if (this._peekToken().type === 14 /* TokenType.CloseParenthesis */ &&
                    this._peekToken(1).type === 10 /* TokenType.Colon */) {
                    isParenthesizedWithItemList = withItemList.length !== 1 || withItemList[0].target !== undefined;
                }
                this._tokenIndex = openParenTokenIndex;
                withItemList = [];
            });
        }
        if (isParenthesizedWithItemList) {
            this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */);
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_9)) {
                this._addSyntaxError(localize_1.LocMessage.parenthesizedContextManagerIllegal(), possibleParen);
            }
        }
        while (true) {
            withItemList.push(this._parseWithItem());
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
            if (this._peekToken().type === 14 /* TokenType.CloseParenthesis */) {
                break;
            }
        }
        if (isParenthesizedWithItemList) {
            if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
                this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), possibleParen);
            }
        }
        let typeComment;
        const withSuite = this._parseSuite(this._isInFunction, /* skipBody */ false, () => {
            const comment = this._getTypeAnnotationCommentText();
            if (comment) {
                typeComment = comment;
            }
        });
        const withNode = parseNodes_1.WithNode.create(withToken, withSuite);
        if (asyncToken) {
            withNode.isAsync = true;
            withNode.asyncToken = asyncToken;
            (0, parseNodes_1.extendRange)(withNode, asyncToken);
        }
        if (typeComment) {
            withNode.typeComment = typeComment;
        }
        withNode.withItems = withItemList;
        withItemList.forEach((withItem) => {
            withItem.parent = withNode;
        });
        return withNode;
    }
    // with_item: test ['as' expr]
    _parseWithItem() {
        const expr = this._parseTestExpression(/* allowAssignmentExpression */ true);
        const itemNode = parseNodes_1.WithItemNode.create(expr);
        if (this._consumeTokenIfKeyword(1 /* KeywordType.As */)) {
            itemNode.target = this._parseExpression(/* allowUnpack */ false);
            itemNode.target.parent = itemNode;
            (0, parseNodes_1.extendRange)(itemNode, itemNode.target);
        }
        return itemNode;
    }
    // decorators: decorator+
    // decorated: decorators (classdef | funcdef | async_funcdef)
    _parseDecorated() {
        const decoratorList = [];
        while (true) {
            if (this._peekOperatorType() === 22 /* OperatorType.MatrixMultiply */) {
                decoratorList.push(this._parseDecorator());
            }
            else {
                break;
            }
        }
        const nextToken = this._peekToken();
        if (nextToken.type === 8 /* TokenType.Keyword */) {
            if (nextToken.keywordType === 3 /* KeywordType.Async */) {
                this._getNextToken();
                if (this._peekKeywordType() !== 10 /* KeywordType.Def */) {
                    this._addSyntaxError(localize_1.LocMessage.expectedFunctionAfterAsync(), this._peekToken());
                }
                else {
                    return this._parseFunctionDef(nextToken, decoratorList);
                }
            }
            else if (nextToken.keywordType === 10 /* KeywordType.Def */) {
                return this._parseFunctionDef(undefined, decoratorList);
            }
            else if (nextToken.keywordType === 7 /* KeywordType.Class */) {
                return this._parseClassDef(decoratorList);
            }
        }
        this._addSyntaxError(localize_1.LocMessage.expectedAfterDecorator(), this._peekToken());
        // Return a dummy class declaration so the completion provider has
        // some parse nodes to work with.
        return parseNodes_1.ClassNode.createDummyForDecorators(decoratorList);
    }
    // decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
    _parseDecorator() {
        const atOperator = this._getNextToken();
        (0, debug_1.assert)(atOperator.operatorType === 22 /* OperatorType.MatrixMultiply */);
        const expression = this._parseTestExpression(/* allowAssignmentExpression */ true);
        // Versions of Python prior to 3.9 support a limited set of
        // expression forms.
        if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_9)) {
            let isSupportedExpressionForm = false;
            if (this._isNameOrMemberAccessExpression(expression)) {
                isSupportedExpressionForm = true;
            }
            else if (expression.nodeType === 9 /* ParseNodeType.Call */ &&
                this._isNameOrMemberAccessExpression(expression.leftExpression)) {
                isSupportedExpressionForm = true;
            }
            if (!isSupportedExpressionForm) {
                this._addSyntaxError(localize_1.LocMessage.expectedDecoratorExpr(), expression);
            }
        }
        const decoratorNode = parseNodes_1.DecoratorNode.create(atOperator, expression);
        if (!this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedDecoratorNewline(), this._peekToken());
            this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
        }
        return decoratorNode;
    }
    _isNameOrMemberAccessExpression(expression) {
        if (expression.nodeType === 38 /* ParseNodeType.Name */) {
            return true;
        }
        else if (expression.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            return this._isNameOrMemberAccessExpression(expression.leftExpression);
        }
        return false;
    }
    // classdef: 'class' NAME ['(' [arglist] ')'] suite
    _parseClassDef(decorators) {
        const classToken = this._getKeywordToken(7 /* KeywordType.Class */);
        let nameToken = this._getTokenIfIdentifier();
        if (!nameToken) {
            this._addSyntaxError(localize_1.LocMessage.expectedClassName(), this._peekToken());
            nameToken = tokenizerTypes_1.IdentifierToken.create(0, 0, '', /* comments */ undefined);
        }
        let typeParameters;
        const possibleOpenBracket = this._peekToken();
        if (possibleOpenBracket.type === 15 /* TokenType.OpenBracket */) {
            typeParameters = this._parseTypeParameterList();
            if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_12)) {
                this._addSyntaxError(localize_1.LocMessage.classTypeParametersIllegal(), typeParameters);
            }
        }
        let argList = [];
        const openParenToken = this._peekToken();
        if (this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */)) {
            argList = this._parseArgList().args;
            if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
                this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), openParenToken);
            }
        }
        const suite = this._parseSuite(/* isFunction */ false, this._parseOptions.skipFunctionAndClassBody);
        const classNode = parseNodes_1.ClassNode.create(classToken, parseNodes_1.NameNode.create(nameToken), suite, typeParameters);
        classNode.arguments = argList;
        argList.forEach((arg) => {
            arg.parent = classNode;
        });
        if (decorators) {
            classNode.decorators = decorators;
            if (decorators.length > 0) {
                decorators.forEach((decorator) => {
                    decorator.parent = classNode;
                });
                (0, parseNodes_1.extendRange)(classNode, decorators[0]);
            }
        }
        return classNode;
    }
    _parsePassStatement() {
        return parseNodes_1.PassNode.create(this._getKeywordToken(30 /* KeywordType.Pass */));
    }
    _parseBreakStatement() {
        const breakToken = this._getKeywordToken(5 /* KeywordType.Break */);
        if (!this._isInLoop) {
            this._addSyntaxError(localize_1.LocMessage.breakOutsideLoop(), breakToken);
        }
        return parseNodes_1.BreakNode.create(breakToken);
    }
    _parseContinueStatement() {
        const continueToken = this._getKeywordToken(8 /* KeywordType.Continue */);
        if (!this._isInLoop) {
            this._addSyntaxError(localize_1.LocMessage.continueOutsideLoop(), continueToken);
        }
        else if (this._isInFinally) {
            this._addSyntaxError(localize_1.LocMessage.continueInFinally(), continueToken);
        }
        return parseNodes_1.ContinueNode.create(continueToken);
    }
    // return_stmt: 'return' [testlist]
    _parseReturnStatement() {
        const returnToken = this._getKeywordToken(32 /* KeywordType.Return */);
        const returnNode = parseNodes_1.ReturnNode.create(returnToken);
        if (!this._isInFunction) {
            this._addSyntaxError(localize_1.LocMessage.returnOutsideFunction(), returnToken);
        }
        if (!this._isNextTokenNeverExpression()) {
            const returnExpr = this._parseTestOrStarListAsExpression(
            /* allowAssignmentExpression */ true, 
            /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedReturnExpr());
            this._reportConditionalErrorForStarTupleElement(returnExpr);
            returnNode.returnExpression = returnExpr;
            returnNode.returnExpression.parent = returnNode;
            (0, parseNodes_1.extendRange)(returnNode, returnExpr);
        }
        return returnNode;
    }
    // import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
    //             'import' ('*' | '(' import_as_names ')' | import_as_names))
    // import_as_names: import_as_name (',' import_as_name)* [',']
    // import_as_name: NAME ['as' NAME]
    _parseFromStatement() {
        const fromToken = this._getKeywordToken(18 /* KeywordType.From */);
        const modName = this._parseDottedModuleName(/* allowJustDots */ true);
        const importFromNode = parseNodes_1.ImportFromNode.create(fromToken, modName);
        // Handle imports from __future__ specially because they can
        // change the way we interpret the rest of the file.
        const isFutureImport = modName.leadingDots === 0 && modName.nameParts.length === 1 && modName.nameParts[0].value === '__future__';
        const possibleInputToken = this._peekToken();
        if (!this._consumeTokenIfKeyword(21 /* KeywordType.Import */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedImport(), this._peekToken());
            if (!modName.hasTrailingDot) {
                importFromNode.missingImportKeyword = true;
            }
        }
        else {
            (0, parseNodes_1.extendRange)(importFromNode, possibleInputToken);
            // Look for "*" token.
            const possibleStarToken = this._peekToken();
            if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
                (0, parseNodes_1.extendRange)(importFromNode, possibleStarToken);
                importFromNode.isWildcardImport = true;
                importFromNode.wildcardToken = possibleStarToken;
                this._containsWildcardImport = true;
            }
            else {
                const openParenToken = this._peekToken();
                const inParen = this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */);
                let trailingCommaToken;
                while (true) {
                    const importName = this._getTokenIfIdentifier();
                    if (!importName) {
                        break;
                    }
                    trailingCommaToken = undefined;
                    const importFromAsNode = parseNodes_1.ImportFromAsNode.create(parseNodes_1.NameNode.create(importName));
                    if (this._consumeTokenIfKeyword(1 /* KeywordType.As */)) {
                        const aliasName = this._getTokenIfIdentifier();
                        if (!aliasName) {
                            this._addSyntaxError(localize_1.LocMessage.expectedImportAlias(), this._peekToken());
                        }
                        else {
                            importFromAsNode.alias = parseNodes_1.NameNode.create(aliasName);
                            importFromAsNode.alias.parent = importFromAsNode;
                            (0, parseNodes_1.extendRange)(importFromAsNode, aliasName);
                        }
                    }
                    importFromNode.imports.push(importFromAsNode);
                    importFromAsNode.parent = importFromNode;
                    (0, parseNodes_1.extendRange)(importFromNode, importFromAsNode);
                    if (isFutureImport) {
                        // Add the future import by name.
                        this._futureImports.add(importName.value);
                    }
                    const nextToken = this._peekToken();
                    if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                        break;
                    }
                    trailingCommaToken = nextToken;
                }
                if (importFromNode.imports.length === 0) {
                    this._addSyntaxError(localize_1.LocMessage.expectedImportSymbols(), this._peekToken());
                }
                if (inParen) {
                    importFromNode.usesParens = true;
                    const nextToken = this._peekToken();
                    if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
                        this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), openParenToken);
                    }
                    else {
                        (0, parseNodes_1.extendRange)(importFromNode, nextToken);
                    }
                }
                else if (trailingCommaToken) {
                    this._addSyntaxError(localize_1.LocMessage.trailingCommaInFromImport(), trailingCommaToken);
                }
            }
        }
        this._importedModules.push({
            nameNode: importFromNode.module,
            leadingDots: importFromNode.module.leadingDots,
            nameParts: importFromNode.module.nameParts.map((p) => p.value),
            importedSymbols: new Set(importFromNode.imports.map((imp) => imp.name.value)),
        });
        let isTypingImport = false;
        if (importFromNode.module.nameParts.length === 1) {
            const firstNamePartValue = importFromNode.module.nameParts[0].value;
            if (firstNamePartValue === 'typing' || firstNamePartValue === 'typing_extensions') {
                isTypingImport = true;
            }
        }
        if (isTypingImport) {
            const typingSymbolsOfInterest = ['Literal', 'TypeAlias', 'Annotated'];
            if (importFromNode.isWildcardImport) {
                typingSymbolsOfInterest.forEach((s) => {
                    this._typingSymbolAliases.set(s, s);
                });
            }
            else {
                importFromNode.imports.forEach((imp) => {
                    var _a;
                    if (typingSymbolsOfInterest.some((s) => s === imp.name.value)) {
                        this._typingSymbolAliases.set(((_a = imp.alias) === null || _a === void 0 ? void 0 : _a.value) || imp.name.value, imp.name.value);
                    }
                });
            }
        }
        return importFromNode;
    }
    // import_name: 'import' dotted_as_names
    // dotted_as_names: dotted_as_name (',' dotted_as_name)*
    // dotted_as_name: dotted_name ['as' NAME]
    _parseImportStatement() {
        var _a;
        const importToken = this._getKeywordToken(21 /* KeywordType.Import */);
        const importNode = parseNodes_1.ImportNode.create(importToken);
        while (true) {
            const modName = this._parseDottedModuleName();
            const importAsNode = parseNodes_1.ImportAsNode.create(modName);
            if (this._consumeTokenIfKeyword(1 /* KeywordType.As */)) {
                const aliasToken = this._getTokenIfIdentifier();
                if (aliasToken) {
                    importAsNode.alias = parseNodes_1.NameNode.create(aliasToken);
                    importAsNode.alias.parent = importAsNode;
                    (0, parseNodes_1.extendRange)(importAsNode, importAsNode.alias);
                }
                else {
                    this._addSyntaxError(localize_1.LocMessage.expectedImportAlias(), this._peekToken());
                }
            }
            if (importAsNode.module.leadingDots > 0) {
                this._addSyntaxError(localize_1.LocMessage.relativeImportNotAllowed(), importAsNode.module);
            }
            importNode.list.push(importAsNode);
            importAsNode.parent = importNode;
            const nameParts = importAsNode.module.nameParts.map((p) => p.value);
            if (importAsNode.alias ||
                importAsNode.module.leadingDots > 0 ||
                importAsNode.module.nameParts.length === 0) {
                this._importedModules.push({
                    nameNode: importAsNode.module,
                    leadingDots: importAsNode.module.leadingDots,
                    nameParts,
                    importedSymbols: undefined,
                });
            }
            else {
                // Implicitly import all modules in the multi-part name if we
                // are not assigning the final module to an alias.
                importAsNode.module.nameParts.forEach((_, index) => {
                    this._importedModules.push({
                        nameNode: importAsNode.module,
                        leadingDots: importAsNode.module.leadingDots,
                        nameParts: nameParts.slice(0, index + 1),
                        importedSymbols: undefined,
                    });
                });
            }
            if (modName.nameParts.length === 1) {
                const firstNamePartValue = modName.nameParts[0].value;
                if (firstNamePartValue === 'typing' || firstNamePartValue === 'typing_extensions') {
                    this._typingImportAliases.push(((_a = importAsNode.alias) === null || _a === void 0 ? void 0 : _a.value) || firstNamePartValue);
                }
            }
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
        }
        if (importNode.list.length > 0) {
            (0, parseNodes_1.extendRange)(importNode, importNode.list[importNode.list.length - 1]);
        }
        return importNode;
    }
    // ('.' | '...')* dotted_name | ('.' | '...')+
    // dotted_name: NAME ('.' NAME)*
    _parseDottedModuleName(allowJustDots = false) {
        var _a;
        const moduleNameNode = parseNodes_1.ModuleNameNode.create(this._peekToken());
        while (true) {
            const token = (_a = this._getTokenIfType(19 /* TokenType.Ellipsis */)) !== null && _a !== void 0 ? _a : this._getTokenIfType(20 /* TokenType.Dot */);
            if (token) {
                if (token.type === 19 /* TokenType.Ellipsis */) {
                    moduleNameNode.leadingDots += 3;
                }
                else {
                    moduleNameNode.leadingDots++;
                }
                (0, parseNodes_1.extendRange)(moduleNameNode, token);
            }
            else {
                break;
            }
        }
        while (true) {
            const identifier = this._getTokenIfIdentifier();
            if (!identifier) {
                if (!allowJustDots || moduleNameNode.leadingDots === 0 || moduleNameNode.nameParts.length > 0) {
                    this._addSyntaxError(localize_1.LocMessage.expectedModuleName(), this._peekToken());
                    moduleNameNode.hasTrailingDot = true;
                }
                break;
            }
            const namePart = parseNodes_1.NameNode.create(identifier);
            moduleNameNode.nameParts.push(namePart);
            namePart.parent = moduleNameNode;
            (0, parseNodes_1.extendRange)(moduleNameNode, namePart);
            const nextToken = this._peekToken();
            if (!this._consumeTokenIfType(20 /* TokenType.Dot */)) {
                break;
            }
            // Extend the module name to include the dot.
            (0, parseNodes_1.extendRange)(moduleNameNode, nextToken);
        }
        return moduleNameNode;
    }
    _parseGlobalStatement() {
        const globalToken = this._getKeywordToken(19 /* KeywordType.Global */);
        const globalNode = parseNodes_1.GlobalNode.create(globalToken);
        globalNode.nameList = this._parseNameList();
        if (globalNode.nameList.length > 0) {
            globalNode.nameList.forEach((name) => {
                name.parent = globalNode;
            });
            (0, parseNodes_1.extendRange)(globalNode, globalNode.nameList[globalNode.nameList.length - 1]);
        }
        return globalNode;
    }
    _parseNonlocalStatement() {
        const nonlocalToken = this._getKeywordToken(27 /* KeywordType.Nonlocal */);
        const nonlocalNode = parseNodes_1.NonlocalNode.create(nonlocalToken);
        nonlocalNode.nameList = this._parseNameList();
        if (nonlocalNode.nameList.length > 0) {
            nonlocalNode.nameList.forEach((name) => {
                name.parent = nonlocalNode;
            });
            (0, parseNodes_1.extendRange)(nonlocalNode, nonlocalNode.nameList[nonlocalNode.nameList.length - 1]);
        }
        return nonlocalNode;
    }
    _parseNameList() {
        const nameList = [];
        while (true) {
            const name = this._getTokenIfIdentifier();
            if (!name) {
                this._addSyntaxError(localize_1.LocMessage.expectedIdentifier(), this._peekToken());
                break;
            }
            nameList.push(parseNodes_1.NameNode.create(name));
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
        }
        return nameList;
    }
    // raise_stmt: 'raise' [test ['from' test]]
    // (old) raise_stmt: 'raise' [test [',' test [',' test]]]
    _parseRaiseStatement() {
        const raiseToken = this._getKeywordToken(31 /* KeywordType.Raise */);
        const raiseNode = parseNodes_1.RaiseNode.create(raiseToken);
        if (!this._isNextTokenNeverExpression()) {
            raiseNode.typeExpression = this._parseTestExpression(/* allowAssignmentExpression */ true);
            raiseNode.typeExpression.parent = raiseNode;
            (0, parseNodes_1.extendRange)(raiseNode, raiseNode.typeExpression);
            if (this._consumeTokenIfKeyword(18 /* KeywordType.From */)) {
                raiseNode.valueExpression = this._parseTestExpression(/* allowAssignmentExpression */ true);
                raiseNode.valueExpression.parent = raiseNode;
                (0, parseNodes_1.extendRange)(raiseNode, raiseNode.valueExpression);
            }
            else {
                if (this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                    // Handle the Python 2.x variant
                    raiseNode.valueExpression = this._parseTestExpression(/* allowAssignmentExpression */ true);
                    raiseNode.valueExpression.parent = raiseNode;
                    (0, parseNodes_1.extendRange)(raiseNode, raiseNode.valueExpression);
                    if (this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                        raiseNode.tracebackExpression = this._parseTestExpression(/* allowAssignmentExpression */ true);
                        raiseNode.tracebackExpression.parent = raiseNode;
                        (0, parseNodes_1.extendRange)(raiseNode, raiseNode.tracebackExpression);
                    }
                }
            }
        }
        return raiseNode;
    }
    // assert_stmt: 'assert' test [',' test]
    _parseAssertStatement() {
        const assertToken = this._getKeywordToken(2 /* KeywordType.Assert */);
        const expr = this._parseTestExpression(/* allowAssignmentExpression */ false);
        const assertNode = parseNodes_1.AssertNode.create(assertToken, expr);
        if (this._consumeTokenIfType(12 /* TokenType.Comma */)) {
            const exceptionExpr = this._parseTestExpression(/* allowAssignmentExpression */ false);
            assertNode.exceptionExpression = exceptionExpr;
            assertNode.exceptionExpression.parent = assertNode;
            (0, parseNodes_1.extendRange)(assertNode, exceptionExpr);
        }
        return assertNode;
    }
    // del_stmt: 'del' exprlist
    _parseDelStatement() {
        const delToken = this._getKeywordToken(11 /* KeywordType.Del */);
        const exprListResult = this._parseExpressionList(/* allowStar */ true);
        if (!exprListResult.parseError && exprListResult.list.length === 0) {
            this._addSyntaxError(localize_1.LocMessage.expectedDelExpr(), this._peekToken());
        }
        const delNode = parseNodes_1.DelNode.create(delToken);
        delNode.expressions = exprListResult.list;
        if (delNode.expressions.length > 0) {
            delNode.expressions.forEach((expr) => {
                expr.parent = delNode;
            });
            (0, parseNodes_1.extendRange)(delNode, delNode.expressions[delNode.expressions.length - 1]);
        }
        return delNode;
    }
    // yield_expr: 'yield' [yield_arg]
    // yield_arg: 'from' test | testlist
    _parseYieldExpression() {
        const yieldToken = this._getKeywordToken(38 /* KeywordType.Yield */);
        const nextToken = this._peekToken();
        if (this._consumeTokenIfKeyword(18 /* KeywordType.From */)) {
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_3)) {
                this._addSyntaxError(localize_1.LocMessage.yieldFromIllegal(), nextToken);
            }
            return parseNodes_1.YieldFromNode.create(yieldToken, this._parseTestExpression(/* allowAssignmentExpression */ false));
        }
        let exprList;
        if (!this._isNextTokenNeverExpression()) {
            exprList = this._parseTestOrStarListAsExpression(
            /* allowAssignmentExpression */ false, 
            /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedYieldExpr());
            this._reportConditionalErrorForStarTupleElement(exprList);
        }
        return parseNodes_1.YieldNode.create(yieldToken, exprList);
    }
    _tryParseYieldExpression() {
        if (this._peekKeywordType() !== 38 /* KeywordType.Yield */) {
            return undefined;
        }
        return this._parseYieldExpression();
    }
    // simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
    _parseSimpleStatement() {
        const statement = parseNodes_1.StatementListNode.create(this._peekToken());
        while (true) {
            // Swallow invalid tokens to make sure we make forward progress.
            if (this._peekTokenType() === 0 /* TokenType.Invalid */) {
                const invalidToken = this._getNextToken();
                const text = this._fileContents.substr(invalidToken.start, invalidToken.length);
                const firstCharCode = text.charCodeAt(0);
                // Remove any non-printable characters.
                this._addSyntaxError(localize_1.LocMessage.invalidTokenChars().format({ text: `\\u${firstCharCode.toString(16)}` }), invalidToken);
                this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
                break;
            }
            const smallStatement = this._parseSmallStatement();
            statement.statements.push(smallStatement);
            smallStatement.parent = statement;
            (0, parseNodes_1.extendRange)(statement, smallStatement);
            if (smallStatement.nodeType === 0 /* ParseNodeType.Error */) {
                // No need to log an error here. We assume that
                // it was already logged by _parseSmallStatement.
                break;
            }
            // Consume the semicolon if present.
            if (!this._consumeTokenIfType(11 /* TokenType.Semicolon */)) {
                break;
            }
            const nextTokenType = this._peekTokenType();
            if (nextTokenType === 2 /* TokenType.NewLine */ || nextTokenType === 1 /* TokenType.EndOfStream */) {
                break;
            }
        }
        if (!this._consumeTokenIfType(2 /* TokenType.NewLine */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedNewlineOrSemicolon(), this._peekToken());
        }
        return statement;
    }
    // small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
    //             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
    // flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
    // import_stmt: import_name | import_from
    _parseSmallStatement() {
        switch (this._peekKeywordType()) {
            case 30 /* KeywordType.Pass */:
                return this._parsePassStatement();
            case 5 /* KeywordType.Break */:
                return this._parseBreakStatement();
            case 8 /* KeywordType.Continue */:
                return this._parseContinueStatement();
            case 32 /* KeywordType.Return */:
                return this._parseReturnStatement();
            case 18 /* KeywordType.From */:
                return this._parseFromStatement();
            case 21 /* KeywordType.Import */:
                return this._parseImportStatement();
            case 19 /* KeywordType.Global */:
                return this._parseGlobalStatement();
            case 27 /* KeywordType.Nonlocal */:
                return this._parseNonlocalStatement();
            case 31 /* KeywordType.Raise */:
                return this._parseRaiseStatement();
            case 2 /* KeywordType.Assert */:
                return this._parseAssertStatement();
            case 11 /* KeywordType.Del */:
                return this._parseDelStatement();
            case 38 /* KeywordType.Yield */:
                return this._parseYieldExpression();
            case 35 /* KeywordType.Type */: {
                // Type is considered a "soft" keyword, so we will treat it
                // as an identifier if it is followed by an unexpected token.
                const peekToken1 = this._peekToken(1);
                const peekToken2 = this._peekToken(2);
                let isInvalidTypeToken = true;
                if (peekToken1.type === 7 /* TokenType.Identifier */ || peekToken1.type === 8 /* TokenType.Keyword */) {
                    if (peekToken2.type === 15 /* TokenType.OpenBracket */) {
                        isInvalidTypeToken = false;
                    }
                    else if (peekToken2.type === 9 /* TokenType.Operator */ &&
                        peekToken2.operatorType === 2 /* OperatorType.Assign */) {
                        isInvalidTypeToken = false;
                    }
                }
                if (!isInvalidTypeToken) {
                    return this._parseTypeAliasStatement();
                }
                break;
            }
        }
        return this._parseExpressionStatement();
    }
    _makeExpressionOrTuple(exprListResult, enclosedInParens) {
        // A single-element tuple with no trailing comma is simply an expression
        // that's surrounded by parens.
        if (exprListResult.list.length === 1 && !exprListResult.trailingComma) {
            if (exprListResult.list[0].nodeType === 56 /* ParseNodeType.Unpack */) {
                this._addSyntaxError(localize_1.LocMessage.unpackOperatorNotAllowed(), exprListResult.list[0]);
            }
            return exprListResult.list[0];
        }
        // To accommodate empty tuples ("()"), we will reach back to get
        // the opening parenthesis as the opening token.
        const tupleStartRange = exprListResult.list.length > 0 ? exprListResult.list[0] : this._peekToken(-1);
        const tupleNode = parseNodes_1.TupleNode.create(tupleStartRange, enclosedInParens);
        tupleNode.expressions = exprListResult.list;
        if (exprListResult.list.length > 0) {
            exprListResult.list.forEach((expr) => {
                expr.parent = tupleNode;
            });
            (0, parseNodes_1.extendRange)(tupleNode, exprListResult.list[exprListResult.list.length - 1]);
        }
        return tupleNode;
    }
    _parseExpressionListAsPossibleTuple(errorCategory, getErrorString, errorToken) {
        if (this._isNextTokenNeverExpression()) {
            this._addSyntaxError(getErrorString(), errorToken);
            return parseNodes_1.ErrorNode.create(errorToken, errorCategory);
        }
        const exprListResult = this._parseExpressionList(/* allowStar */ true);
        if (exprListResult.parseError) {
            return exprListResult.parseError;
        }
        return this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ false);
    }
    _parseTestListAsExpression(errorCategory, getErrorString) {
        if (this._isNextTokenNeverExpression()) {
            return this._handleExpressionParseError(errorCategory, getErrorString());
        }
        const exprListResult = this._parseTestExpressionList();
        if (exprListResult.parseError) {
            return exprListResult.parseError;
        }
        return this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ false);
    }
    _parseTestOrStarListAsExpression(allowAssignmentExpression, allowMultipleUnpack, errorCategory, getErrorString) {
        if (this._isNextTokenNeverExpression()) {
            return this._handleExpressionParseError(errorCategory, getErrorString());
        }
        const exprListResult = this._parseTestOrStarExpressionList(allowAssignmentExpression, allowMultipleUnpack);
        if (exprListResult.parseError) {
            return exprListResult.parseError;
        }
        return this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ false);
    }
    _parseExpressionList(allowStar) {
        return this._parseExpressionListGeneric(() => this._parseExpression(allowStar));
    }
    // testlist: test (',' test)* [',']
    _parseTestExpressionList() {
        return this._parseExpressionListGeneric(() => this._parseTestExpression(/* allowAssignmentExpression */ false));
    }
    _parseTestOrStarExpressionList(allowAssignmentExpression, allowMultipleUnpack) {
        const exprListResult = this._parseExpressionListGeneric(() => this._parseTestOrStarExpression(allowAssignmentExpression));
        if (!allowMultipleUnpack && !exprListResult.parseError) {
            let sawStar = false;
            for (const expr of exprListResult.list) {
                if (expr.nodeType === 56 /* ParseNodeType.Unpack */) {
                    if (sawStar) {
                        this._addSyntaxError(localize_1.LocMessage.duplicateUnpack(), expr);
                        break;
                    }
                    sawStar = true;
                }
            }
        }
        return exprListResult;
    }
    // exp_or_star: expr | star_expr
    // expr: xor_expr ('|' xor_expr)*
    // star_expr: '*' expr
    _parseExpression(allowUnpack) {
        const startToken = this._peekToken();
        if (allowUnpack && this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
            return parseNodes_1.UnpackNode.create(startToken, this._parseExpression(/* allowUnpack */ false));
        }
        return this._parseBitwiseOrExpression();
    }
    // test_or_star: test | star_expr
    _parseTestOrStarExpression(allowAssignmentExpression) {
        if (this._peekOperatorType() === 26 /* OperatorType.Multiply */) {
            return this._parseExpression(/* allowUnpack */ true);
        }
        return this._parseTestExpression(allowAssignmentExpression);
    }
    // test: or_test ['if' or_test 'else' test] | lambdef
    _parseTestExpression(allowAssignmentExpression) {
        if (this._peekKeywordType() === 24 /* KeywordType.Lambda */) {
            return this._parseLambdaExpression();
        }
        const ifExpr = this._parseAssignmentExpression(!allowAssignmentExpression);
        if (ifExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return ifExpr;
        }
        if (!this._consumeTokenIfKeyword(20 /* KeywordType.If */)) {
            return ifExpr;
        }
        const testExpr = this._parseOrTest();
        if (testExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return testExpr;
        }
        if (!this._consumeTokenIfKeyword(13 /* KeywordType.Else */)) {
            return parseNodes_1.TernaryNode.create(ifExpr, testExpr, this._handleExpressionParseError(1 /* ErrorExpressionCategory.MissingElse */, localize_1.LocMessage.expectedElse()));
        }
        const elseExpr = this._parseTestExpression(/* allowAssignmentExpression */ true);
        return parseNodes_1.TernaryNode.create(ifExpr, testExpr, elseExpr);
    }
    // assign_expr: NAME := test
    _parseAssignmentExpression(disallowAssignmentExpression = false) {
        const leftExpr = this._parseOrTest();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        if (leftExpr.nodeType !== 38 /* ParseNodeType.Name */) {
            return leftExpr;
        }
        const walrusToken = this._peekToken();
        if (!this._consumeTokenIfOperator(35 /* OperatorType.Walrus */)) {
            return leftExpr;
        }
        if (!this._assignmentExpressionsAllowed || disallowAssignmentExpression) {
            this._addSyntaxError(localize_1.LocMessage.walrusNotAllowed(), walrusToken);
        }
        if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_8)) {
            this._addSyntaxError(localize_1.LocMessage.walrusIllegal(), walrusToken);
        }
        const rightExpr = this._parseTestExpression(/* allowAssignmentExpression */ false);
        return parseNodes_1.AssignmentExpressionNode.create(leftExpr, rightExpr);
    }
    // or_test: and_test ('or' and_test)*
    _parseOrTest() {
        let leftExpr = this._parseAndTest();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            const peekToken = this._peekToken();
            if (!this._consumeTokenIfKeyword(29 /* KeywordType.Or */)) {
                break;
            }
            const rightExpr = this._parseAndTest();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 37 /* OperatorType.Or */);
        }
        return leftExpr;
    }
    // and_test: not_test ('and' not_test)*
    _parseAndTest() {
        let leftExpr = this._parseNotTest();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            const peekToken = this._peekToken();
            if (!this._consumeTokenIfKeyword(0 /* KeywordType.And */)) {
                break;
            }
            const rightExpr = this._parseNotTest();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 36 /* OperatorType.And */);
        }
        return leftExpr;
    }
    // not_test: 'not' not_test | comparison
    _parseNotTest() {
        const notToken = this._peekToken();
        if (this._consumeTokenIfKeyword(28 /* KeywordType.Not */)) {
            const notExpr = this._parseNotTest();
            return this._createUnaryOperationNode(notToken, notExpr, 38 /* OperatorType.Not */);
        }
        return this._parseComparison();
    }
    // comparison: expr (comp_op expr)*
    // comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
    _parseComparison() {
        let leftExpr = this._parseBitwiseOrExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            let comparisonOperator;
            const peekToken = this._peekToken();
            if (tokenizer_1.Tokenizer.isOperatorComparison(this._peekOperatorType())) {
                comparisonOperator = this._peekOperatorType();
                if (comparisonOperator === 19 /* OperatorType.LessOrGreaterThan */) {
                    this._addSyntaxError(localize_1.LocMessage.operatorLessOrGreaterDeprecated(), peekToken);
                    comparisonOperator = 28 /* OperatorType.NotEquals */;
                }
                this._getNextToken();
            }
            else if (this._consumeTokenIfKeyword(22 /* KeywordType.In */)) {
                comparisonOperator = 41 /* OperatorType.In */;
            }
            else if (this._consumeTokenIfKeyword(23 /* KeywordType.Is */)) {
                if (this._consumeTokenIfKeyword(28 /* KeywordType.Not */)) {
                    comparisonOperator = 40 /* OperatorType.IsNot */;
                }
                else {
                    comparisonOperator = 39 /* OperatorType.Is */;
                }
            }
            else if (this._peekKeywordType() === 28 /* KeywordType.Not */) {
                const tokenAfterNot = this._peekToken(1);
                if (tokenAfterNot.type === 8 /* TokenType.Keyword */ &&
                    tokenAfterNot.keywordType === 22 /* KeywordType.In */) {
                    this._getNextToken();
                    this._getNextToken();
                    comparisonOperator = 42 /* OperatorType.NotIn */;
                }
            }
            if (comparisonOperator === undefined) {
                break;
            }
            const rightExpr = this._parseComparison();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, comparisonOperator);
        }
        return leftExpr;
    }
    // expr: xor_expr ('|' xor_expr)*
    _parseBitwiseOrExpression() {
        let leftExpr = this._parseBitwiseXorExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            const peekToken = this._peekToken();
            if (!this._consumeTokenIfOperator(6 /* OperatorType.BitwiseOr */)) {
                break;
            }
            const rightExpr = this._parseBitwiseXorExpression();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 6 /* OperatorType.BitwiseOr */);
        }
        return leftExpr;
    }
    // xor_expr: and_expr ('^' and_expr)*
    _parseBitwiseXorExpression() {
        let leftExpr = this._parseBitwiseAndExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            const peekToken = this._peekToken();
            if (!this._consumeTokenIfOperator(8 /* OperatorType.BitwiseXor */)) {
                break;
            }
            const rightExpr = this._parseBitwiseAndExpression();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 8 /* OperatorType.BitwiseXor */);
        }
        return leftExpr;
    }
    // and_expr: shift_expr ('&' shift_expr)*
    _parseBitwiseAndExpression() {
        let leftExpr = this._parseShiftExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        while (true) {
            const peekToken = this._peekToken();
            if (!this._consumeTokenIfOperator(3 /* OperatorType.BitwiseAnd */)) {
                break;
            }
            const rightExpr = this._parseShiftExpression();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 3 /* OperatorType.BitwiseAnd */);
        }
        return leftExpr;
    }
    // shift_expr: arith_expr (('<<'|'>>') arith_expr)*
    _parseShiftExpression() {
        let leftExpr = this._parseArithmeticExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        let peekToken = this._peekToken();
        let nextOperator = this._peekOperatorType();
        while (nextOperator === 17 /* OperatorType.LeftShift */ || nextOperator === 31 /* OperatorType.RightShift */) {
            this._getNextToken();
            const rightExpr = this._parseArithmeticExpression();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, nextOperator);
            peekToken = this._peekToken();
            nextOperator = this._peekOperatorType();
        }
        return leftExpr;
    }
    // arith_expr: term (('+'|'-') term)*
    _parseArithmeticExpression() {
        let leftExpr = this._parseArithmeticTerm();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        let peekToken = this._peekToken();
        let nextOperator = this._peekOperatorType();
        while (nextOperator === 0 /* OperatorType.Add */ || nextOperator === 33 /* OperatorType.Subtract */) {
            this._getNextToken();
            const rightExpr = this._parseArithmeticTerm();
            if (rightExpr.nodeType === 0 /* ParseNodeType.Error */) {
                return rightExpr;
            }
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, nextOperator);
            peekToken = this._peekToken();
            nextOperator = this._peekOperatorType();
        }
        return leftExpr;
    }
    // term: factor (('*'|'@'|'/'|'%'|'//') factor)*
    _parseArithmeticTerm() {
        let leftExpr = this._parseArithmeticFactor();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        let peekToken = this._peekToken();
        let nextOperator = this._peekOperatorType();
        while (nextOperator === 26 /* OperatorType.Multiply */ ||
            nextOperator === 22 /* OperatorType.MatrixMultiply */ ||
            nextOperator === 10 /* OperatorType.Divide */ ||
            nextOperator === 24 /* OperatorType.Mod */ ||
            nextOperator === 13 /* OperatorType.FloorDivide */) {
            this._getNextToken();
            const rightExpr = this._parseArithmeticFactor();
            leftExpr = this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, nextOperator);
            peekToken = this._peekToken();
            nextOperator = this._peekOperatorType();
        }
        return leftExpr;
    }
    // factor: ('+'|'-'|'~') factor | power
    // power: atom_expr ['**' factor]
    _parseArithmeticFactor() {
        const nextToken = this._peekToken();
        const nextOperator = this._peekOperatorType();
        if (nextOperator === 0 /* OperatorType.Add */ ||
            nextOperator === 33 /* OperatorType.Subtract */ ||
            nextOperator === 5 /* OperatorType.BitwiseInvert */) {
            this._getNextToken();
            const expression = this._parseArithmeticFactor();
            return this._createUnaryOperationNode(nextToken, expression, nextOperator);
        }
        const leftExpr = this._parseAtomExpression();
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        const peekToken = this._peekToken();
        if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
            const rightExpr = this._parseArithmeticFactor();
            return this._createBinaryOperationNode(leftExpr, rightExpr, peekToken, 29 /* OperatorType.Power */);
        }
        return leftExpr;
    }
    // Determines whether the expression refers to a type exported by the typing
    // or typing_extensions modules. We can directly evaluate the types at binding
    // time. We assume here that the code isn't making use of some custom type alias
    // to refer to the typing types.
    _isTypingAnnotation(typeAnnotation, name) {
        if (typeAnnotation.nodeType === 38 /* ParseNodeType.Name */) {
            const alias = this._typingSymbolAliases.get(typeAnnotation.value);
            if (alias === name) {
                return true;
            }
        }
        else if (typeAnnotation.nodeType === 35 /* ParseNodeType.MemberAccess */) {
            if (typeAnnotation.leftExpression.nodeType === 38 /* ParseNodeType.Name */ &&
                typeAnnotation.memberName.value === name) {
                const baseName = typeAnnotation.leftExpression.value;
                return this._typingImportAliases.some((alias) => alias === baseName);
            }
        }
        return false;
    }
    // atom_expr: ['await'] atom trailer*
    // trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
    _parseAtomExpression() {
        let awaitToken;
        if (this._peekKeywordType() === 4 /* KeywordType.Await */) {
            awaitToken = this._getKeywordToken(4 /* KeywordType.Await */);
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_5)) {
                this._addSyntaxError(localize_1.LocMessage.awaitIllegal(), awaitToken);
            }
        }
        let atomExpression = this._parseAtom();
        if (atomExpression.nodeType === 0 /* ParseNodeType.Error */) {
            return atomExpression;
        }
        // Consume trailers.
        while (true) {
            // Is it a function call?
            const startOfTrailerToken = this._peekToken();
            if (this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */)) {
                // Generally, function calls are not allowed within type annotations,
                // but they are permitted in "Annotated" annotations.
                const wasParsingTypeAnnotation = this._isParsingTypeAnnotation;
                this._isParsingTypeAnnotation = false;
                const argListResult = this._parseArgList();
                const callNode = parseNodes_1.CallNode.create(atomExpression, argListResult.args, argListResult.trailingComma);
                if (argListResult.args.length > 1 || argListResult.trailingComma) {
                    argListResult.args.forEach((arg) => {
                        if (arg.valueExpression.nodeType === 32 /* ParseNodeType.ListComprehension */) {
                            if (!arg.valueExpression.isParenthesized) {
                                this._addSyntaxError(localize_1.LocMessage.generatorNotParenthesized(), arg.valueExpression);
                            }
                        }
                    });
                }
                const nextToken = this._peekToken();
                let isArgListTerminated = false;
                if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
                    this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), startOfTrailerToken);
                    // Consume the remainder of tokens on the line for error
                    // recovery.
                    this._consumeTokensUntilType([2 /* TokenType.NewLine */]);
                    // Extend the node's range to include the rest of the line.
                    // This helps the signatureHelpProvider.
                    (0, parseNodes_1.extendRange)(callNode, this._peekToken());
                }
                else {
                    (0, parseNodes_1.extendRange)(callNode, nextToken);
                    isArgListTerminated = true;
                }
                this._isParsingTypeAnnotation = wasParsingTypeAnnotation;
                atomExpression = callNode;
                if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) {
                    atomExpression = parseNodes_1.ErrorNode.create(atomExpression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
                    this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), atomExpression);
                }
                // If the argument list wasn't terminated, break out of the loop
                if (!isArgListTerminated) {
                    break;
                }
            }
            else if (this._consumeTokenIfType(15 /* TokenType.OpenBracket */)) {
                // Is it an index operator?
                // This is an unfortunate hack that's necessary to accommodate 'Literal'
                // and 'Annotated' type annotations properly. We need to suspend treating
                // strings as type annotations within a Literal or Annotated subscript.
                const wasParsingIndexTrailer = this._isParsingIndexTrailer;
                const wasParsingTypeAnnotation = this._isParsingTypeAnnotation;
                if (this._isTypingAnnotation(atomExpression, 'Literal') ||
                    this._isTypingAnnotation(atomExpression, 'Annotated')) {
                    this._isParsingTypeAnnotation = false;
                }
                this._isParsingIndexTrailer = true;
                const subscriptList = this._parseSubscriptList();
                this._isParsingTypeAnnotation = wasParsingTypeAnnotation;
                this._isParsingIndexTrailer = wasParsingIndexTrailer;
                const closingToken = this._peekToken();
                const indexNode = parseNodes_1.IndexNode.create(atomExpression, subscriptList.list, subscriptList.trailingComma, closingToken);
                (0, parseNodes_1.extendRange)(indexNode, indexNode);
                if (!this._consumeTokenIfType(16 /* TokenType.CloseBracket */)) {
                    // Handle the error case, but don't use the error node in this
                    // case because it creates problems for the completion provider.
                    this._handleExpressionParseError(6 /* ErrorExpressionCategory.MissingIndexCloseBracket */, localize_1.LocMessage.expectedCloseBracket(), startOfTrailerToken, indexNode);
                }
                atomExpression = indexNode;
                if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) {
                    atomExpression = parseNodes_1.ErrorNode.create(atomExpression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
                    this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), atomExpression);
                }
            }
            else if (this._consumeTokenIfType(20 /* TokenType.Dot */)) {
                // Is it a member access?
                const memberName = this._getTokenIfIdentifier();
                if (!memberName) {
                    return this._handleExpressionParseError(7 /* ErrorExpressionCategory.MissingMemberAccessName */, localize_1.LocMessage.expectedMemberName(), startOfTrailerToken, atomExpression, [8 /* TokenType.Keyword */]);
                }
                atomExpression = parseNodes_1.MemberAccessNode.create(atomExpression, parseNodes_1.NameNode.create(memberName));
                if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) {
                    atomExpression = parseNodes_1.ErrorNode.create(atomExpression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
                    this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), atomExpression);
                }
            }
            else {
                break;
            }
        }
        if (awaitToken) {
            return parseNodes_1.AwaitNode.create(awaitToken, atomExpression);
        }
        return atomExpression;
    }
    // subscriptlist: subscript (',' subscript)* [',']
    _parseSubscriptList() {
        const argList = [];
        let sawKeywordArg = false;
        let trailingComma = false;
        while (true) {
            const firstToken = this._peekToken();
            if (firstToken.type !== 10 /* TokenType.Colon */ && this._isNextTokenNeverExpression()) {
                break;
            }
            let argType = 0 /* ArgumentCategory.Simple */;
            if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
                argType = 1 /* ArgumentCategory.UnpackedList */;
            }
            else if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
                argType = 2 /* ArgumentCategory.UnpackedDictionary */;
            }
            const startOfSubscriptIndex = this._tokenIndex;
            let valueExpr = this._parsePossibleSlice();
            let nameIdentifier;
            // Is this a keyword argument?
            if (argType === 0 /* ArgumentCategory.Simple */) {
                if (this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
                    const nameExpr = valueExpr;
                    valueExpr = this._parsePossibleSlice();
                    if (nameExpr.nodeType === 38 /* ParseNodeType.Name */) {
                        nameIdentifier = nameExpr.token;
                    }
                    else {
                        this._addSyntaxError(localize_1.LocMessage.expectedParamName(), nameExpr);
                    }
                }
                else if (valueExpr.nodeType === 38 /* ParseNodeType.Name */ &&
                    this._peekOperatorType() === 35 /* OperatorType.Walrus */) {
                    this._tokenIndex = startOfSubscriptIndex;
                    valueExpr = this._parseTestExpression(/* allowAssignmentExpression */ true);
                    // Python 3.10 and newer allow assignment expressions to be used inside of a subscript.
                    if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_10)) {
                        this._addSyntaxError(localize_1.LocMessage.assignmentExprInSubscript(), valueExpr);
                    }
                }
            }
            const argNode = parseNodes_1.ArgumentNode.create(firstToken, valueExpr, argType);
            if (nameIdentifier) {
                argNode.name = parseNodes_1.NameNode.create(nameIdentifier);
                argNode.name.parent = argNode;
            }
            if (argNode.name) {
                sawKeywordArg = true;
            }
            else if (sawKeywordArg && argNode.argumentCategory === 0 /* ArgumentCategory.Simple */) {
                this._addSyntaxError(localize_1.LocMessage.positionArgAfterNamedArg(), argNode);
            }
            argList.push(argNode);
            if (argNode.name) {
                this._addSyntaxError(localize_1.LocMessage.keywordSubscriptIllegal(), argNode.name);
            }
            if (argType !== 0 /* ArgumentCategory.Simple */) {
                const unpackListAllowed = this._parseOptions.isStubFile ||
                    this._isParsingQuotedText ||
                    this._getLanguageVersion().isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_11);
                if (argType === 1 /* ArgumentCategory.UnpackedList */ && !unpackListAllowed) {
                    this._addSyntaxError(localize_1.LocMessage.unpackedSubscriptIllegal(), argNode);
                }
                if (argType === 2 /* ArgumentCategory.UnpackedDictionary */) {
                    this._addSyntaxError(localize_1.LocMessage.unpackedDictSubscriptIllegal(), argNode);
                }
            }
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                trailingComma = false;
                break;
            }
            trailingComma = true;
        }
        // An empty subscript list is illegal.
        if (argList.length === 0) {
            const errorNode = this._handleExpressionParseError(3 /* ErrorExpressionCategory.MissingIndexOrSlice */, localize_1.LocMessage.expectedSliceIndex(), 
            /* targetToken */ undefined, 
            /* childNode */ undefined, [16 /* TokenType.CloseBracket */]);
            argList.push(parseNodes_1.ArgumentNode.create(this._peekToken(), errorNode, 0 /* ArgumentCategory.Simple */));
        }
        return {
            list: argList,
            trailingComma,
        };
    }
    // subscript: test | [test] ':' [test] [sliceop]
    // sliceop: ':' [test]
    _parsePossibleSlice() {
        const firstToken = this._peekToken();
        const sliceExpressions = [undefined, undefined, undefined];
        let sliceIndex = 0;
        let sawColon = false;
        while (true) {
            const nextTokenType = this._peekTokenType();
            if (nextTokenType === 16 /* TokenType.CloseBracket */ || nextTokenType === 12 /* TokenType.Comma */) {
                break;
            }
            if (nextTokenType !== 10 /* TokenType.Colon */) {
                // Python 3.10 and newer allow assignment expressions to be used inside of a subscript.
                const allowAssignmentExpression = this._parseOptions.isStubFile || this._getLanguageVersion().isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_10);
                sliceExpressions[sliceIndex] = this._parseTestExpression(allowAssignmentExpression);
            }
            sliceIndex++;
            if (sliceIndex >= 3 || !this._consumeTokenIfType(10 /* TokenType.Colon */)) {
                break;
            }
            sawColon = true;
        }
        // If this was a simple expression with no colons return it.
        if (!sawColon) {
            if (sliceExpressions[0]) {
                return sliceExpressions[0];
            }
            return parseNodes_1.ErrorNode.create(this._peekToken(), 3 /* ErrorExpressionCategory.MissingIndexOrSlice */);
        }
        const sliceNode = parseNodes_1.SliceNode.create(firstToken);
        sliceNode.startValue = sliceExpressions[0];
        if (sliceNode.startValue) {
            sliceNode.startValue.parent = sliceNode;
        }
        sliceNode.endValue = sliceExpressions[1];
        if (sliceNode.endValue) {
            sliceNode.endValue.parent = sliceNode;
        }
        sliceNode.stepValue = sliceExpressions[2];
        if (sliceNode.stepValue) {
            sliceNode.stepValue.parent = sliceNode;
        }
        const extension = sliceExpressions[2] || sliceExpressions[1] || sliceExpressions[0];
        if (extension) {
            (0, parseNodes_1.extendRange)(sliceNode, extension);
        }
        return sliceNode;
    }
    // arglist: argument (',' argument)*  [',']
    _parseArgList() {
        const argList = [];
        let sawKeywordArg = false;
        let trailingComma = false;
        while (true) {
            const nextTokenType = this._peekTokenType();
            if (nextTokenType === 14 /* TokenType.CloseParenthesis */ ||
                nextTokenType === 2 /* TokenType.NewLine */ ||
                nextTokenType === 1 /* TokenType.EndOfStream */) {
                break;
            }
            trailingComma = false;
            const arg = this._parseArgument();
            if (arg.name) {
                sawKeywordArg = true;
            }
            else if (sawKeywordArg && arg.argumentCategory === 0 /* ArgumentCategory.Simple */) {
                this._addSyntaxError(localize_1.LocMessage.positionArgAfterNamedArg(), arg);
            }
            argList.push(arg);
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
            trailingComma = true;
        }
        return { args: argList, trailingComma };
    }
    // argument: ( test [comp_for] |
    //             test '=' test |
    //             '**' test |
    //             '*' test )
    _parseArgument() {
        const firstToken = this._peekToken();
        let argType = 0 /* ArgumentCategory.Simple */;
        if (this._consumeTokenIfOperator(26 /* OperatorType.Multiply */)) {
            argType = 1 /* ArgumentCategory.UnpackedList */;
        }
        else if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
            argType = 2 /* ArgumentCategory.UnpackedDictionary */;
        }
        let valueExpr = this._parseTestExpression(/* allowAssignmentExpression */ true);
        let nameIdentifier;
        if (argType === 0 /* ArgumentCategory.Simple */) {
            if (this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
                const nameExpr = valueExpr;
                valueExpr = this._parseTestExpression(/* allowAssignmentExpression */ false);
                if (nameExpr.nodeType === 38 /* ParseNodeType.Name */) {
                    nameIdentifier = nameExpr.token;
                }
                else {
                    this._addSyntaxError(localize_1.LocMessage.expectedParamName(), nameExpr);
                }
            }
            else {
                const listComp = this._tryParseListComprehension(valueExpr, /* isGenerator */ true);
                if (listComp) {
                    valueExpr = listComp;
                }
            }
        }
        const argNode = parseNodes_1.ArgumentNode.create(firstToken, valueExpr, argType);
        if (nameIdentifier) {
            argNode.name = parseNodes_1.NameNode.create(nameIdentifier);
            argNode.name.parent = argNode;
        }
        return argNode;
    }
    // atom: ('(' [yield_expr | testlist_comp] ')' |
    //     '[' [testlist_comp] ']' |
    //     '{' [dictorsetmaker] '}' |
    //     NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' | '__debug__')
    _parseAtom() {
        const nextToken = this._peekToken();
        if (nextToken.type === 19 /* TokenType.Ellipsis */) {
            return parseNodes_1.EllipsisNode.create(this._getNextToken());
        }
        if (nextToken.type === 6 /* TokenType.Number */) {
            return parseNodes_1.NumberNode.create(this._getNextToken());
        }
        if (nextToken.type === 7 /* TokenType.Identifier */) {
            return parseNodes_1.NameNode.create(this._getNextToken());
        }
        if (nextToken.type === 5 /* TokenType.String */ || nextToken.type === 24 /* TokenType.FStringStart */) {
            return this._parseStringList();
        }
        if (nextToken.type === 22 /* TokenType.Backtick */) {
            this._getNextToken();
            // Atoms with backticks are no longer allowed in Python 3.x, but they
            // were a thing in Python 2.x. We'll parse them to improve parse recovery
            // and emit an error.
            this._addSyntaxError(localize_1.LocMessage.backticksIllegal(), nextToken);
            const expressionNode = this._parseTestListAsExpression(2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedExpr());
            this._consumeTokenIfType(22 /* TokenType.Backtick */);
            return expressionNode;
        }
        if (nextToken.type === 13 /* TokenType.OpenParenthesis */) {
            const possibleTupleNode = this._parseTupleAtom();
            if (possibleTupleNode.nodeType === 55 /* ParseNodeType.UnaryOperation */ ||
                possibleTupleNode.nodeType === 6 /* ParseNodeType.Await */ ||
                possibleTupleNode.nodeType === 7 /* ParseNodeType.BinaryOperation */) {
                // Mark binary expressions as parenthesized so we don't attempt
                // to use comparison chaining, which isn't appropriate when the
                // expression is parenthesized. Unary and await expressions
                // are also marked to be able to display them unambiguously.
                possibleTupleNode.parenthesized = true;
            }
            if (possibleTupleNode.nodeType === 48 /* ParseNodeType.StringList */) {
                possibleTupleNode.isParenthesized = true;
            }
            if (possibleTupleNode.nodeType === 32 /* ParseNodeType.ListComprehension */) {
                possibleTupleNode.isParenthesized = true;
            }
            return possibleTupleNode;
        }
        else if (nextToken.type === 15 /* TokenType.OpenBracket */) {
            return this._parseListAtom();
        }
        else if (nextToken.type === 17 /* TokenType.OpenCurlyBrace */) {
            return this._parseDictionaryOrSetAtom();
        }
        if (nextToken.type === 8 /* TokenType.Keyword */) {
            const keywordToken = nextToken;
            if (keywordToken.keywordType === 15 /* KeywordType.False */ ||
                keywordToken.keywordType === 33 /* KeywordType.True */ ||
                keywordToken.keywordType === 9 /* KeywordType.Debug */ ||
                keywordToken.keywordType === 26 /* KeywordType.None */) {
                return parseNodes_1.ConstantNode.create(this._getNextToken());
            }
            // Make an identifier out of the keyword.
            const keywordAsIdentifier = this._getTokenIfIdentifier();
            if (keywordAsIdentifier) {
                return parseNodes_1.NameNode.create(keywordAsIdentifier);
            }
        }
        return this._handleExpressionParseError(2 /* ErrorExpressionCategory.MissingExpression */, localize_1.LocMessage.expectedExpr());
    }
    // Allocates a dummy "error expression" and consumes the remainder
    // of the tokens on the line for error recovery. A partially-completed
    // child node can be passed to help the completion provider determine
    // what to do.
    _handleExpressionParseError(category, errorMsg, targetToken, childNode, additionalStopTokens) {
        var _a;
        this._addSyntaxError(errorMsg, targetToken !== null && targetToken !== void 0 ? targetToken : this._peekToken());
        const stopTokens = [2 /* TokenType.NewLine */];
        if (additionalStopTokens) {
            (0, collectionUtils_1.appendArray)(stopTokens, additionalStopTokens);
        }
        // Using a token that is not included in the error node creates problems.
        // Sibling nodes in parse tree shouldn't overlap each other.
        const nextToken = this._peekToken();
        const initialRange = stopTokens.some((k) => nextToken.type === k)
            ? (_a = targetToken !== null && targetToken !== void 0 ? targetToken : childNode) !== null && _a !== void 0 ? _a : textRange_1.TextRange.create(nextToken.start, /* length */ 0)
            : nextToken;
        const expr = parseNodes_1.ErrorNode.create(initialRange, category, childNode);
        this._consumeTokensUntilType(stopTokens);
        return expr;
    }
    // lambdef: 'lambda' [varargslist] ':' test
    _parseLambdaExpression(allowConditional = true) {
        const lambdaToken = this._getKeywordToken(24 /* KeywordType.Lambda */);
        const argList = this._parseVarArgsList(10 /* TokenType.Colon */, /* allowAnnotations */ false);
        if (!this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedColon(), this._peekToken());
        }
        let testExpr;
        if (allowConditional) {
            testExpr = this._parseTestExpression(/* allowAssignmentExpression */ false);
        }
        else {
            testExpr = this._tryParseLambdaExpression(/* allowConditional */ false) || this._parseOrTest();
        }
        const lambdaNode = parseNodes_1.LambdaNode.create(lambdaToken, testExpr);
        lambdaNode.parameters = argList;
        argList.forEach((arg) => {
            arg.parent = lambdaNode;
        });
        return lambdaNode;
    }
    _tryParseLambdaExpression(allowConditional = true) {
        if (this._peekKeywordType() !== 24 /* KeywordType.Lambda */) {
            return undefined;
        }
        return this._parseLambdaExpression(allowConditional);
    }
    // ('(' [yield_expr | testlist_comp] ')'
    // testlist_comp: (test | star_expr) (comp_for | (',' (test | star_expr))* [','])
    _parseTupleAtom() {
        var _a;
        const startParen = this._getNextToken();
        (0, debug_1.assert)(startParen.type === 13 /* TokenType.OpenParenthesis */);
        const yieldExpr = this._tryParseYieldExpression();
        if (yieldExpr) {
            if (this._peekTokenType() !== 14 /* TokenType.CloseParenthesis */) {
                return this._handleExpressionParseError(8 /* ErrorExpressionCategory.MissingTupleCloseParen */, localize_1.LocMessage.expectedCloseParen(), startParen, yieldExpr);
            }
            else {
                (0, parseNodes_1.extendRange)(yieldExpr, this._getNextToken());
            }
            return yieldExpr;
        }
        const exprListResult = this._parseTestListWithComprehension(/* isGenerator */ true);
        const tupleOrExpression = this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ true);
        (0, parseNodes_1.extendRange)(tupleOrExpression, startParen);
        if (this._peekTokenType() !== 14 /* TokenType.CloseParenthesis */) {
            return this._handleExpressionParseError(8 /* ErrorExpressionCategory.MissingTupleCloseParen */, localize_1.LocMessage.expectedCloseParen(), startParen, (_a = exprListResult.parseError) !== null && _a !== void 0 ? _a : tupleOrExpression);
        }
        else {
            (0, parseNodes_1.extendRange)(tupleOrExpression, this._getNextToken());
        }
        return tupleOrExpression;
    }
    // '[' [testlist_comp] ']'
    // testlist_comp: (test | star_expr) (comp_for | (',' (test | star_expr))* [','])
    _parseListAtom() {
        var _a;
        const startBracket = this._getNextToken();
        (0, debug_1.assert)(startBracket.type === 15 /* TokenType.OpenBracket */);
        const exprListResult = this._parseTestListWithComprehension(/* isGenerator */ false);
        const closeBracket = this._peekToken();
        if (!this._consumeTokenIfType(16 /* TokenType.CloseBracket */)) {
            return this._handleExpressionParseError(9 /* ErrorExpressionCategory.MissingListCloseBracket */, localize_1.LocMessage.expectedCloseBracket(), startBracket, (_a = exprListResult.parseError) !== null && _a !== void 0 ? _a : _createList());
        }
        return _createList();
        function _createList() {
            const listAtom = parseNodes_1.ListNode.create(startBracket);
            if (closeBracket) {
                (0, parseNodes_1.extendRange)(listAtom, closeBracket);
            }
            if (exprListResult.list.length > 0) {
                exprListResult.list.forEach((expr) => {
                    expr.parent = listAtom;
                });
                (0, parseNodes_1.extendRange)(listAtom, exprListResult.list[exprListResult.list.length - 1]);
            }
            listAtom.entries = exprListResult.list;
            return listAtom;
        }
    }
    _parseTestListWithComprehension(isGenerator) {
        let sawComprehension = false;
        return this._parseExpressionListGeneric(() => {
            let expr = this._parseTestOrStarExpression(/* allowAssignmentExpression */ true);
            const listComp = this._tryParseListComprehension(expr, isGenerator);
            if (listComp) {
                expr = listComp;
                sawComprehension = true;
            }
            return expr;
        }, () => this._isNextTokenNeverExpression(), () => sawComprehension);
    }
    // '{' [dictorsetmaker] '}'
    // dictorsetmaker: (
    //    (dictentry (comp_for | (',' dictentry)* [',']))
    //    | (setentry (comp_for | (',' setentry)* [',']))
    // )
    // dictentry: (test ':' test | '**' expr)
    // setentry: test | star_expr
    _parseDictionaryOrSetAtom() {
        const startBrace = this._getNextToken();
        (0, debug_1.assert)(startBrace.type === 17 /* TokenType.OpenCurlyBrace */);
        const dictionaryEntries = [];
        const setEntries = [];
        let isDictionary = false;
        let isSet = false;
        let sawListComprehension = false;
        let isFirstEntry = true;
        let trailingCommaToken;
        while (true) {
            if (this._peekTokenType() === 18 /* TokenType.CloseCurlyBrace */) {
                break;
            }
            trailingCommaToken = undefined;
            let doubleStarExpression;
            let keyExpression;
            let valueExpression;
            const doubleStar = this._peekToken();
            if (this._consumeTokenIfOperator(29 /* OperatorType.Power */)) {
                doubleStarExpression = this._parseExpression(/* allowUnpack */ false);
            }
            else {
                keyExpression = this._parseTestOrStarExpression(/* allowAssignmentExpression */ false);
                if (this._consumeTokenIfType(10 /* TokenType.Colon */)) {
                    valueExpression = this._parseTestExpression(/* allowAssignmentExpression */ false);
                }
            }
            if (keyExpression && valueExpression) {
                if (keyExpression.nodeType === 56 /* ParseNodeType.Unpack */) {
                    this._addSyntaxError(localize_1.LocMessage.unpackInDict(), keyExpression);
                }
                if (isSet) {
                    this._addSyntaxError(localize_1.LocMessage.keyValueInSet(), valueExpression);
                }
                else {
                    const keyEntryNode = parseNodes_1.DictionaryKeyEntryNode.create(keyExpression, valueExpression);
                    let dictEntry = keyEntryNode;
                    const listComp = this._tryParseListComprehension(keyEntryNode, /* isGenerator */ false);
                    if (listComp) {
                        dictEntry = listComp;
                        sawListComprehension = true;
                        if (!isFirstEntry) {
                            this._addSyntaxError(localize_1.LocMessage.comprehensionInDict(), dictEntry);
                        }
                    }
                    dictionaryEntries.push(dictEntry);
                    isDictionary = true;
                }
            }
            else if (doubleStarExpression) {
                if (isSet) {
                    this._addSyntaxError(localize_1.LocMessage.unpackInSet(), doubleStarExpression);
                }
                else {
                    const listEntryNode = parseNodes_1.DictionaryExpandEntryNode.create(doubleStarExpression);
                    (0, parseNodes_1.extendRange)(listEntryNode, doubleStar);
                    let expandEntryNode = listEntryNode;
                    const listComp = this._tryParseListComprehension(listEntryNode, /* isGenerator */ false);
                    if (listComp) {
                        expandEntryNode = listComp;
                        sawListComprehension = true;
                        if (!isFirstEntry) {
                            this._addSyntaxError(localize_1.LocMessage.comprehensionInDict(), doubleStarExpression);
                        }
                    }
                    dictionaryEntries.push(expandEntryNode);
                    isDictionary = true;
                }
            }
            else {
                (0, debug_1.assert)(keyExpression !== undefined);
                if (keyExpression) {
                    if (isDictionary) {
                        const missingValueErrorNode = parseNodes_1.ErrorNode.create(this._peekToken(), 13 /* ErrorExpressionCategory.MissingDictValue */);
                        const keyEntryNode = parseNodes_1.DictionaryKeyEntryNode.create(keyExpression, missingValueErrorNode);
                        dictionaryEntries.push(keyEntryNode);
                        this._addSyntaxError(localize_1.LocMessage.dictKeyValuePairs(), keyExpression);
                    }
                    else {
                        const listComp = this._tryParseListComprehension(keyExpression, /* isGenerator */ false);
                        if (listComp) {
                            keyExpression = listComp;
                            sawListComprehension = true;
                            if (!isFirstEntry) {
                                this._addSyntaxError(localize_1.LocMessage.comprehensionInSet(), keyExpression);
                            }
                        }
                        setEntries.push(keyExpression);
                        isSet = true;
                    }
                }
            }
            // List comprehension statements always end the list.
            if (sawListComprehension) {
                break;
            }
            if (this._peekTokenType() !== 12 /* TokenType.Comma */) {
                break;
            }
            trailingCommaToken = this._getNextToken();
            isFirstEntry = false;
        }
        let closeCurlyBrace = this._peekToken();
        if (!this._consumeTokenIfType(18 /* TokenType.CloseCurlyBrace */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedCloseBrace(), startBrace);
            closeCurlyBrace = undefined;
        }
        if (isSet) {
            const setAtom = parseNodes_1.SetNode.create(startBrace);
            if (closeCurlyBrace) {
                (0, parseNodes_1.extendRange)(setAtom, closeCurlyBrace);
            }
            if (setEntries.length > 0) {
                (0, parseNodes_1.extendRange)(setAtom, setEntries[setEntries.length - 1]);
            }
            setEntries.forEach((entry) => {
                entry.parent = setAtom;
            });
            setAtom.entries = setEntries;
            return setAtom;
        }
        const dictionaryAtom = parseNodes_1.DictionaryNode.create(startBrace);
        if (trailingCommaToken) {
            dictionaryAtom.trailingCommaToken = trailingCommaToken;
            (0, parseNodes_1.extendRange)(dictionaryAtom, trailingCommaToken);
        }
        if (closeCurlyBrace) {
            (0, parseNodes_1.extendRange)(dictionaryAtom, closeCurlyBrace);
        }
        if (dictionaryEntries.length > 0) {
            dictionaryEntries.forEach((entry) => {
                entry.parent = dictionaryAtom;
            });
            (0, parseNodes_1.extendRange)(dictionaryAtom, dictionaryEntries[dictionaryEntries.length - 1]);
        }
        dictionaryAtom.entries = dictionaryEntries;
        return dictionaryAtom;
    }
    _parseExpressionListGeneric(parser, terminalCheck = () => this._isNextTokenNeverExpression(), finalEntryCheck = () => false) {
        let trailingComma = false;
        const list = [];
        let parseError;
        while (true) {
            if (terminalCheck()) {
                break;
            }
            const expr = parser();
            if (expr.nodeType === 0 /* ParseNodeType.Error */) {
                parseError = expr;
                break;
            }
            list.push(expr);
            // Should we stop without checking for a trailing comma?
            if (finalEntryCheck()) {
                break;
            }
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                trailingComma = false;
                break;
            }
            trailingComma = true;
        }
        return { trailingComma, list, parseError };
    }
    // expr_stmt: testlist_star_expr (annassign | augassign (yield_expr | testlist) |
    //                     ('=' (yield_expr | testlist_star_expr))*)
    // testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
    // annassign: ':' test ['=' (yield_expr | testlist_star_expr)]
    // augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
    //             '<<=' | '>>=' | '**=' | '//=')
    _parseExpressionStatement() {
        var _a, _b;
        let leftExpr = this._parseTestOrStarListAsExpression(
        /* allowAssignmentExpression */ false, 
        /* allowMultipleUnpack */ false, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedExpr());
        let annotationExpr;
        if (leftExpr.nodeType === 0 /* ParseNodeType.Error */) {
            return leftExpr;
        }
        // Is this a type annotation assignment?
        if (this._consumeTokenIfType(10 /* TokenType.Colon */)) {
            annotationExpr = this._parseTypeAnnotation();
            leftExpr = parseNodes_1.TypeAnnotationNode.create(leftExpr, annotationExpr);
            if (!this._parseOptions.isStubFile && this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_6)) {
                this._addSyntaxError(localize_1.LocMessage.varAnnotationIllegal(), annotationExpr);
            }
            if (!this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
                return leftExpr;
            }
            // This is an unfortunate hack that's necessary to accommodate 'TypeAlias'
            // declarations properly. We need to treat this assignment differently than
            // most because the expression on the right side is treated like a type
            // annotation and therefore allows string-literal forward declarations.
            const isTypeAliasDeclaration = this._isTypingAnnotation(annotationExpr, 'TypeAlias');
            const wasParsingTypeAnnotation = this._isParsingTypeAnnotation;
            if (isTypeAliasDeclaration) {
                this._isParsingTypeAnnotation = true;
            }
            const rightExpr = (_a = this._tryParseYieldExpression()) !== null && _a !== void 0 ? _a : this._parseTestOrStarListAsExpression(
            /* allowAssignmentExpression */ false, 
            /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedAssignRightHandExpr());
            this._isParsingTypeAnnotation = wasParsingTypeAnnotation;
            return parseNodes_1.AssignmentNode.create(leftExpr, rightExpr);
        }
        // Is this a simple assignment?
        if (this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
            return this._parseChainAssignments(leftExpr);
        }
        if (tokenizer_1.Tokenizer.isOperatorAssignment(this._peekOperatorType())) {
            const operatorToken = this._getNextToken();
            const rightExpr = (_b = this._tryParseYieldExpression()) !== null && _b !== void 0 ? _b : this._parseTestListAsExpression(2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedBinaryRightHandExpr());
            // Make a shallow copy of the dest expression but give it a new ID.
            const destExpr = Object.assign({}, leftExpr);
            destExpr.id = (0, parseNodes_1.getNextNodeId)();
            return parseNodes_1.AugmentedAssignmentNode.create(leftExpr, rightExpr, operatorToken.operatorType, destExpr);
        }
        return leftExpr;
    }
    _parseChainAssignments(leftExpr) {
        var _a;
        // Make a list of assignment targets.
        const assignmentTargets = [leftExpr];
        let rightExpr;
        while (true) {
            rightExpr =
                (_a = this._tryParseYieldExpression()) !== null && _a !== void 0 ? _a : this._parseTestOrStarListAsExpression(
                /* allowAssignmentExpression */ false, 
                /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedAssignRightHandExpr());
            if (rightExpr.nodeType === 0 /* ParseNodeType.Error */) {
                break;
            }
            // Continue until we've consumed the entire chain.
            if (!this._consumeTokenIfOperator(2 /* OperatorType.Assign */)) {
                break;
            }
            assignmentTargets.push(rightExpr);
        }
        // Create a tree of assignment expressions starting with the first one.
        // The final RHS value is assigned to the targets left to right in Python.
        let assignmentNode = parseNodes_1.AssignmentNode.create(assignmentTargets[0], rightExpr);
        // Look for a type annotation comment at the end of the line.
        const typeAnnotationComment = this._parseVariableTypeAnnotationComment();
        if (typeAnnotationComment) {
            if (assignmentTargets.length > 1) {
                // Type comments are not allowed for chained assignments for the
                // same reason that variable type annotations don't support
                // chained assignments. Note that a type comment was used here
                // so it can be later reported as an error by the binder.
                assignmentNode.chainedTypeAnnotationComment = typeAnnotationComment;
            }
            else {
                assignmentNode.typeAnnotationComment = typeAnnotationComment;
                assignmentNode.typeAnnotationComment.parent = assignmentNode;
                (0, parseNodes_1.extendRange)(assignmentNode, assignmentNode.typeAnnotationComment);
            }
        }
        assignmentTargets.forEach((target, index) => {
            if (index > 0) {
                assignmentNode = parseNodes_1.AssignmentNode.create(target, assignmentNode);
            }
        });
        return assignmentNode;
    }
    _parseFunctionTypeAnnotation() {
        const openParenToken = this._peekToken();
        if (!this._consumeTokenIfType(13 /* TokenType.OpenParenthesis */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedOpenParen(), this._peekToken());
            return undefined;
        }
        let paramAnnotations = [];
        while (true) {
            const nextTokenType = this._peekTokenType();
            if (nextTokenType === 14 /* TokenType.CloseParenthesis */ ||
                nextTokenType === 2 /* TokenType.NewLine */ ||
                nextTokenType === 1 /* TokenType.EndOfStream */) {
                break;
            }
            // Consume "*" or "**" indicators but don't do anything with them.
            // (We don't enforce that these are present, absent, or match
            // the corresponding parameter types.)
            this._consumeTokenIfOperator(26 /* OperatorType.Multiply */) || this._consumeTokenIfOperator(29 /* OperatorType.Power */);
            const paramAnnotation = this._parseTypeAnnotation();
            paramAnnotations.push(paramAnnotation);
            if (!this._consumeTokenIfType(12 /* TokenType.Comma */)) {
                break;
            }
        }
        if (!this._consumeTokenIfType(14 /* TokenType.CloseParenthesis */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedCloseParen(), openParenToken);
            this._consumeTokensUntilType([10 /* TokenType.Colon */]);
        }
        if (!this._consumeTokenIfType(21 /* TokenType.Arrow */)) {
            this._addSyntaxError(localize_1.LocMessage.expectedArrow(), this._peekToken());
            return undefined;
        }
        const returnType = this._parseTypeAnnotation();
        let isParamListEllipsis = false;
        if (paramAnnotations.length === 1 && paramAnnotations[0].nodeType === 18 /* ParseNodeType.Ellipsis */) {
            paramAnnotations = [];
            isParamListEllipsis = true;
        }
        return parseNodes_1.FunctionAnnotationNode.create(openParenToken, isParamListEllipsis, paramAnnotations, returnType);
    }
    _parseTypeAnnotation(allowUnpack = false) {
        // Temporary set a flag that indicates we're parsing a type annotation.
        const wasParsingTypeAnnotation = this._isParsingTypeAnnotation;
        this._isParsingTypeAnnotation = true;
        // Allow unpack operators.
        const startToken = this._peekToken();
        const isUnpack = this._consumeTokenIfOperator(26 /* OperatorType.Multiply */);
        if (isUnpack &&
            allowUnpack &&
            !this._parseOptions.isStubFile &&
            !this._isParsingQuotedText &&
            this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_11)) {
            this._addSyntaxError(localize_1.LocMessage.unpackedSubscriptIllegal(), startToken);
        }
        let result = this._parseTestExpression(/* allowAssignmentExpression */ false);
        if (isUnpack) {
            result = parseNodes_1.UnpackNode.create(startToken, result);
        }
        this._isParsingTypeAnnotation = wasParsingTypeAnnotation;
        return result;
    }
    _reportStringTokenErrors(stringToken, unescapedResult) {
        if (stringToken.flags & 65536 /* StringTokenFlags.Unterminated */) {
            this._addSyntaxError(localize_1.LocMessage.stringUnterminated(), stringToken);
        }
        if (unescapedResult === null || unescapedResult === void 0 ? void 0 : unescapedResult.nonAsciiInBytes) {
            this._addSyntaxError(localize_1.LocMessage.stringNonAsciiBytes(), stringToken);
        }
        if (stringToken.flags & 64 /* StringTokenFlags.Format */) {
            if (this._getLanguageVersion().isLessThan(pythonVersion_1.pythonVersion3_6)) {
                this._addSyntaxError(localize_1.LocMessage.formatStringIllegal(), stringToken);
            }
            if (stringToken.flags & 32 /* StringTokenFlags.Bytes */) {
                this._addSyntaxError(localize_1.LocMessage.formatStringBytes(), stringToken);
            }
            if (stringToken.flags & 16 /* StringTokenFlags.Unicode */) {
                this._addSyntaxError(localize_1.LocMessage.formatStringUnicode(), stringToken);
            }
        }
    }
    _makeStringNode(stringToken) {
        const unescapedResult = StringTokenUtils.getUnescapedString(stringToken);
        this._reportStringTokenErrors(stringToken, unescapedResult);
        return parseNodes_1.StringNode.create(stringToken, unescapedResult.value);
    }
    _getTypeAnnotationCommentText() {
        if (this._tokenIndex === 0) {
            return undefined;
        }
        const curToken = this._tokenizerOutput.tokens.getItemAt(this._tokenIndex - 1);
        const nextToken = this._tokenizerOutput.tokens.getItemAt(this._tokenIndex);
        if (curToken.start + curToken.length === nextToken.start) {
            return undefined;
        }
        const interTokenContents = this._fileContents.slice(curToken.start + curToken.length, nextToken.start);
        const commentRegEx = /^(\s*#\s*type:\s*)([^\r\n]*)/;
        const match = interTokenContents.match(commentRegEx);
        if (!match) {
            return undefined;
        }
        // Synthesize a string token and StringNode.
        const typeString = match[2];
        // Ignore all "ignore" comments. Include "[" in the regular
        // expression because mypy supports ignore comments of the
        // form ignore[errorCode, ...]. We'll treat these as regular
        // ignore statements (as though no errorCodes were included).
        if (typeString.trim().match(/^ignore(\s|\[|$)/)) {
            return undefined;
        }
        const tokenOffset = curToken.start + curToken.length + match[1].length;
        return tokenizerTypes_1.StringToken.create(tokenOffset, typeString.length, 0 /* StringTokenFlags.None */, typeString, 0, 
        /* comments */ undefined);
    }
    _parseVariableTypeAnnotationComment() {
        const stringToken = this._getTypeAnnotationCommentText();
        if (!stringToken) {
            return undefined;
        }
        const stringNode = this._makeStringNode(stringToken);
        const stringListNode = parseNodes_1.StringListNode.create([stringNode]);
        const parser = new Parser();
        const parseResults = parser.parseTextExpression(this._fileContents, stringToken.start, stringToken.length, this._parseOptions, 1 /* ParseTextMode.VariableAnnotation */, 
        /* initialParenDepth */ undefined, this._typingSymbolAliases);
        parseResults.diagnostics.forEach((diag) => {
            this._addSyntaxError(diag.message, stringListNode);
        });
        if (!parseResults.parseTree) {
            return undefined;
        }
        (0, debug_1.assert)(parseResults.parseTree.nodeType !== 62 /* ParseNodeType.FunctionAnnotation */);
        return parseResults.parseTree;
    }
    _parseFunctionTypeAnnotationComment(stringToken, functionNode) {
        const stringNode = this._makeStringNode(stringToken);
        const stringListNode = parseNodes_1.StringListNode.create([stringNode]);
        const parser = new Parser();
        const parseResults = parser.parseTextExpression(this._fileContents, stringToken.start, stringToken.length, this._parseOptions, 2 /* ParseTextMode.FunctionAnnotation */, 
        /* initialParenDepth */ undefined, this._typingSymbolAliases);
        parseResults.diagnostics.forEach((diag) => {
            this._addSyntaxError(diag.message, stringListNode);
        });
        if (!parseResults.parseTree || parseResults.parseTree.nodeType !== 62 /* ParseNodeType.FunctionAnnotation */) {
            return;
        }
        const functionAnnotation = parseResults.parseTree;
        functionNode.functionAnnotationComment = functionAnnotation;
        functionAnnotation.parent = functionNode;
        (0, parseNodes_1.extendRange)(functionNode, functionAnnotation);
    }
    _parseFStringReplacementField(fieldExpressions, middleTokens, formatExpressions, nestingDepth = 0) {
        var _a;
        let nextToken = this._getNextToken();
        // The caller should have already confirmed that the next token is an open brace.
        (0, debug_1.assert)(nextToken.type === 17 /* TokenType.OpenCurlyBrace */);
        // Consume the expression.
        const expr = (_a = this._tryParseYieldExpression()) !== null && _a !== void 0 ? _a : this._parseTestOrStarListAsExpression(
        /* allowAssignmentExpression */ true, 
        /* allowMultipleUnpack */ true, 2 /* ErrorExpressionCategory.MissingExpression */, () => localize_1.LocMessage.expectedExpr());
        fieldExpressions.push(expr);
        if (expr.nodeType === 0 /* ParseNodeType.Error */) {
            return false;
        }
        // Consume an optional "=" token after the expression.
        nextToken = this._peekToken();
        if (nextToken.type === 9 /* TokenType.Operator */ &&
            nextToken.operatorType === 2 /* OperatorType.Assign */) {
            // This feature requires Python 3.8 or newer.
            if (this._parseOptions.pythonVersion.isLessThan(pythonVersion_1.pythonVersion3_8)) {
                this._addSyntaxError(localize_1.LocMessage.formatStringDebuggingIllegal(), nextToken);
            }
            this._getNextToken();
            nextToken = this._peekToken();
        }
        // Consume an optional !r, !s, or !a token.
        if (nextToken.type === 23 /* TokenType.ExclamationMark */) {
            this._getNextToken();
            nextToken = this._peekToken();
            if (nextToken.type !== 7 /* TokenType.Identifier */) {
                this._addSyntaxError(localize_1.LocMessage.formatStringExpectedConversion(), nextToken);
            }
            else {
                this._getNextToken();
                nextToken = this._peekToken();
            }
        }
        if (nextToken.type === 10 /* TokenType.Colon */) {
            this._getNextToken();
            this._parseFStringFormatString(fieldExpressions, middleTokens, formatExpressions, nestingDepth);
            nextToken = this._peekToken();
        }
        if (nextToken.type !== 18 /* TokenType.CloseCurlyBrace */) {
            this._addSyntaxError(localize_1.LocMessage.formatStringUnterminated(), nextToken);
            return false;
        }
        else {
            this._getNextToken();
        }
        // Indicate success.
        return true;
    }
    _parseFStringFormatString(fieldExpressions, middleTokens, formatExpressions, nestingDepth) {
        while (true) {
            const nextToken = this._peekToken();
            if (nextToken.type === 18 /* TokenType.CloseCurlyBrace */ || nextToken.type === 26 /* TokenType.FStringEnd */) {
                break;
            }
            if (nextToken.type === 25 /* TokenType.FStringMiddle */) {
                this._getNextToken();
                continue;
            }
            if (nextToken.type === 17 /* TokenType.OpenCurlyBrace */) {
                // The Python interpreter reports an error at the point where the
                // nesting level exceeds 1. Don't report the error again for deeper nestings.
                if (nestingDepth === 2) {
                    this._addSyntaxError(localize_1.LocMessage.formatStringNestedFormatSpecifier(), nextToken);
                }
                this._parseFStringReplacementField(fieldExpressions, middleTokens, formatExpressions, nestingDepth + 1);
                continue;
            }
            break;
        }
    }
    _parseFormatString(startToken) {
        const middleTokens = [];
        const fieldExpressions = [];
        const formatExpressions = [];
        let endToken = undefined;
        // Consume middle tokens and expressions until we hit a "{" or "}" token.
        while (true) {
            const nextToken = this._peekToken();
            if (nextToken.type === 26 /* TokenType.FStringEnd */) {
                endToken = nextToken;
                if ((endToken.flags & 65536 /* StringTokenFlags.Unterminated */) !== 0) {
                    this._addSyntaxError(localize_1.LocMessage.stringUnterminated(), startToken);
                }
                this._getNextToken();
                break;
            }
            if (nextToken.type === 25 /* TokenType.FStringMiddle */) {
                middleTokens.push(nextToken);
                this._getNextToken();
                continue;
            }
            if (nextToken.type === 17 /* TokenType.OpenCurlyBrace */) {
                if (!this._parseFStringReplacementField(fieldExpressions, middleTokens, formatExpressions)) {
                    // An error was reported. Try to recover the parse.
                    if (this._consumeTokensUntilType([26 /* TokenType.FStringEnd */, 2 /* TokenType.NewLine */])) {
                        if (this._peekToken().type === 26 /* TokenType.FStringEnd */) {
                            this._getNextToken();
                        }
                    }
                    break;
                }
                continue;
            }
            // We've hit an error. Consume tokens until we find the end.
            if (this._consumeTokensUntilType([26 /* TokenType.FStringEnd */])) {
                this._getNextToken();
            }
            this._addSyntaxError(nextToken.type === 18 /* TokenType.CloseCurlyBrace */
                ? localize_1.LocMessage.formatStringBrace()
                : localize_1.LocMessage.stringUnterminated(), nextToken);
            break;
        }
        this._reportStringTokenErrors(startToken);
        return parseNodes_1.FormatStringNode.create(startToken, endToken, middleTokens, fieldExpressions, formatExpressions);
    }
    _createBinaryOperationNode(leftExpression, rightExpression, operatorToken, operator) {
        // Determine if we're exceeding the max parse depth. If so, replace
        // the subnode with an error node. Otherwise we risk crashing in the binder
        // or type evaluator.
        if (leftExpression.maxChildDepth !== undefined && leftExpression.maxChildDepth >= maxChildNodeDepth) {
            leftExpression = parseNodes_1.ErrorNode.create(leftExpression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
            this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), leftExpression);
        }
        if (rightExpression.maxChildDepth !== undefined && rightExpression.maxChildDepth >= maxChildNodeDepth) {
            rightExpression = parseNodes_1.ErrorNode.create(rightExpression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
            this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), rightExpression);
        }
        return parseNodes_1.BinaryOperationNode.create(leftExpression, rightExpression, operatorToken, operator);
    }
    _createUnaryOperationNode(operatorToken, expression, operator) {
        // Determine if we're exceeding the max parse depth. If so, replace
        // the subnode with an error node. Otherwise we risk crashing in the binder
        // or type evaluator.
        if (expression.maxChildDepth !== undefined && expression.maxChildDepth >= maxChildNodeDepth) {
            expression = parseNodes_1.ErrorNode.create(expression, 14 /* ErrorExpressionCategory.MaxDepthExceeded */);
            this._addSyntaxError(localize_1.LocMessage.maxParseDepthExceeded(), expression);
        }
        return parseNodes_1.UnaryOperationNode.create(operatorToken, expression, operator);
    }
    _parseStringList() {
        const stringList = [];
        while (true) {
            const nextToken = this._peekToken();
            if (nextToken.type === 5 /* TokenType.String */) {
                stringList.push(this._makeStringNode(this._getNextToken()));
            }
            else if (nextToken.type === 24 /* TokenType.FStringStart */) {
                stringList.push(this._parseFormatString(this._getNextToken()));
            }
            else {
                break;
            }
        }
        const stringNode = parseNodes_1.StringListNode.create(stringList);
        // If we're parsing a type annotation, parse the contents of the string.
        if (this._isParsingTypeAnnotation) {
            // Don't allow multiple strings because we have no way of reporting
            // parse errors that span strings.
            if (stringNode.strings.length > 1) {
                if (this._isParsingQuotedText) {
                    this._addSyntaxError(localize_1.LocMessage.annotationSpansStrings(), stringNode);
                }
            }
            else if (stringNode.strings[0].nodeType === 27 /* ParseNodeType.FormatString */) {
                if (this._isParsingQuotedText) {
                    this._addSyntaxError(localize_1.LocMessage.annotationFormatString(), stringNode);
                }
            }
            else {
                const stringToken = stringNode.strings[0].token;
                const stringValue = StringTokenUtils.getUnescapedString(stringNode.strings[0].token);
                const unescapedString = stringValue.value;
                const tokenOffset = stringToken.start;
                const prefixLength = stringToken.prefixLength + stringToken.quoteMarkLength;
                // Don't allow escape characters because we have no way of mapping
                // error ranges back to the escaped text.
                if (unescapedString.length !== stringToken.length - prefixLength - stringToken.quoteMarkLength) {
                    if (this._isParsingQuotedText) {
                        this._addSyntaxError(localize_1.LocMessage.annotationStringEscape(), stringNode);
                    }
                }
                else if ((stringToken.flags & (8 /* StringTokenFlags.Raw */ | 32 /* StringTokenFlags.Bytes */ | 64 /* StringTokenFlags.Format */)) ===
                    0) {
                    const parser = new Parser();
                    const parseResults = parser.parseTextExpression(this._fileContents, tokenOffset + prefixLength, unescapedString.length, this._parseOptions, 1 /* ParseTextMode.VariableAnnotation */, (stringNode.strings[0].token.flags & 4 /* StringTokenFlags.Triplicate */) !== 0 ? 1 : 0, this._typingSymbolAliases);
                    if (parseResults.diagnostics.length === 0 ||
                        this._parseOptions.reportErrorsForParsedStringContents) {
                        parseResults.diagnostics.forEach((diag) => {
                            this._addSyntaxError(diag.message, stringNode);
                        });
                        if (parseResults.parseTree) {
                            (0, debug_1.assert)(parseResults.parseTree.nodeType !== 62 /* ParseNodeType.FunctionAnnotation */);
                            stringNode.typeAnnotation = parseResults.parseTree;
                            stringNode.typeAnnotation.parent = stringNode;
                        }
                    }
                }
            }
        }
        return stringNode;
    }
    // Python 3.8 added support for star (unpack) expressions in tuples
    // following a return or yield statement in cases where the tuple
    // wasn't surrounded in parentheses.
    _reportConditionalErrorForStarTupleElement(possibleTupleExpr) {
        if (possibleTupleExpr.nodeType !== 52 /* ParseNodeType.Tuple */) {
            return;
        }
        if (possibleTupleExpr.enclosedInParens) {
            return;
        }
        if (this._parseOptions.pythonVersion.isGreaterOrEqualTo(pythonVersion_1.pythonVersion3_8)) {
            return;
        }
        for (const expr of possibleTupleExpr.expressions) {
            if (expr.nodeType === 56 /* ParseNodeType.Unpack */) {
                this._addSyntaxError(localize_1.LocMessage.unpackTuplesIllegal(), expr);
                return;
            }
        }
    }
    // Peeks at the next token and returns true if it can never
    // represent the start of an expression.
    _isNextTokenNeverExpression() {
        const nextToken = this._peekToken();
        switch (nextToken.type) {
            case 8 /* TokenType.Keyword */: {
                switch (this._peekKeywordType()) {
                    case 17 /* KeywordType.For */:
                    case 22 /* KeywordType.In */:
                    case 20 /* KeywordType.If */:
                        return true;
                }
                break;
            }
            case 9 /* TokenType.Operator */: {
                switch (this._peekOperatorType()) {
                    case 1 /* OperatorType.AddEqual */:
                    case 34 /* OperatorType.SubtractEqual */:
                    case 27 /* OperatorType.MultiplyEqual */:
                    case 11 /* OperatorType.DivideEqual */:
                    case 25 /* OperatorType.ModEqual */:
                    case 4 /* OperatorType.BitwiseAndEqual */:
                    case 7 /* OperatorType.BitwiseOrEqual */:
                    case 9 /* OperatorType.BitwiseXorEqual */:
                    case 18 /* OperatorType.LeftShiftEqual */:
                    case 32 /* OperatorType.RightShiftEqual */:
                    case 30 /* OperatorType.PowerEqual */:
                    case 14 /* OperatorType.FloorDivideEqual */:
                    case 2 /* OperatorType.Assign */:
                        return true;
                }
                break;
            }
            case 3 /* TokenType.Indent */:
            case 4 /* TokenType.Dedent */:
            case 2 /* TokenType.NewLine */:
            case 1 /* TokenType.EndOfStream */:
            case 11 /* TokenType.Semicolon */:
            case 14 /* TokenType.CloseParenthesis */:
            case 16 /* TokenType.CloseBracket */:
            case 18 /* TokenType.CloseCurlyBrace */:
            case 12 /* TokenType.Comma */:
            case 10 /* TokenType.Colon */:
            case 23 /* TokenType.ExclamationMark */:
            case 25 /* TokenType.FStringMiddle */:
            case 26 /* TokenType.FStringEnd */:
                return true;
        }
        return false;
    }
    _disallowAssignmentExpression(callback) {
        const wasAllowed = this._assignmentExpressionsAllowed;
        this._assignmentExpressionsAllowed = false;
        callback();
        this._assignmentExpressionsAllowed = wasAllowed;
    }
    _getNextToken() {
        const token = this._tokenizerOutput.tokens.getItemAt(this._tokenIndex);
        if (!this._atEof()) {
            this._tokenIndex++;
        }
        return token;
    }
    _atEof() {
        // Are we pointing at the last token in the stream (which is
        // assumed to be an end-of-stream token)?
        return this._tokenIndex >= this._tokenizerOutput.tokens.count - 1;
    }
    _peekToken(count = 0) {
        if (this._tokenIndex + count < 0) {
            return this._tokenizerOutput.tokens.getItemAt(0);
        }
        if (this._tokenIndex + count >= this._tokenizerOutput.tokens.count) {
            return this._tokenizerOutput.tokens.getItemAt(this._tokenizerOutput.tokens.count - 1);
        }
        return this._tokenizerOutput.tokens.getItemAt(this._tokenIndex + count);
    }
    _peekTokenType() {
        return this._peekToken().type;
    }
    _peekKeywordType() {
        const nextToken = this._peekToken();
        if (nextToken.type !== 8 /* TokenType.Keyword */) {
            return undefined;
        }
        return nextToken.keywordType;
    }
    _peekOperatorType() {
        const nextToken = this._peekToken();
        if (nextToken.type !== 9 /* TokenType.Operator */) {
            return undefined;
        }
        return nextToken.operatorType;
    }
    _getTokenIfIdentifier() {
        const nextToken = this._peekToken();
        if (nextToken.type === 7 /* TokenType.Identifier */) {
            return this._getNextToken();
        }
        // If the next token is invalid, treat it as an identifier.
        if (nextToken.type === 0 /* TokenType.Invalid */) {
            this._getNextToken();
            this._addSyntaxError(localize_1.LocMessage.invalidIdentifierChar(), nextToken);
            return tokenizerTypes_1.IdentifierToken.create(nextToken.start, nextToken.length, '', nextToken.comments);
        }
        // If this is a "soft keyword", it can be converted into an identifier.
        if (nextToken.type === 8 /* TokenType.Keyword */) {
            const keywordType = this._peekKeywordType();
            if (tokenizerTypes_1.softKeywords.find((type) => type === keywordType)) {
                const keywordText = this._fileContents.substr(nextToken.start, nextToken.length);
                this._getNextToken();
                return tokenizerTypes_1.IdentifierToken.create(nextToken.start, nextToken.length, keywordText, nextToken.comments);
            }
        }
        return undefined;
    }
    // Consumes tokens until the next one in the stream is
    // either a specified terminator or the end-of-stream
    // token.
    _consumeTokensUntilType(terminators) {
        while (true) {
            const token = this._peekToken();
            if (terminators.some((term) => term === token.type)) {
                return true;
            }
            if (token.type === 1 /* TokenType.EndOfStream */) {
                return false;
            }
            this._getNextToken();
        }
    }
    _getTokenIfType(tokenType) {
        if (this._peekTokenType() === tokenType) {
            return this._getNextToken();
        }
        return undefined;
    }
    _consumeTokenIfType(tokenType) {
        return !!this._getTokenIfType(tokenType);
    }
    _consumeTokenIfKeyword(keywordType) {
        if (this._peekKeywordType() === keywordType) {
            this._getNextToken();
            return true;
        }
        return false;
    }
    _consumeTokenIfOperator(operatorType) {
        if (this._peekOperatorType() === operatorType) {
            this._getNextToken();
            return true;
        }
        return false;
    }
    _getKeywordToken(keywordType) {
        const keywordToken = this._getNextToken();
        (0, debug_1.assert)(keywordToken.type === 8 /* TokenType.Keyword */);
        (0, debug_1.assert)(keywordToken.keywordType === keywordType);
        return keywordToken;
    }
    _getLanguageVersion() {
        return this._parseOptions.pythonVersion;
    }
    _suppressErrors(callback) {
        const errorsWereSuppressed = this._areErrorsSuppressed;
        try {
            this._areErrorsSuppressed = true;
            callback();
        }
        finally {
            this._areErrorsSuppressed = errorsWereSuppressed;
        }
    }
    _addSyntaxError(message, range) {
        (0, debug_1.assert)(range !== undefined);
        if (!this._areErrorsSuppressed) {
            this._diagSink.addError(message, (0, positionUtils_1.convertOffsetsToRange)(range.start, range.start + range.length, this._tokenizerOutput.lines));
        }
    }
}
exports.Parser = Parser;


/***/ }),

/***/ "../pyright-internal/src/parser/stringTokenUtils.ts":
/*!**********************************************************!*\
  !*** ../pyright-internal/src/parser/stringTokenUtils.ts ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * stringTokenUtils.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Methods that handle unescaping of escaped string token
 * literal values.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getUnescapedString = void 0;
function completeUnescapedString(incomplete, originalString) {
    const newValue = incomplete.valueParts.join('');
    // Use the original string if it's identical. This prevents us from allocating memory to hold
    // a copy (a copy is made because the original string is a 'slice' of another, so it doesn't exist in the cache yet).
    const value = originalString !== newValue ? newValue : originalString;
    return {
        ...incomplete,
        value,
    };
}
function getUnescapedString(stringToken) {
    const escapedString = stringToken.escapedValue;
    const isRaw = (stringToken.flags & 8 /* StringTokenFlags.Raw */) !== 0;
    if (isRaw) {
        return {
            value: escapedString,
            unescapeErrors: [],
            nonAsciiInBytes: false,
        };
    }
    const charCodes = [];
    for (let index = 0; index < escapedString.length; index++) {
        charCodes.push(escapedString.charCodeAt(index));
    }
    const isBytes = (stringToken.flags & 32 /* StringTokenFlags.Bytes */) !== 0;
    // Handle the common case in an expedited manner.
    if (!charCodes.some((curChar) => curChar === 13 /* Char.CarriageReturn */ || curChar === 10 /* Char.LineFeed */ || curChar === 92 /* Char.Backslash */)) {
        return {
            value: escapedString,
            unescapeErrors: [],
            nonAsciiInBytes: isBytes && charCodes.some((curChar) => curChar >= 128),
        };
    }
    let strOffset = 0;
    const output = {
        valueParts: [],
        unescapeErrors: [],
        nonAsciiInBytes: false,
    };
    const addInvalidEscapeOffset = () => {
        // Invalid escapes are not reported for raw strings.
        if (!isRaw) {
            output.unescapeErrors.push({
                offset: strOffset - 1,
                length: 2,
                errorType: 0 /* UnescapeErrorType.InvalidEscapeSequence */,
            });
        }
    };
    const getEscapedCharacter = (offset = 0) => {
        if (strOffset + offset >= charCodes.length) {
            return 3 /* Char.EndOfText */;
        }
        return charCodes[strOffset + offset];
    };
    const scanHexEscape = (digitCount) => {
        let foundIllegalHexDigit = false;
        let hexValue = 0;
        let localValue = '';
        for (let i = 0; i < digitCount; i++) {
            const charCode = getEscapedCharacter(1 + i);
            if (!_isHexCharCode(charCode)) {
                foundIllegalHexDigit = true;
                break;
            }
            hexValue = 16 * hexValue + _getHexDigitValue(charCode);
        }
        if (foundIllegalHexDigit) {
            addInvalidEscapeOffset();
            localValue = '\\' + String.fromCharCode(getEscapedCharacter());
            strOffset++;
        }
        else {
            localValue = String.fromCharCode(hexValue);
            strOffset += 1 + digitCount;
        }
        return localValue;
    };
    const appendOutputChar = (charCode) => {
        const char = String.fromCharCode(charCode);
        output.valueParts.push(char);
    };
    while (true) {
        let curChar = getEscapedCharacter();
        if (curChar === 3 /* Char.EndOfText */) {
            return completeUnescapedString(output, escapedString);
        }
        if (curChar === 92 /* Char.Backslash */) {
            // Move past the escape (backslash) character.
            strOffset++;
            if (isRaw) {
                appendOutputChar(curChar);
                continue;
            }
            curChar = getEscapedCharacter();
            let localValue = '';
            if (curChar === 13 /* Char.CarriageReturn */ || curChar === 10 /* Char.LineFeed */) {
                if (curChar === 13 /* Char.CarriageReturn */ && getEscapedCharacter(1) === 10 /* Char.LineFeed */) {
                    if (isRaw) {
                        localValue += String.fromCharCode(curChar);
                    }
                    strOffset++;
                    curChar = getEscapedCharacter();
                }
                if (isRaw) {
                    localValue = '\\' + localValue + String.fromCharCode(curChar);
                }
                strOffset++;
            }
            else {
                if (isRaw) {
                    localValue = '\\' + String.fromCharCode(curChar);
                    strOffset++;
                }
                else {
                    switch (curChar) {
                        case 92 /* Char.Backslash */:
                        case 39 /* Char.SingleQuote */:
                        case 34 /* Char.DoubleQuote */:
                            localValue = String.fromCharCode(curChar);
                            strOffset++;
                            break;
                        case 97 /* Char.a */:
                            localValue = '\u0007';
                            strOffset++;
                            break;
                        case 98 /* Char.b */:
                            localValue = '\b';
                            strOffset++;
                            break;
                        case 102 /* Char.f */:
                            localValue = '\f';
                            strOffset++;
                            break;
                        case 110 /* Char.n */:
                            localValue = '\n';
                            strOffset++;
                            break;
                        case 114 /* Char.r */:
                            localValue = '\r';
                            strOffset++;
                            break;
                        case 116 /* Char.t */:
                            localValue = '\t';
                            strOffset++;
                            break;
                        case 118 /* Char.v */:
                            localValue = '\v';
                            strOffset++;
                            break;
                        case 120 /* Char.x */:
                            localValue = scanHexEscape(2);
                            break;
                        case 78 /* Char.N */: {
                            let foundIllegalChar = false;
                            let charCount = 1;
                            if (getEscapedCharacter(charCount) !== 123 /* Char.OpenBrace */) {
                                foundIllegalChar = true;
                            }
                            else {
                                charCount++;
                                while (true) {
                                    const lookaheadChar = getEscapedCharacter(charCount);
                                    if (lookaheadChar === 125 /* Char.CloseBrace */) {
                                        break;
                                    }
                                    else if (!_isAlphaNumericChar(lookaheadChar) &&
                                        lookaheadChar !== 45 /* Char.Hyphen */ &&
                                        !_isWhitespaceChar(lookaheadChar)) {
                                        foundIllegalChar = true;
                                        break;
                                    }
                                    else {
                                        charCount++;
                                    }
                                }
                            }
                            if (foundIllegalChar) {
                                addInvalidEscapeOffset();
                                localValue = '\\' + String.fromCharCode(curChar);
                                strOffset++;
                            }
                            else {
                                // We don't have the Unicode name database handy, so
                                // assume that the name is valid and use a '-' as a
                                // replacement character.
                                localValue = '-';
                                strOffset += 1 + charCount;
                            }
                            break;
                        }
                        case 117 /* Char.u */:
                            localValue = scanHexEscape(4);
                            break;
                        case 85 /* Char.U */:
                            localValue = scanHexEscape(8);
                            break;
                        default:
                            if (_isOctalCharCode(curChar)) {
                                let octalCode = curChar - 48 /* Char._0 */;
                                strOffset++;
                                curChar = getEscapedCharacter();
                                if (_isOctalCharCode(curChar)) {
                                    octalCode = octalCode * 8 + curChar - 48 /* Char._0 */;
                                    strOffset++;
                                    curChar = getEscapedCharacter();
                                    if (_isOctalCharCode(curChar)) {
                                        octalCode = octalCode * 8 + curChar - 48 /* Char._0 */;
                                        strOffset++;
                                    }
                                }
                                localValue = String.fromCharCode(octalCode);
                            }
                            else {
                                localValue = '\\';
                                addInvalidEscapeOffset();
                            }
                            break;
                    }
                }
            }
            output.valueParts.push(localValue);
        }
        else if (curChar === 10 /* Char.LineFeed */ || curChar === 13 /* Char.CarriageReturn */) {
            // Skip over the escaped new line (either one or two characters).
            if (curChar === 13 /* Char.CarriageReturn */ && getEscapedCharacter(1) === 10 /* Char.LineFeed */) {
                appendOutputChar(curChar);
                strOffset++;
                curChar = getEscapedCharacter();
            }
            appendOutputChar(curChar);
            strOffset++;
        }
        else {
            // There's nothing to unescape, so output the escaped character directly.
            if (isBytes && curChar >= 128) {
                output.nonAsciiInBytes = true;
            }
            appendOutputChar(curChar);
            strOffset++;
        }
    }
}
exports.getUnescapedString = getUnescapedString;
function _isWhitespaceChar(charCode) {
    return charCode === 32 /* Char.Space */ || charCode === 9 /* Char.Tab */;
}
function _isAlphaNumericChar(charCode) {
    if (charCode >= 48 /* Char._0 */ && charCode <= 57 /* Char._9 */) {
        return true;
    }
    if (charCode >= 97 /* Char.a */ && charCode <= 122 /* Char.z */) {
        return true;
    }
    if (charCode >= 65 /* Char.A */ && charCode <= 90 /* Char.Z */) {
        return true;
    }
    return false;
}
function _isOctalCharCode(charCode) {
    return charCode >= 48 /* Char._0 */ && charCode <= 55 /* Char._7 */;
}
function _isHexCharCode(charCode) {
    if (charCode >= 48 /* Char._0 */ && charCode <= 57 /* Char._9 */) {
        return true;
    }
    if (charCode >= 97 /* Char.a */ && charCode <= 102 /* Char.f */) {
        return true;
    }
    if (charCode >= 65 /* Char.A */ && charCode <= 70 /* Char.F */) {
        return true;
    }
    return false;
}
function _getHexDigitValue(charCode) {
    if (charCode >= 48 /* Char._0 */ && charCode <= 57 /* Char._9 */) {
        return charCode - 48 /* Char._0 */;
    }
    if (charCode >= 97 /* Char.a */ && charCode <= 102 /* Char.f */) {
        return charCode - 97 /* Char.a */ + 10;
    }
    if (charCode >= 65 /* Char.A */ && charCode <= 70 /* Char.F */) {
        return charCode - 65 /* Char.A */ + 10;
    }
    return 0;
}


/***/ }),

/***/ "../pyright-internal/src/parser/tokenizer.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/parser/tokenizer.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * tokenizer.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from vscode-python repository:
 *  https://github.com/Microsoft/vscode-python
 *
 * Converts a Python program text stream into a stream of tokens.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Tokenizer = void 0;
const parseTreeUtils_1 = __webpack_require__(/*! ../analyzer/parseTreeUtils */ "../pyright-internal/src/analyzer/parseTreeUtils.ts");
const sourceFile_1 = __webpack_require__(/*! ../analyzer/sourceFile */ "../pyright-internal/src/analyzer/sourceFile.ts");
const textRangeCollection_1 = __webpack_require__(/*! ../common/textRangeCollection */ "../pyright-internal/src/common/textRangeCollection.ts");
const characters_1 = __webpack_require__(/*! ./characters */ "../pyright-internal/src/parser/characters.ts");
const characterStream_1 = __webpack_require__(/*! ./characterStream */ "../pyright-internal/src/parser/characterStream.ts");
const tokenizerTypes_1 = __webpack_require__(/*! ./tokenizerTypes */ "../pyright-internal/src/parser/tokenizerTypes.ts");
// This must be a Map, as operations like {}["constructor"] succeed.
const _keywords = new Map([
    ['and', 0 /* KeywordType.And */],
    ['as', 1 /* KeywordType.As */],
    ['assert', 2 /* KeywordType.Assert */],
    ['async', 3 /* KeywordType.Async */],
    ['await', 4 /* KeywordType.Await */],
    ['break', 5 /* KeywordType.Break */],
    ['case', 6 /* KeywordType.Case */],
    ['class', 7 /* KeywordType.Class */],
    ['continue', 8 /* KeywordType.Continue */],
    ['__debug__', 9 /* KeywordType.Debug */],
    ['def', 10 /* KeywordType.Def */],
    ['del', 11 /* KeywordType.Del */],
    ['elif', 12 /* KeywordType.Elif */],
    ['else', 13 /* KeywordType.Else */],
    ['except', 14 /* KeywordType.Except */],
    ['finally', 16 /* KeywordType.Finally */],
    ['for', 17 /* KeywordType.For */],
    ['from', 18 /* KeywordType.From */],
    ['global', 19 /* KeywordType.Global */],
    ['if', 20 /* KeywordType.If */],
    ['import', 21 /* KeywordType.Import */],
    ['in', 22 /* KeywordType.In */],
    ['is', 23 /* KeywordType.Is */],
    ['lambda', 24 /* KeywordType.Lambda */],
    ['match', 25 /* KeywordType.Match */],
    ['nonlocal', 27 /* KeywordType.Nonlocal */],
    ['not', 28 /* KeywordType.Not */],
    ['or', 29 /* KeywordType.Or */],
    ['pass', 30 /* KeywordType.Pass */],
    ['raise', 31 /* KeywordType.Raise */],
    ['return', 32 /* KeywordType.Return */],
    ['try', 34 /* KeywordType.Try */],
    ['type', 35 /* KeywordType.Type */],
    ['while', 36 /* KeywordType.While */],
    ['with', 37 /* KeywordType.With */],
    ['yield', 38 /* KeywordType.Yield */],
    ['False', 15 /* KeywordType.False */],
    ['None', 26 /* KeywordType.None */],
    ['True', 33 /* KeywordType.True */],
]);
const _softKeywords = new Set(['match', 'case', 'type']);
const _operatorInfo = {
    [0 /* OperatorType.Add */]: 1 /* OperatorFlags.Unary */ | 2 /* OperatorFlags.Binary */,
    [1 /* OperatorType.AddEqual */]: 4 /* OperatorFlags.Assignment */,
    [2 /* OperatorType.Assign */]: 4 /* OperatorFlags.Assignment */,
    [3 /* OperatorType.BitwiseAnd */]: 2 /* OperatorFlags.Binary */,
    [4 /* OperatorType.BitwiseAndEqual */]: 4 /* OperatorFlags.Assignment */,
    [5 /* OperatorType.BitwiseInvert */]: 1 /* OperatorFlags.Unary */,
    [6 /* OperatorType.BitwiseOr */]: 2 /* OperatorFlags.Binary */,
    [7 /* OperatorType.BitwiseOrEqual */]: 4 /* OperatorFlags.Assignment */,
    [8 /* OperatorType.BitwiseXor */]: 2 /* OperatorFlags.Binary */,
    [9 /* OperatorType.BitwiseXorEqual */]: 4 /* OperatorFlags.Assignment */,
    [10 /* OperatorType.Divide */]: 2 /* OperatorFlags.Binary */,
    [11 /* OperatorType.DivideEqual */]: 4 /* OperatorFlags.Assignment */,
    [12 /* OperatorType.Equals */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [13 /* OperatorType.FloorDivide */]: 2 /* OperatorFlags.Binary */,
    [14 /* OperatorType.FloorDivideEqual */]: 4 /* OperatorFlags.Assignment */,
    [15 /* OperatorType.GreaterThan */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [16 /* OperatorType.GreaterThanOrEqual */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [17 /* OperatorType.LeftShift */]: 2 /* OperatorFlags.Binary */,
    [18 /* OperatorType.LeftShiftEqual */]: 4 /* OperatorFlags.Assignment */,
    [19 /* OperatorType.LessOrGreaterThan */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */ | 16 /* OperatorFlags.Deprecated */,
    [20 /* OperatorType.LessThan */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [21 /* OperatorType.LessThanOrEqual */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [22 /* OperatorType.MatrixMultiply */]: 2 /* OperatorFlags.Binary */,
    [23 /* OperatorType.MatrixMultiplyEqual */]: 4 /* OperatorFlags.Assignment */,
    [24 /* OperatorType.Mod */]: 2 /* OperatorFlags.Binary */,
    [25 /* OperatorType.ModEqual */]: 4 /* OperatorFlags.Assignment */,
    [26 /* OperatorType.Multiply */]: 2 /* OperatorFlags.Binary */,
    [27 /* OperatorType.MultiplyEqual */]: 4 /* OperatorFlags.Assignment */,
    [28 /* OperatorType.NotEquals */]: 2 /* OperatorFlags.Binary */ | 8 /* OperatorFlags.Comparison */,
    [29 /* OperatorType.Power */]: 2 /* OperatorFlags.Binary */,
    [30 /* OperatorType.PowerEqual */]: 4 /* OperatorFlags.Assignment */,
    [31 /* OperatorType.RightShift */]: 2 /* OperatorFlags.Binary */,
    [32 /* OperatorType.RightShiftEqual */]: 4 /* OperatorFlags.Assignment */,
    [33 /* OperatorType.Subtract */]: 2 /* OperatorFlags.Binary */,
    [34 /* OperatorType.SubtractEqual */]: 4 /* OperatorFlags.Assignment */,
    [36 /* OperatorType.And */]: 2 /* OperatorFlags.Binary */,
    [37 /* OperatorType.Or */]: 2 /* OperatorFlags.Binary */,
    [38 /* OperatorType.Not */]: 1 /* OperatorFlags.Unary */,
    [39 /* OperatorType.Is */]: 2 /* OperatorFlags.Binary */,
    [40 /* OperatorType.IsNot */]: 2 /* OperatorFlags.Binary */,
    [41 /* OperatorType.In */]: 2 /* OperatorFlags.Binary */,
    [42 /* OperatorType.NotIn */]: 2 /* OperatorFlags.Binary */,
};
const _byteOrderMarker = 0xfeff;
const defaultTabSize = 8;
class Tokenizer {
    constructor() {
        this._cs = new characterStream_1.CharacterStream('');
        this._tokens = [];
        this._prevLineStart = 0;
        this._parenDepth = 0;
        this._lineRanges = [];
        this._indentAmounts = [];
        this._typeIgnoreLines = new Map();
        this._pyrightIgnoreLines = new Map();
        this._fStringStack = [];
        // Total times CR, CR/LF, and LF are used to terminate
        // lines. Used to determine the predominant line ending.
        this._crCount = 0;
        this._crLfCount = 0;
        this._lfCount = 0;
        // Number of times an indent token is emitted.
        this._indentCount = 0;
        // Number of times an indent token is emitted and a tab character
        // is present (used to determine predominant tab sequence).
        this._indentTabCount = 0;
        // Number of spaces that are added for an indent token
        // (used to determine predominant tab sequence).
        this._indentSpacesTotal = 0;
        // Number of single or double quote string literals found
        // in the code.
        this._singleQuoteCount = 0;
        this._doubleQuoteCount = 0;
        // ipython mode
        this._ipythonMode = sourceFile_1.IPythonMode.None;
    }
    tokenize(text, start, length, initialParenDepth = 0, ipythonMode = sourceFile_1.IPythonMode.None) {
        if (start === undefined) {
            start = 0;
        }
        else if (start < 0 || start > text.length) {
            throw new Error(`Invalid range start (start=${start}, text.length=${text.length})`);
        }
        if (length === undefined) {
            length = text.length;
        }
        else if (length < 0 || start + length > text.length) {
            throw new Error(`Invalid range length (start=${start}, length=${length}, text.length=${text.length})`);
        }
        else if (start + length < text.length) {
            text = text.slice(0, start + length);
        }
        this._cs = new characterStream_1.CharacterStream(text);
        this._cs.position = start;
        this._tokens = [];
        this._prevLineStart = 0;
        this._parenDepth = initialParenDepth;
        this._lineRanges = [];
        this._indentAmounts = [];
        this._ipythonMode = ipythonMode;
        const end = start + length;
        if (start === 0) {
            this._readIndentationAfterNewLine();
        }
        while (!this._cs.isEndOfStream()) {
            this._addNextToken();
            if (this._cs.position >= end) {
                break;
            }
        }
        // Insert any implied FStringEnd tokens.
        while (this._activeFString) {
            this._tokens.push(tokenizerTypes_1.FStringEndToken.create(this._cs.position, 0, this._activeFString.startToken.flags | 65536 /* StringTokenFlags.Unterminated */));
            this._activeFString = this._fStringStack.pop();
        }
        // Insert an implied new line to make parsing easier.
        if (this._tokens.length === 0 || this._tokens[this._tokens.length - 1].type !== 2 /* TokenType.NewLine */) {
            this._tokens.push(tokenizerTypes_1.NewLineToken.create(this._cs.position, 0, 3 /* NewLineType.Implied */, this._getComments()));
        }
        // Insert any implied dedent tokens.
        this._setIndent(this._cs.position, 0, 0, /* isSpacePresent */ false, /* isTabPresent */ false);
        // Add a final end-of-stream token to make parsing easier.
        this._tokens.push(tokenizerTypes_1.Token.create(1 /* TokenType.EndOfStream */, this._cs.position, 0, this._getComments()));
        // Add the final line range.
        this._addLineRange();
        // If the last line ended in a line-end character, add an empty line.
        if (this._lineRanges.length > 0) {
            const lastLine = this._lineRanges[this._lineRanges.length - 1];
            const lastCharOfLastLine = text.charCodeAt(lastLine.start + lastLine.length - 1);
            if (lastCharOfLastLine === 13 /* Char.CarriageReturn */ || lastCharOfLastLine === 10 /* Char.LineFeed */) {
                this._lineRanges.push({ start: this._cs.position, length: 0 });
            }
        }
        let predominantEndOfLineSequence = '\n';
        if (this._crCount > this._crLfCount && this._crCount > this._lfCount) {
            predominantEndOfLineSequence = '\r';
        }
        else if (this._crLfCount > this._crCount && this._crLfCount > this._lfCount) {
            predominantEndOfLineSequence = '\r\n';
        }
        let predominantTabSequence = '    ';
        let hasPredominantTabSequence = false;
        // If more than half of the indents use tab sequences,
        // assume we're using tabs rather than spaces.
        if (this._indentTabCount > this._indentCount / 2) {
            hasPredominantTabSequence = true;
            predominantTabSequence = '\t';
        }
        else if (this._indentCount > 0) {
            hasPredominantTabSequence = true;
            // Compute the average number of spaces per indent
            // to estimate the predominant tab value.
            let averageSpacePerIndent = Math.round(this._indentSpacesTotal / this._indentCount);
            if (averageSpacePerIndent < 1) {
                averageSpacePerIndent = 1;
            }
            else if (averageSpacePerIndent > defaultTabSize) {
                averageSpacePerIndent = defaultTabSize;
            }
            predominantTabSequence = '';
            for (let i = 0; i < averageSpacePerIndent; i++) {
                predominantTabSequence += ' ';
            }
        }
        return {
            tokens: new textRangeCollection_1.TextRangeCollection(this._tokens),
            lines: new textRangeCollection_1.TextRangeCollection(this._lineRanges),
            typeIgnoreLines: this._typeIgnoreLines,
            typeIgnoreAll: this._typeIgnoreAll,
            pyrightIgnoreLines: this._pyrightIgnoreLines,
            predominantEndOfLineSequence,
            hasPredominantTabSequence,
            predominantTabSequence,
            predominantSingleQuoteCharacter: this._singleQuoteCount >= this._doubleQuoteCount ? "'" : '"',
        };
    }
    static getOperatorInfo(operatorType) {
        return _operatorInfo[operatorType];
    }
    static isPythonKeyword(name, includeSoftKeywords = false) {
        const keyword = _keywords.get(name);
        if (!keyword) {
            return false;
        }
        if (includeSoftKeywords) {
            return true;
        }
        return !_softKeywords.has(name);
    }
    static isOperatorAssignment(operatorType) {
        if (operatorType === undefined || _operatorInfo[operatorType] === undefined) {
            return false;
        }
        return (_operatorInfo[operatorType] & 4 /* OperatorFlags.Assignment */) !== 0;
    }
    static isOperatorComparison(operatorType) {
        if (operatorType === undefined || _operatorInfo[operatorType] === undefined) {
            return false;
        }
        return (_operatorInfo[operatorType] & 8 /* OperatorFlags.Comparison */) !== 0;
    }
    _addNextToken() {
        // Are we in the middle of an f-string but not in a replacement field?
        if (this._activeFString &&
            (!this._activeFString.activeReplacementField ||
                this._activeFString.activeReplacementField.inFormatSpecifier)) {
            this._handleFStringMiddle();
        }
        else {
            this._cs.skipWhitespace();
        }
        if (this._cs.isEndOfStream()) {
            return;
        }
        if (!this._handleCharacter()) {
            this._cs.moveNext();
        }
    }
    // Consumes one or more characters from the character stream and pushes
    // tokens onto the token list. Returns true if the caller should advance
    // to the next character.
    _handleCharacter() {
        var _a, _b;
        // f-strings, b-strings, etc
        const stringPrefixLength = this._getStringPrefixLength();
        if (stringPrefixLength >= 0) {
            let stringPrefix = '';
            if (stringPrefixLength > 0) {
                stringPrefix = this._cs.getText().slice(this._cs.position, this._cs.position + stringPrefixLength);
                // Indeed a string
                this._cs.advance(stringPrefixLength);
            }
            const quoteTypeFlags = this._getQuoteTypeFlags(stringPrefix);
            if (quoteTypeFlags !== 0 /* StringTokenFlags.None */) {
                this._handleString(quoteTypeFlags, stringPrefixLength);
                return true;
            }
        }
        if (this._cs.currentChar === 35 /* Char.Hash */) {
            this._handleComment();
            return true;
        }
        if (this._ipythonMode) {
            const kind = this._getIPythonMagicsKind();
            if (kind === 'line') {
                this._handleIPythonMagics(this._cs.currentChar === 37 /* Char.Percent */ ? 1 /* CommentType.IPythonMagic */ : 2 /* CommentType.IPythonShellEscape */);
                return true;
            }
            if (kind === 'cell') {
                this._handleIPythonMagics(this._cs.currentChar === 37 /* Char.Percent */
                    ? 3 /* CommentType.IPythonCellMagic */
                    : 4 /* CommentType.IPythonCellShellEscape */);
                return true;
            }
        }
        switch (this._cs.currentChar) {
            case _byteOrderMarker: {
                // Skip the BOM if it's at the start of the file.
                if (this._cs.position === 0) {
                    return false;
                }
                return this._handleInvalid();
            }
            case 13 /* Char.CarriageReturn */: {
                const length = this._cs.nextChar === 10 /* Char.LineFeed */ ? 2 : 1;
                const newLineType = length === 2 ? 2 /* NewLineType.CarriageReturnLineFeed */ : 0 /* NewLineType.CarriageReturn */;
                this._handleNewLine(length, newLineType);
                return true;
            }
            case 10 /* Char.LineFeed */: {
                this._handleNewLine(1, 1 /* NewLineType.LineFeed */);
                return true;
            }
            case 92 /* Char.Backslash */: {
                if (this._cs.nextChar === 13 /* Char.CarriageReturn */) {
                    if (this._cs.lookAhead(2) === 10 /* Char.LineFeed */) {
                        this._cs.advance(3);
                    }
                    else {
                        this._cs.advance(2);
                    }
                    this._addLineRange();
                    return true;
                }
                else if (this._cs.nextChar === 10 /* Char.LineFeed */) {
                    this._cs.advance(2);
                    this._addLineRange();
                    return true;
                }
                return this._handleInvalid();
            }
            case 40 /* Char.OpenParenthesis */: {
                this._parenDepth++;
                this._tokens.push(tokenizerTypes_1.Token.create(13 /* TokenType.OpenParenthesis */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 41 /* Char.CloseParenthesis */: {
                if (this._parenDepth > 0) {
                    this._parenDepth--;
                }
                this._tokens.push(tokenizerTypes_1.Token.create(14 /* TokenType.CloseParenthesis */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 91 /* Char.OpenBracket */: {
                this._parenDepth++;
                this._tokens.push(tokenizerTypes_1.Token.create(15 /* TokenType.OpenBracket */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 93 /* Char.CloseBracket */: {
                if (this._parenDepth > 0) {
                    this._parenDepth--;
                }
                this._tokens.push(tokenizerTypes_1.Token.create(16 /* TokenType.CloseBracket */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 123 /* Char.OpenBrace */: {
                this._parenDepth++;
                this._tokens.push(tokenizerTypes_1.Token.create(17 /* TokenType.OpenCurlyBrace */, this._cs.position, 1, this._getComments()));
                if (this._activeFString) {
                    // Are we starting a new replacement field?
                    if (!this._activeFString.activeReplacementField ||
                        this._activeFString.activeReplacementField.inFormatSpecifier) {
                        // If there is already an active replacement field, push it
                        // on the stack so we can pop it later.
                        if (this._activeFString.activeReplacementField) {
                            this._activeFString.replacementFieldStack.push(this._activeFString.activeReplacementField);
                        }
                        // Create a new active replacement field context.
                        this._activeFString.activeReplacementField = {
                            inFormatSpecifier: false,
                            parenDepth: this._parenDepth,
                        };
                    }
                }
                break;
            }
            case 125 /* Char.CloseBrace */: {
                if (this._activeFString &&
                    ((_a = this._activeFString.activeReplacementField) === null || _a === void 0 ? void 0 : _a.parenDepth) === this._parenDepth) {
                    this._activeFString.activeReplacementField = this._activeFString.replacementFieldStack.pop();
                }
                if (this._parenDepth > 0) {
                    this._parenDepth--;
                }
                this._tokens.push(tokenizerTypes_1.Token.create(18 /* TokenType.CloseCurlyBrace */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 44 /* Char.Comma */: {
                this._tokens.push(tokenizerTypes_1.Token.create(12 /* TokenType.Comma */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 96 /* Char.Backtick */: {
                this._tokens.push(tokenizerTypes_1.Token.create(22 /* TokenType.Backtick */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 59 /* Char.Semicolon */: {
                this._tokens.push(tokenizerTypes_1.Token.create(11 /* TokenType.Semicolon */, this._cs.position, 1, this._getComments()));
                break;
            }
            case 58 /* Char.Colon */: {
                if (this._cs.nextChar === 61 /* Char.Equal */) {
                    if (!this._activeFString ||
                        !this._activeFString.activeReplacementField ||
                        this._activeFString.activeReplacementField.parenDepth !== this._parenDepth) {
                        this._tokens.push(tokenizerTypes_1.OperatorToken.create(this._cs.position, 2, 35 /* OperatorType.Walrus */, this._getComments()));
                        this._cs.advance(1);
                        break;
                    }
                }
                this._tokens.push(tokenizerTypes_1.Token.create(10 /* TokenType.Colon */, this._cs.position, 1, this._getComments()));
                if (((_b = this._activeFString) === null || _b === void 0 ? void 0 : _b.activeReplacementField) &&
                    this._parenDepth === this._activeFString.activeReplacementField.parenDepth) {
                    this._activeFString.activeReplacementField.inFormatSpecifier = true;
                }
                break;
            }
            default: {
                if (this._isPossibleNumber()) {
                    if (this._tryNumber()) {
                        return true;
                    }
                }
                if (this._cs.currentChar === 46 /* Char.Period */) {
                    if (this._cs.nextChar === 46 /* Char.Period */ && this._cs.lookAhead(2) === 46 /* Char.Period */) {
                        this._tokens.push(tokenizerTypes_1.Token.create(19 /* TokenType.Ellipsis */, this._cs.position, 3, this._getComments()));
                        this._cs.advance(3);
                        return true;
                    }
                    this._tokens.push(tokenizerTypes_1.Token.create(20 /* TokenType.Dot */, this._cs.position, 1, this._getComments()));
                    break;
                }
                if (!this._tryIdentifier()) {
                    if (!this._tryOperator()) {
                        return this._handleInvalid();
                    }
                }
                return true;
            }
        }
        return false;
    }
    _addLineRange() {
        const lineLength = this._cs.position - this._prevLineStart;
        if (lineLength > 0) {
            this._lineRanges.push({ start: this._prevLineStart, length: lineLength });
        }
        this._prevLineStart = this._cs.position;
    }
    _handleNewLine(length, newLineType) {
        if (this._parenDepth === 0 && newLineType !== 3 /* NewLineType.Implied */) {
            // New lines are ignored within parentheses.
            // We'll also avoid adding multiple newlines in a row to simplify parsing.
            if (this._tokens.length === 0 || this._tokens[this._tokens.length - 1].type !== 2 /* TokenType.NewLine */) {
                this._tokens.push(tokenizerTypes_1.NewLineToken.create(this._cs.position, length, newLineType, this._getComments()));
            }
        }
        if (newLineType === 0 /* NewLineType.CarriageReturn */) {
            this._crCount++;
        }
        else if (newLineType === 2 /* NewLineType.CarriageReturnLineFeed */) {
            this._crLfCount++;
        }
        else {
            this._lfCount++;
        }
        this._cs.advance(length);
        this._addLineRange();
        this._readIndentationAfterNewLine();
    }
    _readIndentationAfterNewLine() {
        let tab1Spaces = 0;
        let tab8Spaces = 0;
        let isTabPresent = false;
        let isSpacePresent = false;
        const startOffset = this._cs.position;
        while (!this._cs.isEndOfStream()) {
            switch (this._cs.currentChar) {
                case 32 /* Char.Space */:
                    tab1Spaces++;
                    tab8Spaces++;
                    isSpacePresent = true;
                    this._cs.moveNext();
                    break;
                case 9 /* Char.Tab */:
                    // Translate tabs into spaces assuming both 1-space
                    // and 8-space tab stops.
                    tab1Spaces++;
                    tab8Spaces += defaultTabSize - (tab8Spaces % defaultTabSize);
                    isTabPresent = true;
                    this._cs.moveNext();
                    break;
                case 12 /* Char.FormFeed */:
                    tab1Spaces = 0;
                    tab8Spaces = 0;
                    isTabPresent = false;
                    isSpacePresent = false;
                    this._cs.moveNext();
                    break;
                default:
                    // Non-blank line. Set the current indent level.
                    this._setIndent(startOffset, tab1Spaces, tab8Spaces, isSpacePresent, isTabPresent);
                    return;
                case 35 /* Char.Hash */:
                case 10 /* Char.LineFeed */:
                case 13 /* Char.CarriageReturn */:
                    // Blank line -- no need to adjust indentation.
                    return;
            }
        }
    }
    // The caller must specify two space count values. The first assumes
    // that tabs are translated into one-space tab stops. The second assumes
    // that tabs are translated into eight-space tab stops.
    _setIndent(startOffset, tab1Spaces, tab8Spaces, isSpacePresent, isTabPresent) {
        // Indentations are ignored within a parenthesized clause.
        if (this._parenDepth > 0) {
            return;
        }
        // Insert indent or dedent tokens as necessary.
        if (this._indentAmounts.length === 0) {
            if (tab8Spaces > 0) {
                this._indentCount++;
                if (isTabPresent) {
                    this._indentTabCount++;
                }
                this._indentSpacesTotal += tab8Spaces;
                this._indentAmounts.push({
                    tab1Spaces,
                    tab8Spaces,
                    isSpacePresent,
                    isTabPresent,
                });
                this._tokens.push(tokenizerTypes_1.IndentToken.create(startOffset, tab1Spaces, tab8Spaces, false, this._getComments()));
            }
        }
        else {
            const prevTabInfo = this._indentAmounts[this._indentAmounts.length - 1];
            if (prevTabInfo.tab8Spaces < tab8Spaces) {
                // The Python spec says that if there is ambiguity about how tabs should
                // be translated into spaces because the user has intermixed tabs and
                // spaces, it should be an error. We'll record this condition in the token
                // so the parser can later report it.
                const isIndentAmbiguous = ((prevTabInfo.isSpacePresent && isTabPresent) || (prevTabInfo.isTabPresent && isSpacePresent)) &&
                    prevTabInfo.tab1Spaces >= tab1Spaces;
                this._indentCount++;
                if (isTabPresent) {
                    this._indentTabCount++;
                }
                this._indentSpacesTotal += tab8Spaces - this._indentAmounts[this._indentAmounts.length - 1].tab8Spaces;
                this._indentAmounts.push({
                    tab1Spaces,
                    tab8Spaces,
                    isSpacePresent,
                    isTabPresent,
                });
                this._tokens.push(tokenizerTypes_1.IndentToken.create(startOffset, tab1Spaces, tab8Spaces, isIndentAmbiguous, this._getComments()));
            }
            else if (prevTabInfo.tab8Spaces === tab8Spaces) {
                // The Python spec says that if there is ambiguity about how tabs should
                // be translated into spaces because the user has intermixed tabs and
                // spaces, it should be an error. We'll record this condition in the token
                // so the parser can later report it.
                if ((prevTabInfo.isSpacePresent && isTabPresent) || (prevTabInfo.isTabPresent && isSpacePresent)) {
                    this._tokens.push(tokenizerTypes_1.IndentToken.create(startOffset, tab1Spaces, tab8Spaces, true, this._getComments()));
                }
            }
            else {
                // The Python spec says that if there is ambiguity about how tabs should
                // be translated into spaces because the user has intermixed tabs and
                // spaces, it should be an error. We'll record this condition in the token
                // so the parser can later report it.
                let isDedentAmbiguous = (prevTabInfo.isSpacePresent && isTabPresent) || (prevTabInfo.isTabPresent && isSpacePresent);
                // The Python spec says that dedent amounts need to match the indent
                // amount exactly. An error is generated at runtime if it doesn't.
                // We'll record that error condition within the token, allowing the
                // parser to report it later.
                const dedentPoints = [];
                while (this._indentAmounts.length > 0 &&
                    this._indentAmounts[this._indentAmounts.length - 1].tab8Spaces > tab8Spaces) {
                    dedentPoints.push(this._indentAmounts.length > 1
                        ? this._indentAmounts[this._indentAmounts.length - 2].tab8Spaces
                        : 0);
                    this._indentAmounts.pop();
                }
                dedentPoints.forEach((dedentAmount, index) => {
                    const matchesIndent = index < dedentPoints.length - 1 || dedentAmount === tab8Spaces;
                    const actualDedentAmount = index < dedentPoints.length - 1 ? dedentAmount : tab8Spaces;
                    this._tokens.push(tokenizerTypes_1.DedentToken.create(this._cs.position, 0, actualDedentAmount, matchesIndent, isDedentAmbiguous, this._getComments()));
                    isDedentAmbiguous = false;
                });
            }
        }
    }
    _tryIdentifier() {
        const swallowRemainingChars = () => {
            while (true) {
                if ((0, characters_1.isIdentifierChar)(this._cs.currentChar)) {
                    this._cs.moveNext();
                }
                else if ((0, characters_1.isIdentifierChar)(this._cs.currentChar, this._cs.nextChar)) {
                    this._cs.moveNext();
                    this._cs.moveNext();
                }
                else {
                    break;
                }
            }
        };
        const start = this._cs.position;
        if ((0, characters_1.isIdentifierStartChar)(this._cs.currentChar)) {
            this._cs.moveNext();
            swallowRemainingChars();
        }
        else if ((0, characters_1.isIdentifierStartChar)(this._cs.currentChar, this._cs.nextChar)) {
            this._cs.moveNext();
            this._cs.moveNext();
            swallowRemainingChars();
        }
        if (this._cs.position > start) {
            const value = this._cs.getText().slice(start, this._cs.position);
            if (_keywords.has(value)) {
                this._tokens.push(tokenizerTypes_1.KeywordToken.create(start, this._cs.position - start, _keywords.get(value), this._getComments()));
            }
            else {
                this._tokens.push(tokenizerTypes_1.IdentifierToken.create(start, this._cs.position - start, value, this._getComments()));
            }
            return true;
        }
        return false;
    }
    _isPossibleNumber() {
        if ((0, characters_1.isDecimal)(this._cs.currentChar)) {
            return true;
        }
        if (this._cs.currentChar === 46 /* Char.Period */ && (0, characters_1.isDecimal)(this._cs.nextChar)) {
            return true;
        }
        return false;
    }
    _tryNumber() {
        const start = this._cs.position;
        if (this._cs.currentChar === 48 /* Char._0 */) {
            let radix = 0;
            let leadingChars = 0;
            // Try hex => hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
            if ((this._cs.nextChar === 120 /* Char.x */ || this._cs.nextChar === 88 /* Char.X */) && (0, characters_1.isHex)(this._cs.lookAhead(2))) {
                this._cs.advance(2);
                leadingChars = 2;
                while ((0, characters_1.isHex)(this._cs.currentChar)) {
                    this._cs.moveNext();
                }
                radix = 16;
            }
            // Try binary => bininteger: "0" ("b" | "B") (["_"] bindigit)+
            else if ((this._cs.nextChar === 98 /* Char.b */ || this._cs.nextChar === 66 /* Char.B */) &&
                (0, characters_1.isBinary)(this._cs.lookAhead(2))) {
                this._cs.advance(2);
                leadingChars = 2;
                while ((0, characters_1.isBinary)(this._cs.currentChar)) {
                    this._cs.moveNext();
                }
                radix = 2;
            }
            // Try octal => octinteger: "0" ("o" | "O") (["_"] octdigit)+
            else if ((this._cs.nextChar === 111 /* Char.o */ || this._cs.nextChar === 79 /* Char.O */) && (0, characters_1.isOctal)(this._cs.lookAhead(2))) {
                this._cs.advance(2);
                leadingChars = 2;
                while ((0, characters_1.isOctal)(this._cs.currentChar)) {
                    this._cs.moveNext();
                }
                radix = 8;
            }
            if (radix > 0) {
                const text = this._cs.getText().slice(start, this._cs.position);
                const simpleIntText = text.replace(/_/g, '');
                let intValue = parseInt(simpleIntText.slice(leadingChars), radix);
                if (!isNaN(intValue)) {
                    const bigIntValue = BigInt(simpleIntText);
                    if (!isFinite(intValue) ||
                        intValue < Number.MIN_SAFE_INTEGER ||
                        intValue > Number.MAX_SAFE_INTEGER) {
                        intValue = bigIntValue;
                    }
                    this._tokens.push(tokenizerTypes_1.NumberToken.create(start, text.length, intValue, true, false, this._getComments()));
                    return true;
                }
            }
        }
        let isDecimalInteger = false;
        let mightBeFloatingPoint = false;
        // Try decimal int =>
        //    decinteger: nonzerodigit (["_"] digit)* | "0" (["_"] "0")*
        //    nonzerodigit: "1"..."9"
        //    digit: "0"..."9"
        if (this._cs.currentChar >= 49 /* Char._1 */ && this._cs.currentChar <= 57 /* Char._9 */) {
            while ((0, characters_1.isDecimal)(this._cs.currentChar)) {
                mightBeFloatingPoint = true;
                this._cs.moveNext();
            }
            isDecimalInteger =
                this._cs.currentChar !== 46 /* Char.Period */ &&
                    this._cs.currentChar !== 101 /* Char.e */ &&
                    this._cs.currentChar !== 69 /* Char.E */;
        }
        // "0" (["_"] "0")*
        if (this._cs.currentChar === 48 /* Char._0 */) {
            mightBeFloatingPoint = true;
            while (this._cs.currentChar === 48 /* Char._0 */ || this._cs.currentChar === 95 /* Char.Underscore */) {
                this._cs.moveNext();
            }
            isDecimalInteger =
                this._cs.currentChar !== 46 /* Char.Period */ &&
                    this._cs.currentChar !== 101 /* Char.e */ &&
                    this._cs.currentChar !== 69 /* Char.E */ &&
                    (this._cs.currentChar < 49 /* Char._1 */ || this._cs.currentChar > 57 /* Char._9 */);
        }
        if (isDecimalInteger) {
            let text = this._cs.getText().slice(start, this._cs.position);
            const simpleIntText = text.replace(/_/g, '');
            let intValue = parseInt(simpleIntText, 10);
            if (!isNaN(intValue)) {
                let isImaginary = false;
                const bigIntValue = BigInt(simpleIntText);
                if (!isFinite(intValue) ||
                    bigIntValue < Number.MIN_SAFE_INTEGER ||
                    bigIntValue > Number.MAX_SAFE_INTEGER) {
                    intValue = bigIntValue;
                }
                if (this._cs.currentChar === 106 /* Char.j */ || this._cs.currentChar === 74 /* Char.J */) {
                    isImaginary = true;
                    text += String.fromCharCode(this._cs.currentChar);
                    this._cs.moveNext();
                }
                this._tokens.push(tokenizerTypes_1.NumberToken.create(start, text.length, intValue, true, isImaginary, this._getComments()));
                return true;
            }
        }
        // Floating point. Sign and leading digits were already skipped over.
        this._cs.position = start;
        if (mightBeFloatingPoint ||
            (this._cs.currentChar === 46 /* Char.Period */ && this._cs.nextChar >= 48 /* Char._0 */ && this._cs.nextChar <= 57 /* Char._9 */)) {
            if (this._skipFloatingPointCandidate()) {
                let text = this._cs.getText().slice(start, this._cs.position);
                const value = parseFloat(text);
                if (!isNaN(value)) {
                    let isImaginary = false;
                    if (this._cs.currentChar === 106 /* Char.j */ || this._cs.currentChar === 74 /* Char.J */) {
                        isImaginary = true;
                        text += String.fromCharCode(this._cs.currentChar);
                        this._cs.moveNext();
                    }
                    this._tokens.push(tokenizerTypes_1.NumberToken.create(start, this._cs.position - start, value, false, isImaginary, this._getComments()));
                    return true;
                }
            }
        }
        this._cs.position = start;
        return false;
    }
    _tryOperator() {
        var _a, _b;
        let length = 0;
        const nextChar = this._cs.nextChar;
        let operatorType;
        switch (this._cs.currentChar) {
            case 43 /* Char.Plus */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 1 /* OperatorType.AddEqual */ : 0 /* OperatorType.Add */;
                break;
            case 38 /* Char.Ampersand */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 4 /* OperatorType.BitwiseAndEqual */ : 3 /* OperatorType.BitwiseAnd */;
                break;
            case 124 /* Char.Bar */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 7 /* OperatorType.BitwiseOrEqual */ : 6 /* OperatorType.BitwiseOr */;
                break;
            case 94 /* Char.Caret */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 9 /* OperatorType.BitwiseXorEqual */ : 8 /* OperatorType.BitwiseXor */;
                break;
            case 61 /* Char.Equal */:
                if (((_a = this._activeFString) === null || _a === void 0 ? void 0 : _a.activeReplacementField) &&
                    ((_b = this._activeFString) === null || _b === void 0 ? void 0 : _b.activeReplacementField.parenDepth) === this._parenDepth &&
                    !this._activeFString.activeReplacementField.inFormatSpecifier &&
                    nextChar !== 61 /* Char.Equal */) {
                    length = 1;
                    operatorType = 2 /* OperatorType.Assign */;
                    break;
                }
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 12 /* OperatorType.Equals */ : 2 /* OperatorType.Assign */;
                break;
            case 33 /* Char.ExclamationMark */:
                if (nextChar !== 61 /* Char.Equal */) {
                    if (this._activeFString) {
                        // Handle the conversion separator (!) within an f-string.
                        this._tokens.push(tokenizerTypes_1.Token.create(23 /* TokenType.ExclamationMark */, this._cs.position, 1, this._getComments()));
                        this._cs.advance(1);
                        return true;
                    }
                    return false;
                }
                length = 2;
                operatorType = 28 /* OperatorType.NotEquals */;
                break;
            case 37 /* Char.Percent */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 25 /* OperatorType.ModEqual */ : 24 /* OperatorType.Mod */;
                break;
            case 126 /* Char.Tilde */:
                length = 1;
                operatorType = 5 /* OperatorType.BitwiseInvert */;
                break;
            case 45 /* Char.Hyphen */:
                if (nextChar === 62 /* Char.Greater */) {
                    this._tokens.push(tokenizerTypes_1.Token.create(21 /* TokenType.Arrow */, this._cs.position, 2, this._getComments()));
                    this._cs.advance(2);
                    return true;
                }
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 34 /* OperatorType.SubtractEqual */ : 33 /* OperatorType.Subtract */;
                break;
            case 42 /* Char.Asterisk */:
                if (nextChar === 42 /* Char.Asterisk */) {
                    length = this._cs.lookAhead(2) === 61 /* Char.Equal */ ? 3 : 2;
                    operatorType = length === 3 ? 30 /* OperatorType.PowerEqual */ : 29 /* OperatorType.Power */;
                }
                else {
                    length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                    operatorType = length === 2 ? 27 /* OperatorType.MultiplyEqual */ : 26 /* OperatorType.Multiply */;
                }
                break;
            case 47 /* Char.Slash */:
                if (nextChar === 47 /* Char.Slash */) {
                    length = this._cs.lookAhead(2) === 61 /* Char.Equal */ ? 3 : 2;
                    operatorType = length === 3 ? 14 /* OperatorType.FloorDivideEqual */ : 13 /* OperatorType.FloorDivide */;
                }
                else {
                    length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                    operatorType = length === 2 ? 11 /* OperatorType.DivideEqual */ : 10 /* OperatorType.Divide */;
                }
                break;
            case 60 /* Char.Less */:
                if (nextChar === 60 /* Char.Less */) {
                    length = this._cs.lookAhead(2) === 61 /* Char.Equal */ ? 3 : 2;
                    operatorType = length === 3 ? 18 /* OperatorType.LeftShiftEqual */ : 17 /* OperatorType.LeftShift */;
                }
                else if (nextChar === 62 /* Char.Greater */) {
                    length = 2;
                    operatorType = 19 /* OperatorType.LessOrGreaterThan */;
                }
                else {
                    length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                    operatorType = length === 2 ? 21 /* OperatorType.LessThanOrEqual */ : 20 /* OperatorType.LessThan */;
                }
                break;
            case 62 /* Char.Greater */:
                if (nextChar === 62 /* Char.Greater */) {
                    length = this._cs.lookAhead(2) === 61 /* Char.Equal */ ? 3 : 2;
                    operatorType = length === 3 ? 32 /* OperatorType.RightShiftEqual */ : 31 /* OperatorType.RightShift */;
                }
                else {
                    length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                    operatorType = length === 2 ? 16 /* OperatorType.GreaterThanOrEqual */ : 15 /* OperatorType.GreaterThan */;
                }
                break;
            case 64 /* Char.At */:
                length = nextChar === 61 /* Char.Equal */ ? 2 : 1;
                operatorType = length === 2 ? 23 /* OperatorType.MatrixMultiplyEqual */ : 22 /* OperatorType.MatrixMultiply */;
                break;
            default:
                return false;
        }
        this._tokens.push(tokenizerTypes_1.OperatorToken.create(this._cs.position, length, operatorType, this._getComments()));
        this._cs.advance(length);
        return length > 0;
    }
    _handleInvalid() {
        const start = this._cs.position;
        while (true) {
            if (this._cs.currentChar === 10 /* Char.LineFeed */ ||
                this._cs.currentChar === 13 /* Char.CarriageReturn */ ||
                this._cs.isAtWhiteSpace() ||
                this._cs.isEndOfStream()) {
                break;
            }
            if ((0, characters_1.isSurrogateChar)(this._cs.currentChar)) {
                this._cs.moveNext();
                this._cs.moveNext();
            }
            else {
                this._cs.moveNext();
            }
        }
        const length = this._cs.position - start;
        if (length > 0) {
            this._tokens.push(tokenizerTypes_1.Token.create(0 /* TokenType.Invalid */, start, length, this._getComments()));
            return true;
        }
        return false;
    }
    _getComments() {
        const prevComments = this._comments;
        this._comments = undefined;
        return prevComments;
    }
    _getIPythonMagicsKind() {
        if (!isMagicChar(this._cs.currentChar)) {
            return undefined;
        }
        const prevToken = this._tokens.length > 0 ? this._tokens[this._tokens.length - 1] : undefined;
        if (prevToken !== undefined && !(0, parseTreeUtils_1.isWhitespace)(prevToken)) {
            return undefined;
        }
        if (this._cs.nextChar === this._cs.currentChar) {
            // Eat up next magic char.
            this._cs.moveNext();
            return 'cell';
        }
        return 'line';
        function isMagicChar(ch) {
            return ch === 37 /* Char.Percent */ || ch === 33 /* Char.ExclamationMark */;
        }
    }
    _handleIPythonMagics(type) {
        const start = this._cs.position + 1;
        let begin = start;
        do {
            this._cs.skipToEol();
            if (type === 1 /* CommentType.IPythonMagic */ || type === 2 /* CommentType.IPythonShellEscape */) {
                const length = this._cs.position - begin;
                const value = this._cs.getText().slice(begin, begin + length);
                // is it multiline magics?
                // %magic command \
                //        next arguments
                if (!value.match(/\\\s*$/)) {
                    break;
                }
            }
            this._cs.moveNext();
            begin = this._cs.position + 1;
        } while (!this._cs.isEndOfStream());
        const length = this._cs.position - start;
        const comment = tokenizerTypes_1.Comment.create(start, length, this._cs.getText().slice(start, start + length), type);
        this._addComments(comment);
    }
    _handleComment() {
        var _a, _b;
        const start = this._cs.position + 1;
        this._cs.skipToEol();
        const length = this._cs.position - start;
        const comment = tokenizerTypes_1.Comment.create(start, length, this._cs.getText().slice(start, start + length));
        const typeIgnoreRegexMatch = comment.value.match(/((^|#)\s*)type:\s*ignore(\s*\[([\s*\w-,]*)\]|\s|$)/);
        if (typeIgnoreRegexMatch) {
            const commentStart = start + ((_a = typeIgnoreRegexMatch.index) !== null && _a !== void 0 ? _a : 0);
            const textRange = {
                start: commentStart + typeIgnoreRegexMatch[1].length,
                length: typeIgnoreRegexMatch[0].length - typeIgnoreRegexMatch[1].length,
            };
            const ignoreComment = {
                range: textRange,
                rulesList: this._getIgnoreCommentRulesList(commentStart, typeIgnoreRegexMatch),
            };
            if (this._tokens.findIndex((t) => t.type !== 2 /* TokenType.NewLine */ && t && t.type !== 3 /* TokenType.Indent */) < 0) {
                this._typeIgnoreAll = ignoreComment;
            }
            else {
                this._typeIgnoreLines.set(this._lineRanges.length, ignoreComment);
            }
        }
        const pyrightIgnoreRegexMatch = comment.value.match(/((^|#)\s*)pyright:\s*ignore(\s*\[([\s*\w-,]*)\]|\s|$)/);
        if (pyrightIgnoreRegexMatch) {
            const commentStart = start + ((_b = pyrightIgnoreRegexMatch.index) !== null && _b !== void 0 ? _b : 0);
            const textRange = {
                start: commentStart + pyrightIgnoreRegexMatch[1].length,
                length: pyrightIgnoreRegexMatch[0].length - pyrightIgnoreRegexMatch[1].length,
            };
            const ignoreComment = {
                range: textRange,
                rulesList: this._getIgnoreCommentRulesList(commentStart, pyrightIgnoreRegexMatch),
            };
            this._pyrightIgnoreLines.set(this._lineRanges.length, ignoreComment);
        }
        this._addComments(comment);
    }
    // Extracts the individual rules within a "type: ignore [x, y, z]" comment.
    _getIgnoreCommentRulesList(start, match) {
        if (match.length < 5 || match[4] === undefined) {
            return [];
        }
        const splitElements = match[4].split(',');
        const commentRules = [];
        let currentOffset = start + match[0].indexOf('[') + 1;
        for (const element of splitElements) {
            const frontTrimmed = element.trimStart();
            currentOffset += element.length - frontTrimmed.length;
            const endTrimmed = frontTrimmed.trimEnd();
            if (endTrimmed.length > 0) {
                commentRules.push({
                    range: { start: currentOffset, length: endTrimmed.length },
                    text: endTrimmed,
                });
            }
            currentOffset += frontTrimmed.length + 1;
        }
        return commentRules;
    }
    _addComments(comment) {
        if (this._comments) {
            this._comments.push(comment);
        }
        else {
            this._comments = [comment];
        }
    }
    _getStringPrefixLength() {
        if (this._cs.currentChar === 39 /* Char.SingleQuote */ || this._cs.currentChar === 34 /* Char.DoubleQuote */) {
            // Simple string, no prefix
            return 0;
        }
        if (this._cs.nextChar === 39 /* Char.SingleQuote */ || this._cs.nextChar === 34 /* Char.DoubleQuote */) {
            switch (this._cs.currentChar) {
                case 102 /* Char.f */:
                case 70 /* Char.F */:
                case 114 /* Char.r */:
                case 82 /* Char.R */:
                case 98 /* Char.b */:
                case 66 /* Char.B */:
                case 117 /* Char.u */:
                case 85 /* Char.U */:
                    // Single-char prefix like u"" or r""
                    return 1;
                default:
                    break;
            }
        }
        if (this._cs.lookAhead(2) === 39 /* Char.SingleQuote */ || this._cs.lookAhead(2) === 34 /* Char.DoubleQuote */) {
            const prefix = this._cs
                .getText()
                .slice(this._cs.position, this._cs.position + 2)
                .toLowerCase();
            switch (prefix) {
                case 'rf':
                case 'fr':
                case 'ur':
                case 'ru':
                case 'br':
                case 'rb':
                    return 2;
                default:
                    break;
            }
        }
        return -1;
    }
    _getQuoteTypeFlags(prefix) {
        let flags = 0 /* StringTokenFlags.None */;
        prefix = prefix.toLowerCase();
        for (let i = 0; i < prefix.length; i++) {
            switch (prefix[i]) {
                case 'u':
                    flags |= 16 /* StringTokenFlags.Unicode */;
                    break;
                case 'b':
                    flags |= 32 /* StringTokenFlags.Bytes */;
                    break;
                case 'r':
                    flags |= 8 /* StringTokenFlags.Raw */;
                    break;
                case 'f':
                    flags |= 64 /* StringTokenFlags.Format */;
                    break;
            }
        }
        if (this._cs.currentChar === 39 /* Char.SingleQuote */) {
            flags |= 1 /* StringTokenFlags.SingleQuote */;
            if (this._cs.nextChar === 39 /* Char.SingleQuote */ && this._cs.lookAhead(2) === 39 /* Char.SingleQuote */) {
                flags |= 4 /* StringTokenFlags.Triplicate */;
            }
        }
        else if (this._cs.currentChar === 34 /* Char.DoubleQuote */) {
            flags |= 2 /* StringTokenFlags.DoubleQuote */;
            if (this._cs.nextChar === 34 /* Char.DoubleQuote */ && this._cs.lookAhead(2) === 34 /* Char.DoubleQuote */) {
                flags |= 4 /* StringTokenFlags.Triplicate */;
            }
        }
        return flags;
    }
    _handleString(flags, stringPrefixLength) {
        var _a;
        const start = this._cs.position - stringPrefixLength;
        if (flags & 64 /* StringTokenFlags.Format */) {
            if (flags & 4 /* StringTokenFlags.Triplicate */) {
                this._cs.advance(3);
            }
            else {
                this._cs.moveNext();
            }
            const end = this._cs.position;
            const fStringStartToken = tokenizerTypes_1.FStringStartToken.create(start, end - start, flags, stringPrefixLength, this._getComments());
            // Create a new f-string context and push it on the stack.
            const fStringContext = {
                startToken: fStringStartToken,
                replacementFieldStack: [],
            };
            if (this._activeFString) {
                this._fStringStack.push(this._activeFString);
            }
            this._activeFString = fStringContext;
            this._tokens.push(fStringStartToken);
        }
        else {
            if (flags & 4 /* StringTokenFlags.Triplicate */) {
                this._cs.advance(3);
            }
            else {
                this._cs.moveNext();
                if (flags & 1 /* StringTokenFlags.SingleQuote */) {
                    this._singleQuoteCount++;
                }
                else {
                    this._doubleQuoteCount++;
                }
            }
            const stringLiteralInfo = this._skipToEndOfStringLiteral(flags);
            const end = this._cs.position;
            // If this is an unterminated string, see if it matches the string type
            // of an active f-string. If so, we'll treat it as an f-string end
            // token rather than an unterminated regular string. This helps with
            // parse error recovery if a closing bracket is missing in an f-string.
            if ((stringLiteralInfo.flags & 65536 /* StringTokenFlags.Unterminated */) !== 0 &&
                ((_a = this._activeFString) === null || _a === void 0 ? void 0 : _a.activeReplacementField)) {
                if ((flags &
                    (32 /* StringTokenFlags.Bytes */ |
                        16 /* StringTokenFlags.Unicode */ |
                        8 /* StringTokenFlags.Raw */ |
                        64 /* StringTokenFlags.Format */)) ===
                    0) {
                    const quoteTypeMask = 4 /* StringTokenFlags.Triplicate */ | 2 /* StringTokenFlags.DoubleQuote */ | 1 /* StringTokenFlags.SingleQuote */;
                    if ((this._activeFString.startToken.flags & quoteTypeMask) === (flags & quoteTypeMask)) {
                        // Unwind to the start of this string token and terminate any replacement fields
                        // that are active. This will cause the tokenizer to re-process the quote as an
                        // FStringEnd token.
                        this._cs.position = start;
                        while (this._activeFString.replacementFieldStack.length > 0) {
                            this._activeFString.activeReplacementField =
                                this._activeFString.replacementFieldStack.pop();
                        }
                        this._parenDepth = this._activeFString.activeReplacementField.parenDepth - 1;
                        this._activeFString.activeReplacementField = undefined;
                        return;
                    }
                }
            }
            this._tokens.push(tokenizerTypes_1.StringToken.create(start, end - start, stringLiteralInfo.flags, stringLiteralInfo.escapedValue, stringPrefixLength, this._getComments()));
        }
    }
    // Scans for either the FString end token or a replacement field.
    _handleFStringMiddle() {
        var _a;
        const activeFString = this._activeFString;
        const inFormatSpecifier = !!((_a = this._activeFString.activeReplacementField) === null || _a === void 0 ? void 0 : _a.inFormatSpecifier);
        const start = this._cs.position;
        const flags = activeFString.startToken.flags;
        const stringLiteralInfo = this._skipToEndOfStringLiteral(flags, inFormatSpecifier);
        const end = this._cs.position;
        const isUnterminated = (stringLiteralInfo.flags & 65536 /* StringTokenFlags.Unterminated */) !== 0;
        const sawReplacementFieldStart = (stringLiteralInfo.flags & 128 /* StringTokenFlags.ReplacementFieldStart */) !== 0;
        const sawReplacementFieldEnd = (stringLiteralInfo.flags & 256 /* StringTokenFlags.ReplacementFieldEnd */) !== 0;
        const sawEndQuote = !isUnterminated && !sawReplacementFieldStart && !sawReplacementFieldEnd;
        let middleTokenLength = end - start;
        if (sawEndQuote) {
            middleTokenLength -= activeFString.startToken.quoteMarkLength;
        }
        if (middleTokenLength > 0 || isUnterminated) {
            this._tokens.push(tokenizerTypes_1.FStringMiddleToken.create(start, middleTokenLength, stringLiteralInfo.flags, stringLiteralInfo.escapedValue));
        }
        if (sawEndQuote) {
            this._tokens.push(tokenizerTypes_1.FStringEndToken.create(start + middleTokenLength, activeFString.startToken.quoteMarkLength, stringLiteralInfo.flags));
            this._activeFString = this._fStringStack.pop();
        }
        else if (isUnterminated) {
            this._activeFString = this._fStringStack.pop();
        }
    }
    _skipToEndOfStringLiteral(flags, inFormatSpecifier = false) {
        const quoteChar = flags & 1 /* StringTokenFlags.SingleQuote */ ? 39 /* Char.SingleQuote */ : 34 /* Char.DoubleQuote */;
        const isTriplicate = (flags & 4 /* StringTokenFlags.Triplicate */) !== 0;
        const isFString = (flags & 64 /* StringTokenFlags.Format */) !== 0;
        let isInNamedUnicodeEscape = false;
        const start = this._cs.position;
        let escapedValueLength = 0;
        const getEscapedValue = () => this._cs.getText().slice(start, start + escapedValueLength);
        while (true) {
            if (this._cs.isEndOfStream()) {
                // Hit the end of file without a termination.
                flags |= 65536 /* StringTokenFlags.Unterminated */;
                return {
                    escapedValue: getEscapedValue(),
                    flags,
                };
            }
            if (this._cs.currentChar === 92 /* Char.Backslash */) {
                escapedValueLength++;
                // Move past the escape (backslash) character.
                this._cs.moveNext();
                // Handle the special escape sequence /N{name} for unicode characters.
                if (!isInNamedUnicodeEscape &&
                    this._cs.getCurrentChar() === 78 /* Char.N */ &&
                    this._cs.nextChar === 123 /* Char.OpenBrace */) {
                    flags |= 512 /* StringTokenFlags.NamedUnicodeEscape */;
                    isInNamedUnicodeEscape = true;
                }
                else {
                    // If this is an f-string, the only escapes that are allowed is for
                    // a single or double quote symbol or a newline/carriage return.
                    const isEscapedQuote = this._cs.getCurrentChar() === 39 /* Char.SingleQuote */ ||
                        this._cs.getCurrentChar() === 34 /* Char.DoubleQuote */;
                    const isEscapedNewLine = this._cs.getCurrentChar() === 13 /* Char.CarriageReturn */ ||
                        this._cs.getCurrentChar() === 10 /* Char.LineFeed */;
                    const isEscapedBackslash = this._cs.getCurrentChar() === 92 /* Char.Backslash */;
                    if (!isFString || isEscapedBackslash || isEscapedQuote || isEscapedNewLine) {
                        if (isEscapedNewLine) {
                            if (this._cs.getCurrentChar() === 13 /* Char.CarriageReturn */ &&
                                this._cs.nextChar === 10 /* Char.LineFeed */) {
                                escapedValueLength++;
                                this._cs.moveNext();
                            }
                            escapedValueLength++;
                            this._cs.moveNext();
                            this._addLineRange();
                        }
                        else {
                            escapedValueLength++;
                            this._cs.moveNext();
                        }
                    }
                }
            }
            else if (this._cs.currentChar === 10 /* Char.LineFeed */ || this._cs.currentChar === 13 /* Char.CarriageReturn */) {
                if (!isTriplicate && !isFString) {
                    // Unterminated single-line string
                    flags |= 65536 /* StringTokenFlags.Unterminated */;
                    return {
                        escapedValue: getEscapedValue(),
                        flags,
                    };
                }
                // Skip over the new line (either one or two characters).
                if (this._cs.currentChar === 13 /* Char.CarriageReturn */ && this._cs.nextChar === 10 /* Char.LineFeed */) {
                    escapedValueLength++;
                    this._cs.moveNext();
                }
                escapedValueLength++;
                this._cs.moveNext();
                this._addLineRange();
            }
            else if (!isTriplicate && this._cs.currentChar === quoteChar) {
                this._cs.moveNext();
                break;
            }
            else if (isTriplicate &&
                this._cs.currentChar === quoteChar &&
                this._cs.nextChar === quoteChar &&
                this._cs.lookAhead(2) === quoteChar) {
                this._cs.advance(3);
                break;
            }
            else if (!isInNamedUnicodeEscape && isFString && this._cs.currentChar === 123 /* Char.OpenBrace */) {
                if (inFormatSpecifier || this._cs.nextChar !== 123 /* Char.OpenBrace */) {
                    flags |= 128 /* StringTokenFlags.ReplacementFieldStart */;
                    break;
                }
                else {
                    escapedValueLength++;
                    this._cs.moveNext();
                    escapedValueLength++;
                    this._cs.moveNext();
                }
            }
            else if (isInNamedUnicodeEscape && this._cs.currentChar === 125 /* Char.CloseBrace */) {
                isInNamedUnicodeEscape = false;
                escapedValueLength++;
                this._cs.moveNext();
            }
            else if (isFString && this._cs.currentChar === 125 /* Char.CloseBrace */) {
                if (inFormatSpecifier || this._cs.nextChar !== 125 /* Char.CloseBrace */) {
                    flags |= 256 /* StringTokenFlags.ReplacementFieldEnd */;
                    break;
                }
                else {
                    escapedValueLength++;
                    this._cs.moveNext();
                    escapedValueLength++;
                    this._cs.moveNext();
                }
            }
            else {
                escapedValueLength++;
                this._cs.moveNext();
            }
        }
        return {
            escapedValue: getEscapedValue(),
            flags,
        };
    }
    _skipFloatingPointCandidate() {
        // Determine end of the potential floating point number
        const start = this._cs.position;
        this._skipFractionalNumber();
        if (this._cs.position > start) {
            // Optional exponent sign
            if (this._cs.currentChar === 101 /* Char.e */ || this._cs.currentChar === 69 /* Char.E */) {
                this._cs.moveNext();
                // Skip exponent value
                this._skipDecimalNumber(/* allowSign */ true);
            }
        }
        return this._cs.position > start;
    }
    _skipFractionalNumber() {
        this._skipDecimalNumber(false);
        if (this._cs.currentChar === 46 /* Char.Period */) {
            // Optional period
            this._cs.moveNext();
        }
        this._skipDecimalNumber(false);
    }
    _skipDecimalNumber(allowSign) {
        if (allowSign && (this._cs.currentChar === 45 /* Char.Hyphen */ || this._cs.currentChar === 43 /* Char.Plus */)) {
            // Optional sign
            this._cs.moveNext();
        }
        while ((0, characters_1.isDecimal)(this._cs.currentChar)) {
            // Skip integer part
            this._cs.moveNext();
        }
    }
}
exports.Tokenizer = Tokenizer;


/***/ }),

/***/ "../pyright-internal/src/parser/tokenizerTypes.ts":
/*!********************************************************!*\
  !*** ../pyright-internal/src/parser/tokenizerTypes.ts ***!
  \********************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * tokenizerTypes.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 * Author: Eric Traut
 *
 * Based on code from vscode-python repository:
 *  https://github.com/Microsoft/vscode-python
 *
 * Interface, enumeration and class definitions used within
 * the Python tokenizer.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.IdentifierToken = exports.OperatorToken = exports.NumberToken = exports.FStringEndToken = exports.FStringMiddleToken = exports.FStringStartToken = exports.StringToken = exports.KeywordToken = exports.NewLineToken = exports.DedentToken = exports.IndentToken = exports.Token = exports.Comment = exports.softKeywords = void 0;
exports.softKeywords = [9 /* KeywordType.Debug */, 25 /* KeywordType.Match */, 6 /* KeywordType.Case */, 35 /* KeywordType.Type */];
var Comment;
(function (Comment) {
    function create(start, length, value, type = 0 /* CommentType.Regular */) {
        const comment = {
            type,
            start,
            length,
            value,
        };
        return comment;
    }
    Comment.create = create;
})(Comment || (exports.Comment = Comment = {}));
var Token;
(function (Token) {
    function create(type, start, length, comments) {
        const token = {
            start,
            length,
            type,
            comments,
        };
        return token;
    }
    Token.create = create;
})(Token || (exports.Token = Token = {}));
var IndentToken;
(function (IndentToken) {
    function create(start, length, indentAmount, isIndentAmbiguous, comments) {
        const token = {
            start,
            length,
            type: 3 /* TokenType.Indent */,
            isIndentAmbiguous,
            comments,
            indentAmount,
        };
        return token;
    }
    IndentToken.create = create;
})(IndentToken || (exports.IndentToken = IndentToken = {}));
var DedentToken;
(function (DedentToken) {
    function create(start, length, indentAmount, matchesIndent, isDedentAmbiguous, comments) {
        const token = {
            start,
            length,
            type: 4 /* TokenType.Dedent */,
            comments,
            indentAmount,
            matchesIndent,
            isDedentAmbiguous,
        };
        return token;
    }
    DedentToken.create = create;
})(DedentToken || (exports.DedentToken = DedentToken = {}));
var NewLineToken;
(function (NewLineToken) {
    function create(start, length, newLineType, comments) {
        const token = {
            start,
            length,
            type: 2 /* TokenType.NewLine */,
            comments,
            newLineType,
        };
        return token;
    }
    NewLineToken.create = create;
})(NewLineToken || (exports.NewLineToken = NewLineToken = {}));
var KeywordToken;
(function (KeywordToken) {
    function create(start, length, keywordType, comments) {
        const token = {
            start,
            length,
            type: 8 /* TokenType.Keyword */,
            comments,
            keywordType,
        };
        return token;
    }
    KeywordToken.create = create;
})(KeywordToken || (exports.KeywordToken = KeywordToken = {}));
var StringToken;
(function (StringToken) {
    function create(start, length, flags, escapedValue, prefixLength, comments) {
        const token = {
            start,
            length,
            type: 5 /* TokenType.String */,
            flags,
            escapedValue,
            prefixLength,
            quoteMarkLength: flags & 4 /* StringTokenFlags.Triplicate */ ? 3 : 1,
            comments,
        };
        return token;
    }
    StringToken.create = create;
})(StringToken || (exports.StringToken = StringToken = {}));
var FStringStartToken;
(function (FStringStartToken) {
    function create(start, length, flags, prefixLength, comments) {
        const token = {
            start,
            length,
            type: 24 /* TokenType.FStringStart */,
            flags,
            prefixLength,
            quoteMarkLength: flags & 4 /* StringTokenFlags.Triplicate */ ? 3 : 1,
            comments,
        };
        return token;
    }
    FStringStartToken.create = create;
})(FStringStartToken || (exports.FStringStartToken = FStringStartToken = {}));
var FStringMiddleToken;
(function (FStringMiddleToken) {
    function create(start, length, flags, escapedValue) {
        const token = {
            start,
            length,
            type: 25 /* TokenType.FStringMiddle */,
            flags,
            escapedValue,
        };
        return token;
    }
    FStringMiddleToken.create = create;
})(FStringMiddleToken || (exports.FStringMiddleToken = FStringMiddleToken = {}));
var FStringEndToken;
(function (FStringEndToken) {
    function create(start, length, flags) {
        const token = {
            start,
            length,
            type: 26 /* TokenType.FStringEnd */,
            flags,
        };
        return token;
    }
    FStringEndToken.create = create;
})(FStringEndToken || (exports.FStringEndToken = FStringEndToken = {}));
var NumberToken;
(function (NumberToken) {
    function create(start, length, value, isInteger, isImaginary, comments) {
        const token = {
            start,
            length,
            type: 6 /* TokenType.Number */,
            isInteger,
            isImaginary,
            value,
            comments,
        };
        return token;
    }
    NumberToken.create = create;
})(NumberToken || (exports.NumberToken = NumberToken = {}));
var OperatorToken;
(function (OperatorToken) {
    function create(start, length, operatorType, comments) {
        const token = {
            start,
            length,
            type: 9 /* TokenType.Operator */,
            operatorType,
            comments,
        };
        return token;
    }
    OperatorToken.create = create;
})(OperatorToken || (exports.OperatorToken = OperatorToken = {}));
var IdentifierToken;
(function (IdentifierToken) {
    function create(start, length, value, comments) {
        // Perform "NFKC normalization", as per the Python lexical spec.
        const normalizedValue = value.normalize('NFKC');
        const token = {
            start,
            length,
            type: 7 /* TokenType.Identifier */,
            value: normalizedValue,
            comments,
        };
        return token;
    }
    IdentifierToken.create = create;
})(IdentifierToken || (exports.IdentifierToken = IdentifierToken = {}));


/***/ }),

/***/ "../pyright-internal/src/parser/unicode.ts":
/*!*************************************************!*\
  !*** ../pyright-internal/src/parser/unicode.ts ***!
  \*************************************************/
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/*
 * unicode.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * Tables that encode Unicode character codes for various Unicode-
 * defined categories used in the Python spec.
 *
 * Generated by build/generateUnicodeTables.py from the UnicodeData.txt
 * metadata file for Unicode 15.1.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unicodePc = exports.unicodeNdSurrogate = exports.unicodeNd = exports.unicodeMcSurrogate = exports.unicodeMc = exports.unicodeMnSurrogate = exports.unicodeMn = exports.unicodeNlSurrogate = exports.unicodeNl = exports.unicodeLmSurrogate = exports.unicodeLm = exports.unicodeLoSurrogate = exports.unicodeLo = exports.unicodeLt = exports.unicodeLlSurrogate = exports.unicodeLl = exports.unicodeLuSurrogate = exports.unicodeLu = void 0;
exports.unicodeLu = [
    [0x0041, 0x005a],
    [0x00c0, 0x00d6],
    [0x00d8, 0x00de],
    0x0100,
    0x0102,
    0x0104,
    0x0106,
    0x0108,
    0x010a,
    0x010c,
    0x010e,
    0x0110,
    0x0112,
    0x0114,
    0x0116,
    0x0118,
    0x011a,
    0x011c,
    0x011e,
    0x0120,
    0x0122,
    0x0124,
    0x0126,
    0x0128,
    0x012a,
    0x012c,
    0x012e,
    0x0130,
    0x0132,
    0x0134,
    0x0136,
    0x0139,
    0x013b,
    0x013d,
    0x013f,
    0x0141,
    0x0143,
    0x0145,
    0x0147,
    0x014a,
    0x014c,
    0x014e,
    0x0150,
    0x0152,
    0x0154,
    0x0156,
    0x0158,
    0x015a,
    0x015c,
    0x015e,
    0x0160,
    0x0162,
    0x0164,
    0x0166,
    0x0168,
    0x016a,
    0x016c,
    0x016e,
    0x0170,
    0x0172,
    0x0174,
    0x0176,
    [0x0178, 0x0179],
    0x017b,
    0x017d,
    [0x0181, 0x0182],
    0x0184,
    [0x0186, 0x0187],
    [0x0189, 0x018b],
    [0x018e, 0x0191],
    [0x0193, 0x0194],
    [0x0196, 0x0198],
    [0x019c, 0x019d],
    [0x019f, 0x01a0],
    0x01a2,
    0x01a4,
    [0x01a6, 0x01a7],
    0x01a9,
    0x01ac,
    [0x01ae, 0x01af],
    [0x01b1, 0x01b3],
    0x01b5,
    [0x01b7, 0x01b8],
    0x01bc,
    0x01c4,
    0x01c7,
    0x01ca,
    0x01cd,
    0x01cf,
    0x01d1,
    0x01d3,
    0x01d5,
    0x01d7,
    0x01d9,
    0x01db,
    0x01de,
    0x01e0,
    0x01e2,
    0x01e4,
    0x01e6,
    0x01e8,
    0x01ea,
    0x01ec,
    0x01ee,
    0x01f1,
    0x01f4,
    [0x01f6, 0x01f8],
    0x01fa,
    0x01fc,
    0x01fe,
    0x0200,
    0x0202,
    0x0204,
    0x0206,
    0x0208,
    0x020a,
    0x020c,
    0x020e,
    0x0210,
    0x0212,
    0x0214,
    0x0216,
    0x0218,
    0x021a,
    0x021c,
    0x021e,
    0x0220,
    0x0222,
    0x0224,
    0x0226,
    0x0228,
    0x022a,
    0x022c,
    0x022e,
    0x0230,
    0x0232,
    [0x023a, 0x023b],
    [0x023d, 0x023e],
    0x0241,
    [0x0243, 0x0246],
    0x0248,
    0x024a,
    0x024c,
    0x024e,
    0x0370,
    0x0372,
    0x0376,
    0x037f,
    0x0386,
    [0x0388, 0x038a],
    0x038c,
    [0x038e, 0x038f],
    [0x0391, 0x03a1],
    [0x03a3, 0x03ab],
    0x03cf,
    [0x03d2, 0x03d4],
    0x03d8,
    0x03da,
    0x03dc,
    0x03de,
    0x03e0,
    0x03e2,
    0x03e4,
    0x03e6,
    0x03e8,
    0x03ea,
    0x03ec,
    0x03ee,
    0x03f4,
    0x03f7,
    [0x03f9, 0x03fa],
    [0x03fd, 0x042f],
    0x0460,
    0x0462,
    0x0464,
    0x0466,
    0x0468,
    0x046a,
    0x046c,
    0x046e,
    0x0470,
    0x0472,
    0x0474,
    0x0476,
    0x0478,
    0x047a,
    0x047c,
    0x047e,
    0x0480,
    0x048a,
    0x048c,
    0x048e,
    0x0490,
    0x0492,
    0x0494,
    0x0496,
    0x0498,
    0x049a,
    0x049c,
    0x049e,
    0x04a0,
    0x04a2,
    0x04a4,
    0x04a6,
    0x04a8,
    0x04aa,
    0x04ac,
    0x04ae,
    0x04b0,
    0x04b2,
    0x04b4,
    0x04b6,
    0x04b8,
    0x04ba,
    0x04bc,
    0x04be,
    [0x04c0, 0x04c1],
    0x04c3,
    0x04c5,
    0x04c7,
    0x04c9,
    0x04cb,
    0x04cd,
    0x04d0,
    0x04d2,
    0x04d4,
    0x04d6,
    0x04d8,
    0x04da,
    0x04dc,
    0x04de,
    0x04e0,
    0x04e2,
    0x04e4,
    0x04e6,
    0x04e8,
    0x04ea,
    0x04ec,
    0x04ee,
    0x04f0,
    0x04f2,
    0x04f4,
    0x04f6,
    0x04f8,
    0x04fa,
    0x04fc,
    0x04fe,
    0x0500,
    0x0502,
    0x0504,
    0x0506,
    0x0508,
    0x050a,
    0x050c,
    0x050e,
    0x0510,
    0x0512,
    0x0514,
    0x0516,
    0x0518,
    0x051a,
    0x051c,
    0x051e,
    0x0520,
    0x0522,
    0x0524,
    0x0526,
    0x0528,
    0x052a,
    0x052c,
    0x052e,
    [0x0531, 0x0556],
    [0x10a0, 0x10c5],
    0x10c7,
    0x10cd,
    [0x13a0, 0x13f5],
    [0x1c90, 0x1cba],
    [0x1cbd, 0x1cbf],
    0x1e00,
    0x1e02,
    0x1e04,
    0x1e06,
    0x1e08,
    0x1e0a,
    0x1e0c,
    0x1e0e,
    0x1e10,
    0x1e12,
    0x1e14,
    0x1e16,
    0x1e18,
    0x1e1a,
    0x1e1c,
    0x1e1e,
    0x1e20,
    0x1e22,
    0x1e24,
    0x1e26,
    0x1e28,
    0x1e2a,
    0x1e2c,
    0x1e2e,
    0x1e30,
    0x1e32,
    0x1e34,
    0x1e36,
    0x1e38,
    0x1e3a,
    0x1e3c,
    0x1e3e,
    0x1e40,
    0x1e42,
    0x1e44,
    0x1e46,
    0x1e48,
    0x1e4a,
    0x1e4c,
    0x1e4e,
    0x1e50,
    0x1e52,
    0x1e54,
    0x1e56,
    0x1e58,
    0x1e5a,
    0x1e5c,
    0x1e5e,
    0x1e60,
    0x1e62,
    0x1e64,
    0x1e66,
    0x1e68,
    0x1e6a,
    0x1e6c,
    0x1e6e,
    0x1e70,
    0x1e72,
    0x1e74,
    0x1e76,
    0x1e78,
    0x1e7a,
    0x1e7c,
    0x1e7e,
    0x1e80,
    0x1e82,
    0x1e84,
    0x1e86,
    0x1e88,
    0x1e8a,
    0x1e8c,
    0x1e8e,
    0x1e90,
    0x1e92,
    0x1e94,
    0x1e9e,
    0x1ea0,
    0x1ea2,
    0x1ea4,
    0x1ea6,
    0x1ea8,
    0x1eaa,
    0x1eac,
    0x1eae,
    0x1eb0,
    0x1eb2,
    0x1eb4,
    0x1eb6,
    0x1eb8,
    0x1eba,
    0x1ebc,
    0x1ebe,
    0x1ec0,
    0x1ec2,
    0x1ec4,
    0x1ec6,
    0x1ec8,
    0x1eca,
    0x1ecc,
    0x1ece,
    0x1ed0,
    0x1ed2,
    0x1ed4,
    0x1ed6,
    0x1ed8,
    0x1eda,
    0x1edc,
    0x1ede,
    0x1ee0,
    0x1ee2,
    0x1ee4,
    0x1ee6,
    0x1ee8,
    0x1eea,
    0x1eec,
    0x1eee,
    0x1ef0,
    0x1ef2,
    0x1ef4,
    0x1ef6,
    0x1ef8,
    0x1efa,
    0x1efc,
    0x1efe,
    [0x1f08, 0x1f0f],
    [0x1f18, 0x1f1d],
    [0x1f28, 0x1f2f],
    [0x1f38, 0x1f3f],
    [0x1f48, 0x1f4d],
    0x1f59,
    0x1f5b,
    0x1f5d,
    0x1f5f,
    [0x1f68, 0x1f6f],
    [0x1fb8, 0x1fbb],
    [0x1fc8, 0x1fcb],
    [0x1fd8, 0x1fdb],
    [0x1fe8, 0x1fec],
    [0x1ff8, 0x1ffb],
    0x2102,
    0x2107,
    [0x210b, 0x210d],
    [0x2110, 0x2112],
    0x2115,
    [0x2119, 0x211d],
    0x2124,
    0x2126,
    0x2128,
    [0x212a, 0x212d],
    [0x2130, 0x2133],
    [0x213e, 0x213f],
    0x2145,
    0x2183,
    [0x2c00, 0x2c2f],
    0x2c60,
    [0x2c62, 0x2c64],
    0x2c67,
    0x2c69,
    0x2c6b,
    [0x2c6d, 0x2c70],
    0x2c72,
    0x2c75,
    [0x2c7e, 0x2c80],
    0x2c82,
    0x2c84,
    0x2c86,
    0x2c88,
    0x2c8a,
    0x2c8c,
    0x2c8e,
    0x2c90,
    0x2c92,
    0x2c94,
    0x2c96,
    0x2c98,
    0x2c9a,
    0x2c9c,
    0x2c9e,
    0x2ca0,
    0x2ca2,
    0x2ca4,
    0x2ca6,
    0x2ca8,
    0x2caa,
    0x2cac,
    0x2cae,
    0x2cb0,
    0x2cb2,
    0x2cb4,
    0x2cb6,
    0x2cb8,
    0x2cba,
    0x2cbc,
    0x2cbe,
    0x2cc0,
    0x2cc2,
    0x2cc4,
    0x2cc6,
    0x2cc8,
    0x2cca,
    0x2ccc,
    0x2cce,
    0x2cd0,
    0x2cd2,
    0x2cd4,
    0x2cd6,
    0x2cd8,
    0x2cda,
    0x2cdc,
    0x2cde,
    0x2ce0,
    0x2ce2,
    0x2ceb,
    0x2ced,
    0x2cf2,
    0xa640,
    0xa642,
    0xa644,
    0xa646,
    0xa648,
    0xa64a,
    0xa64c,
    0xa64e,
    0xa650,
    0xa652,
    0xa654,
    0xa656,
    0xa658,
    0xa65a,
    0xa65c,
    0xa65e,
    0xa660,
    0xa662,
    0xa664,
    0xa666,
    0xa668,
    0xa66a,
    0xa66c,
    0xa680,
    0xa682,
    0xa684,
    0xa686,
    0xa688,
    0xa68a,
    0xa68c,
    0xa68e,
    0xa690,
    0xa692,
    0xa694,
    0xa696,
    0xa698,
    0xa69a,
    0xa722,
    0xa724,
    0xa726,
    0xa728,
    0xa72a,
    0xa72c,
    0xa72e,
    0xa732,
    0xa734,
    0xa736,
    0xa738,
    0xa73a,
    0xa73c,
    0xa73e,
    0xa740,
    0xa742,
    0xa744,
    0xa746,
    0xa748,
    0xa74a,
    0xa74c,
    0xa74e,
    0xa750,
    0xa752,
    0xa754,
    0xa756,
    0xa758,
    0xa75a,
    0xa75c,
    0xa75e,
    0xa760,
    0xa762,
    0xa764,
    0xa766,
    0xa768,
    0xa76a,
    0xa76c,
    0xa76e,
    0xa779,
    0xa77b,
    [0xa77d, 0xa77e],
    0xa780,
    0xa782,
    0xa784,
    0xa786,
    0xa78b,
    0xa78d,
    0xa790,
    0xa792,
    0xa796,
    0xa798,
    0xa79a,
    0xa79c,
    0xa79e,
    0xa7a0,
    0xa7a2,
    0xa7a4,
    0xa7a6,
    0xa7a8,
    [0xa7aa, 0xa7ae],
    [0xa7b0, 0xa7b4],
    0xa7b6,
    0xa7b8,
    0xa7ba,
    0xa7bc,
    0xa7be,
    0xa7c0,
    0xa7c2,
    [0xa7c4, 0xa7c7],
    0xa7c9,
    0xa7d0,
    0xa7d6,
    0xa7d8,
    0xa7f5,
    [0xff21, 0xff3a],
    [0x10400, 0x10427],
    [0x104b0, 0x104d3],
    [0x10570, 0x1057a],
    [0x1057c, 0x1058a],
    [0x1058c, 0x10592],
    [0x10594, 0x10595],
    [0x10c80, 0x10cb2],
    [0x118a0, 0x118bf],
    [0x16e40, 0x16e5f],
    [0x1d400, 0x1d419],
    [0x1d434, 0x1d44d],
    [0x1d468, 0x1d481],
    0x1d49c,
    [0x1d49e, 0x1d49f],
    0x1d4a2,
    [0x1d4a5, 0x1d4a6],
    [0x1d4a9, 0x1d4ac],
    [0x1d4ae, 0x1d4b5],
    [0x1d4d0, 0x1d4e9],
    [0x1d504, 0x1d505],
    [0x1d507, 0x1d50a],
    [0x1d50d, 0x1d514],
    [0x1d516, 0x1d51c],
    [0x1d538, 0x1d539],
    [0x1d53b, 0x1d53e],
    [0x1d540, 0x1d544],
    0x1d546,
    [0x1d54a, 0x1d550],
    [0x1d56c, 0x1d585],
    [0x1d5a0, 0x1d5b9],
    [0x1d5d4, 0x1d5ed],
    [0x1d608, 0x1d621],
    [0x1d63c, 0x1d655],
    [0x1d670, 0x1d689],
    [0x1d6a8, 0x1d6c0],
    [0x1d6e2, 0x1d6fa],
    [0x1d71c, 0x1d734],
    [0x1d756, 0x1d76e],
    [0x1d790, 0x1d7a8],
    0x1d7ca,
    [0x1e900, 0x1e921],
];
exports.unicodeLuSurrogate = {
    0xd801: [
        [0xdc00, 0xdc27],
        [0xdcb0, 0xdcd3],
        [0xdd70, 0xdd7a],
        [0xdd7c, 0xdd8a],
        [0xdd8c, 0xdd92],
        [0xdd94, 0xdd95], // 0x10594..0x10595
    ],
    0xd803: [
        [0xdc80, 0xdcb2], // 0x10C80..0x10CB2
    ],
    0xd806: [
        [0xdca0, 0xdcbf], // 0x118A0..0x118BF
    ],
    0xd81b: [
        [0xde40, 0xde5f], // 0x16E40..0x16E5F
    ],
    0xd835: [
        [0xdc00, 0xdc19],
        [0xdc34, 0xdc4d],
        [0xdc68, 0xdc81],
        0xdc9c,
        [0xdc9e, 0xdc9f],
        0xdca2,
        [0xdca5, 0xdca6],
        [0xdca9, 0xdcac],
        [0xdcae, 0xdcb5],
        [0xdcd0, 0xdce9],
        [0xdd04, 0xdd05],
        [0xdd07, 0xdd0a],
        [0xdd0d, 0xdd14],
        [0xdd16, 0xdd1c],
        [0xdd38, 0xdd39],
        [0xdd3b, 0xdd3e],
        [0xdd40, 0xdd44],
        0xdd46,
        [0xdd4a, 0xdd50],
        [0xdd6c, 0xdd85],
        [0xdda0, 0xddb9],
        [0xddd4, 0xdded],
        [0xde08, 0xde21],
        [0xde3c, 0xde55],
        [0xde70, 0xde89],
        [0xdea8, 0xdec0],
        [0xdee2, 0xdefa],
        [0xdf1c, 0xdf34],
        [0xdf56, 0xdf6e],
        [0xdf90, 0xdfa8],
        0xdfca, // 0x1D7CA
    ],
    0xd83a: [
        [0xdd00, 0xdd21], // 0x1E900..0x1E921
    ],
};
exports.unicodeLl = [
    [0x0061, 0x007a],
    0x00b5,
    [0x00df, 0x00f6],
    [0x00f8, 0x00ff],
    0x0101,
    0x0103,
    0x0105,
    0x0107,
    0x0109,
    0x010b,
    0x010d,
    0x010f,
    0x0111,
    0x0113,
    0x0115,
    0x0117,
    0x0119,
    0x011b,
    0x011d,
    0x011f,
    0x0121,
    0x0123,
    0x0125,
    0x0127,
    0x0129,
    0x012b,
    0x012d,
    0x012f,
    0x0131,
    0x0133,
    0x0135,
    [0x0137, 0x0138],
    0x013a,
    0x013c,
    0x013e,
    0x0140,
    0x0142,
    0x0144,
    0x0146,
    [0x0148, 0x0149],
    0x014b,
    0x014d,
    0x014f,
    0x0151,
    0x0153,
    0x0155,
    0x0157,
    0x0159,
    0x015b,
    0x015d,
    0x015f,
    0x0161,
    0x0163,
    0x0165,
    0x0167,
    0x0169,
    0x016b,
    0x016d,
    0x016f,
    0x0171,
    0x0173,
    0x0175,
    0x0177,
    0x017a,
    0x017c,
    [0x017e, 0x0180],
    0x0183,
    0x0185,
    0x0188,
    [0x018c, 0x018d],
    0x0192,
    0x0195,
    [0x0199, 0x019b],
    0x019e,
    0x01a1,
    0x01a3,
    0x01a5,
    0x01a8,
    [0x01aa, 0x01ab],
    0x01ad,
    0x01b0,
    0x01b4,
    0x01b6,
    [0x01b9, 0x01ba],
    [0x01bd, 0x01bf],
    0x01c6,
    0x01c9,
    0x01cc,
    0x01ce,
    0x01d0,
    0x01d2,
    0x01d4,
    0x01d6,
    0x01d8,
    0x01da,
    [0x01dc, 0x01dd],
    0x01df,
    0x01e1,
    0x01e3,
    0x01e5,
    0x01e7,
    0x01e9,
    0x01eb,
    0x01ed,
    [0x01ef, 0x01f0],
    0x01f3,
    0x01f5,
    0x01f9,
    0x01fb,
    0x01fd,
    0x01ff,
    0x0201,
    0x0203,
    0x0205,
    0x0207,
    0x0209,
    0x020b,
    0x020d,
    0x020f,
    0x0211,
    0x0213,
    0x0215,
    0x0217,
    0x0219,
    0x021b,
    0x021d,
    0x021f,
    0x0221,
    0x0223,
    0x0225,
    0x0227,
    0x0229,
    0x022b,
    0x022d,
    0x022f,
    0x0231,
    [0x0233, 0x0239],
    0x023c,
    [0x023f, 0x0240],
    0x0242,
    0x0247,
    0x0249,
    0x024b,
    0x024d,
    [0x024f, 0x0293],
    [0x0295, 0x02af],
    0x0371,
    0x0373,
    0x0377,
    [0x037b, 0x037d],
    0x0390,
    [0x03ac, 0x03ce],
    [0x03d0, 0x03d1],
    [0x03d5, 0x03d7],
    0x03d9,
    0x03db,
    0x03dd,
    0x03df,
    0x03e1,
    0x03e3,
    0x03e5,
    0x03e7,
    0x03e9,
    0x03eb,
    0x03ed,
    [0x03ef, 0x03f3],
    0x03f5,
    0x03f8,
    [0x03fb, 0x03fc],
    [0x0430, 0x045f],
    0x0461,
    0x0463,
    0x0465,
    0x0467,
    0x0469,
    0x046b,
    0x046d,
    0x046f,
    0x0471,
    0x0473,
    0x0475,
    0x0477,
    0x0479,
    0x047b,
    0x047d,
    0x047f,
    0x0481,
    0x048b,
    0x048d,
    0x048f,
    0x0491,
    0x0493,
    0x0495,
    0x0497,
    0x0499,
    0x049b,
    0x049d,
    0x049f,
    0x04a1,
    0x04a3,
    0x04a5,
    0x04a7,
    0x04a9,
    0x04ab,
    0x04ad,
    0x04af,
    0x04b1,
    0x04b3,
    0x04b5,
    0x04b7,
    0x04b9,
    0x04bb,
    0x04bd,
    0x04bf,
    0x04c2,
    0x04c4,
    0x04c6,
    0x04c8,
    0x04ca,
    0x04cc,
    [0x04ce, 0x04cf],
    0x04d1,
    0x04d3,
    0x04d5,
    0x04d7,
    0x04d9,
    0x04db,
    0x04dd,
    0x04df,
    0x04e1,
    0x04e3,
    0x04e5,
    0x04e7,
    0x04e9,
    0x04eb,
    0x04ed,
    0x04ef,
    0x04f1,
    0x04f3,
    0x04f5,
    0x04f7,
    0x04f9,
    0x04fb,
    0x04fd,
    0x04ff,
    0x0501,
    0x0503,
    0x0505,
    0x0507,
    0x0509,
    0x050b,
    0x050d,
    0x050f,
    0x0511,
    0x0513,
    0x0515,
    0x0517,
    0x0519,
    0x051b,
    0x051d,
    0x051f,
    0x0521,
    0x0523,
    0x0525,
    0x0527,
    0x0529,
    0x052b,
    0x052d,
    0x052f,
    [0x0560, 0x0588],
    [0x10d0, 0x10fa],
    [0x10fd, 0x10ff],
    [0x13f8, 0x13fd],
    [0x1c80, 0x1c88],
    [0x1d00, 0x1d2b],
    [0x1d6b, 0x1d77],
    [0x1d79, 0x1d9a],
    0x1e01,
    0x1e03,
    0x1e05,
    0x1e07,
    0x1e09,
    0x1e0b,
    0x1e0d,
    0x1e0f,
    0x1e11,
    0x1e13,
    0x1e15,
    0x1e17,
    0x1e19,
    0x1e1b,
    0x1e1d,
    0x1e1f,
    0x1e21,
    0x1e23,
    0x1e25,
    0x1e27,
    0x1e29,
    0x1e2b,
    0x1e2d,
    0x1e2f,
    0x1e31,
    0x1e33,
    0x1e35,
    0x1e37,
    0x1e39,
    0x1e3b,
    0x1e3d,
    0x1e3f,
    0x1e41,
    0x1e43,
    0x1e45,
    0x1e47,
    0x1e49,
    0x1e4b,
    0x1e4d,
    0x1e4f,
    0x1e51,
    0x1e53,
    0x1e55,
    0x1e57,
    0x1e59,
    0x1e5b,
    0x1e5d,
    0x1e5f,
    0x1e61,
    0x1e63,
    0x1e65,
    0x1e67,
    0x1e69,
    0x1e6b,
    0x1e6d,
    0x1e6f,
    0x1e71,
    0x1e73,
    0x1e75,
    0x1e77,
    0x1e79,
    0x1e7b,
    0x1e7d,
    0x1e7f,
    0x1e81,
    0x1e83,
    0x1e85,
    0x1e87,
    0x1e89,
    0x1e8b,
    0x1e8d,
    0x1e8f,
    0x1e91,
    0x1e93,
    [0x1e95, 0x1e9d],
    0x1e9f,
    0x1ea1,
    0x1ea3,
    0x1ea5,
    0x1ea7,
    0x1ea9,
    0x1eab,
    0x1ead,
    0x1eaf,
    0x1eb1,
    0x1eb3,
    0x1eb5,
    0x1eb7,
    0x1eb9,
    0x1ebb,
    0x1ebd,
    0x1ebf,
    0x1ec1,
    0x1ec3,
    0x1ec5,
    0x1ec7,
    0x1ec9,
    0x1ecb,
    0x1ecd,
    0x1ecf,
    0x1ed1,
    0x1ed3,
    0x1ed5,
    0x1ed7,
    0x1ed9,
    0x1edb,
    0x1edd,
    0x1edf,
    0x1ee1,
    0x1ee3,
    0x1ee5,
    0x1ee7,
    0x1ee9,
    0x1eeb,
    0x1eed,
    0x1eef,
    0x1ef1,
    0x1ef3,
    0x1ef5,
    0x1ef7,
    0x1ef9,
    0x1efb,
    0x1efd,
    [0x1eff, 0x1f07],
    [0x1f10, 0x1f15],
    [0x1f20, 0x1f27],
    [0x1f30, 0x1f37],
    [0x1f40, 0x1f45],
    [0x1f50, 0x1f57],
    [0x1f60, 0x1f67],
    [0x1f70, 0x1f7d],
    [0x1f80, 0x1f87],
    [0x1f90, 0x1f97],
    [0x1fa0, 0x1fa7],
    [0x1fb0, 0x1fb4],
    [0x1fb6, 0x1fb7],
    0x1fbe,
    [0x1fc2, 0x1fc4],
    [0x1fc6, 0x1fc7],
    [0x1fd0, 0x1fd3],
    [0x1fd6, 0x1fd7],
    [0x1fe0, 0x1fe7],
    [0x1ff2, 0x1ff4],
    [0x1ff6, 0x1ff7],
    0x210a,
    [0x210e, 0x210f],
    0x2113,
    0x212f,
    0x2134,
    0x2139,
    [0x213c, 0x213d],
    [0x2146, 0x2149],
    0x214e,
    0x2184,
    [0x2c30, 0x2c5f],
    0x2c61,
    [0x2c65, 0x2c66],
    0x2c68,
    0x2c6a,
    0x2c6c,
    0x2c71,
    [0x2c73, 0x2c74],
    [0x2c76, 0x2c7b],
    0x2c81,
    0x2c83,
    0x2c85,
    0x2c87,
    0x2c89,
    0x2c8b,
    0x2c8d,
    0x2c8f,
    0x2c91,
    0x2c93,
    0x2c95,
    0x2c97,
    0x2c99,
    0x2c9b,
    0x2c9d,
    0x2c9f,
    0x2ca1,
    0x2ca3,
    0x2ca5,
    0x2ca7,
    0x2ca9,
    0x2cab,
    0x2cad,
    0x2caf,
    0x2cb1,
    0x2cb3,
    0x2cb5,
    0x2cb7,
    0x2cb9,
    0x2cbb,
    0x2cbd,
    0x2cbf,
    0x2cc1,
    0x2cc3,
    0x2cc5,
    0x2cc7,
    0x2cc9,
    0x2ccb,
    0x2ccd,
    0x2ccf,
    0x2cd1,
    0x2cd3,
    0x2cd5,
    0x2cd7,
    0x2cd9,
    0x2cdb,
    0x2cdd,
    0x2cdf,
    0x2ce1,
    [0x2ce3, 0x2ce4],
    0x2cec,
    0x2cee,
    0x2cf3,
    [0x2d00, 0x2d25],
    0x2d27,
    0x2d2d,
    0xa641,
    0xa643,
    0xa645,
    0xa647,
    0xa649,
    0xa64b,
    0xa64d,
    0xa64f,
    0xa651,
    0xa653,
    0xa655,
    0xa657,
    0xa659,
    0xa65b,
    0xa65d,
    0xa65f,
    0xa661,
    0xa663,
    0xa665,
    0xa667,
    0xa669,
    0xa66b,
    0xa66d,
    0xa681,
    0xa683,
    0xa685,
    0xa687,
    0xa689,
    0xa68b,
    0xa68d,
    0xa68f,
    0xa691,
    0xa693,
    0xa695,
    0xa697,
    0xa699,
    0xa69b,
    0xa723,
    0xa725,
    0xa727,
    0xa729,
    0xa72b,
    0xa72d,
    [0xa72f, 0xa731],
    0xa733,
    0xa735,
    0xa737,
    0xa739,
    0xa73b,
    0xa73d,
    0xa73f,
    0xa741,
    0xa743,
    0xa745,
    0xa747,
    0xa749,
    0xa74b,
    0xa74d,
    0xa74f,
    0xa751,
    0xa753,
    0xa755,
    0xa757,
    0xa759,
    0xa75b,
    0xa75d,
    0xa75f,
    0xa761,
    0xa763,
    0xa765,
    0xa767,
    0xa769,
    0xa76b,
    0xa76d,
    0xa76f,
    [0xa771, 0xa778],
    0xa77a,
    0xa77c,
    0xa77f,
    0xa781,
    0xa783,
    0xa785,
    0xa787,
    0xa78c,
    0xa78e,
    0xa791,
    [0xa793, 0xa795],
    0xa797,
    0xa799,
    0xa79b,
    0xa79d,
    0xa79f,
    0xa7a1,
    0xa7a3,
    0xa7a5,
    0xa7a7,
    0xa7a9,
    0xa7af,
    0xa7b5,
    0xa7b7,
    0xa7b9,
    0xa7bb,
    0xa7bd,
    0xa7bf,
    0xa7c1,
    0xa7c3,
    0xa7c8,
    0xa7ca,
    0xa7d1,
    0xa7d3,
    0xa7d5,
    0xa7d7,
    0xa7d9,
    0xa7f6,
    0xa7fa,
    [0xab30, 0xab5a],
    [0xab60, 0xab68],
    [0xab70, 0xabbf],
    [0xfb00, 0xfb06],
    [0xfb13, 0xfb17],
    [0xff41, 0xff5a],
    [0x10428, 0x1044f],
    [0x104d8, 0x104fb],
    [0x10597, 0x105a1],
    [0x105a3, 0x105b1],
    [0x105b3, 0x105b9],
    [0x105bb, 0x105bc],
    [0x10cc0, 0x10cf2],
    [0x118c0, 0x118df],
    [0x16e60, 0x16e7f],
    [0x1d41a, 0x1d433],
    [0x1d44e, 0x1d454],
    [0x1d456, 0x1d467],
    [0x1d482, 0x1d49b],
    [0x1d4b6, 0x1d4b9],
    0x1d4bb,
    [0x1d4bd, 0x1d4c3],
    [0x1d4c5, 0x1d4cf],
    [0x1d4ea, 0x1d503],
    [0x1d51e, 0x1d537],
    [0x1d552, 0x1d56b],
    [0x1d586, 0x1d59f],
    [0x1d5ba, 0x1d5d3],
    [0x1d5ee, 0x1d607],
    [0x1d622, 0x1d63b],
    [0x1d656, 0x1d66f],
    [0x1d68a, 0x1d6a5],
    [0x1d6c2, 0x1d6da],
    [0x1d6dc, 0x1d6e1],
    [0x1d6fc, 0x1d714],
    [0x1d716, 0x1d71b],
    [0x1d736, 0x1d74e],
    [0x1d750, 0x1d755],
    [0x1d770, 0x1d788],
    [0x1d78a, 0x1d78f],
    [0x1d7aa, 0x1d7c2],
    [0x1d7c4, 0x1d7c9],
    0x1d7cb,
    [0x1df00, 0x1df09],
    [0x1df0b, 0x1df1e],
    [0x1df25, 0x1df2a],
    [0x1e922, 0x1e943],
];
exports.unicodeLlSurrogate = {
    0xd801: [
        [0xdc28, 0xdc4f],
        [0xdcd8, 0xdcfb],
        [0xdd97, 0xdda1],
        [0xdda3, 0xddb1],
        [0xddb3, 0xddb9],
        [0xddbb, 0xddbc], // 0x105BB..0x105BC
    ],
    0xd803: [
        [0xdcc0, 0xdcf2], // 0x10CC0..0x10CF2
    ],
    0xd806: [
        [0xdcc0, 0xdcdf], // 0x118C0..0x118DF
    ],
    0xd81b: [
        [0xde60, 0xde7f], // 0x16E60..0x16E7F
    ],
    0xd835: [
        [0xdc1a, 0xdc33],
        [0xdc4e, 0xdc54],
        [0xdc56, 0xdc67],
        [0xdc82, 0xdc9b],
        [0xdcb6, 0xdcb9],
        0xdcbb,
        [0xdcbd, 0xdcc3],
        [0xdcc5, 0xdccf],
        [0xdcea, 0xdd03],
        [0xdd1e, 0xdd37],
        [0xdd52, 0xdd6b],
        [0xdd86, 0xdd9f],
        [0xddba, 0xddd3],
        [0xddee, 0xde07],
        [0xde22, 0xde3b],
        [0xde56, 0xde6f],
        [0xde8a, 0xdea5],
        [0xdec2, 0xdeda],
        [0xdedc, 0xdee1],
        [0xdefc, 0xdf14],
        [0xdf16, 0xdf1b],
        [0xdf36, 0xdf4e],
        [0xdf50, 0xdf55],
        [0xdf70, 0xdf88],
        [0xdf8a, 0xdf8f],
        [0xdfaa, 0xdfc2],
        [0xdfc4, 0xdfc9],
        0xdfcb, // 0x1D7CB
    ],
    0xd837: [
        [0xdf00, 0xdf09],
        [0xdf0b, 0xdf1e],
        [0xdf25, 0xdf2a], // 0x1DF25..0x1DF2A
    ],
    0xd83a: [
        [0xdd22, 0xdd43], // 0x1E922..0x1E943
    ],
};
exports.unicodeLt = [
    0x01c5,
    0x01c8,
    0x01cb,
    0x01f2,
    [0x1f88, 0x1f8f],
    [0x1f98, 0x1f9f],
    [0x1fa8, 0x1faf],
    0x1fbc,
    0x1fcc,
    0x1ffc,
];
exports.unicodeLo = [
    0x00aa,
    0x00ba,
    0x01bb,
    [0x01c0, 0x01c3],
    0x0294,
    [0x05d0, 0x05ea],
    [0x05ef, 0x05f2],
    [0x0620, 0x063f],
    [0x0641, 0x064a],
    [0x066e, 0x066f],
    [0x0671, 0x06d3],
    0x06d5,
    [0x06ee, 0x06ef],
    [0x06fa, 0x06fc],
    0x06ff,
    0x0710,
    [0x0712, 0x072f],
    [0x074d, 0x07a5],
    0x07b1,
    [0x07ca, 0x07ea],
    [0x0800, 0x0815],
    [0x0840, 0x0858],
    [0x0860, 0x086a],
    [0x0870, 0x0887],
    [0x0889, 0x088e],
    [0x08a0, 0x08c8],
    [0x0904, 0x0939],
    0x093d,
    0x0950,
    [0x0958, 0x0961],
    [0x0972, 0x0980],
    [0x0985, 0x098c],
    [0x098f, 0x0990],
    [0x0993, 0x09a8],
    [0x09aa, 0x09b0],
    0x09b2,
    [0x09b6, 0x09b9],
    0x09bd,
    0x09ce,
    [0x09dc, 0x09dd],
    [0x09df, 0x09e1],
    [0x09f0, 0x09f1],
    0x09fc,
    [0x0a05, 0x0a0a],
    [0x0a0f, 0x0a10],
    [0x0a13, 0x0a28],
    [0x0a2a, 0x0a30],
    [0x0a32, 0x0a33],
    [0x0a35, 0x0a36],
    [0x0a38, 0x0a39],
    [0x0a59, 0x0a5c],
    0x0a5e,
    [0x0a72, 0x0a74],
    [0x0a85, 0x0a8d],
    [0x0a8f, 0x0a91],
    [0x0a93, 0x0aa8],
    [0x0aaa, 0x0ab0],
    [0x0ab2, 0x0ab3],
    [0x0ab5, 0x0ab9],
    0x0abd,
    0x0ad0,
    [0x0ae0, 0x0ae1],
    0x0af9,
    [0x0b05, 0x0b0c],
    [0x0b0f, 0x0b10],
    [0x0b13, 0x0b28],
    [0x0b2a, 0x0b30],
    [0x0b32, 0x0b33],
    [0x0b35, 0x0b39],
    0x0b3d,
    [0x0b5c, 0x0b5d],
    [0x0b5f, 0x0b61],
    0x0b71,
    0x0b83,
    [0x0b85, 0x0b8a],
    [0x0b8e, 0x0b90],
    [0x0b92, 0x0b95],
    [0x0b99, 0x0b9a],
    0x0b9c,
    [0x0b9e, 0x0b9f],
    [0x0ba3, 0x0ba4],
    [0x0ba8, 0x0baa],
    [0x0bae, 0x0bb9],
    0x0bd0,
    [0x0c05, 0x0c0c],
    [0x0c0e, 0x0c10],
    [0x0c12, 0x0c28],
    [0x0c2a, 0x0c39],
    0x0c3d,
    [0x0c58, 0x0c5a],
    0x0c5d,
    [0x0c60, 0x0c61],
    0x0c80,
    [0x0c85, 0x0c8c],
    [0x0c8e, 0x0c90],
    [0x0c92, 0x0ca8],
    [0x0caa, 0x0cb3],
    [0x0cb5, 0x0cb9],
    0x0cbd,
    [0x0cdd, 0x0cde],
    [0x0ce0, 0x0ce1],
    [0x0cf1, 0x0cf2],
    [0x0d04, 0x0d0c],
    [0x0d0e, 0x0d10],
    [0x0d12, 0x0d3a],
    0x0d3d,
    0x0d4e,
    [0x0d54, 0x0d56],
    [0x0d5f, 0x0d61],
    [0x0d7a, 0x0d7f],
    [0x0d85, 0x0d96],
    [0x0d9a, 0x0db1],
    [0x0db3, 0x0dbb],
    0x0dbd,
    [0x0dc0, 0x0dc6],
    [0x0e01, 0x0e30],
    [0x0e32, 0x0e33],
    [0x0e40, 0x0e45],
    [0x0e81, 0x0e82],
    0x0e84,
    [0x0e86, 0x0e8a],
    [0x0e8c, 0x0ea3],
    0x0ea5,
    [0x0ea7, 0x0eb0],
    [0x0eb2, 0x0eb3],
    0x0ebd,
    [0x0ec0, 0x0ec4],
    [0x0edc, 0x0edf],
    0x0f00,
    [0x0f40, 0x0f47],
    [0x0f49, 0x0f6c],
    [0x0f88, 0x0f8c],
    [0x1000, 0x102a],
    0x103f,
    [0x1050, 0x1055],
    [0x105a, 0x105d],
    0x1061,
    [0x1065, 0x1066],
    [0x106e, 0x1070],
    [0x1075, 0x1081],
    0x108e,
    [0x1100, 0x1248],
    [0x124a, 0x124d],
    [0x1250, 0x1256],
    0x1258,
    [0x125a, 0x125d],
    [0x1260, 0x1288],
    [0x128a, 0x128d],
    [0x1290, 0x12b0],
    [0x12b2, 0x12b5],
    [0x12b8, 0x12be],
    0x12c0,
    [0x12c2, 0x12c5],
    [0x12c8, 0x12d6],
    [0x12d8, 0x1310],
    [0x1312, 0x1315],
    [0x1318, 0x135a],
    [0x1380, 0x138f],
    [0x1401, 0x166c],
    [0x166f, 0x167f],
    [0x1681, 0x169a],
    [0x16a0, 0x16ea],
    [0x16f1, 0x16f8],
    [0x1700, 0x1711],
    [0x171f, 0x1731],
    [0x1740, 0x1751],
    [0x1760, 0x176c],
    [0x176e, 0x1770],
    [0x1780, 0x17b3],
    0x17dc,
    [0x1820, 0x1842],
    [0x1844, 0x1878],
    [0x1880, 0x1884],
    [0x1887, 0x18a8],
    0x18aa,
    [0x18b0, 0x18f5],
    [0x1900, 0x191e],
    [0x1950, 0x196d],
    [0x1970, 0x1974],
    [0x1980, 0x19ab],
    [0x19b0, 0x19c9],
    [0x1a00, 0x1a16],
    [0x1a20, 0x1a54],
    [0x1b05, 0x1b33],
    [0x1b45, 0x1b4c],
    [0x1b83, 0x1ba0],
    [0x1bae, 0x1baf],
    [0x1bba, 0x1be5],
    [0x1c00, 0x1c23],
    [0x1c4d, 0x1c4f],
    [0x1c5a, 0x1c77],
    [0x1ce9, 0x1cec],
    [0x1cee, 0x1cf3],
    [0x1cf5, 0x1cf6],
    0x1cfa,
    [0x2135, 0x2138],
    [0x2d30, 0x2d67],
    [0x2d80, 0x2d96],
    [0x2da0, 0x2da6],
    [0x2da8, 0x2dae],
    [0x2db0, 0x2db6],
    [0x2db8, 0x2dbe],
    [0x2dc0, 0x2dc6],
    [0x2dc8, 0x2dce],
    [0x2dd0, 0x2dd6],
    [0x2dd8, 0x2dde],
    0x3006,
    0x303c,
    [0x3041, 0x3096],
    0x309f,
    [0x30a1, 0x30fa],
    0x30ff,
    [0x3105, 0x312f],
    [0x3131, 0x318e],
    [0x31a0, 0x31bf],
    [0x31f0, 0x31ff],
    [0x3400, 0x4dbf],
    [0x4e00, 0xa014],
    [0xa016, 0xa48c],
    [0xa4d0, 0xa4f7],
    [0xa500, 0xa60b],
    [0xa610, 0xa61f],
    [0xa62a, 0xa62b],
    0xa66e,
    [0xa6a0, 0xa6e5],
    0xa78f,
    0xa7f7,
    [0xa7fb, 0xa801],
    [0xa803, 0xa805],
    [0xa807, 0xa80a],
    [0xa80c, 0xa822],
    [0xa840, 0xa873],
    [0xa882, 0xa8b3],
    [0xa8f2, 0xa8f7],
    0xa8fb,
    [0xa8fd, 0xa8fe],
    [0xa90a, 0xa925],
    [0xa930, 0xa946],
    [0xa960, 0xa97c],
    [0xa984, 0xa9b2],
    [0xa9e0, 0xa9e4],
    [0xa9e7, 0xa9ef],
    [0xa9fa, 0xa9fe],
    [0xaa00, 0xaa28],
    [0xaa40, 0xaa42],
    [0xaa44, 0xaa4b],
    [0xaa60, 0xaa6f],
    [0xaa71, 0xaa76],
    0xaa7a,
    [0xaa7e, 0xaaaf],
    0xaab1,
    [0xaab5, 0xaab6],
    [0xaab9, 0xaabd],
    0xaac0,
    0xaac2,
    [0xaadb, 0xaadc],
    [0xaae0, 0xaaea],
    0xaaf2,
    [0xab01, 0xab06],
    [0xab09, 0xab0e],
    [0xab11, 0xab16],
    [0xab20, 0xab26],
    [0xab28, 0xab2e],
    [0xabc0, 0xabe2],
    [0xac00, 0xd7a3],
    [0xd7b0, 0xd7c6],
    [0xd7cb, 0xd7fb],
    [0xf900, 0xfa6d],
    [0xfa70, 0xfad9],
    0xfb1d,
    [0xfb1f, 0xfb28],
    [0xfb2a, 0xfb36],
    [0xfb38, 0xfb3c],
    0xfb3e,
    [0xfb40, 0xfb41],
    [0xfb43, 0xfb44],
    [0xfb46, 0xfbb1],
    [0xfbd3, 0xfd3d],
    [0xfd50, 0xfd8f],
    [0xfd92, 0xfdc7],
    [0xfdf0, 0xfdfb],
    [0xfe70, 0xfe74],
    [0xfe76, 0xfefc],
    [0xff66, 0xff6f],
    [0xff71, 0xff9d],
    [0xffa0, 0xffbe],
    [0xffc2, 0xffc7],
    [0xffca, 0xffcf],
    [0xffd2, 0xffd7],
    [0xffda, 0xffdc],
    [0x10000, 0x1000b],
    [0x1000d, 0x10026],
    [0x10028, 0x1003a],
    [0x1003c, 0x1003d],
    [0x1003f, 0x1004d],
    [0x10050, 0x1005d],
    [0x10080, 0x100fa],
    [0x10280, 0x1029c],
    [0x102a0, 0x102d0],
    [0x10300, 0x1031f],
    [0x1032d, 0x10340],
    [0x10342, 0x10349],
    [0x10350, 0x10375],
    [0x10380, 0x1039d],
    [0x103a0, 0x103c3],
    [0x103c8, 0x103cf],
    [0x10450, 0x1049d],
    [0x10500, 0x10527],
    [0x10530, 0x10563],
    [0x10600, 0x10736],
    [0x10740, 0x10755],
    [0x10760, 0x10767],
    [0x10800, 0x10805],
    0x10808,
    [0x1080a, 0x10835],
    [0x10837, 0x10838],
    0x1083c,
    [0x1083f, 0x10855],
    [0x10860, 0x10876],
    [0x10880, 0x1089e],
    [0x108e0, 0x108f2],
    [0x108f4, 0x108f5],
    [0x10900, 0x10915],
    [0x10920, 0x10939],
    [0x10980, 0x109b7],
    [0x109be, 0x109bf],
    0x10a00,
    [0x10a10, 0x10a13],
    [0x10a15, 0x10a17],
    [0x10a19, 0x10a35],
    [0x10a60, 0x10a7c],
    [0x10a80, 0x10a9c],
    [0x10ac0, 0x10ac7],
    [0x10ac9, 0x10ae4],
    [0x10b00, 0x10b35],
    [0x10b40, 0x10b55],
    [0x10b60, 0x10b72],
    [0x10b80, 0x10b91],
    [0x10c00, 0x10c48],
    [0x10d00, 0x10d23],
    [0x10e80, 0x10ea9],
    [0x10eb0, 0x10eb1],
    [0x10f00, 0x10f1c],
    0x10f27,
    [0x10f30, 0x10f45],
    [0x10f70, 0x10f81],
    [0x10fb0, 0x10fc4],
    [0x10fe0, 0x10ff6],
    [0x11003, 0x11037],
    [0x11071, 0x11072],
    0x11075,
    [0x11083, 0x110af],
    [0x110d0, 0x110e8],
    [0x11103, 0x11126],
    0x11144,
    0x11147,
    [0x11150, 0x11172],
    0x11176,
    [0x11183, 0x111b2],
    [0x111c1, 0x111c4],
    0x111da,
    0x111dc,
    [0x11200, 0x11211],
    [0x11213, 0x1122b],
    [0x1123f, 0x11240],
    [0x11280, 0x11286],
    0x11288,
    [0x1128a, 0x1128d],
    [0x1128f, 0x1129d],
    [0x1129f, 0x112a8],
    [0x112b0, 0x112de],
    [0x11305, 0x1130c],
    [0x1130f, 0x11310],
    [0x11313, 0x11328],
    [0x1132a, 0x11330],
    [0x11332, 0x11333],
    [0x11335, 0x11339],
    0x1133d,
    0x11350,
    [0x1135d, 0x11361],
    [0x11400, 0x11434],
    [0x11447, 0x1144a],
    [0x1145f, 0x11461],
    [0x11480, 0x114af],
    [0x114c4, 0x114c5],
    0x114c7,
    [0x11580, 0x115ae],
    [0x115d8, 0x115db],
    [0x11600, 0x1162f],
    0x11644,
    [0x11680, 0x116aa],
    0x116b8,
    [0x11700, 0x1171a],
    [0x11740, 0x11746],
    [0x11800, 0x1182b],
    [0x118ff, 0x11906],
    0x11909,
    [0x1190c, 0x11913],
    [0x11915, 0x11916],
    [0x11918, 0x1192f],
    0x1193f,
    0x11941,
    [0x119a0, 0x119a7],
    [0x119aa, 0x119d0],
    0x119e1,
    0x119e3,
    0x11a00,
    [0x11a0b, 0x11a32],
    0x11a3a,
    0x11a50,
    [0x11a5c, 0x11a89],
    0x11a9d,
    [0x11ab0, 0x11af8],
    [0x11c00, 0x11c08],
    [0x11c0a, 0x11c2e],
    0x11c40,
    [0x11c72, 0x11c8f],
    [0x11d00, 0x11d06],
    [0x11d08, 0x11d09],
    [0x11d0b, 0x11d30],
    0x11d46,
    [0x11d60, 0x11d65],
    [0x11d67, 0x11d68],
    [0x11d6a, 0x11d89],
    0x11d98,
    [0x11ee0, 0x11ef2],
    0x11f02,
    [0x11f04, 0x11f10],
    [0x11f12, 0x11f33],
    0x11fb0,
    [0x12000, 0x12399],
    [0x12480, 0x12543],
    [0x12f90, 0x12ff0],
    [0x13000, 0x1342f],
    [0x13441, 0x13446],
    [0x14400, 0x14646],
    [0x16800, 0x16a38],
    [0x16a40, 0x16a5e],
    [0x16a70, 0x16abe],
    [0x16ad0, 0x16aed],
    [0x16b00, 0x16b2f],
    [0x16b63, 0x16b77],
    [0x16b7d, 0x16b8f],
    [0x16f00, 0x16f4a],
    0x16f50,
    [0x17000, 0x187f7],
    [0x18800, 0x18cd5],
    [0x18d00, 0x18d08],
    [0x1b000, 0x1b122],
    0x1b132,
    [0x1b150, 0x1b152],
    0x1b155,
    [0x1b164, 0x1b167],
    [0x1b170, 0x1b2fb],
    [0x1bc00, 0x1bc6a],
    [0x1bc70, 0x1bc7c],
    [0x1bc80, 0x1bc88],
    [0x1bc90, 0x1bc99],
    0x1df0a,
    [0x1e100, 0x1e12c],
    0x1e14e,
    [0x1e290, 0x1e2ad],
    [0x1e2c0, 0x1e2eb],
    [0x1e4d0, 0x1e4ea],
    [0x1e7e0, 0x1e7e6],
    [0x1e7e8, 0x1e7eb],
    [0x1e7ed, 0x1e7ee],
    [0x1e7f0, 0x1e7fe],
    [0x1e800, 0x1e8c4],
    [0x1ee00, 0x1ee03],
    [0x1ee05, 0x1ee1f],
    [0x1ee21, 0x1ee22],
    0x1ee24,
    0x1ee27,
    [0x1ee29, 0x1ee32],
    [0x1ee34, 0x1ee37],
    0x1ee39,
    0x1ee3b,
    0x1ee42,
    0x1ee47,
    0x1ee49,
    0x1ee4b,
    [0x1ee4d, 0x1ee4f],
    [0x1ee51, 0x1ee52],
    0x1ee54,
    0x1ee57,
    0x1ee59,
    0x1ee5b,
    0x1ee5d,
    0x1ee5f,
    [0x1ee61, 0x1ee62],
    0x1ee64,
    [0x1ee67, 0x1ee6a],
    [0x1ee6c, 0x1ee72],
    [0x1ee74, 0x1ee77],
    [0x1ee79, 0x1ee7c],
    0x1ee7e,
    [0x1ee80, 0x1ee89],
    [0x1ee8b, 0x1ee9b],
    [0x1eea1, 0x1eea3],
    [0x1eea5, 0x1eea9],
    [0x1eeab, 0x1eebb],
    [0x20000, 0x2a6df],
    [0x2a700, 0x2b739],
    [0x2b740, 0x2b81d],
    [0x2b820, 0x2cea1],
    [0x2ceb0, 0x2ebe0],
    [0x2ebf0, 0x2ee5d],
    [0x2f800, 0x2fa1d],
    [0x30000, 0x3134a],
    [0x31350, 0x323af],
];
exports.unicodeLoSurrogate = {
    0xd800: [
        [0xdc00, 0xdc0b],
        [0xdc0d, 0xdc26],
        [0xdc28, 0xdc3a],
        [0xdc3c, 0xdc3d],
        [0xdc3f, 0xdc4d],
        [0xdc50, 0xdc5d],
        [0xdc80, 0xdcfa],
        [0xde80, 0xde9c],
        [0xdea0, 0xded0],
        [0xdf00, 0xdf1f],
        [0xdf2d, 0xdf40],
        [0xdf42, 0xdf49],
        [0xdf50, 0xdf75],
        [0xdf80, 0xdf9d],
        [0xdfa0, 0xdfc3],
        [0xdfc8, 0xdfcf], // 0x103C8..0x103CF
    ],
    0xd801: [
        [0xdc50, 0xdc9d],
        [0xdd00, 0xdd27],
        [0xdd30, 0xdd63],
        [0xde00, 0xdf36],
        [0xdf40, 0xdf55],
        [0xdf60, 0xdf67], // 0x10760..0x10767
    ],
    0xd802: [
        [0xdc00, 0xdc05],
        0xdc08,
        [0xdc0a, 0xdc35],
        [0xdc37, 0xdc38],
        0xdc3c,
        [0xdc3f, 0xdc55],
        [0xdc60, 0xdc76],
        [0xdc80, 0xdc9e],
        [0xdce0, 0xdcf2],
        [0xdcf4, 0xdcf5],
        [0xdd00, 0xdd15],
        [0xdd20, 0xdd39],
        [0xdd80, 0xddb7],
        [0xddbe, 0xddbf],
        0xde00,
        [0xde10, 0xde13],
        [0xde15, 0xde17],
        [0xde19, 0xde35],
        [0xde60, 0xde7c],
        [0xde80, 0xde9c],
        [0xdec0, 0xdec7],
        [0xdec9, 0xdee4],
        [0xdf00, 0xdf35],
        [0xdf40, 0xdf55],
        [0xdf60, 0xdf72],
        [0xdf80, 0xdf91], // 0x10B80..0x10B91
    ],
    0xd803: [
        [0xdc00, 0xdc48],
        [0xdd00, 0xdd23],
        [0xde80, 0xdea9],
        [0xdeb0, 0xdeb1],
        [0xdf00, 0xdf1c],
        0xdf27,
        [0xdf30, 0xdf45],
        [0xdf70, 0xdf81],
        [0xdfb0, 0xdfc4],
        [0xdfe0, 0xdff6], // 0x10FE0..0x10FF6
    ],
    0xd804: [
        [0xdc03, 0xdc37],
        [0xdc71, 0xdc72],
        0xdc75,
        [0xdc83, 0xdcaf],
        [0xdcd0, 0xdce8],
        [0xdd03, 0xdd26],
        0xdd44,
        0xdd47,
        [0xdd50, 0xdd72],
        0xdd76,
        [0xdd83, 0xddb2],
        [0xddc1, 0xddc4],
        0xddda,
        0xdddc,
        [0xde00, 0xde11],
        [0xde13, 0xde2b],
        [0xde3f, 0xde40],
        [0xde80, 0xde86],
        0xde88,
        [0xde8a, 0xde8d],
        [0xde8f, 0xde9d],
        [0xde9f, 0xdea8],
        [0xdeb0, 0xdede],
        [0xdf05, 0xdf0c],
        [0xdf0f, 0xdf10],
        [0xdf13, 0xdf28],
        [0xdf2a, 0xdf30],
        [0xdf32, 0xdf33],
        [0xdf35, 0xdf39],
        0xdf3d,
        0xdf50,
        [0xdf5d, 0xdf61], // 0x1135D..0x11361
    ],
    0xd805: [
        [0xdc00, 0xdc34],
        [0xdc47, 0xdc4a],
        [0xdc5f, 0xdc61],
        [0xdc80, 0xdcaf],
        [0xdcc4, 0xdcc5],
        0xdcc7,
        [0xdd80, 0xddae],
        [0xddd8, 0xdddb],
        [0xde00, 0xde2f],
        0xde44,
        [0xde80, 0xdeaa],
        0xdeb8,
        [0xdf00, 0xdf1a],
        [0xdf40, 0xdf46], // 0x11740..0x11746
    ],
    0xd806: [
        [0xdc00, 0xdc2b],
        [0xdcff, 0xdd06],
        0xdd09,
        [0xdd0c, 0xdd13],
        [0xdd15, 0xdd16],
        [0xdd18, 0xdd2f],
        0xdd3f,
        0xdd41,
        [0xdda0, 0xdda7],
        [0xddaa, 0xddd0],
        0xdde1,
        0xdde3,
        0xde00,
        [0xde0b, 0xde32],
        0xde3a,
        0xde50,
        [0xde5c, 0xde89],
        0xde9d,
        [0xdeb0, 0xdef8], // 0x11AB0..0x11AF8
    ],
    0xd807: [
        [0xdc00, 0xdc08],
        [0xdc0a, 0xdc2e],
        0xdc40,
        [0xdc72, 0xdc8f],
        [0xdd00, 0xdd06],
        [0xdd08, 0xdd09],
        [0xdd0b, 0xdd30],
        0xdd46,
        [0xdd60, 0xdd65],
        [0xdd67, 0xdd68],
        [0xdd6a, 0xdd89],
        0xdd98,
        [0xdee0, 0xdef2],
        0xdf02,
        [0xdf04, 0xdf10],
        [0xdf12, 0xdf33],
        0xdfb0, // 0x11FB0
    ],
    0xd808: [
        [0xdc00, 0xdf99], // 0x12000..0x12399
    ],
    0xd809: [
        [0xdc80, 0xdd43], // 0x12480..0x12543
    ],
    0xd80b: [
        [0xdf90, 0xdff0], // 0x12F90..0x12FF0
    ],
    0xd80c: [
        [0xdc00, 0xdfff], // 0x13000..0x133FF
    ],
    0xd80d: [
        [0xdc00, 0xdc2f],
        [0xdc41, 0xdc46], // 0x13441..0x13446
    ],
    0xd811: [
        [0xdc00, 0xde46], // 0x14400..0x14646
    ],
    0xd81a: [
        [0xdc00, 0xde38],
        [0xde40, 0xde5e],
        [0xde70, 0xdebe],
        [0xded0, 0xdeed],
        [0xdf00, 0xdf2f],
        [0xdf63, 0xdf77],
        [0xdf7d, 0xdf8f], // 0x16B7D..0x16B8F
    ],
    0xd81b: [
        [0xdf00, 0xdf4a],
        0xdf50, // 0x16F50
    ],
    0xd81c: [
        [0xdc00, 0xdfff], // 0x17000..0x173FF
    ],
    0xd81d: [
        [0xdc00, 0xdfff], // 0x17400..0x177FF
    ],
    0xd81e: [
        [0xdc00, 0xdfff], // 0x17800..0x17BFF
    ],
    0xd81f: [
        [0xdc00, 0xdfff], // 0x17C00..0x17FFF
    ],
    0xd820: [
        [0xdc00, 0xdfff], // 0x18000..0x183FF
    ],
    0xd821: [
        [0xdc00, 0xdff7], // 0x18400..0x187F7
    ],
    0xd822: [
        [0xdc00, 0xdfff], // 0x18800..0x18BFF
    ],
    0xd823: [
        [0xdc00, 0xdcd5],
        [0xdd00, 0xdd08], // 0x18D00..0x18D08
    ],
    0xd82c: [
        [0xdc00, 0xdd22],
        0xdd32,
        [0xdd50, 0xdd52],
        0xdd55,
        [0xdd64, 0xdd67],
        [0xdd70, 0xdefb], // 0x1B170..0x1B2FB
    ],
    0xd82f: [
        [0xdc00, 0xdc6a],
        [0xdc70, 0xdc7c],
        [0xdc80, 0xdc88],
        [0xdc90, 0xdc99], // 0x1BC90..0x1BC99
    ],
    0xd837: [
        0xdf0a, // 0x1DF0A
    ],
    0xd838: [
        [0xdd00, 0xdd2c],
        0xdd4e,
        [0xde90, 0xdead],
        [0xdec0, 0xdeeb], // 0x1E2C0..0x1E2EB
    ],
    0xd839: [
        [0xdcd0, 0xdcea],
        [0xdfe0, 0xdfe6],
        [0xdfe8, 0xdfeb],
        [0xdfed, 0xdfee],
        [0xdff0, 0xdffe], // 0x1E7F0..0x1E7FE
    ],
    0xd83a: [
        [0xdc00, 0xdcc4], // 0x1E800..0x1E8C4
    ],
    0xd83b: [
        [0xde00, 0xde03],
        [0xde05, 0xde1f],
        [0xde21, 0xde22],
        0xde24,
        0xde27,
        [0xde29, 0xde32],
        [0xde34, 0xde37],
        0xde39,
        0xde3b,
        0xde42,
        0xde47,
        0xde49,
        0xde4b,
        [0xde4d, 0xde4f],
        [0xde51, 0xde52],
        0xde54,
        0xde57,
        0xde59,
        0xde5b,
        0xde5d,
        0xde5f,
        [0xde61, 0xde62],
        0xde64,
        [0xde67, 0xde6a],
        [0xde6c, 0xde72],
        [0xde74, 0xde77],
        [0xde79, 0xde7c],
        0xde7e,
        [0xde80, 0xde89],
        [0xde8b, 0xde9b],
        [0xdea1, 0xdea3],
        [0xdea5, 0xdea9],
        [0xdeab, 0xdebb], // 0x1EEAB..0x1EEBB
    ],
    0xd840: [
        [0xdc00, 0xdfff], // 0x20000..0x203FF
    ],
    0xd841: [
        [0xdc00, 0xdfff], // 0x20400..0x207FF
    ],
    0xd842: [
        [0xdc00, 0xdfff], // 0x20800..0x20BFF
    ],
    0xd843: [
        [0xdc00, 0xdfff], // 0x20C00..0x20FFF
    ],
    0xd844: [
        [0xdc00, 0xdfff], // 0x21000..0x213FF
    ],
    0xd845: [
        [0xdc00, 0xdfff], // 0x21400..0x217FF
    ],
    0xd846: [
        [0xdc00, 0xdfff], // 0x21800..0x21BFF
    ],
    0xd847: [
        [0xdc00, 0xdfff], // 0x21C00..0x21FFF
    ],
    0xd848: [
        [0xdc00, 0xdfff], // 0x22000..0x223FF
    ],
    0xd849: [
        [0xdc00, 0xdfff], // 0x22400..0x227FF
    ],
    0xd84a: [
        [0xdc00, 0xdfff], // 0x22800..0x22BFF
    ],
    0xd84b: [
        [0xdc00, 0xdfff], // 0x22C00..0x22FFF
    ],
    0xd84c: [
        [0xdc00, 0xdfff], // 0x23000..0x233FF
    ],
    0xd84d: [
        [0xdc00, 0xdfff], // 0x23400..0x237FF
    ],
    0xd84e: [
        [0xdc00, 0xdfff], // 0x23800..0x23BFF
    ],
    0xd84f: [
        [0xdc00, 0xdfff], // 0x23C00..0x23FFF
    ],
    0xd850: [
        [0xdc00, 0xdfff], // 0x24000..0x243FF
    ],
    0xd851: [
        [0xdc00, 0xdfff], // 0x24400..0x247FF
    ],
    0xd852: [
        [0xdc00, 0xdfff], // 0x24800..0x24BFF
    ],
    0xd853: [
        [0xdc00, 0xdfff], // 0x24C00..0x24FFF
    ],
    0xd854: [
        [0xdc00, 0xdfff], // 0x25000..0x253FF
    ],
    0xd855: [
        [0xdc00, 0xdfff], // 0x25400..0x257FF
    ],
    0xd856: [
        [0xdc00, 0xdfff], // 0x25800..0x25BFF
    ],
    0xd857: [
        [0xdc00, 0xdfff], // 0x25C00..0x25FFF
    ],
    0xd858: [
        [0xdc00, 0xdfff], // 0x26000..0x263FF
    ],
    0xd859: [
        [0xdc00, 0xdfff], // 0x26400..0x267FF
    ],
    0xd85a: [
        [0xdc00, 0xdfff], // 0x26800..0x26BFF
    ],
    0xd85b: [
        [0xdc00, 0xdfff], // 0x26C00..0x26FFF
    ],
    0xd85c: [
        [0xdc00, 0xdfff], // 0x27000..0x273FF
    ],
    0xd85d: [
        [0xdc00, 0xdfff], // 0x27400..0x277FF
    ],
    0xd85e: [
        [0xdc00, 0xdfff], // 0x27800..0x27BFF
    ],
    0xd85f: [
        [0xdc00, 0xdfff], // 0x27C00..0x27FFF
    ],
    0xd860: [
        [0xdc00, 0xdfff], // 0x28000..0x283FF
    ],
    0xd861: [
        [0xdc00, 0xdfff], // 0x28400..0x287FF
    ],
    0xd862: [
        [0xdc00, 0xdfff], // 0x28800..0x28BFF
    ],
    0xd863: [
        [0xdc00, 0xdfff], // 0x28C00..0x28FFF
    ],
    0xd864: [
        [0xdc00, 0xdfff], // 0x29000..0x293FF
    ],
    0xd865: [
        [0xdc00, 0xdfff], // 0x29400..0x297FF
    ],
    0xd866: [
        [0xdc00, 0xdfff], // 0x29800..0x29BFF
    ],
    0xd867: [
        [0xdc00, 0xdfff], // 0x29C00..0x29FFF
    ],
    0xd868: [
        [0xdc00, 0xdfff], // 0x2A000..0x2A3FF
    ],
    0xd869: [
        [0xdc00, 0xdedf],
        [0xdf00, 0xdfff], // 0x2A700..0x2A7FF
    ],
    0xd86a: [
        [0xdc00, 0xdfff], // 0x2A800..0x2ABFF
    ],
    0xd86b: [
        [0xdc00, 0xdfff], // 0x2AC00..0x2AFFF
    ],
    0xd86c: [
        [0xdc00, 0xdfff], // 0x2B000..0x2B3FF
    ],
    0xd86d: [
        [0xdc00, 0xdf39],
        [0xdf40, 0xdfff], // 0x2B740..0x2B7FF
    ],
    0xd86e: [
        [0xdc00, 0xdc1d],
        [0xdc20, 0xdfff], // 0x2B820..0x2BBFF
    ],
    0xd86f: [
        [0xdc00, 0xdfff], // 0x2BC00..0x2BFFF
    ],
    0xd870: [
        [0xdc00, 0xdfff], // 0x2C000..0x2C3FF
    ],
    0xd871: [
        [0xdc00, 0xdfff], // 0x2C400..0x2C7FF
    ],
    0xd872: [
        [0xdc00, 0xdfff], // 0x2C800..0x2CBFF
    ],
    0xd873: [
        [0xdc00, 0xdea1],
        [0xdeb0, 0xdfff], // 0x2CEB0..0x2CFFF
    ],
    0xd874: [
        [0xdc00, 0xdfff], // 0x2D000..0x2D3FF
    ],
    0xd875: [
        [0xdc00, 0xdfff], // 0x2D400..0x2D7FF
    ],
    0xd876: [
        [0xdc00, 0xdfff], // 0x2D800..0x2DBFF
    ],
    0xd877: [
        [0xdc00, 0xdfff], // 0x2DC00..0x2DFFF
    ],
    0xd878: [
        [0xdc00, 0xdfff], // 0x2E000..0x2E3FF
    ],
    0xd879: [
        [0xdc00, 0xdfff], // 0x2E400..0x2E7FF
    ],
    0xd87a: [
        [0xdc00, 0xdfe0],
        [0xdff0, 0xdfff], // 0x2EBF0..0x2EBFF
    ],
    0xd87b: [
        [0xdc00, 0xde5d], // 0x2EC00..0x2EE5D
    ],
    0xd87e: [
        [0xdc00, 0xde1d], // 0x2F800..0x2FA1D
    ],
    0xd880: [
        [0xdc00, 0xdfff], // 0x30000..0x303FF
    ],
    0xd881: [
        [0xdc00, 0xdfff], // 0x30400..0x307FF
    ],
    0xd882: [
        [0xdc00, 0xdfff], // 0x30800..0x30BFF
    ],
    0xd883: [
        [0xdc00, 0xdfff], // 0x30C00..0x30FFF
    ],
    0xd884: [
        [0xdc00, 0xdf4a],
        [0xdf50, 0xdfff], // 0x31350..0x313FF
    ],
    0xd885: [
        [0xdc00, 0xdfff], // 0x31400..0x317FF
    ],
    0xd886: [
        [0xdc00, 0xdfff], // 0x31800..0x31BFF
    ],
    0xd887: [
        [0xdc00, 0xdfff], // 0x31C00..0x31FFF
    ],
    0xd888: [
        [0xdc00, 0xdfaf], // 0x32000..0x323AF
    ],
};
exports.unicodeLm = [
    [0x02b0, 0x02c1],
    [0x02c6, 0x02d1],
    [0x02e0, 0x02e4],
    0x02ec,
    0x02ee,
    0x0374,
    0x037a,
    0x0559,
    0x0640,
    [0x06e5, 0x06e6],
    [0x07f4, 0x07f5],
    0x07fa,
    0x081a,
    0x0824,
    0x0828,
    0x08c9,
    0x0971,
    0x0e46,
    0x0ec6,
    0x10fc,
    0x17d7,
    0x1843,
    0x1aa7,
    [0x1c78, 0x1c7d],
    [0x1d2c, 0x1d6a],
    0x1d78,
    [0x1d9b, 0x1dbf],
    0x2071,
    0x207f,
    [0x2090, 0x209c],
    [0x2c7c, 0x2c7d],
    0x2d6f,
    0x2e2f,
    0x3005,
    [0x3031, 0x3035],
    0x303b,
    [0x309d, 0x309e],
    [0x30fc, 0x30fe],
    0xa015,
    [0xa4f8, 0xa4fd],
    0xa60c,
    0xa67f,
    [0xa69c, 0xa69d],
    [0xa717, 0xa71f],
    0xa770,
    0xa788,
    [0xa7f2, 0xa7f4],
    [0xa7f8, 0xa7f9],
    0xa9cf,
    0xa9e6,
    0xaa70,
    0xaadd,
    [0xaaf3, 0xaaf4],
    [0xab5c, 0xab5f],
    0xab69,
    0xff70,
    [0xff9e, 0xff9f],
    [0x10780, 0x10785],
    [0x10787, 0x107b0],
    [0x107b2, 0x107ba],
    [0x16b40, 0x16b43],
    [0x16f93, 0x16f9f],
    [0x16fe0, 0x16fe1],
    0x16fe3,
    [0x1aff0, 0x1aff3],
    [0x1aff5, 0x1affb],
    [0x1affd, 0x1affe],
    [0x1e030, 0x1e06d],
    [0x1e137, 0x1e13d],
    0x1e4eb,
    0x1e94b,
];
exports.unicodeLmSurrogate = {
    0xd801: [
        [0xdf80, 0xdf85],
        [0xdf87, 0xdfb0],
        [0xdfb2, 0xdfba], // 0x107B2..0x107BA
    ],
    0xd81a: [
        [0xdf40, 0xdf43], // 0x16B40..0x16B43
    ],
    0xd81b: [
        [0xdf93, 0xdf9f],
        [0xdfe0, 0xdfe1],
        0xdfe3, // 0x16FE3
    ],
    0xd82b: [
        [0xdff0, 0xdff3],
        [0xdff5, 0xdffb],
        [0xdffd, 0xdffe], // 0x1AFFD..0x1AFFE
    ],
    0xd838: [
        [0xdc30, 0xdc6d],
        [0xdd37, 0xdd3d], // 0x1E137..0x1E13D
    ],
    0xd839: [
        0xdceb, // 0x1E4EB
    ],
    0xd83a: [
        0xdd4b, // 0x1E94B
    ],
};
exports.unicodeNl = [
    [0x16ee, 0x16f0],
    [0x2160, 0x2182],
    [0x2185, 0x2188],
    0x3007,
    [0x3021, 0x3029],
    [0x3038, 0x303a],
    [0xa6e6, 0xa6ef],
    [0x10140, 0x10174],
    0x10341,
    0x1034a,
    [0x103d1, 0x103d5],
    [0x12400, 0x1246e],
];
exports.unicodeNlSurrogate = {
    0xd800: [
        [0xdd40, 0xdd74],
        0xdf41,
        0xdf4a,
        [0xdfd1, 0xdfd5], // 0x103D1..0x103D5
    ],
    0xd809: [
        [0xdc00, 0xdc6e], // 0x12400..0x1246E
    ],
};
exports.unicodeMn = [
    [0x0300, 0x036f],
    [0x0483, 0x0487],
    [0x0591, 0x05bd],
    0x05bf,
    [0x05c1, 0x05c2],
    [0x05c4, 0x05c5],
    0x05c7,
    [0x0610, 0x061a],
    [0x064b, 0x065f],
    0x0670,
    [0x06d6, 0x06dc],
    [0x06df, 0x06e4],
    [0x06e7, 0x06e8],
    [0x06ea, 0x06ed],
    0x0711,
    [0x0730, 0x074a],
    [0x07a6, 0x07b0],
    [0x07eb, 0x07f3],
    0x07fd,
    [0x0816, 0x0819],
    [0x081b, 0x0823],
    [0x0825, 0x0827],
    [0x0829, 0x082d],
    [0x0859, 0x085b],
    [0x0898, 0x089f],
    [0x08ca, 0x08e1],
    [0x08e3, 0x0902],
    0x093a,
    0x093c,
    [0x0941, 0x0948],
    0x094d,
    [0x0951, 0x0957],
    [0x0962, 0x0963],
    0x0981,
    0x09bc,
    [0x09c1, 0x09c4],
    0x09cd,
    [0x09e2, 0x09e3],
    0x09fe,
    [0x0a01, 0x0a02],
    0x0a3c,
    [0x0a41, 0x0a42],
    [0x0a47, 0x0a48],
    [0x0a4b, 0x0a4d],
    0x0a51,
    [0x0a70, 0x0a71],
    0x0a75,
    [0x0a81, 0x0a82],
    0x0abc,
    [0x0ac1, 0x0ac5],
    [0x0ac7, 0x0ac8],
    0x0acd,
    [0x0ae2, 0x0ae3],
    [0x0afa, 0x0aff],
    0x0b01,
    0x0b3c,
    0x0b3f,
    [0x0b41, 0x0b44],
    0x0b4d,
    [0x0b55, 0x0b56],
    [0x0b62, 0x0b63],
    0x0b82,
    0x0bc0,
    0x0bcd,
    0x0c00,
    0x0c04,
    0x0c3c,
    [0x0c3e, 0x0c40],
    [0x0c46, 0x0c48],
    [0x0c4a, 0x0c4d],
    [0x0c55, 0x0c56],
    [0x0c62, 0x0c63],
    0x0c81,
    0x0cbc,
    0x0cbf,
    0x0cc6,
    [0x0ccc, 0x0ccd],
    [0x0ce2, 0x0ce3],
    [0x0d00, 0x0d01],
    [0x0d3b, 0x0d3c],
    [0x0d41, 0x0d44],
    0x0d4d,
    [0x0d62, 0x0d63],
    0x0d81,
    0x0dca,
    [0x0dd2, 0x0dd4],
    0x0dd6,
    0x0e31,
    [0x0e34, 0x0e3a],
    [0x0e47, 0x0e4e],
    0x0eb1,
    [0x0eb4, 0x0ebc],
    [0x0ec8, 0x0ece],
    [0x0f18, 0x0f19],
    0x0f35,
    0x0f37,
    0x0f39,
    [0x0f71, 0x0f7e],
    [0x0f80, 0x0f84],
    [0x0f86, 0x0f87],
    [0x0f8d, 0x0f97],
    [0x0f99, 0x0fbc],
    0x0fc6,
    [0x102d, 0x1030],
    [0x1032, 0x1037],
    [0x1039, 0x103a],
    [0x103d, 0x103e],
    [0x1058, 0x1059],
    [0x105e, 0x1060],
    [0x1071, 0x1074],
    0x1082,
    [0x1085, 0x1086],
    0x108d,
    0x109d,
    [0x135d, 0x135f],
    [0x1712, 0x1714],
    [0x1732, 0x1733],
    [0x1752, 0x1753],
    [0x1772, 0x1773],
    [0x17b4, 0x17b5],
    [0x17b7, 0x17bd],
    0x17c6,
    [0x17c9, 0x17d3],
    0x17dd,
    [0x180b, 0x180d],
    0x180f,
    [0x1885, 0x1886],
    0x18a9,
    [0x1920, 0x1922],
    [0x1927, 0x1928],
    0x1932,
    [0x1939, 0x193b],
    [0x1a17, 0x1a18],
    0x1a1b,
    0x1a56,
    [0x1a58, 0x1a5e],
    0x1a60,
    0x1a62,
    [0x1a65, 0x1a6c],
    [0x1a73, 0x1a7c],
    0x1a7f,
    [0x1ab0, 0x1abd],
    [0x1abf, 0x1ace],
    [0x1b00, 0x1b03],
    0x1b34,
    [0x1b36, 0x1b3a],
    0x1b3c,
    0x1b42,
    [0x1b6b, 0x1b73],
    [0x1b80, 0x1b81],
    [0x1ba2, 0x1ba5],
    [0x1ba8, 0x1ba9],
    [0x1bab, 0x1bad],
    0x1be6,
    [0x1be8, 0x1be9],
    0x1bed,
    [0x1bef, 0x1bf1],
    [0x1c2c, 0x1c33],
    [0x1c36, 0x1c37],
    [0x1cd0, 0x1cd2],
    [0x1cd4, 0x1ce0],
    [0x1ce2, 0x1ce8],
    0x1ced,
    0x1cf4,
    [0x1cf8, 0x1cf9],
    [0x1dc0, 0x1dff],
    [0x20d0, 0x20dc],
    0x20e1,
    [0x20e5, 0x20f0],
    [0x2cef, 0x2cf1],
    0x2d7f,
    [0x2de0, 0x2dff],
    [0x302a, 0x302d],
    [0x3099, 0x309a],
    0xa66f,
    [0xa674, 0xa67d],
    [0xa69e, 0xa69f],
    [0xa6f0, 0xa6f1],
    0xa802,
    0xa806,
    0xa80b,
    [0xa825, 0xa826],
    0xa82c,
    [0xa8c4, 0xa8c5],
    [0xa8e0, 0xa8f1],
    0xa8ff,
    [0xa926, 0xa92d],
    [0xa947, 0xa951],
    [0xa980, 0xa982],
    0xa9b3,
    [0xa9b6, 0xa9b9],
    [0xa9bc, 0xa9bd],
    0xa9e5,
    [0xaa29, 0xaa2e],
    [0xaa31, 0xaa32],
    [0xaa35, 0xaa36],
    0xaa43,
    0xaa4c,
    0xaa7c,
    0xaab0,
    [0xaab2, 0xaab4],
    [0xaab7, 0xaab8],
    [0xaabe, 0xaabf],
    0xaac1,
    [0xaaec, 0xaaed],
    0xaaf6,
    0xabe5,
    0xabe8,
    0xabed,
    0xfb1e,
    [0xfe00, 0xfe0f],
    [0xfe20, 0xfe2f],
    0x101fd,
    0x102e0,
    [0x10376, 0x1037a],
    [0x10a01, 0x10a03],
    [0x10a05, 0x10a06],
    [0x10a0c, 0x10a0f],
    [0x10a38, 0x10a3a],
    0x10a3f,
    [0x10ae5, 0x10ae6],
    [0x10d24, 0x10d27],
    [0x10eab, 0x10eac],
    [0x10efd, 0x10eff],
    [0x10f46, 0x10f50],
    [0x10f82, 0x10f85],
    0x11001,
    [0x11038, 0x11046],
    0x11070,
    [0x11073, 0x11074],
    [0x1107f, 0x11081],
    [0x110b3, 0x110b6],
    [0x110b9, 0x110ba],
    0x110c2,
    [0x11100, 0x11102],
    [0x11127, 0x1112b],
    [0x1112d, 0x11134],
    0x11173,
    [0x11180, 0x11181],
    [0x111b6, 0x111be],
    [0x111c9, 0x111cc],
    0x111cf,
    [0x1122f, 0x11231],
    0x11234,
    [0x11236, 0x11237],
    0x1123e,
    0x11241,
    0x112df,
    [0x112e3, 0x112ea],
    [0x11300, 0x11301],
    [0x1133b, 0x1133c],
    0x11340,
    [0x11366, 0x1136c],
    [0x11370, 0x11374],
    [0x11438, 0x1143f],
    [0x11442, 0x11444],
    0x11446,
    0x1145e,
    [0x114b3, 0x114b8],
    0x114ba,
    [0x114bf, 0x114c0],
    [0x114c2, 0x114c3],
    [0x115b2, 0x115b5],
    [0x115bc, 0x115bd],
    [0x115bf, 0x115c0],
    [0x115dc, 0x115dd],
    [0x11633, 0x1163a],
    0x1163d,
    [0x1163f, 0x11640],
    0x116ab,
    0x116ad,
    [0x116b0, 0x116b5],
    0x116b7,
    [0x1171d, 0x1171f],
    [0x11722, 0x11725],
    [0x11727, 0x1172b],
    [0x1182f, 0x11837],
    [0x11839, 0x1183a],
    [0x1193b, 0x1193c],
    0x1193e,
    0x11943,
    [0x119d4, 0x119d7],
    [0x119da, 0x119db],
    0x119e0,
    [0x11a01, 0x11a0a],
    [0x11a33, 0x11a38],
    [0x11a3b, 0x11a3e],
    0x11a47,
    [0x11a51, 0x11a56],
    [0x11a59, 0x11a5b],
    [0x11a8a, 0x11a96],
    [0x11a98, 0x11a99],
    [0x11c30, 0x11c36],
    [0x11c38, 0x11c3d],
    0x11c3f,
    [0x11c92, 0x11ca7],
    [0x11caa, 0x11cb0],
    [0x11cb2, 0x11cb3],
    [0x11cb5, 0x11cb6],
    [0x11d31, 0x11d36],
    0x11d3a,
    [0x11d3c, 0x11d3d],
    [0x11d3f, 0x11d45],
    0x11d47,
    [0x11d90, 0x11d91],
    0x11d95,
    0x11d97,
    [0x11ef3, 0x11ef4],
    [0x11f00, 0x11f01],
    [0x11f36, 0x11f3a],
    0x11f40,
    0x11f42,
    0x13440,
    [0x13447, 0x13455],
    [0x16af0, 0x16af4],
    [0x16b30, 0x16b36],
    0x16f4f,
    [0x16f8f, 0x16f92],
    0x16fe4,
    [0x1bc9d, 0x1bc9e],
    [0x1cf00, 0x1cf2d],
    [0x1cf30, 0x1cf46],
    [0x1d167, 0x1d169],
    [0x1d17b, 0x1d182],
    [0x1d185, 0x1d18b],
    [0x1d1aa, 0x1d1ad],
    [0x1d242, 0x1d244],
    [0x1da00, 0x1da36],
    [0x1da3b, 0x1da6c],
    0x1da75,
    0x1da84,
    [0x1da9b, 0x1da9f],
    [0x1daa1, 0x1daaf],
    [0x1e000, 0x1e006],
    [0x1e008, 0x1e018],
    [0x1e01b, 0x1e021],
    [0x1e023, 0x1e024],
    [0x1e026, 0x1e02a],
    0x1e08f,
    [0x1e130, 0x1e136],
    0x1e2ae,
    [0x1e2ec, 0x1e2ef],
    [0x1e4ec, 0x1e4ef],
    [0x1e8d0, 0x1e8d6],
    [0x1e944, 0x1e94a],
    [0xe0100, 0xe01ef],
];
exports.unicodeMnSurrogate = {
    0xd800: [
        0xddfd,
        0xdee0,
        [0xdf76, 0xdf7a], // 0x10376..0x1037A
    ],
    0xd802: [
        [0xde01, 0xde03],
        [0xde05, 0xde06],
        [0xde0c, 0xde0f],
        [0xde38, 0xde3a],
        0xde3f,
        [0xdee5, 0xdee6], // 0x10AE5..0x10AE6
    ],
    0xd803: [
        [0xdd24, 0xdd27],
        [0xdeab, 0xdeac],
        [0xdefd, 0xdeff],
        [0xdf46, 0xdf50],
        [0xdf82, 0xdf85], // 0x10F82..0x10F85
    ],
    0xd804: [
        0xdc01,
        [0xdc38, 0xdc46],
        0xdc70,
        [0xdc73, 0xdc74],
        [0xdc7f, 0xdc81],
        [0xdcb3, 0xdcb6],
        [0xdcb9, 0xdcba],
        0xdcc2,
        [0xdd00, 0xdd02],
        [0xdd27, 0xdd2b],
        [0xdd2d, 0xdd34],
        0xdd73,
        [0xdd80, 0xdd81],
        [0xddb6, 0xddbe],
        [0xddc9, 0xddcc],
        0xddcf,
        [0xde2f, 0xde31],
        0xde34,
        [0xde36, 0xde37],
        0xde3e,
        0xde41,
        0xdedf,
        [0xdee3, 0xdeea],
        [0xdf00, 0xdf01],
        [0xdf3b, 0xdf3c],
        0xdf40,
        [0xdf66, 0xdf6c],
        [0xdf70, 0xdf74], // 0x11370..0x11374
    ],
    0xd805: [
        [0xdc38, 0xdc3f],
        [0xdc42, 0xdc44],
        0xdc46,
        0xdc5e,
        [0xdcb3, 0xdcb8],
        0xdcba,
        [0xdcbf, 0xdcc0],
        [0xdcc2, 0xdcc3],
        [0xddb2, 0xddb5],
        [0xddbc, 0xddbd],
        [0xddbf, 0xddc0],
        [0xdddc, 0xdddd],
        [0xde33, 0xde3a],
        0xde3d,
        [0xde3f, 0xde40],
        0xdeab,
        0xdead,
        [0xdeb0, 0xdeb5],
        0xdeb7,
        [0xdf1d, 0xdf1f],
        [0xdf22, 0xdf25],
        [0xdf27, 0xdf2b], // 0x11727..0x1172B
    ],
    0xd806: [
        [0xdc2f, 0xdc37],
        [0xdc39, 0xdc3a],
        [0xdd3b, 0xdd3c],
        0xdd3e,
        0xdd43,
        [0xddd4, 0xddd7],
        [0xddda, 0xdddb],
        0xdde0,
        [0xde01, 0xde0a],
        [0xde33, 0xde38],
        [0xde3b, 0xde3e],
        0xde47,
        [0xde51, 0xde56],
        [0xde59, 0xde5b],
        [0xde8a, 0xde96],
        [0xde98, 0xde99], // 0x11A98..0x11A99
    ],
    0xd807: [
        [0xdc30, 0xdc36],
        [0xdc38, 0xdc3d],
        0xdc3f,
        [0xdc92, 0xdca7],
        [0xdcaa, 0xdcb0],
        [0xdcb2, 0xdcb3],
        [0xdcb5, 0xdcb6],
        [0xdd31, 0xdd36],
        0xdd3a,
        [0xdd3c, 0xdd3d],
        [0xdd3f, 0xdd45],
        0xdd47,
        [0xdd90, 0xdd91],
        0xdd95,
        0xdd97,
        [0xdef3, 0xdef4],
        [0xdf00, 0xdf01],
        [0xdf36, 0xdf3a],
        0xdf40,
        0xdf42, // 0x11F42
    ],
    0xd80d: [
        0xdc40,
        [0xdc47, 0xdc55], // 0x13447..0x13455
    ],
    0xd81a: [
        [0xdef0, 0xdef4],
        [0xdf30, 0xdf36], // 0x16B30..0x16B36
    ],
    0xd81b: [
        0xdf4f,
        [0xdf8f, 0xdf92],
        0xdfe4, // 0x16FE4
    ],
    0xd82f: [
        [0xdc9d, 0xdc9e], // 0x1BC9D..0x1BC9E
    ],
    0xd833: [
        [0xdf00, 0xdf2d],
        [0xdf30, 0xdf46], // 0x1CF30..0x1CF46
    ],
    0xd834: [
        [0xdd67, 0xdd69],
        [0xdd7b, 0xdd82],
        [0xdd85, 0xdd8b],
        [0xddaa, 0xddad],
        [0xde42, 0xde44], // 0x1D242..0x1D244
    ],
    0xd836: [
        [0xde00, 0xde36],
        [0xde3b, 0xde6c],
        0xde75,
        0xde84,
        [0xde9b, 0xde9f],
        [0xdea1, 0xdeaf], // 0x1DAA1..0x1DAAF
    ],
    0xd838: [
        [0xdc00, 0xdc06],
        [0xdc08, 0xdc18],
        [0xdc1b, 0xdc21],
        [0xdc23, 0xdc24],
        [0xdc26, 0xdc2a],
        0xdc8f,
        [0xdd30, 0xdd36],
        0xdeae,
        [0xdeec, 0xdeef], // 0x1E2EC..0x1E2EF
    ],
    0xd839: [
        [0xdcec, 0xdcef], // 0x1E4EC..0x1E4EF
    ],
    0xd83a: [
        [0xdcd0, 0xdcd6],
        [0xdd44, 0xdd4a], // 0x1E944..0x1E94A
    ],
    0xdb40: [
        [0xdd00, 0xddef], // 0xE0100..0xE01EF
    ],
};
exports.unicodeMc = [
    0x0903,
    0x093b,
    [0x093e, 0x0940],
    [0x0949, 0x094c],
    [0x094e, 0x094f],
    [0x0982, 0x0983],
    [0x09be, 0x09c0],
    [0x09c7, 0x09c8],
    [0x09cb, 0x09cc],
    0x09d7,
    0x0a03,
    [0x0a3e, 0x0a40],
    0x0a83,
    [0x0abe, 0x0ac0],
    0x0ac9,
    [0x0acb, 0x0acc],
    [0x0b02, 0x0b03],
    0x0b3e,
    0x0b40,
    [0x0b47, 0x0b48],
    [0x0b4b, 0x0b4c],
    0x0b57,
    [0x0bbe, 0x0bbf],
    [0x0bc1, 0x0bc2],
    [0x0bc6, 0x0bc8],
    [0x0bca, 0x0bcc],
    0x0bd7,
    [0x0c01, 0x0c03],
    [0x0c41, 0x0c44],
    [0x0c82, 0x0c83],
    0x0cbe,
    [0x0cc0, 0x0cc4],
    [0x0cc7, 0x0cc8],
    [0x0cca, 0x0ccb],
    [0x0cd5, 0x0cd6],
    0x0cf3,
    [0x0d02, 0x0d03],
    [0x0d3e, 0x0d40],
    [0x0d46, 0x0d48],
    [0x0d4a, 0x0d4c],
    0x0d57,
    [0x0d82, 0x0d83],
    [0x0dcf, 0x0dd1],
    [0x0dd8, 0x0ddf],
    [0x0df2, 0x0df3],
    [0x0f3e, 0x0f3f],
    0x0f7f,
    [0x102b, 0x102c],
    0x1031,
    0x1038,
    [0x103b, 0x103c],
    [0x1056, 0x1057],
    [0x1062, 0x1064],
    [0x1067, 0x106d],
    [0x1083, 0x1084],
    [0x1087, 0x108c],
    0x108f,
    [0x109a, 0x109c],
    0x1715,
    0x1734,
    0x17b6,
    [0x17be, 0x17c5],
    [0x17c7, 0x17c8],
    [0x1923, 0x1926],
    [0x1929, 0x192b],
    [0x1930, 0x1931],
    [0x1933, 0x1938],
    [0x1a19, 0x1a1a],
    0x1a55,
    0x1a57,
    0x1a61,
    [0x1a63, 0x1a64],
    [0x1a6d, 0x1a72],
    0x1b04,
    0x1b35,
    0x1b3b,
    [0x1b3d, 0x1b41],
    [0x1b43, 0x1b44],
    0x1b82,
    0x1ba1,
    [0x1ba6, 0x1ba7],
    0x1baa,
    0x1be7,
    [0x1bea, 0x1bec],
    0x1bee,
    [0x1bf2, 0x1bf3],
    [0x1c24, 0x1c2b],
    [0x1c34, 0x1c35],
    0x1ce1,
    0x1cf7,
    [0x302e, 0x302f],
    [0xa823, 0xa824],
    0xa827,
    [0xa880, 0xa881],
    [0xa8b4, 0xa8c3],
    [0xa952, 0xa953],
    0xa983,
    [0xa9b4, 0xa9b5],
    [0xa9ba, 0xa9bb],
    [0xa9be, 0xa9c0],
    [0xaa2f, 0xaa30],
    [0xaa33, 0xaa34],
    0xaa4d,
    0xaa7b,
    0xaa7d,
    0xaaeb,
    [0xaaee, 0xaaef],
    0xaaf5,
    [0xabe3, 0xabe4],
    [0xabe6, 0xabe7],
    [0xabe9, 0xabea],
    0xabec,
    0x11000,
    0x11002,
    0x11082,
    [0x110b0, 0x110b2],
    [0x110b7, 0x110b8],
    0x1112c,
    [0x11145, 0x11146],
    0x11182,
    [0x111b3, 0x111b5],
    [0x111bf, 0x111c0],
    0x111ce,
    [0x1122c, 0x1122e],
    [0x11232, 0x11233],
    0x11235,
    [0x112e0, 0x112e2],
    [0x11302, 0x11303],
    [0x1133e, 0x1133f],
    [0x11341, 0x11344],
    [0x11347, 0x11348],
    [0x1134b, 0x1134d],
    0x11357,
    [0x11362, 0x11363],
    [0x11435, 0x11437],
    [0x11440, 0x11441],
    0x11445,
    [0x114b0, 0x114b2],
    0x114b9,
    [0x114bb, 0x114be],
    0x114c1,
    [0x115af, 0x115b1],
    [0x115b8, 0x115bb],
    0x115be,
    [0x11630, 0x11632],
    [0x1163b, 0x1163c],
    0x1163e,
    0x116ac,
    [0x116ae, 0x116af],
    0x116b6,
    [0x11720, 0x11721],
    0x11726,
    [0x1182c, 0x1182e],
    0x11838,
    [0x11930, 0x11935],
    [0x11937, 0x11938],
    0x1193d,
    0x11940,
    0x11942,
    [0x119d1, 0x119d3],
    [0x119dc, 0x119df],
    0x119e4,
    0x11a39,
    [0x11a57, 0x11a58],
    0x11a97,
    0x11c2f,
    0x11c3e,
    0x11ca9,
    0x11cb1,
    0x11cb4,
    [0x11d8a, 0x11d8e],
    [0x11d93, 0x11d94],
    0x11d96,
    [0x11ef5, 0x11ef6],
    0x11f03,
    [0x11f34, 0x11f35],
    [0x11f3e, 0x11f3f],
    0x11f41,
    [0x16f51, 0x16f87],
    [0x16ff0, 0x16ff1],
    [0x1d165, 0x1d166],
    [0x1d16d, 0x1d172],
];
exports.unicodeMcSurrogate = {
    0xd804: [
        0xdc00,
        0xdc02,
        0xdc82,
        [0xdcb0, 0xdcb2],
        [0xdcb7, 0xdcb8],
        0xdd2c,
        [0xdd45, 0xdd46],
        0xdd82,
        [0xddb3, 0xddb5],
        [0xddbf, 0xddc0],
        0xddce,
        [0xde2c, 0xde2e],
        [0xde32, 0xde33],
        0xde35,
        [0xdee0, 0xdee2],
        [0xdf02, 0xdf03],
        [0xdf3e, 0xdf3f],
        [0xdf41, 0xdf44],
        [0xdf47, 0xdf48],
        [0xdf4b, 0xdf4d],
        0xdf57,
        [0xdf62, 0xdf63], // 0x11362..0x11363
    ],
    0xd805: [
        [0xdc35, 0xdc37],
        [0xdc40, 0xdc41],
        0xdc45,
        [0xdcb0, 0xdcb2],
        0xdcb9,
        [0xdcbb, 0xdcbe],
        0xdcc1,
        [0xddaf, 0xddb1],
        [0xddb8, 0xddbb],
        0xddbe,
        [0xde30, 0xde32],
        [0xde3b, 0xde3c],
        0xde3e,
        0xdeac,
        [0xdeae, 0xdeaf],
        0xdeb6,
        [0xdf20, 0xdf21],
        0xdf26, // 0x11726
    ],
    0xd806: [
        [0xdc2c, 0xdc2e],
        0xdc38,
        [0xdd30, 0xdd35],
        [0xdd37, 0xdd38],
        0xdd3d,
        0xdd40,
        0xdd42,
        [0xddd1, 0xddd3],
        [0xdddc, 0xdddf],
        0xdde4,
        0xde39,
        [0xde57, 0xde58],
        0xde97, // 0x11A97
    ],
    0xd807: [
        0xdc2f,
        0xdc3e,
        0xdca9,
        0xdcb1,
        0xdcb4,
        [0xdd8a, 0xdd8e],
        [0xdd93, 0xdd94],
        0xdd96,
        [0xdef5, 0xdef6],
        0xdf03,
        [0xdf34, 0xdf35],
        [0xdf3e, 0xdf3f],
        0xdf41, // 0x11F41
    ],
    0xd81b: [
        [0xdf51, 0xdf87],
        [0xdff0, 0xdff1], // 0x16FF0..0x16FF1
    ],
    0xd834: [
        [0xdd65, 0xdd66],
        [0xdd6d, 0xdd72], // 0x1D16D..0x1D172
    ],
};
exports.unicodeNd = [
    [0x0030, 0x0039],
    [0x0660, 0x0669],
    [0x06f0, 0x06f9],
    [0x07c0, 0x07c9],
    [0x0966, 0x096f],
    [0x09e6, 0x09ef],
    [0x0a66, 0x0a6f],
    [0x0ae6, 0x0aef],
    [0x0b66, 0x0b6f],
    [0x0be6, 0x0bef],
    [0x0c66, 0x0c6f],
    [0x0ce6, 0x0cef],
    [0x0d66, 0x0d6f],
    [0x0de6, 0x0def],
    [0x0e50, 0x0e59],
    [0x0ed0, 0x0ed9],
    [0x0f20, 0x0f29],
    [0x1040, 0x1049],
    [0x1090, 0x1099],
    [0x17e0, 0x17e9],
    [0x1810, 0x1819],
    [0x1946, 0x194f],
    [0x19d0, 0x19d9],
    [0x1a80, 0x1a89],
    [0x1a90, 0x1a99],
    [0x1b50, 0x1b59],
    [0x1bb0, 0x1bb9],
    [0x1c40, 0x1c49],
    [0x1c50, 0x1c59],
    [0xa620, 0xa629],
    [0xa8d0, 0xa8d9],
    [0xa900, 0xa909],
    [0xa9d0, 0xa9d9],
    [0xa9f0, 0xa9f9],
    [0xaa50, 0xaa59],
    [0xabf0, 0xabf9],
    [0xff10, 0xff19],
    [0x104a0, 0x104a9],
    [0x10d30, 0x10d39],
    [0x11066, 0x1106f],
    [0x110f0, 0x110f9],
    [0x11136, 0x1113f],
    [0x111d0, 0x111d9],
    [0x112f0, 0x112f9],
    [0x11450, 0x11459],
    [0x114d0, 0x114d9],
    [0x11650, 0x11659],
    [0x116c0, 0x116c9],
    [0x11730, 0x11739],
    [0x118e0, 0x118e9],
    [0x11950, 0x11959],
    [0x11c50, 0x11c59],
    [0x11d50, 0x11d59],
    [0x11da0, 0x11da9],
    [0x11f50, 0x11f59],
    [0x16a60, 0x16a69],
    [0x16ac0, 0x16ac9],
    [0x16b50, 0x16b59],
    [0x1d7ce, 0x1d7ff],
    [0x1e140, 0x1e149],
    [0x1e2f0, 0x1e2f9],
    [0x1e4f0, 0x1e4f9],
    [0x1e950, 0x1e959],
    [0x1fbf0, 0x1fbf9],
];
exports.unicodeNdSurrogate = {
    0xd801: [
        [0xdca0, 0xdca9], // 0x104A0..0x104A9
    ],
    0xd803: [
        [0xdd30, 0xdd39], // 0x10D30..0x10D39
    ],
    0xd804: [
        [0xdc66, 0xdc6f],
        [0xdcf0, 0xdcf9],
        [0xdd36, 0xdd3f],
        [0xddd0, 0xddd9],
        [0xdef0, 0xdef9], // 0x112F0..0x112F9
    ],
    0xd805: [
        [0xdc50, 0xdc59],
        [0xdcd0, 0xdcd9],
        [0xde50, 0xde59],
        [0xdec0, 0xdec9],
        [0xdf30, 0xdf39], // 0x11730..0x11739
    ],
    0xd806: [
        [0xdce0, 0xdce9],
        [0xdd50, 0xdd59], // 0x11950..0x11959
    ],
    0xd807: [
        [0xdc50, 0xdc59],
        [0xdd50, 0xdd59],
        [0xdda0, 0xdda9],
        [0xdf50, 0xdf59], // 0x11F50..0x11F59
    ],
    0xd81a: [
        [0xde60, 0xde69],
        [0xdec0, 0xdec9],
        [0xdf50, 0xdf59], // 0x16B50..0x16B59
    ],
    0xd835: [
        [0xdfce, 0xdfff], // 0x1D7CE..0x1D7FF
    ],
    0xd838: [
        [0xdd40, 0xdd49],
        [0xdef0, 0xdef9], // 0x1E2F0..0x1E2F9
    ],
    0xd839: [
        [0xdcf0, 0xdcf9], // 0x1E4F0..0x1E4F9
    ],
    0xd83a: [
        [0xdd50, 0xdd59], // 0x1E950..0x1E959
    ],
    0xd83e: [
        [0xdff0, 0xdff9], // 0x1FBF0..0x1FBF9
    ],
};
exports.unicodePc = [
    0x005f,
    [0x203f, 0x2040],
    0x2054,
    [0xfe33, 0xfe34],
    [0xfe4d, 0xfe4f],
    0xff3f,
];


/***/ }),

/***/ "../pyright-internal/src/pyrightFileSystem.ts":
/*!****************************************************!*\
  !*** ../pyright-internal/src/pyrightFileSystem.ts ***!
  \****************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * pyrightFileSystem.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * A file system that knows how to deal with partial stub files.
 * Files within a partial stub package act as though they are
 * copied into the associated package, and the combined set of
 * files is treated as one.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PyrightFileSystem = exports.SupportPartialStubs = void 0;
const pyTypedUtils_1 = __webpack_require__(/*! ./analyzer/pyTypedUtils */ "../pyright-internal/src/analyzer/pyTypedUtils.ts");
const pathConsts_1 = __webpack_require__(/*! ./common/pathConsts */ "../pyright-internal/src/common/pathConsts.ts");
const uriUtils_1 = __webpack_require__(/*! ./common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const readonlyAugmentedFileSystem_1 = __webpack_require__(/*! ./readonlyAugmentedFileSystem */ "../pyright-internal/src/readonlyAugmentedFileSystem.ts");
var SupportPartialStubs;
(function (SupportPartialStubs) {
    function is(value) {
        return (value.isPartialStubPackagesScanned &&
            value.isPathScanned &&
            value.processPartialStubPackages &&
            value.clearPartialStubs);
    }
    SupportPartialStubs.is = is;
})(SupportPartialStubs || (exports.SupportPartialStubs = SupportPartialStubs = {}));
class PyrightFileSystem extends readonlyAugmentedFileSystem_1.ReadOnlyAugmentedFileSystem {
    constructor(realFS) {
        super(realFS);
        // Root paths processed
        this._rootSearched = new Set();
        // Partial stub package paths processed
        this._partialStubPackagePaths = new Set();
    }
    mkdirSync(uri, options) {
        this.realFS.mkdirSync(uri, options);
    }
    chdir(uri) {
        this.realFS.chdir(uri);
    }
    writeFileSync(uri, data, encoding) {
        this.realFS.writeFileSync(this.getOriginalPath(uri), data, encoding);
    }
    rmdirSync(uri) {
        this.realFS.rmdirSync(this.getOriginalPath(uri));
    }
    unlinkSync(uri) {
        this.realFS.unlinkSync(this.getOriginalPath(uri));
    }
    createWriteStream(uri) {
        return this.realFS.createWriteStream(this.getOriginalPath(uri));
    }
    copyFileSync(src, dst) {
        this.realFS.copyFileSync(this.getOriginalPath(src), this.getOriginalPath(dst));
    }
    isPartialStubPackagesScanned(execEnv) {
        return execEnv.root ? this.isPathScanned(execEnv.root) : false;
    }
    isPathScanned(uri) {
        return this._rootSearched.has(uri.key);
    }
    processPartialStubPackages(paths, roots, bundledStubPath, allowMoving) {
        var _a;
        const allowMovingFn = allowMoving !== null && allowMoving !== void 0 ? allowMoving : this._allowMoving.bind(this);
        for (const path of paths) {
            this._rootSearched.add(path.key);
            if (!this.realFS.existsSync(path) || !(0, uriUtils_1.isDirectory)(this.realFS, path)) {
                continue;
            }
            let dirEntries = [];
            try {
                dirEntries = this.realFS.readdirEntriesSync(path);
            }
            catch {
                // Leave empty set of dir entries to process.
            }
            const isBundledStub = path.equals(bundledStubPath);
            for (const entry of dirEntries) {
                const partialStubPackagePath = path.combinePaths(entry.name);
                const isDirectory = !entry.isSymbolicLink()
                    ? entry.isDirectory()
                    : !!((_a = (0, uriUtils_1.tryStat)(this.realFS, partialStubPackagePath)) === null || _a === void 0 ? void 0 : _a.isDirectory());
                if (!isDirectory || !entry.name.endsWith(pathConsts_1.stubsSuffix)) {
                    continue;
                }
                const pyTypedInfo = (0, pyTypedUtils_1.getPyTypedInfo)(this.realFS, partialStubPackagePath);
                if (!pyTypedInfo || !pyTypedInfo.isPartiallyTyped) {
                    // Stub-Package is fully typed.
                    continue;
                }
                // We found partially typed stub-packages.
                this._partialStubPackagePaths.add(partialStubPackagePath.key);
                // Search the root to see whether we have matching package installed.
                let partialStubs;
                const packageName = entry.name.substr(0, entry.name.length - pathConsts_1.stubsSuffix.length);
                for (const root of roots) {
                    const packagePath = root.combinePaths(packageName);
                    try {
                        const stat = (0, uriUtils_1.tryStat)(this.realFS, packagePath);
                        if (!(stat === null || stat === void 0 ? void 0 : stat.isDirectory())) {
                            continue;
                        }
                        // If partial stub we found is from bundled stub and library installed is marked as py.typed
                        // ignore bundled partial stub.
                        if (!allowMovingFn(isBundledStub, (0, pyTypedUtils_1.getPyTypedInfo)(this.realFS, packagePath), pyTypedInfo)) {
                            continue;
                        }
                        // Merge partial stub packages to the library.
                        partialStubs = partialStubs !== null && partialStubs !== void 0 ? partialStubs : this._getRelativePathPartialStubs(partialStubPackagePath);
                        for (const partialStub of partialStubs) {
                            const originalPyiFile = partialStubPackagePath.resolvePaths(partialStub);
                            const mappedPyiFile = packagePath.resolvePaths(partialStub);
                            this.recordMovedEntry(mappedPyiFile, originalPyiFile, packagePath);
                        }
                    }
                    catch {
                        // ignore
                    }
                }
            }
        }
    }
    clearPartialStubs() {
        super.clear();
        this._rootSearched.clear();
        this._partialStubPackagePaths.clear();
    }
    isMovedEntry(uri) {
        return this._partialStubPackagePaths.has(uri.key) || super.isMovedEntry(uri);
    }
    _allowMoving(isBundled, packagePyTyped, _stubPyTyped) {
        if (!isBundled) {
            return true;
        }
        // If partial stub we found is from bundled stub and library installed is marked as py.typed
        // allow moving only if the package is marked as partially typed.
        return !packagePyTyped || packagePyTyped.isPartiallyTyped;
    }
    _getRelativePathPartialStubs(partialStubPath) {
        const relativePaths = [];
        const searchAllStubs = (uri) => {
            for (const entry of this.realFS.readdirEntriesSync(uri)) {
                const filePath = uri.combinePaths(entry.name);
                let isDirectory = entry.isDirectory();
                let isFile = entry.isFile();
                if (entry.isSymbolicLink()) {
                    const stat = (0, uriUtils_1.tryStat)(this.realFS, filePath);
                    if (stat) {
                        isDirectory = stat.isDirectory();
                        isFile = stat.isFile();
                    }
                }
                if (isDirectory) {
                    searchAllStubs(filePath);
                }
                if (isFile && entry.name.endsWith('.pyi')) {
                    const relative = partialStubPath.getRelativePathComponents(filePath).join('/');
                    if (relative) {
                        relativePaths.push(relative);
                    }
                }
            }
        };
        searchAllStubs(partialStubPath);
        return relativePaths;
    }
}
exports.PyrightFileSystem = PyrightFileSystem;


/***/ }),

/***/ "../pyright-internal/src/readonlyAugmentedFileSystem.ts":
/*!**************************************************************!*\
  !*** ../pyright-internal/src/readonlyAugmentedFileSystem.ts ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * readonlyAugmentedFileSystem.ts
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 *
 * A file system that lets one to augment backing file system but not allow
 * modifying the backing file system.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ReadOnlyAugmentedFileSystem = void 0;
const collectionUtils_1 = __webpack_require__(/*! ./common/collectionUtils */ "../pyright-internal/src/common/collectionUtils.ts");
const fileSystem_1 = __webpack_require__(/*! ./common/fileSystem */ "../pyright-internal/src/common/fileSystem.ts");
class ReadOnlyAugmentedFileSystem {
    constructor(realFS) {
        this.realFS = realFS;
        // Mapped file to original file map
        this._entryMap = new Map();
        // Original file to mapped file map
        this._reverseEntryMap = new Map();
        // Mapped files per a containing folder map
        this._folderMap = new Map();
    }
    existsSync(uri) {
        if (this.isMovedEntry(uri)) {
            // Pretend partial stub folder and its files not exist
            return false;
        }
        return this.realFS.existsSync(this.getOriginalPath(uri));
    }
    mkdirSync(uri, options) {
        throw new Error('Operation is not allowed.');
    }
    chdir(uri) {
        throw new Error('Operation is not allowed.');
    }
    readdirEntriesSync(uri) {
        const entries = [];
        const movedEntries = this._folderMap.get(uri.key);
        if (!movedEntries || this.realFS.existsSync(uri)) {
            (0, collectionUtils_1.appendArray)(entries, this.realFS.readdirEntriesSync(uri).filter((item) => {
                // Filter out the stub package directory and any
                // entries that will be overwritten by stub package
                // virtual items.
                return (!this.isMovedEntry(uri.combinePaths(item.name)) &&
                    !(movedEntries === null || movedEntries === void 0 ? void 0 : movedEntries.some((movedEntry) => movedEntry.name === item.name)));
            }));
        }
        if (!movedEntries) {
            return entries;
        }
        return entries.concat(movedEntries.map((e) => new fileSystem_1.VirtualDirent(e.name, e.isFile)));
    }
    readdirSync(uri) {
        return this.readdirEntriesSync(uri).map((p) => p.name);
    }
    readFileSync(uri, encoding) {
        return this.realFS.readFileSync(this.getOriginalPath(uri), encoding);
    }
    writeFileSync(uri, data, encoding) {
        throw new Error('Operation is not allowed.');
    }
    statSync(uri) {
        return this.realFS.statSync(this.getOriginalPath(uri));
    }
    rmdirSync(uri) {
        throw new Error('Operation is not allowed.');
    }
    unlinkSync(uri) {
        throw new Error('Operation is not allowed.');
    }
    realpathSync(uri) {
        if (this._entryMap.has(uri.key)) {
            return uri;
        }
        return this.realFS.realpathSync(uri);
    }
    getModulePath() {
        return this.realFS.getModulePath();
    }
    createFileSystemWatcher(paths, listener) {
        return this.realFS.createFileSystemWatcher(paths, listener);
    }
    createReadStream(uri) {
        return this.realFS.createReadStream(this.getOriginalPath(uri));
    }
    createWriteStream(uri) {
        throw new Error('Operation is not allowed.');
    }
    copyFileSync(src, dst) {
        throw new Error('Operation is not allowed.');
    }
    // Async I/O
    readFile(uri) {
        return this.realFS.readFile(this.getOriginalPath(uri));
    }
    readFileText(uri, encoding) {
        return this.realFS.readFileText(this.getOriginalPath(uri), encoding);
    }
    realCasePath(uri) {
        return this.realFS.realCasePath(uri);
    }
    // See whether the file is mapped to another location.
    isMappedUri(fileUri) {
        return this._entryMap.has(fileUri.key) || this.realFS.isMappedUri(fileUri);
    }
    // Get original filepath if the given filepath is mapped.
    getOriginalUri(mappedFileUri) {
        return this.realFS.getOriginalUri(this.getOriginalPath(mappedFileUri));
    }
    // Get mapped filepath if the given filepath is mapped.
    getMappedUri(originalFileUri) {
        var _a;
        const mappedFileUri = this.realFS.getMappedUri(originalFileUri);
        return (_a = this._reverseEntryMap.get(mappedFileUri.key)) !== null && _a !== void 0 ? _a : mappedFileUri;
    }
    isInZip(uri) {
        return this.realFS.isInZip(uri);
    }
    recordMovedEntry(mappedUri, originalUri, rootPath) {
        this._entryMap.set(mappedUri.key, originalUri);
        this._reverseEntryMap.set(originalUri.key, mappedUri);
        const directory = mappedUri.getDirectory();
        const folderInfo = (0, collectionUtils_1.getOrAdd)(this._folderMap, directory.key, () => []);
        const name = mappedUri.fileName;
        if (!folderInfo.some((entry) => entry.name === name)) {
            folderInfo.push({ name, isFile: true });
        }
        // Add the directory entries for the sub paths as well.
        const subPathEntries = rootPath.getRelativePathComponents(directory);
        for (let i = 0; i < subPathEntries.length; i++) {
            const subdir = rootPath.combinePaths(...subPathEntries.slice(0, i + 1));
            const parent = subdir.getDirectory().key;
            const dirInfo = (0, collectionUtils_1.getOrAdd)(this._folderMap, parent, () => []);
            const dirName = subdir.fileName;
            if (!dirInfo.some((entry) => entry.name === dirName)) {
                dirInfo.push({ name: dirName, isFile: false });
            }
        }
    }
    getOriginalPath(mappedFileUri) {
        var _a;
        return (_a = this._entryMap.get(mappedFileUri.key)) !== null && _a !== void 0 ? _a : mappedFileUri;
    }
    isMovedEntry(uri) {
        return this._reverseEntryMap.has(uri.key);
    }
    clear() {
        this._entryMap.clear();
        this._reverseEntryMap.clear();
        this._folderMap.clear();
    }
}
exports.ReadOnlyAugmentedFileSystem = ReadOnlyAugmentedFileSystem;


/***/ }),

/***/ "../pyright-internal/src/server.ts":
/*!*****************************************!*\
  !*** ../pyright-internal/src/server.ts ***!
  \*****************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * server.ts
 *
 * Implements pyright language server.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PyrightServer = void 0;
const vscode_languageserver_1 = __webpack_require__(/*! vscode-languageserver */ "../pyright-internal/node_modules/vscode-languageserver/lib/node/main.js");
const cacheManager_1 = __webpack_require__(/*! ./analyzer/cacheManager */ "../pyright-internal/src/analyzer/cacheManager.ts");
const importResolver_1 = __webpack_require__(/*! ./analyzer/importResolver */ "../pyright-internal/src/analyzer/importResolver.ts");
const pythonPathUtils_1 = __webpack_require__(/*! ./analyzer/pythonPathUtils */ "../pyright-internal/src/analyzer/pythonPathUtils.ts");
const backgroundAnalysis_1 = __webpack_require__(/*! ./backgroundAnalysis */ "../pyright-internal/src/backgroundAnalysis.ts");
const commandController_1 = __webpack_require__(/*! ./commands/commandController */ "../pyright-internal/src/commands/commandController.ts");
const cancellationUtils_1 = __webpack_require__(/*! ./common/cancellationUtils */ "../pyright-internal/src/common/cancellationUtils.ts");
const configOptions_1 = __webpack_require__(/*! ./common/configOptions */ "../pyright-internal/src/common/configOptions.ts");
const console_1 = __webpack_require__(/*! ./common/console */ "../pyright-internal/src/common/console.ts");
const core_1 = __webpack_require__(/*! ./common/core */ "../pyright-internal/src/common/core.ts");
const envVarUtils_1 = __webpack_require__(/*! ./common/envVarUtils */ "../pyright-internal/src/common/envVarUtils.ts");
const fileBasedCancellationUtils_1 = __webpack_require__(/*! ./common/fileBasedCancellationUtils */ "../pyright-internal/src/common/fileBasedCancellationUtils.ts");
const fullAccessHost_1 = __webpack_require__(/*! ./common/fullAccessHost */ "../pyright-internal/src/common/fullAccessHost.ts");
const realFileSystem_1 = __webpack_require__(/*! ./common/realFileSystem */ "../pyright-internal/src/common/realFileSystem.ts");
const serviceProviderExtensions_1 = __webpack_require__(/*! ./common/serviceProviderExtensions */ "../pyright-internal/src/common/serviceProviderExtensions.ts");
const uri_1 = __webpack_require__(/*! ./common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
const uriUtils_1 = __webpack_require__(/*! ./common/uri/uriUtils */ "../pyright-internal/src/common/uri/uriUtils.ts");
const languageServerBase_1 = __webpack_require__(/*! ./languageServerBase */ "../pyright-internal/src/languageServerBase.ts");
const codeActionProvider_1 = __webpack_require__(/*! ./languageService/codeActionProvider */ "../pyright-internal/src/languageService/codeActionProvider.ts");
const pyrightFileSystem_1 = __webpack_require__(/*! ./pyrightFileSystem */ "../pyright-internal/src/pyrightFileSystem.ts");
const workspaceFactory_1 = __webpack_require__(/*! ./workspaceFactory */ "../pyright-internal/src/workspaceFactory.ts");
const constants_1 = __webpack_require__(/*! ./constants */ "../pyright-internal/src/constants.ts");
const maxAnalysisTimeInForeground = { openFilesTimeInMs: 50, noOpenFilesTimeInMs: 200 };
class PyrightServer extends languageServerBase_1.LanguageServerBase {
    constructor(connection, maxWorkers, realFileSystem) {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const version = (__webpack_require__(/*! ../package.json */ "../pyright-internal/package.json").version) || '';
        const tempFile = new realFileSystem_1.RealTempFile();
        const console = new console_1.ConsoleWithLogLevel(connection.console);
        const fileWatcherProvider = new realFileSystem_1.WorkspaceFileWatcherProvider();
        const fileSystem = realFileSystem !== null && realFileSystem !== void 0 ? realFileSystem : (0, realFileSystem_1.createFromRealFileSystem)(tempFile, console, fileWatcherProvider);
        const pyrightFs = new pyrightFileSystem_1.PyrightFileSystem(fileSystem);
        const cacheManager = new cacheManager_1.CacheManager(maxWorkers);
        const serviceProvider = (0, serviceProviderExtensions_1.createServiceProvider)(pyrightFs, tempFile, console, cacheManager);
        // When executed from CLI command (pyright-langserver), __rootDirectory is
        // already defined. When executed from VSCode extension, rootDirectory should
        // be __dirname.
        const rootDirectory = (0, uriUtils_1.getRootUri)(serviceProvider) || uri_1.Uri.file(__dirname, serviceProvider);
        const realPathRoot = pyrightFs.realCasePath(rootDirectory);
        super({
            productName: constants_1.toolName,
            rootDirectory: realPathRoot,
            version,
            serviceProvider,
            fileWatcherHandler: fileWatcherProvider,
            cancellationProvider: new fileBasedCancellationUtils_1.FileBasedCancellationProvider('bg'),
            maxAnalysisTimeInForeground,
            supportedCodeActions: [vscode_languageserver_1.CodeActionKind.QuickFix, vscode_languageserver_1.CodeActionKind.SourceOrganizeImports],
        }, connection);
        this._controller = new commandController_1.CommandController(this);
    }
    async getSettings(workspace) {
        const serverSettings = {
            watchForSourceChanges: true,
            watchForLibraryChanges: true,
            watchForConfigChanges: true,
            openFilesOnly: true,
            useLibraryCodeForTypes: true,
            disableLanguageServices: false,
            disableTaggedHints: false,
            disableOrganizeImports: false,
            typeCheckingMode: 'all',
            diagnosticSeverityOverrides: {},
            logLevel: console_1.LogLevel.Info,
            autoImportCompletions: true,
            functionSignatureDisplay: configOptions_1.SignatureDisplayType.formatted,
        };
        try {
            const workspaces = this.workspaceFactory.getNonDefaultWorkspaces(workspaceFactory_1.WellKnownWorkspaceKinds.Regular);
            const pythonSection = await this.getConfiguration(workspace.rootUri, 'python');
            if (pythonSection) {
                const pythonPath = pythonSection.pythonPath;
                if (pythonPath && (0, core_1.isString)(pythonPath) && !(0, pythonPathUtils_1.isPythonBinary)(pythonPath)) {
                    serverSettings.pythonPath = (0, envVarUtils_1.resolvePathWithEnvVariables)(workspace, pythonPath, workspaces);
                }
                const venvPath = pythonSection.venvPath;
                if (venvPath && (0, core_1.isString)(venvPath)) {
                    serverSettings.venvPath = (0, envVarUtils_1.resolvePathWithEnvVariables)(workspace, venvPath, workspaces);
                }
            }
            const pythonAnalysisSection = await this.getConfiguration(workspace.rootUri, 'basedpyright.analysis');
            if (pythonAnalysisSection) {
                const typeshedPaths = pythonAnalysisSection.typeshedPaths;
                if (typeshedPaths && Array.isArray(typeshedPaths) && typeshedPaths.length > 0) {
                    const typeshedPath = typeshedPaths[0];
                    if (typeshedPath && (0, core_1.isString)(typeshedPath)) {
                        serverSettings.typeshedPath = (0, envVarUtils_1.resolvePathWithEnvVariables)(workspace, typeshedPath, workspaces);
                    }
                }
                const stubPath = pythonAnalysisSection.stubPath;
                if (stubPath && (0, core_1.isString)(stubPath)) {
                    serverSettings.stubPath = (0, envVarUtils_1.resolvePathWithEnvVariables)(workspace, stubPath, workspaces);
                }
                const diagnosticSeverityOverrides = pythonAnalysisSection.diagnosticSeverityOverrides;
                if (diagnosticSeverityOverrides) {
                    for (const [name, value] of Object.entries(diagnosticSeverityOverrides)) {
                        const ruleName = this.getDiagnosticRuleName(name);
                        const severity = this.getSeverityOverrides(value);
                        if (ruleName && severity) {
                            serverSettings.diagnosticSeverityOverrides[ruleName] = severity;
                        }
                    }
                }
                if (pythonAnalysisSection.diagnosticMode !== undefined) {
                    serverSettings.openFilesOnly = this.isOpenFilesOnly(pythonAnalysisSection.diagnosticMode);
                }
                else if (pythonAnalysisSection.openFilesOnly !== undefined) {
                    serverSettings.openFilesOnly = !!pythonAnalysisSection.openFilesOnly;
                }
                if (pythonAnalysisSection.useLibraryCodeForTypes !== undefined) {
                    serverSettings.useLibraryCodeForTypes = !!pythonAnalysisSection.useLibraryCodeForTypes;
                }
                serverSettings.logLevel = (0, console_1.convertLogLevel)(pythonAnalysisSection.logLevel);
                serverSettings.autoSearchPaths = !!pythonAnalysisSection.autoSearchPaths;
                const extraPaths = pythonAnalysisSection.extraPaths;
                if (extraPaths && Array.isArray(extraPaths) && extraPaths.length > 0) {
                    serverSettings.extraPaths = extraPaths
                        .filter((p) => p && (0, core_1.isString)(p))
                        .map((p) => (0, envVarUtils_1.resolvePathWithEnvVariables)(workspace, p, workspaces))
                        .filter(core_1.isDefined);
                }
                serverSettings.includeFileSpecs = this._getStringValues(pythonAnalysisSection.include);
                serverSettings.excludeFileSpecs = this._getStringValues(pythonAnalysisSection.exclude);
                serverSettings.ignoreFileSpecs = this._getStringValues(pythonAnalysisSection.ignore);
                if (pythonAnalysisSection.typeCheckingMode !== undefined) {
                    serverSettings.typeCheckingMode = pythonAnalysisSection.typeCheckingMode;
                }
                if (pythonAnalysisSection.autoImportCompletions !== undefined) {
                    serverSettings.autoImportCompletions = pythonAnalysisSection.autoImportCompletions;
                }
                if (serverSettings.logLevel === console_1.LogLevel.Log &&
                    pythonAnalysisSection.logTypeEvaluationTime !== undefined) {
                    serverSettings.logTypeEvaluationTime = pythonAnalysisSection.logTypeEvaluationTime;
                }
                if (pythonAnalysisSection.typeEvaluationTimeThreshold !== undefined) {
                    serverSettings.typeEvaluationTimeThreshold = pythonAnalysisSection.typeEvaluationTimeThreshold;
                }
            }
            else {
                serverSettings.autoSearchPaths = true;
            }
            const pyrightSection = await this.getConfiguration(workspace.rootUri, 'basedpyright');
            if (pyrightSection) {
                if (pyrightSection.openFilesOnly !== undefined) {
                    serverSettings.openFilesOnly = !!pyrightSection.openFilesOnly;
                }
                if (pyrightSection.useLibraryCodeForTypes !== undefined) {
                    serverSettings.useLibraryCodeForTypes = !!pyrightSection.useLibraryCodeForTypes;
                }
                serverSettings.disableLanguageServices = !!pyrightSection.disableLanguageServices;
                serverSettings.disableTaggedHints = !!pyrightSection.disableTaggedHints;
                serverSettings.disableOrganizeImports = !!pyrightSection.disableOrganizeImports;
                const typeCheckingMode = pyrightSection.typeCheckingMode;
                if (typeCheckingMode && (0, core_1.isString)(typeCheckingMode)) {
                    serverSettings.typeCheckingMode = typeCheckingMode;
                }
            }
        }
        catch (error) {
            this.console.error(`Error reading settings: ${error}`);
        }
        return serverSettings;
    }
    createBackgroundAnalysis(serviceId) {
        if ((0, core_1.isDebugMode)() || !(0, cancellationUtils_1.getCancellationFolderName)()) {
            // Don't do background analysis if we're in debug mode or an old client
            // is used where cancellation is not supported.
            return undefined;
        }
        return new backgroundAnalysis_1.BackgroundAnalysis(this.serverOptions.serviceProvider);
    }
    createHost() {
        return new fullAccessHost_1.FullAccessHost(this.serverOptions.serviceProvider);
    }
    createImportResolver(serviceProvider, options, host) {
        const importResolver = new importResolver_1.ImportResolver(serviceProvider, options, host);
        // In case there was cached information in the file system related to
        // import resolution, invalidate it now.
        importResolver.invalidateCache();
        return importResolver;
    }
    executeCommand(params, token) {
        return this._controller.execute(params, token);
    }
    isLongRunningCommand(command) {
        return this._controller.isLongRunningCommand(command);
    }
    isRefactoringCommand(command) {
        return this._controller.isRefactoringCommand(command);
    }
    async executeCodeAction(params, token) {
        this.recordUserInteractionTime();
        const uri = uri_1.Uri.parse(params.textDocument.uri, this.serverOptions.serviceProvider);
        const workspace = await this.getWorkspaceForFile(uri);
        return codeActionProvider_1.CodeActionProvider.getCodeActionsForPosition(workspace, uri, params.range, params.context.only, token);
    }
    createProgressReporter() {
        // The old progress notifications are kept for backwards compatibility with
        // clients that do not support work done progress.
        let workDoneProgress;
        return {
            isEnabled: (data) => true,
            begin: () => {
                if (this.client.hasWindowProgressCapability) {
                    workDoneProgress = this.connection.window.createWorkDoneProgress();
                    workDoneProgress
                        .then((progress) => {
                        progress.begin('');
                    })
                        .ignoreErrors();
                }
                else {
                    this.connection.sendNotification('pyright/beginProgress');
                }
            },
            report: (message) => {
                if (workDoneProgress) {
                    workDoneProgress
                        .then((progress) => {
                        progress.report(message);
                    })
                        .ignoreErrors();
                }
                else {
                    this.connection.sendNotification('pyright/reportProgress', message);
                }
            },
            end: () => {
                if (workDoneProgress) {
                    workDoneProgress
                        .then((progress) => {
                        progress.done();
                    })
                        .ignoreErrors();
                    workDoneProgress = undefined;
                }
                else {
                    this.connection.sendNotification('pyright/endProgress');
                }
            },
        };
    }
    _getStringValues(values) {
        if (!values || !Array.isArray(values) || values.length === 0) {
            return [];
        }
        return values.filter((p) => p && (0, core_1.isString)(p));
    }
}
exports.PyrightServer = PyrightServer;


/***/ }),

/***/ "../pyright-internal/src/workspaceFactory.ts":
/*!***************************************************!*\
  !*** ../pyright-internal/src/workspaceFactory.ts ***!
  \***************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * workspaceFactory.ts
 *
 * Workspace management related functionality.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceFactory = exports.createInitStatus = exports.WorkspacePythonPathKind = exports.WellKnownWorkspaceKinds = void 0;
const deferred_1 = __webpack_require__(/*! ./common/deferred */ "../pyright-internal/src/common/deferred.ts");
const uri_1 = __webpack_require__(/*! ./common/uri/uri */ "../pyright-internal/src/common/uri/uri.ts");
let WorkspaceFactoryIdCounter = 0;
var WellKnownWorkspaceKinds;
(function (WellKnownWorkspaceKinds) {
    WellKnownWorkspaceKinds["Default"] = "default";
    WellKnownWorkspaceKinds["Regular"] = "regular";
    WellKnownWorkspaceKinds["Limited"] = "limited";
    WellKnownWorkspaceKinds["Cloned"] = "cloned";
    WellKnownWorkspaceKinds["Test"] = "test";
})(WellKnownWorkspaceKinds || (exports.WellKnownWorkspaceKinds = WellKnownWorkspaceKinds = {}));
var WorkspacePythonPathKind;
(function (WorkspacePythonPathKind) {
    WorkspacePythonPathKind["Immutable"] = "immutable";
    WorkspacePythonPathKind["Mutable"] = "mutable";
})(WorkspacePythonPathKind || (exports.WorkspacePythonPathKind = WorkspacePythonPathKind = {}));
function createInitStatus() {
    // Due to the way we get `python path`, `include/exclude` from settings to initialize workspace,
    // we need to wait for getSettings to finish before letting IDE features to use workspace (`isInitialized` field).
    // So most of cases, whenever we create new workspace, we send request to workspace/configuration right way
    // except one place which is `initialize` LSP call.
    // In `initialize` method where we create `initial workspace`, we can't do that since LSP spec doesn't allow
    // LSP server from sending any request to client until `initialized` method is called.
    // This flag indicates whether we had our initial updateSetting call or not after `initialized` call.
    let called = false;
    const deferred = (0, deferred_1.createDeferred)();
    const self = {
        promise: deferred.promise,
        resolve: () => {
            called = true;
            deferred.resolve();
        },
        markCalled: () => {
            called = true;
        },
        reset: () => {
            if (!called) {
                return self;
            }
            return createInitStatus();
        },
        resolved: () => {
            return deferred.resolved;
        },
    };
    return self;
}
exports.createInitStatus = createInitStatus;
class WorkspaceFactory {
    constructor(_console, _isWeb, _createService, _isPythonPathImmutable, _onWorkspaceCreated, _onWorkspaceRemoved, _serviceProvider) {
        this._console = _console;
        this._isWeb = _isWeb;
        this._createService = _createService;
        this._isPythonPathImmutable = _isPythonPathImmutable;
        this._onWorkspaceCreated = _onWorkspaceCreated;
        this._onWorkspaceRemoved = _onWorkspaceRemoved;
        this._serviceProvider = _serviceProvider;
        this._defaultWorkspacePath = '<default>';
        this._map = new Map();
        this._id = WorkspaceFactoryIdCounter++;
        this._console.log(`WorkspaceFactory ${this._id} created`);
    }
    handleInitialize(params) {
        // Create a service instance for each of the workspace folders.
        if (params.workspaceFolders) {
            params.workspaceFolders.forEach((folder) => {
                this._add(uri_1.Uri.parse(folder.uri, this._serviceProvider), folder.name, undefined, WorkspacePythonPathKind.Mutable, [WellKnownWorkspaceKinds.Regular]);
            });
        }
        else if (params.rootPath) {
            this._add(uri_1.Uri.file(params.rootPath, this._serviceProvider), '', undefined, WorkspacePythonPathKind.Mutable, [WellKnownWorkspaceKinds.Regular]);
        }
    }
    handleWorkspaceFoldersChanged(params) {
        params.removed.forEach((workspaceInfo) => {
            const uri = uri_1.Uri.parse(workspaceInfo.uri, this._serviceProvider);
            // Delete all workspaces for this folder. Even the ones generated for notebook kernels.
            const workspaces = this.getNonDefaultWorkspaces().filter((w) => w.rootUri.equals(uri));
            workspaces.forEach((w) => {
                this._remove(w);
            });
        });
        params.added.forEach((workspaceInfo) => {
            const uri = uri_1.Uri.parse(workspaceInfo.uri, this._serviceProvider);
            // If there's a workspace that contains this folder, we need to mimic files from this workspace to
            // to the new one. Otherwise the subfolder won't have the changes for the files in it.
            const containing = this.items().filter((w) => uri.startsWith(w.rootUri))[0];
            // Add the new workspace.
            const newWorkspace = this._add(uri, workspaceInfo.name, undefined, WorkspacePythonPathKind.Mutable, [
                WellKnownWorkspaceKinds.Regular,
            ]);
            // Move files from the containing workspace to the new one that are in the new folder.
            if (containing) {
                this._mimicOpenFiles(containing, newWorkspace, (f) => f.startsWith(uri));
            }
        });
    }
    items() {
        return Array.from(this._map.values());
    }
    applyPythonPath(workspace, newPythonPath) {
        // See if were allowed to apply the new python path
        if (workspace.pythonPathKind === WorkspacePythonPathKind.Mutable && newPythonPath) {
            const originalPythonPath = workspace.pythonPath;
            workspace.pythonPath = newPythonPath;
            // This may not be the workspace in our map. Update the workspace in the map too.
            // This can happen during startup were the Initialize creates a workspace and then
            // onDidChangeConfiguration is called right away.
            const key = this._getWorkspaceKey(workspace);
            const workspaceInMap = this._map.get(key);
            if (workspaceInMap) {
                workspaceInMap.pythonPath = newPythonPath;
            }
            // If the python path has changed, we may need to move the immutable files to the correct workspace.
            if (originalPythonPath && !newPythonPath.equals(originalPythonPath) && workspaceInMap) {
                // Potentially move immutable files from one workspace to another.
                this._moveImmutableFilesToCorrectWorkspace(originalPythonPath, workspaceInMap);
            }
        }
        // Return the python path that should be used (whether hardcoded or configured)
        return workspace.pythonPath;
    }
    clear() {
        this._map.forEach((workspace) => {
            workspace.isInitialized.resolve();
            workspace.service.dispose();
        });
        this._map.clear();
        this._console.log(`WorkspaceFactory ${this._id} clear`);
    }
    hasMultipleWorkspaces(kind) {
        if (this._map.size === 0 || this._map.size === 1) {
            return false;
        }
        let count = 0;
        for (const kv of this._map) {
            if (!kind || kv[1].kinds.some((k) => k === kind)) {
                count++;
            }
            if (count > 1) {
                return true;
            }
        }
        return false;
    }
    getContainingWorkspace(filePath, pythonPath) {
        return this._getBestRegularWorkspace(this.getNonDefaultWorkspaces(WellKnownWorkspaceKinds.Regular).filter((w) => filePath.startsWith(w.rootUri)), pythonPath);
    }
    moveFiles(filePaths, fromWorkspace, toWorkspace) {
        if (fromWorkspace === toWorkspace) {
            return;
        }
        try {
            filePaths.forEach((f) => {
                var _a, _b;
                const fileInfo = fromWorkspace.service.backgroundAnalysisProgram.program.getSourceFileInfo(f);
                if (fileInfo) {
                    // Copy the source file data (closing can destroy the sourceFile)
                    const version = (_a = fileInfo.sourceFile.getClientVersion()) !== null && _a !== void 0 ? _a : null;
                    const content = fileInfo.sourceFile.getFileContent() || '';
                    const ipythonMode = fileInfo.sourceFile.getIPythonMode();
                    const chainedSourceFile = (_b = fileInfo.chainedSourceFile) === null || _b === void 0 ? void 0 : _b.sourceFile.getUri();
                    // Remove the file from the old workspace first (closing will propagate to the toWorkspace automatically).
                    fromWorkspace.service.setFileClosed(f, /* isTracked */ false);
                    // Then open it in the toWorkspace so that it is marked tracked there.
                    toWorkspace.service.setFileOpened(f, version, content, ipythonMode, chainedSourceFile);
                }
            });
            // If the fromWorkspace has no more files in it (and it's an immutable pythonPath), then remove it.
            this.removeUnused(fromWorkspace);
        }
        catch (e) {
            this._console.error(e.toString());
        }
    }
    getNonDefaultWorkspaces(kind) {
        const workspaces = [];
        this._map.forEach((workspace) => {
            if (!workspace.rootUri) {
                return;
            }
            if (kind && !workspace.kinds.some((k) => k === kind)) {
                return;
            }
            workspaces.push(workspace);
        });
        return workspaces;
    }
    // Returns the best workspace for a file. Waits for the workspace to be finished handling other events before
    // returning the appropriate workspace.
    async getWorkspaceForFile(uri, pythonPath) {
        // Wait for all workspaces to be initialized before attempting to find the best workspace. Otherwise
        // the list of files won't be complete and the `contains` check might fail.
        await Promise.all(this.items().map((w) => w.isInitialized.promise));
        // Find or create best match.
        const workspace = await this._getOrCreateBestWorkspaceForFile(uri, pythonPath);
        // The workspace may have just been created. Wait for it to be initialized before returning it.
        await workspace.isInitialized.promise;
        return workspace;
    }
    getWorkspaceForFileSync(filePath, pythonPath) {
        // Find or create best match.
        return this._getOrCreateBestWorkspaceFileSync(filePath, pythonPath);
    }
    async getContainingWorkspacesForFile(filePath) {
        // Wait for all workspaces to be initialized before attempting to find the best workspace. Otherwise
        // the list of files won't be complete and the `contains` check might fail.
        await Promise.all(this.items().map((w) => w.isInitialized.promise));
        // Find or create best match.
        const workspaces = this.getContainingWorkspacesForFileSync(filePath);
        // The workspaces may have just been created, wait for them all to be initialized
        await Promise.all(workspaces.map((w) => w.isInitialized.promise));
        return workspaces;
    }
    getContainingWorkspacesForFileSync(fileUri) {
        // All workspaces that track the file should be considered.
        let workspaces = this.items().filter((w) => w.service.isTracked(fileUri));
        // If that list is empty, get the best workspace
        if (workspaces.length === 0) {
            workspaces.push(this._getOrCreateBestWorkspaceFileSync(fileUri, undefined));
        }
        // If the file is immutable, then only return that workspace.
        if (this._isPythonPathImmutable(fileUri)) {
            workspaces = workspaces.filter((w) => w.pythonPathKind === WorkspacePythonPathKind.Immutable);
        }
        return workspaces;
    }
    removeUnused(workspace) {
        // Only remove this workspace is it's not being used for immutable files and it's an immutable path kind.
        if (workspace.service.getOpenFiles().filter((f) => this._isPythonPathImmutable(f)).length === 0 &&
            workspace.pythonPathKind === WorkspacePythonPathKind.Immutable) {
            // Destroy the workspace since it only had immutable files in it.
            this._remove(workspace);
        }
    }
    async _moveImmutableFilesToCorrectWorkspace(oldPythonPath, mutableWorkspace) {
        var _a;
        // If the python path changes we may need to move some immutable files around.
        // For example, if a notebook had the old python path, we need to create a new workspace
        // for the notebook.
        // If a notebook has the new python path but is currently in a workspace with the path hardcoded, we need to move it to
        // this workspace.
        const oldPathFiles = mutableWorkspace.service.getOpenFiles().filter((f) => this._isPythonPathImmutable(f));
        const exitingWorkspaceWithSamePath = this.items().find((w) => w.pythonPath === mutableWorkspace.pythonPath && w !== mutableWorkspace);
        const newPathFiles = (_a = exitingWorkspaceWithSamePath === null || exitingWorkspaceWithSamePath === void 0 ? void 0 : exitingWorkspaceWithSamePath.service.getOpenFiles().filter((f) => this._isPythonPathImmutable(f))) !== null && _a !== void 0 ? _a : [];
        // Immutable files that were in this mutableWorkspace have to be moved
        // to a (potentially) new workspace (with the old path).
        if (oldPathFiles.length > 0) {
            // Given that all of these files were in the same workspace, there should be only
            // one immutable workspace for all of them. So we can just use the first file.
            const workspace = this._getOrCreateBestWorkspaceFileSync(oldPathFiles[0], oldPythonPath);
            if (workspace !== mutableWorkspace) {
                this.moveFiles(oldPathFiles, mutableWorkspace, workspace);
            }
        }
        // Immutable files from a different workspace (with the same path as the new path)
        // have to be moved to the mutable workspace (which now has the new path)
        if (exitingWorkspaceWithSamePath) {
            this.moveFiles(newPathFiles, exitingWorkspaceWithSamePath, mutableWorkspace);
            this.removeUnused(exitingWorkspaceWithSamePath);
        }
    }
    _add(rootUri, name, pythonPath, pythonPathKind, kinds) {
        const uri = rootUri !== null && rootUri !== void 0 ? rootUri : uri_1.Uri.empty();
        // Update the kind based if the uri is local or not
        if (!kinds.includes(WellKnownWorkspaceKinds.Default) && (!uri.isLocal() || this._isWeb)) {
            // Web based workspace should be limited.
            kinds = [...kinds, WellKnownWorkspaceKinds.Limited];
        }
        const result = {
            workspaceName: name,
            rootUri,
            kinds,
            pythonPath,
            pythonPathKind,
            service: this._createService(name, uri, kinds),
            disableLanguageServices: false,
            disableTaggedHints: false,
            disableOrganizeImports: false,
            disableWorkspaceSymbol: false,
            isInitialized: createInitStatus(),
            searchPathsToWatch: [],
            pythonEnvironmentName: pythonPath === null || pythonPath === void 0 ? void 0 : pythonPath.toString(),
        };
        // Stick in our map
        const key = this._getWorkspaceKey(result);
        // Make sure to delete existing workspaces if there are any.
        this._remove(result);
        this._console.log(`WorkspaceFactory ${this._id} add ${key}`);
        this._map.set(key, result);
        // Tell our owner we added something. Order matters here as we
        // don't want to fire the workspace created while the old copy of this
        // workspace is still in the map.
        this._onWorkspaceCreated(result);
        return result;
    }
    _remove(value) {
        const key = this._getWorkspaceKey(value);
        const workspace = this._map.get(key);
        if (workspace) {
            workspace.isInitialized.resolve();
            this._onWorkspaceRemoved(workspace);
            workspace.service.dispose();
            this._console.log(`WorkspaceFactory ${this._id} remove ${key}`);
            this._map.delete(key);
        }
    }
    _getDefaultWorkspaceKey(pythonPath) {
        return `${this._defaultWorkspacePath}:${pythonPath !== undefined ? pythonPath : WorkspacePythonPathKind.Mutable}`;
    }
    _getWorkspaceKey(value) {
        // Special the root path for the default workspace. It will be created
        // without a root path
        const rootPath = value.kinds.includes(WellKnownWorkspaceKinds.Default)
            ? this._defaultWorkspacePath
            : value.rootUri;
        // Key is defined by the rootPath and the pythonPath. We might include platform in this, but for now
        // platform is only used by the import resolver.
        return `${rootPath}:${value.pythonPathKind === WorkspacePythonPathKind.Mutable ? value.pythonPathKind : value.pythonPath}`;
    }
    async _getOrCreateBestWorkspaceForFile(uri, pythonPath) {
        var _a;
        // Find the current best workspace (without creating a new one)
        let bestInstance = this._getBestWorkspaceForFile(uri, pythonPath);
        // Make sure the best instance is initialized so that it has its pythonPath.
        await bestInstance.isInitialized.promise;
        // If this best instance doesn't match the pythonPath, then we need to create a new one.
        if (pythonPath !== undefined && !((_a = bestInstance.pythonPath) === null || _a === void 0 ? void 0 : _a.equals(pythonPath))) {
            bestInstance = this._createImmutableCopy(bestInstance, pythonPath);
        }
        return bestInstance;
    }
    _getOrCreateBestWorkspaceFileSync(uri, pythonPath) {
        var _a;
        // Find the current best workspace (without creating a new one)
        let bestInstance = this._getBestWorkspaceForFile(uri, pythonPath);
        // If this best instance doesn't match the pythonPath, then we need to create a new one.
        if (pythonPath !== undefined && !((_a = bestInstance.pythonPath) === null || _a === void 0 ? void 0 : _a.equals(pythonPath))) {
            bestInstance = this._createImmutableCopy(bestInstance, pythonPath);
        }
        return bestInstance;
    }
    _mimicOpenFiles(source, dest, predicate) {
        var _a;
        // All mutable open files in the first workspace should be opened in the new workspace.
        // Immutable files should stay where they are since they're tied to a specific workspace.
        const files = source.service.getOpenFiles().filter((f) => !this._isPythonPathImmutable(f));
        for (const file of files) {
            const sourceFileInfo = source.service.backgroundAnalysisProgram.program.getSourceFileInfo(file);
            if (sourceFileInfo && predicate(file)) {
                const sourceFile = sourceFileInfo.sourceFile;
                const fileContents = sourceFile.getFileContent();
                dest.service.setFileOpened(file, sourceFile.getClientVersion() || null, fileContents || '', sourceFile.getIPythonMode(), (_a = sourceFileInfo.chainedSourceFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getUri());
            }
        }
    }
    _createImmutableCopy(workspace, pythonPath) {
        const result = this._add(workspace.rootUri, workspace.workspaceName, pythonPath, WorkspacePythonPathKind.Immutable, workspace.kinds);
        // Copy over the open files
        this._mimicOpenFiles(workspace, result, () => true);
        return result;
    }
    _getBestWorkspaceForFile(uri, pythonPath) {
        var _a;
        let bestInstance;
        // The order of how we find the best matching workspace for the given file is
        // 1. The given file is the workspace itself (ex, a file being a virtual workspace itself).
        // 2. The given file matches the fileSpec of the service under the workspace
        //    (the file is a user file the workspace provides LSP service for).
        // 3. The given file doesn't match anything but we have only 1 regular workspace
        //    (ex, open a library file from the workspace).
        // 4. The given file doesn't match anything and there are multiple workspaces but one of workspaces
        //    contains the file (ex, open a library file already imported by a workspace).
        // 5. If none of the above works, then it matches the default workspace.
        // First find the workspaces that are tracking the file
        const regularWorkspaces = this.getNonDefaultWorkspaces(WellKnownWorkspaceKinds.Regular);
        const trackingWorkspaces = this.items()
            .filter((w) => w.service.isTracked(uri))
            .filter(isNormalWorkspace);
        // Then find the best in all of those that actually matches the pythonPath.
        bestInstance = this._getBestRegularWorkspace(trackingWorkspaces, pythonPath);
        // If it's not in a tracked workspace, see if we only have regular workspaces with the same
        // length root path
        if (bestInstance === undefined &&
            regularWorkspaces.every((w) => w.rootUri.getPathLength() === regularWorkspaces[0].rootUri.getPathLength())) {
            bestInstance = this._getBestRegularWorkspace(regularWorkspaces, pythonPath);
        }
        // If the regular workspaces don't all have the same length or they don't
        // actually match on the python path, then try the workspaces that already have the file open or scanned.
        if (bestInstance === undefined || !((_a = bestInstance.pythonPath) === null || _a === void 0 ? void 0 : _a.equals(pythonPath))) {
            bestInstance =
                this._getBestRegularWorkspace(regularWorkspaces.filter((w) => w.service.hasSourceFile(uri)), pythonPath) || bestInstance;
        }
        // If that still didn't work, that must mean we don't have a workspace. Create a default one.
        if (bestInstance === undefined) {
            bestInstance = this._getOrCreateDefaultWorkspace(pythonPath);
        }
        return bestInstance;
    }
    _getOrCreateDefaultWorkspace(pythonPath) {
        // Default key depends upon the pythonPath
        let defaultWorkspace = this._map.get(this._getDefaultWorkspaceKey(pythonPath));
        if (!defaultWorkspace) {
            // Create a default workspace for files that are outside
            // of all workspaces.
            defaultWorkspace = this._add(undefined, this._defaultWorkspacePath, pythonPath, pythonPath !== undefined ? WorkspacePythonPathKind.Immutable : WorkspacePythonPathKind.Mutable, [WellKnownWorkspaceKinds.Default]);
        }
        return defaultWorkspace;
    }
    _getLongestPathWorkspace(workspaces) {
        const longestPath = workspaces.reduce((previousPath, currentWorkspace) => {
            if (!previousPath) {
                return currentWorkspace.rootUri;
            }
            if (currentWorkspace.rootUri.getPathLength() > previousPath.getPathLength()) {
                return currentWorkspace.rootUri;
            }
            return previousPath;
        }, uri_1.Uri.empty());
        return workspaces.find((w) => w.rootUri === longestPath);
    }
    _getBestRegularWorkspace(workspaces, pythonPath) {
        if (workspaces.length === 0) {
            return undefined;
        }
        // If there's only one, then it's the best.
        if (workspaces.length === 1) {
            return workspaces[0];
        }
        // If there's any that match the python path, take the one with the longest path from those.
        if (pythonPath !== undefined) {
            const matchingWorkspaces = workspaces.filter((w) => w.pythonPath === pythonPath);
            if (matchingWorkspaces.length > 0) {
                return this._getLongestPathWorkspace(matchingWorkspaces);
            }
        }
        // Otherwise, just take the longest path.
        return this._getLongestPathWorkspace(workspaces);
    }
}
exports.WorkspaceFactory = WorkspaceFactory;
function isNormalWorkspace(workspace) {
    return !!workspace.rootUri;
}


/***/ }),

/***/ "assert":
/*!*************************!*\
  !*** external "assert" ***!
  \*************************/
/***/ ((module) => {

"use strict";
module.exports = require("assert");

/***/ }),

/***/ "child_process":
/*!********************************!*\
  !*** external "child_process" ***!
  \********************************/
/***/ ((module) => {

"use strict";
module.exports = require("child_process");

/***/ }),

/***/ "crypto":
/*!*************************!*\
  !*** external "crypto" ***!
  \*************************/
/***/ ((module) => {

"use strict";
module.exports = require("crypto");

/***/ }),

/***/ "events":
/*!*************************!*\
  !*** external "events" ***!
  \*************************/
/***/ ((module) => {

"use strict";
module.exports = require("events");

/***/ }),

/***/ "fs":
/*!*********************!*\
  !*** external "fs" ***!
  \*********************/
/***/ ((module) => {

"use strict";
module.exports = require("fs");

/***/ }),

/***/ "net":
/*!**********************!*\
  !*** external "net" ***!
  \**********************/
/***/ ((module) => {

"use strict";
module.exports = require("net");

/***/ }),

/***/ "node:util":
/*!****************************!*\
  !*** external "node:util" ***!
  \****************************/
/***/ ((module) => {

"use strict";
module.exports = require("node:util");

/***/ }),

/***/ "os":
/*!*********************!*\
  !*** external "os" ***!
  \*********************/
/***/ ((module) => {

"use strict";
module.exports = require("os");

/***/ }),

/***/ "path":
/*!***********************!*\
  !*** external "path" ***!
  \***********************/
/***/ ((module) => {

"use strict";
module.exports = require("path");

/***/ }),

/***/ "readline":
/*!***************************!*\
  !*** external "readline" ***!
  \***************************/
/***/ ((module) => {

"use strict";
module.exports = require("readline");

/***/ }),

/***/ "stream":
/*!*************************!*\
  !*** external "stream" ***!
  \*************************/
/***/ ((module) => {

"use strict";
module.exports = require("stream");

/***/ }),

/***/ "url":
/*!**********************!*\
  !*** external "url" ***!
  \**********************/
/***/ ((module) => {

"use strict";
module.exports = require("url");

/***/ }),

/***/ "util":
/*!***********************!*\
  !*** external "util" ***!
  \***********************/
/***/ ((module) => {

"use strict";
module.exports = require("util");

/***/ }),

/***/ "v8":
/*!*********************!*\
  !*** external "v8" ***!
  \*********************/
/***/ ((module) => {

"use strict";
module.exports = require("v8");

/***/ }),

/***/ "worker_threads":
/*!*********************************!*\
  !*** external "worker_threads" ***!
  \*********************************/
/***/ ((module) => {

"use strict";
module.exports = require("worker_threads");

/***/ }),

/***/ "zlib":
/*!***********************!*\
  !*** external "zlib" ***!
  \***********************/
/***/ ((module) => {

"use strict";
module.exports = require("zlib");

/***/ }),

/***/ "../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js":
/*!************************************************************************************!*\
  !*** ../pyright-internal/node_modules/vscode-languageserver-types/lib/esm/main.js ***!
  \************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AnnotatedTextEdit: () => (/* binding */ AnnotatedTextEdit),
/* harmony export */   ChangeAnnotation: () => (/* binding */ ChangeAnnotation),
/* harmony export */   ChangeAnnotationIdentifier: () => (/* binding */ ChangeAnnotationIdentifier),
/* harmony export */   CodeAction: () => (/* binding */ CodeAction),
/* harmony export */   CodeActionContext: () => (/* binding */ CodeActionContext),
/* harmony export */   CodeActionKind: () => (/* binding */ CodeActionKind),
/* harmony export */   CodeActionTriggerKind: () => (/* binding */ CodeActionTriggerKind),
/* harmony export */   CodeDescription: () => (/* binding */ CodeDescription),
/* harmony export */   CodeLens: () => (/* binding */ CodeLens),
/* harmony export */   Color: () => (/* binding */ Color),
/* harmony export */   ColorInformation: () => (/* binding */ ColorInformation),
/* harmony export */   ColorPresentation: () => (/* binding */ ColorPresentation),
/* harmony export */   Command: () => (/* binding */ Command),
/* harmony export */   CompletionItem: () => (/* binding */ CompletionItem),
/* harmony export */   CompletionItemKind: () => (/* binding */ CompletionItemKind),
/* harmony export */   CompletionItemLabelDetails: () => (/* binding */ CompletionItemLabelDetails),
/* harmony export */   CompletionItemTag: () => (/* binding */ CompletionItemTag),
/* harmony export */   CompletionList: () => (/* binding */ CompletionList),
/* harmony export */   CreateFile: () => (/* binding */ CreateFile),
/* harmony export */   DeleteFile: () => (/* binding */ DeleteFile),
/* harmony export */   Diagnostic: () => (/* binding */ Diagnostic),
/* harmony export */   DiagnosticRelatedInformation: () => (/* binding */ DiagnosticRelatedInformation),
/* harmony export */   DiagnosticSeverity: () => (/* binding */ DiagnosticSeverity),
/* harmony export */   DiagnosticTag: () => (/* binding */ DiagnosticTag),
/* harmony export */   DocumentHighlight: () => (/* binding */ DocumentHighlight),
/* harmony export */   DocumentHighlightKind: () => (/* binding */ DocumentHighlightKind),
/* harmony export */   DocumentLink: () => (/* binding */ DocumentLink),
/* harmony export */   DocumentSymbol: () => (/* binding */ DocumentSymbol),
/* harmony export */   DocumentUri: () => (/* binding */ DocumentUri),
/* harmony export */   EOL: () => (/* binding */ EOL),
/* harmony export */   FoldingRange: () => (/* binding */ FoldingRange),
/* harmony export */   FoldingRangeKind: () => (/* binding */ FoldingRangeKind),
/* harmony export */   FormattingOptions: () => (/* binding */ FormattingOptions),
/* harmony export */   Hover: () => (/* binding */ Hover),
/* harmony export */   InlayHint: () => (/* binding */ InlayHint),
/* harmony export */   InlayHintKind: () => (/* binding */ InlayHintKind),
/* harmony export */   InlayHintLabelPart: () => (/* binding */ InlayHintLabelPart),
/* harmony export */   InlineCompletionContext: () => (/* binding */ InlineCompletionContext),
/* harmony export */   InlineCompletionItem: () => (/* binding */ InlineCompletionItem),
/* harmony export */   InlineCompletionList: () => (/* binding */ InlineCompletionList),
/* harmony export */   InlineCompletionTriggerKind: () => (/* binding */ InlineCompletionTriggerKind),
/* harmony export */   InlineValueContext: () => (/* binding */ InlineValueContext),
/* harmony export */   InlineValueEvaluatableExpression: () => (/* binding */ InlineValueEvaluatableExpression),
/* harmony export */   InlineValueText: () => (/* binding */ InlineValueText),
/* harmony export */   InlineValueVariableLookup: () => (/* binding */ InlineValueVariableLookup),
/* harmony export */   InsertReplaceEdit: () => (/* binding */ InsertReplaceEdit),
/* harmony export */   InsertTextFormat: () => (/* binding */ InsertTextFormat),
/* harmony export */   InsertTextMode: () => (/* binding */ InsertTextMode),
/* harmony export */   LanguageKind: () => (/* binding */ LanguageKind),
/* harmony export */   Location: () => (/* binding */ Location),
/* harmony export */   LocationLink: () => (/* binding */ LocationLink),
/* harmony export */   MarkedString: () => (/* binding */ MarkedString),
/* harmony export */   MarkupContent: () => (/* binding */ MarkupContent),
/* harmony export */   MarkupKind: () => (/* binding */ MarkupKind),
/* harmony export */   OptionalVersionedTextDocumentIdentifier: () => (/* binding */ OptionalVersionedTextDocumentIdentifier),
/* harmony export */   ParameterInformation: () => (/* binding */ ParameterInformation),
/* harmony export */   Position: () => (/* binding */ Position),
/* harmony export */   Range: () => (/* binding */ Range),
/* harmony export */   RenameFile: () => (/* binding */ RenameFile),
/* harmony export */   SelectedCompletionInfo: () => (/* binding */ SelectedCompletionInfo),
/* harmony export */   SelectionRange: () => (/* binding */ SelectionRange),
/* harmony export */   SemanticTokenModifiers: () => (/* binding */ SemanticTokenModifiers),
/* harmony export */   SemanticTokenTypes: () => (/* binding */ SemanticTokenTypes),
/* harmony export */   SemanticTokens: () => (/* binding */ SemanticTokens),
/* harmony export */   SignatureInformation: () => (/* binding */ SignatureInformation),
/* harmony export */   SnippetTextEdit: () => (/* binding */ SnippetTextEdit),
/* harmony export */   StringValue: () => (/* binding */ StringValue),
/* harmony export */   SymbolInformation: () => (/* binding */ SymbolInformation),
/* harmony export */   SymbolKind: () => (/* binding */ SymbolKind),
/* harmony export */   SymbolTag: () => (/* binding */ SymbolTag),
/* harmony export */   TextDocument: () => (/* binding */ TextDocument),
/* harmony export */   TextDocumentEdit: () => (/* binding */ TextDocumentEdit),
/* harmony export */   TextDocumentIdentifier: () => (/* binding */ TextDocumentIdentifier),
/* harmony export */   TextDocumentItem: () => (/* binding */ TextDocumentItem),
/* harmony export */   TextEdit: () => (/* binding */ TextEdit),
/* harmony export */   URI: () => (/* binding */ URI),
/* harmony export */   VersionedTextDocumentIdentifier: () => (/* binding */ VersionedTextDocumentIdentifier),
/* harmony export */   WorkspaceChange: () => (/* binding */ WorkspaceChange),
/* harmony export */   WorkspaceEdit: () => (/* binding */ WorkspaceEdit),
/* harmony export */   WorkspaceFolder: () => (/* binding */ WorkspaceFolder),
/* harmony export */   WorkspaceSymbol: () => (/* binding */ WorkspaceSymbol),
/* harmony export */   integer: () => (/* binding */ integer),
/* harmony export */   uinteger: () => (/* binding */ uinteger)
/* harmony export */ });

var DocumentUri;
(function(DocumentUri2) {
  function is(value) {
    return typeof value === "string";
  }
  DocumentUri2.is = is;
})(DocumentUri || (DocumentUri = {}));
var URI;
(function(URI2) {
  function is(value) {
    return typeof value === "string";
  }
  URI2.is = is;
})(URI || (URI = {}));
var integer;
(function(integer2) {
  integer2.MIN_VALUE = -2147483648;
  integer2.MAX_VALUE = 2147483647;
  function is(value) {
    return typeof value === "number" && integer2.MIN_VALUE <= value && value <= integer2.MAX_VALUE;
  }
  integer2.is = is;
})(integer || (integer = {}));
var uinteger;
(function(uinteger2) {
  uinteger2.MIN_VALUE = 0;
  uinteger2.MAX_VALUE = 2147483647;
  function is(value) {
    return typeof value === "number" && uinteger2.MIN_VALUE <= value && value <= uinteger2.MAX_VALUE;
  }
  uinteger2.is = is;
})(uinteger || (uinteger = {}));
var Position;
(function(Position2) {
  function create(line, character) {
    if (line === Number.MAX_VALUE) {
      line = uinteger.MAX_VALUE;
    }
    if (character === Number.MAX_VALUE) {
      character = uinteger.MAX_VALUE;
    }
    return { line, character };
  }
  Position2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
  }
  Position2.is = is;
})(Position || (Position = {}));
var Range;
(function(Range2) {
  function create(one, two, three, four) {
    if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
      return { start: Position.create(one, two), end: Position.create(three, four) };
    } else if (Position.is(one) && Position.is(two)) {
      return { start: one, end: two };
    } else {
      throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`);
    }
  }
  Range2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
  }
  Range2.is = is;
})(Range || (Range = {}));
var Location;
(function(Location2) {
  function create(uri, range) {
    return { uri, range };
  }
  Location2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
  }
  Location2.is = is;
})(Location || (Location = {}));
var LocationLink;
(function(LocationLink2) {
  function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
    return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
  }
  LocationLink2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
  }
  LocationLink2.is = is;
})(LocationLink || (LocationLink = {}));
var Color;
(function(Color2) {
  function create(red, green, blue, alpha) {
    return {
      red,
      green,
      blue,
      alpha
    };
  }
  Color2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1);
  }
  Color2.is = is;
})(Color || (Color = {}));
var ColorInformation;
(function(ColorInformation2) {
  function create(range, color) {
    return {
      range,
      color
    };
  }
  ColorInformation2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
  }
  ColorInformation2.is = is;
})(ColorInformation || (ColorInformation = {}));
var ColorPresentation;
(function(ColorPresentation2) {
  function create(label, textEdit, additionalTextEdits) {
    return {
      label,
      textEdit,
      additionalTextEdits
    };
  }
  ColorPresentation2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
  }
  ColorPresentation2.is = is;
})(ColorPresentation || (ColorPresentation = {}));
var FoldingRangeKind;
(function(FoldingRangeKind2) {
  FoldingRangeKind2.Comment = "comment";
  FoldingRangeKind2.Imports = "imports";
  FoldingRangeKind2.Region = "region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
var FoldingRange;
(function(FoldingRange2) {
  function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
    const result = {
      startLine,
      endLine
    };
    if (Is.defined(startCharacter)) {
      result.startCharacter = startCharacter;
    }
    if (Is.defined(endCharacter)) {
      result.endCharacter = endCharacter;
    }
    if (Is.defined(kind)) {
      result.kind = kind;
    }
    if (Is.defined(collapsedText)) {
      result.collapsedText = collapsedText;
    }
    return result;
  }
  FoldingRange2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
  }
  FoldingRange2.is = is;
})(FoldingRange || (FoldingRange = {}));
var DiagnosticRelatedInformation;
(function(DiagnosticRelatedInformation2) {
  function create(location, message) {
    return {
      location,
      message
    };
  }
  DiagnosticRelatedInformation2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
  }
  DiagnosticRelatedInformation2.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
var DiagnosticSeverity;
(function(DiagnosticSeverity2) {
  DiagnosticSeverity2.Error = 1;
  DiagnosticSeverity2.Warning = 2;
  DiagnosticSeverity2.Information = 3;
  DiagnosticSeverity2.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
var DiagnosticTag;
(function(DiagnosticTag2) {
  DiagnosticTag2.Unnecessary = 1;
  DiagnosticTag2.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
var CodeDescription;
(function(CodeDescription2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.string(candidate.href);
  }
  CodeDescription2.is = is;
})(CodeDescription || (CodeDescription = {}));
var Diagnostic;
(function(Diagnostic2) {
  function create(range, message, severity, code, source, relatedInformation) {
    const result = { range, message };
    if (Is.defined(severity)) {
      result.severity = severity;
    }
    if (Is.defined(code)) {
      result.code = code;
    }
    if (Is.defined(source)) {
      result.source = source;
    }
    if (Is.defined(relatedInformation)) {
      result.relatedInformation = relatedInformation;
    }
    return result;
  }
  Diagnostic2.create = create;
  function is(value) {
    var _a;
    const candidate = value;
    return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
  }
  Diagnostic2.is = is;
})(Diagnostic || (Diagnostic = {}));
var Command;
(function(Command2) {
  function create(title, command, ...args) {
    const result = { title, command };
    if (Is.defined(args) && args.length > 0) {
      result.arguments = args;
    }
    return result;
  }
  Command2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.title) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip)) && Is.string(candidate.command);
  }
  Command2.is = is;
})(Command || (Command = {}));
var TextEdit;
(function(TextEdit2) {
  function replace(range, newText) {
    return { range, newText };
  }
  TextEdit2.replace = replace;
  function insert(position, newText) {
    return { range: { start: position, end: position }, newText };
  }
  TextEdit2.insert = insert;
  function del(range) {
    return { range, newText: "" };
  }
  TextEdit2.del = del;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range);
  }
  TextEdit2.is = is;
})(TextEdit || (TextEdit = {}));
var ChangeAnnotation;
(function(ChangeAnnotation2) {
  function create(label, needsConfirmation, description) {
    const result = { label };
    if (needsConfirmation !== void 0) {
      result.needsConfirmation = needsConfirmation;
    }
    if (description !== void 0) {
      result.description = description;
    }
    return result;
  }
  ChangeAnnotation2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
  }
  ChangeAnnotation2.is = is;
})(ChangeAnnotation || (ChangeAnnotation = {}));
var ChangeAnnotationIdentifier;
(function(ChangeAnnotationIdentifier2) {
  function is(value) {
    const candidate = value;
    return Is.string(candidate);
  }
  ChangeAnnotationIdentifier2.is = is;
})(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
var AnnotatedTextEdit;
(function(AnnotatedTextEdit2) {
  function replace(range, newText, annotation) {
    return { range, newText, annotationId: annotation };
  }
  AnnotatedTextEdit2.replace = replace;
  function insert(position, newText, annotation) {
    return { range: { start: position, end: position }, newText, annotationId: annotation };
  }
  AnnotatedTextEdit2.insert = insert;
  function del(range, annotation) {
    return { range, newText: "", annotationId: annotation };
  }
  AnnotatedTextEdit2.del = del;
  function is(value) {
    const candidate = value;
    return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
  }
  AnnotatedTextEdit2.is = is;
})(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
var TextDocumentEdit;
(function(TextDocumentEdit2) {
  function create(textDocument, edits) {
    return { textDocument, edits };
  }
  TextDocumentEdit2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
  }
  TextDocumentEdit2.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
var CreateFile;
(function(CreateFile2) {
  function create(uri, options, annotation) {
    const result = {
      kind: "create",
      uri
    };
    if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
      result.options = options;
    }
    if (annotation !== void 0) {
      result.annotationId = annotation;
    }
    return result;
  }
  CreateFile2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
  }
  CreateFile2.is = is;
})(CreateFile || (CreateFile = {}));
var RenameFile;
(function(RenameFile2) {
  function create(oldUri, newUri, options, annotation) {
    const result = {
      kind: "rename",
      oldUri,
      newUri
    };
    if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
      result.options = options;
    }
    if (annotation !== void 0) {
      result.annotationId = annotation;
    }
    return result;
  }
  RenameFile2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
  }
  RenameFile2.is = is;
})(RenameFile || (RenameFile = {}));
var DeleteFile;
(function(DeleteFile2) {
  function create(uri, options, annotation) {
    const result = {
      kind: "delete",
      uri
    };
    if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
      result.options = options;
    }
    if (annotation !== void 0) {
      result.annotationId = annotation;
    }
    return result;
  }
  DeleteFile2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
  }
  DeleteFile2.is = is;
})(DeleteFile || (DeleteFile = {}));
var WorkspaceEdit;
(function(WorkspaceEdit2) {
  function is(value) {
    const candidate = value;
    return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every((change) => {
      if (Is.string(change.kind)) {
        return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
      } else {
        return TextDocumentEdit.is(change);
      }
    }));
  }
  WorkspaceEdit2.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
class TextEditChangeImpl {
  constructor(edits, changeAnnotations) {
    this.edits = edits;
    this.changeAnnotations = changeAnnotations;
  }
  insert(position, newText, annotation) {
    let edit;
    let id;
    if (annotation === void 0) {
      edit = TextEdit.insert(position, newText);
    } else if (ChangeAnnotationIdentifier.is(annotation)) {
      id = annotation;
      edit = AnnotatedTextEdit.insert(position, newText, annotation);
    } else {
      this.assertChangeAnnotations(this.changeAnnotations);
      id = this.changeAnnotations.manage(annotation);
      edit = AnnotatedTextEdit.insert(position, newText, id);
    }
    this.edits.push(edit);
    if (id !== void 0) {
      return id;
    }
  }
  replace(range, newText, annotation) {
    let edit;
    let id;
    if (annotation === void 0) {
      edit = TextEdit.replace(range, newText);
    } else if (ChangeAnnotationIdentifier.is(annotation)) {
      id = annotation;
      edit = AnnotatedTextEdit.replace(range, newText, annotation);
    } else {
      this.assertChangeAnnotations(this.changeAnnotations);
      id = this.changeAnnotations.manage(annotation);
      edit = AnnotatedTextEdit.replace(range, newText, id);
    }
    this.edits.push(edit);
    if (id !== void 0) {
      return id;
    }
  }
  delete(range, annotation) {
    let edit;
    let id;
    if (annotation === void 0) {
      edit = TextEdit.del(range);
    } else if (ChangeAnnotationIdentifier.is(annotation)) {
      id = annotation;
      edit = AnnotatedTextEdit.del(range, annotation);
    } else {
      this.assertChangeAnnotations(this.changeAnnotations);
      id = this.changeAnnotations.manage(annotation);
      edit = AnnotatedTextEdit.del(range, id);
    }
    this.edits.push(edit);
    if (id !== void 0) {
      return id;
    }
  }
  add(edit) {
    this.edits.push(edit);
  }
  all() {
    return this.edits;
  }
  clear() {
    this.edits.splice(0, this.edits.length);
  }
  assertChangeAnnotations(value) {
    if (value === void 0) {
      throw new Error(`Text edit change is not configured to manage change annotations.`);
    }
  }
}
var SnippetTextEdit;
(function(SnippetTextEdit2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Range.is(candidate.range) && StringValue.isSnippet(candidate.snippet) && (candidate.annotationId === void 0 || (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)));
  }
  SnippetTextEdit2.is = is;
})(SnippetTextEdit || (SnippetTextEdit = {}));
class ChangeAnnotations {
  constructor(annotations) {
    this._annotations = annotations === void 0 ? /* @__PURE__ */ Object.create(null) : annotations;
    this._counter = 0;
    this._size = 0;
  }
  all() {
    return this._annotations;
  }
  get size() {
    return this._size;
  }
  manage(idOrAnnotation, annotation) {
    let id;
    if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
      id = idOrAnnotation;
    } else {
      id = this.nextId();
      annotation = idOrAnnotation;
    }
    if (this._annotations[id] !== void 0) {
      throw new Error(`Id ${id} is already in use.`);
    }
    if (annotation === void 0) {
      throw new Error(`No annotation provided for id ${id}`);
    }
    this._annotations[id] = annotation;
    this._size++;
    return id;
  }
  nextId() {
    this._counter++;
    return this._counter.toString();
  }
}
class WorkspaceChange {
  constructor(workspaceEdit) {
    this._textEditChanges = /* @__PURE__ */ Object.create(null);
    if (workspaceEdit !== void 0) {
      this._workspaceEdit = workspaceEdit;
      if (workspaceEdit.documentChanges) {
        this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
        workspaceEdit.changeAnnotations = this._changeAnnotations.all();
        workspaceEdit.documentChanges.forEach((change) => {
          if (TextDocumentEdit.is(change)) {
            const textEditChange = new TextEditChangeImpl(change.edits, this._changeAnnotations);
            this._textEditChanges[change.textDocument.uri] = textEditChange;
          }
        });
      } else if (workspaceEdit.changes) {
        Object.keys(workspaceEdit.changes).forEach((key) => {
          const textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
          this._textEditChanges[key] = textEditChange;
        });
      }
    } else {
      this._workspaceEdit = {};
    }
  }
  /**
   * Returns the underlying {@link WorkspaceEdit} literal
   * use to be returned from a workspace edit operation like rename.
   */
  get edit() {
    this.initDocumentChanges();
    if (this._changeAnnotations !== void 0) {
      if (this._changeAnnotations.size === 0) {
        this._workspaceEdit.changeAnnotations = void 0;
      } else {
        this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
      }
    }
    return this._workspaceEdit;
  }
  getTextEditChange(key) {
    if (OptionalVersionedTextDocumentIdentifier.is(key)) {
      this.initDocumentChanges();
      if (this._workspaceEdit.documentChanges === void 0) {
        throw new Error("Workspace edit is not configured for document changes.");
      }
      const textDocument = { uri: key.uri, version: key.version };
      let result = this._textEditChanges[textDocument.uri];
      if (!result) {
        const edits = [];
        const textDocumentEdit = {
          textDocument,
          edits
        };
        this._workspaceEdit.documentChanges.push(textDocumentEdit);
        result = new TextEditChangeImpl(edits, this._changeAnnotations);
        this._textEditChanges[textDocument.uri] = result;
      }
      return result;
    } else {
      this.initChanges();
      if (this._workspaceEdit.changes === void 0) {
        throw new Error("Workspace edit is not configured for normal text edit changes.");
      }
      let result = this._textEditChanges[key];
      if (!result) {
        const edits = [];
        this._workspaceEdit.changes[key] = edits;
        result = new TextEditChangeImpl(edits);
        this._textEditChanges[key] = result;
      }
      return result;
    }
  }
  initDocumentChanges() {
    if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
      this._changeAnnotations = new ChangeAnnotations();
      this._workspaceEdit.documentChanges = [];
      this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
    }
  }
  initChanges() {
    if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
      this._workspaceEdit.changes = /* @__PURE__ */ Object.create(null);
    }
  }
  createFile(uri, optionsOrAnnotation, options) {
    this.initDocumentChanges();
    if (this._workspaceEdit.documentChanges === void 0) {
      throw new Error("Workspace edit is not configured for document changes.");
    }
    let annotation;
    if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
      annotation = optionsOrAnnotation;
    } else {
      options = optionsOrAnnotation;
    }
    let operation;
    let id;
    if (annotation === void 0) {
      operation = CreateFile.create(uri, options);
    } else {
      id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
      operation = CreateFile.create(uri, options, id);
    }
    this._workspaceEdit.documentChanges.push(operation);
    if (id !== void 0) {
      return id;
    }
  }
  renameFile(oldUri, newUri, optionsOrAnnotation, options) {
    this.initDocumentChanges();
    if (this._workspaceEdit.documentChanges === void 0) {
      throw new Error("Workspace edit is not configured for document changes.");
    }
    let annotation;
    if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
      annotation = optionsOrAnnotation;
    } else {
      options = optionsOrAnnotation;
    }
    let operation;
    let id;
    if (annotation === void 0) {
      operation = RenameFile.create(oldUri, newUri, options);
    } else {
      id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
      operation = RenameFile.create(oldUri, newUri, options, id);
    }
    this._workspaceEdit.documentChanges.push(operation);
    if (id !== void 0) {
      return id;
    }
  }
  deleteFile(uri, optionsOrAnnotation, options) {
    this.initDocumentChanges();
    if (this._workspaceEdit.documentChanges === void 0) {
      throw new Error("Workspace edit is not configured for document changes.");
    }
    let annotation;
    if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
      annotation = optionsOrAnnotation;
    } else {
      options = optionsOrAnnotation;
    }
    let operation;
    let id;
    if (annotation === void 0) {
      operation = DeleteFile.create(uri, options);
    } else {
      id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
      operation = DeleteFile.create(uri, options, id);
    }
    this._workspaceEdit.documentChanges.push(operation);
    if (id !== void 0) {
      return id;
    }
  }
}
var TextDocumentIdentifier;
(function(TextDocumentIdentifier2) {
  function create(uri) {
    return { uri };
  }
  TextDocumentIdentifier2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.uri);
  }
  TextDocumentIdentifier2.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
var VersionedTextDocumentIdentifier;
(function(VersionedTextDocumentIdentifier2) {
  function create(uri, version) {
    return { uri, version };
  }
  VersionedTextDocumentIdentifier2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
  }
  VersionedTextDocumentIdentifier2.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
var OptionalVersionedTextDocumentIdentifier;
(function(OptionalVersionedTextDocumentIdentifier2) {
  function create(uri, version) {
    return { uri, version };
  }
  OptionalVersionedTextDocumentIdentifier2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
  }
  OptionalVersionedTextDocumentIdentifier2.is = is;
})(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
var LanguageKind;
(function(LanguageKind2) {
  LanguageKind2.ABAP = "abap";
  LanguageKind2.WindowsBat = "bat";
  LanguageKind2.BibTeX = "bibtex";
  LanguageKind2.Clojure = "clojure";
  LanguageKind2.Coffeescript = "coffeescript";
  LanguageKind2.C = "c";
  LanguageKind2.CPP = "cpp";
  LanguageKind2.CSharp = "csharp";
  LanguageKind2.CSS = "css";
  LanguageKind2.D = "d";
  LanguageKind2.Delphi = "pascal";
  LanguageKind2.Diff = "diff";
  LanguageKind2.Dart = "dart";
  LanguageKind2.Dockerfile = "dockerfile";
  LanguageKind2.Elixir = "elixir";
  LanguageKind2.Erlang = "erlang";
  LanguageKind2.FSharp = "fsharp";
  LanguageKind2.GitCommit = "git-commit";
  LanguageKind2.GitRebase = "rebase";
  LanguageKind2.Go = "go";
  LanguageKind2.Groovy = "groovy";
  LanguageKind2.Handlebars = "handlebars";
  LanguageKind2.Haskell = "haskell";
  LanguageKind2.HTML = "html";
  LanguageKind2.Ini = "ini";
  LanguageKind2.Java = "java";
  LanguageKind2.JavaScript = "javascript";
  LanguageKind2.JavaScriptReact = "javascriptreact";
  LanguageKind2.JSON = "json";
  LanguageKind2.LaTeX = "latex";
  LanguageKind2.Less = "less";
  LanguageKind2.Lua = "lua";
  LanguageKind2.Makefile = "makefile";
  LanguageKind2.Markdown = "markdown";
  LanguageKind2.ObjectiveC = "objective-c";
  LanguageKind2.ObjectiveCPP = "objective-cpp";
  LanguageKind2.Pascal = "pascal";
  LanguageKind2.Perl = "perl";
  LanguageKind2.Perl6 = "perl6";
  LanguageKind2.PHP = "php";
  LanguageKind2.Powershell = "powershell";
  LanguageKind2.Pug = "jade";
  LanguageKind2.Python = "python";
  LanguageKind2.R = "r";
  LanguageKind2.Razor = "razor";
  LanguageKind2.Ruby = "ruby";
  LanguageKind2.Rust = "rust";
  LanguageKind2.SCSS = "scss";
  LanguageKind2.SASS = "sass";
  LanguageKind2.Scala = "scala";
  LanguageKind2.ShaderLab = "shaderlab";
  LanguageKind2.ShellScript = "shellscript";
  LanguageKind2.SQL = "sql";
  LanguageKind2.Swift = "swift";
  LanguageKind2.TypeScript = "typescript";
  LanguageKind2.TypeScriptReact = "typescriptreact";
  LanguageKind2.TeX = "tex";
  LanguageKind2.VisualBasic = "vb";
  LanguageKind2.XML = "xml";
  LanguageKind2.XSL = "xsl";
  LanguageKind2.YAML = "yaml";
})(LanguageKind || (LanguageKind = {}));
var TextDocumentItem;
(function(TextDocumentItem2) {
  function create(uri, languageId, version, text) {
    return { uri, languageId, version, text };
  }
  TextDocumentItem2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
  }
  TextDocumentItem2.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
var MarkupKind;
(function(MarkupKind2) {
  MarkupKind2.PlainText = "plaintext";
  MarkupKind2.Markdown = "markdown";
  function is(value) {
    const candidate = value;
    return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown;
  }
  MarkupKind2.is = is;
})(MarkupKind || (MarkupKind = {}));
var MarkupContent;
(function(MarkupContent2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
  }
  MarkupContent2.is = is;
})(MarkupContent || (MarkupContent = {}));
var CompletionItemKind;
(function(CompletionItemKind2) {
  CompletionItemKind2.Text = 1;
  CompletionItemKind2.Method = 2;
  CompletionItemKind2.Function = 3;
  CompletionItemKind2.Constructor = 4;
  CompletionItemKind2.Field = 5;
  CompletionItemKind2.Variable = 6;
  CompletionItemKind2.Class = 7;
  CompletionItemKind2.Interface = 8;
  CompletionItemKind2.Module = 9;
  CompletionItemKind2.Property = 10;
  CompletionItemKind2.Unit = 11;
  CompletionItemKind2.Value = 12;
  CompletionItemKind2.Enum = 13;
  CompletionItemKind2.Keyword = 14;
  CompletionItemKind2.Snippet = 15;
  CompletionItemKind2.Color = 16;
  CompletionItemKind2.File = 17;
  CompletionItemKind2.Reference = 18;
  CompletionItemKind2.Folder = 19;
  CompletionItemKind2.EnumMember = 20;
  CompletionItemKind2.Constant = 21;
  CompletionItemKind2.Struct = 22;
  CompletionItemKind2.Event = 23;
  CompletionItemKind2.Operator = 24;
  CompletionItemKind2.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
var InsertTextFormat;
(function(InsertTextFormat2) {
  InsertTextFormat2.PlainText = 1;
  InsertTextFormat2.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
var CompletionItemTag;
(function(CompletionItemTag2) {
  CompletionItemTag2.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
var InsertReplaceEdit;
(function(InsertReplaceEdit2) {
  function create(newText, insert, replace) {
    return { newText, insert, replace };
  }
  InsertReplaceEdit2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
  }
  InsertReplaceEdit2.is = is;
})(InsertReplaceEdit || (InsertReplaceEdit = {}));
var InsertTextMode;
(function(InsertTextMode2) {
  InsertTextMode2.asIs = 1;
  InsertTextMode2.adjustIndentation = 2;
})(InsertTextMode || (InsertTextMode = {}));
var CompletionItemLabelDetails;
(function(CompletionItemLabelDetails2) {
  function is(value) {
    const candidate = value;
    return candidate && (Is.string(candidate.detail) || candidate.detail === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
  }
  CompletionItemLabelDetails2.is = is;
})(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));
var CompletionItem;
(function(CompletionItem2) {
  function create(label) {
    return { label };
  }
  CompletionItem2.create = create;
})(CompletionItem || (CompletionItem = {}));
var CompletionList;
(function(CompletionList2) {
  function create(items, isIncomplete) {
    return { items: items ? items : [], isIncomplete: !!isIncomplete };
  }
  CompletionList2.create = create;
})(CompletionList || (CompletionList = {}));
var MarkedString;
(function(MarkedString2) {
  function fromPlainText(plainText) {
    return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
  }
  MarkedString2.fromPlainText = fromPlainText;
  function is(value) {
    const candidate = value;
    return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
  }
  MarkedString2.is = is;
})(MarkedString || (MarkedString = {}));
var Hover;
(function(Hover2) {
  function is(value) {
    const candidate = value;
    return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
  }
  Hover2.is = is;
})(Hover || (Hover = {}));
var ParameterInformation;
(function(ParameterInformation2) {
  function create(label, documentation) {
    return documentation ? { label, documentation } : { label };
  }
  ParameterInformation2.create = create;
})(ParameterInformation || (ParameterInformation = {}));
var SignatureInformation;
(function(SignatureInformation2) {
  function create(label, documentation, ...parameters) {
    const result = { label };
    if (Is.defined(documentation)) {
      result.documentation = documentation;
    }
    if (Is.defined(parameters)) {
      result.parameters = parameters;
    } else {
      result.parameters = [];
    }
    return result;
  }
  SignatureInformation2.create = create;
})(SignatureInformation || (SignatureInformation = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind2) {
  DocumentHighlightKind2.Text = 1;
  DocumentHighlightKind2.Read = 2;
  DocumentHighlightKind2.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
var DocumentHighlight;
(function(DocumentHighlight2) {
  function create(range, kind) {
    const result = { range };
    if (Is.number(kind)) {
      result.kind = kind;
    }
    return result;
  }
  DocumentHighlight2.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
var SymbolKind;
(function(SymbolKind2) {
  SymbolKind2.File = 1;
  SymbolKind2.Module = 2;
  SymbolKind2.Namespace = 3;
  SymbolKind2.Package = 4;
  SymbolKind2.Class = 5;
  SymbolKind2.Method = 6;
  SymbolKind2.Property = 7;
  SymbolKind2.Field = 8;
  SymbolKind2.Constructor = 9;
  SymbolKind2.Enum = 10;
  SymbolKind2.Interface = 11;
  SymbolKind2.Function = 12;
  SymbolKind2.Variable = 13;
  SymbolKind2.Constant = 14;
  SymbolKind2.String = 15;
  SymbolKind2.Number = 16;
  SymbolKind2.Boolean = 17;
  SymbolKind2.Array = 18;
  SymbolKind2.Object = 19;
  SymbolKind2.Key = 20;
  SymbolKind2.Null = 21;
  SymbolKind2.EnumMember = 22;
  SymbolKind2.Struct = 23;
  SymbolKind2.Event = 24;
  SymbolKind2.Operator = 25;
  SymbolKind2.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
var SymbolTag;
(function(SymbolTag2) {
  SymbolTag2.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
var SymbolInformation;
(function(SymbolInformation2) {
  function create(name, kind, range, uri, containerName) {
    const result = {
      name,
      kind,
      location: { uri, range }
    };
    if (containerName) {
      result.containerName = containerName;
    }
    return result;
  }
  SymbolInformation2.create = create;
})(SymbolInformation || (SymbolInformation = {}));
var WorkspaceSymbol;
(function(WorkspaceSymbol2) {
  function create(name, kind, uri, range) {
    return range !== void 0 ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } };
  }
  WorkspaceSymbol2.create = create;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
var DocumentSymbol;
(function(DocumentSymbol2) {
  function create(name, detail, kind, range, selectionRange, children) {
    const result = {
      name,
      detail,
      kind,
      range,
      selectionRange
    };
    if (children !== void 0) {
      result.children = children;
    }
    return result;
  }
  DocumentSymbol2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags));
  }
  DocumentSymbol2.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
var CodeActionKind;
(function(CodeActionKind2) {
  CodeActionKind2.Empty = "";
  CodeActionKind2.QuickFix = "quickfix";
  CodeActionKind2.Refactor = "refactor";
  CodeActionKind2.RefactorExtract = "refactor.extract";
  CodeActionKind2.RefactorInline = "refactor.inline";
  CodeActionKind2.RefactorMove = "refactor.move";
  CodeActionKind2.RefactorRewrite = "refactor.rewrite";
  CodeActionKind2.Source = "source";
  CodeActionKind2.SourceOrganizeImports = "source.organizeImports";
  CodeActionKind2.SourceFixAll = "source.fixAll";
  CodeActionKind2.Notebook = "notebook";
})(CodeActionKind || (CodeActionKind = {}));
var CodeActionTriggerKind;
(function(CodeActionTriggerKind2) {
  CodeActionTriggerKind2.Invoked = 1;
  CodeActionTriggerKind2.Automatic = 2;
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
var CodeActionContext;
(function(CodeActionContext2) {
  function create(diagnostics, only, triggerKind) {
    const result = { diagnostics };
    if (only !== void 0 && only !== null) {
      result.only = only;
    }
    if (triggerKind !== void 0 && triggerKind !== null) {
      result.triggerKind = triggerKind;
    }
    return result;
  }
  CodeActionContext2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === void 0 || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
  }
  CodeActionContext2.is = is;
})(CodeActionContext || (CodeActionContext = {}));
var CodeAction;
(function(CodeAction2) {
  function create(title, kindOrCommandOrEdit, kind) {
    const result = { title };
    let checkKind = true;
    if (typeof kindOrCommandOrEdit === "string") {
      checkKind = false;
      result.kind = kindOrCommandOrEdit;
    } else if (Command.is(kindOrCommandOrEdit)) {
      result.command = kindOrCommandOrEdit;
    } else {
      result.edit = kindOrCommandOrEdit;
    }
    if (checkKind && kind !== void 0) {
      result.kind = kind;
    }
    return result;
  }
  CodeAction2.create = create;
  function is(value) {
    const candidate = value;
    return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
  }
  CodeAction2.is = is;
})(CodeAction || (CodeAction = {}));
var CodeLens;
(function(CodeLens2) {
  function create(range, data) {
    const result = { range };
    if (Is.defined(data)) {
      result.data = data;
    }
    return result;
  }
  CodeLens2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
  }
  CodeLens2.is = is;
})(CodeLens || (CodeLens = {}));
var FormattingOptions;
(function(FormattingOptions2) {
  function create(tabSize, insertSpaces) {
    return { tabSize, insertSpaces };
  }
  FormattingOptions2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
  }
  FormattingOptions2.is = is;
})(FormattingOptions || (FormattingOptions = {}));
var DocumentLink;
(function(DocumentLink2) {
  function create(range, target, data) {
    return { range, target, data };
  }
  DocumentLink2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
  }
  DocumentLink2.is = is;
})(DocumentLink || (DocumentLink = {}));
var SelectionRange;
(function(SelectionRange2) {
  function create(range, parent) {
    return { range, parent };
  }
  SelectionRange2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
  }
  SelectionRange2.is = is;
})(SelectionRange || (SelectionRange = {}));
var SemanticTokenTypes;
(function(SemanticTokenTypes2) {
  SemanticTokenTypes2["namespace"] = "namespace";
  SemanticTokenTypes2["type"] = "type";
  SemanticTokenTypes2["class"] = "class";
  SemanticTokenTypes2["enum"] = "enum";
  SemanticTokenTypes2["interface"] = "interface";
  SemanticTokenTypes2["struct"] = "struct";
  SemanticTokenTypes2["typeParameter"] = "typeParameter";
  SemanticTokenTypes2["parameter"] = "parameter";
  SemanticTokenTypes2["variable"] = "variable";
  SemanticTokenTypes2["property"] = "property";
  SemanticTokenTypes2["enumMember"] = "enumMember";
  SemanticTokenTypes2["event"] = "event";
  SemanticTokenTypes2["function"] = "function";
  SemanticTokenTypes2["method"] = "method";
  SemanticTokenTypes2["macro"] = "macro";
  SemanticTokenTypes2["keyword"] = "keyword";
  SemanticTokenTypes2["modifier"] = "modifier";
  SemanticTokenTypes2["comment"] = "comment";
  SemanticTokenTypes2["string"] = "string";
  SemanticTokenTypes2["number"] = "number";
  SemanticTokenTypes2["regexp"] = "regexp";
  SemanticTokenTypes2["operator"] = "operator";
  SemanticTokenTypes2["decorator"] = "decorator";
})(SemanticTokenTypes || (SemanticTokenTypes = {}));
var SemanticTokenModifiers;
(function(SemanticTokenModifiers2) {
  SemanticTokenModifiers2["declaration"] = "declaration";
  SemanticTokenModifiers2["definition"] = "definition";
  SemanticTokenModifiers2["readonly"] = "readonly";
  SemanticTokenModifiers2["static"] = "static";
  SemanticTokenModifiers2["deprecated"] = "deprecated";
  SemanticTokenModifiers2["abstract"] = "abstract";
  SemanticTokenModifiers2["async"] = "async";
  SemanticTokenModifiers2["modification"] = "modification";
  SemanticTokenModifiers2["documentation"] = "documentation";
  SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary";
})(SemanticTokenModifiers || (SemanticTokenModifiers = {}));
var SemanticTokens;
(function(SemanticTokens2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
  }
  SemanticTokens2.is = is;
})(SemanticTokens || (SemanticTokens = {}));
var InlineValueText;
(function(InlineValueText2) {
  function create(range, text) {
    return { range, text };
  }
  InlineValueText2.create = create;
  function is(value) {
    const candidate = value;
    return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);
  }
  InlineValueText2.is = is;
})(InlineValueText || (InlineValueText = {}));
var InlineValueVariableLookup;
(function(InlineValueVariableLookup2) {
  function create(range, variableName, caseSensitiveLookup) {
    return { range, variableName, caseSensitiveLookup };
  }
  InlineValueVariableLookup2.create = create;
  function is(value) {
    const candidate = value;
    return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === void 0);
  }
  InlineValueVariableLookup2.is = is;
})(InlineValueVariableLookup || (InlineValueVariableLookup = {}));
var InlineValueEvaluatableExpression;
(function(InlineValueEvaluatableExpression2) {
  function create(range, expression) {
    return { range, expression };
  }
  InlineValueEvaluatableExpression2.create = create;
  function is(value) {
    const candidate = value;
    return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === void 0);
  }
  InlineValueEvaluatableExpression2.is = is;
})(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));
var InlineValueContext;
(function(InlineValueContext2) {
  function create(frameId, stoppedLocation) {
    return { frameId, stoppedLocation };
  }
  InlineValueContext2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Range.is(value.stoppedLocation);
  }
  InlineValueContext2.is = is;
})(InlineValueContext || (InlineValueContext = {}));
var InlayHintKind;
(function(InlayHintKind2) {
  InlayHintKind2.Type = 1;
  InlayHintKind2.Parameter = 2;
  function is(value) {
    return value === 1 || value === 2;
  }
  InlayHintKind2.is = is;
})(InlayHintKind || (InlayHintKind = {}));
var InlayHintLabelPart;
(function(InlayHintLabelPart2) {
  function create(value) {
    return { value };
  }
  InlayHintLabelPart2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === void 0 || Location.is(candidate.location)) && (candidate.command === void 0 || Command.is(candidate.command));
  }
  InlayHintLabelPart2.is = is;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
var InlayHint;
(function(InlayHint2) {
  function create(position, label, kind) {
    const result = { position, label };
    if (kind !== void 0) {
      result.kind = kind;
    }
    return result;
  }
  InlayHint2.create = create;
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === void 0 || InlayHintKind.is(candidate.kind)) && candidate.textEdits === void 0 || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === void 0 || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === void 0 || Is.boolean(candidate.paddingRight));
  }
  InlayHint2.is = is;
})(InlayHint || (InlayHint = {}));
var StringValue;
(function(StringValue2) {
  function createSnippet(value) {
    return { kind: "snippet", value };
  }
  StringValue2.createSnippet = createSnippet;
  function isSnippet(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && candidate.kind === "snippet" && Is.string(candidate.value);
  }
  StringValue2.isSnippet = isSnippet;
})(StringValue || (StringValue = {}));
var InlineCompletionItem;
(function(InlineCompletionItem2) {
  function create(insertText, filterText, range, command) {
    return { insertText, filterText, range, command };
  }
  InlineCompletionItem2.create = create;
})(InlineCompletionItem || (InlineCompletionItem = {}));
var InlineCompletionList;
(function(InlineCompletionList2) {
  function create(items) {
    return { items };
  }
  InlineCompletionList2.create = create;
})(InlineCompletionList || (InlineCompletionList = {}));
var InlineCompletionTriggerKind;
(function(InlineCompletionTriggerKind2) {
  InlineCompletionTriggerKind2.Invoked = 1;
  InlineCompletionTriggerKind2.Automatic = 2;
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var SelectedCompletionInfo;
(function(SelectedCompletionInfo2) {
  function create(range, text) {
    return { range, text };
  }
  SelectedCompletionInfo2.create = create;
})(SelectedCompletionInfo || (SelectedCompletionInfo = {}));
var InlineCompletionContext;
(function(InlineCompletionContext2) {
  function create(triggerKind, selectedCompletionInfo) {
    return { triggerKind, selectedCompletionInfo };
  }
  InlineCompletionContext2.create = create;
})(InlineCompletionContext || (InlineCompletionContext = {}));
var WorkspaceFolder;
(function(WorkspaceFolder2) {
  function is(value) {
    const candidate = value;
    return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);
  }
  WorkspaceFolder2.is = is;
})(WorkspaceFolder || (WorkspaceFolder = {}));
const EOL = ["\n", "\r\n", "\r"];
var TextDocument;
(function(TextDocument2) {
  function create(uri, languageId, version, content) {
    return new FullTextDocument(uri, languageId, version, content);
  }
  TextDocument2.create = create;
  function is(value) {
    const candidate = value;
    return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
  }
  TextDocument2.is = is;
  function applyEdits(document, edits) {
    let text = document.getText();
    const sortedEdits = mergeSort(edits, (a, b) => {
      const diff = a.range.start.line - b.range.start.line;
      if (diff === 0) {
        return a.range.start.character - b.range.start.character;
      }
      return diff;
    });
    let lastModifiedOffset = text.length;
    for (let i = sortedEdits.length - 1; i >= 0; i--) {
      const e = sortedEdits[i];
      const startOffset = document.offsetAt(e.range.start);
      const endOffset = document.offsetAt(e.range.end);
      if (endOffset <= lastModifiedOffset) {
        text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
      } else {
        throw new Error("Overlapping edit");
      }
      lastModifiedOffset = startOffset;
    }
    return text;
  }
  TextDocument2.applyEdits = applyEdits;
  function mergeSort(data, compare) {
    if (data.length <= 1) {
      return data;
    }
    const p = data.length / 2 | 0;
    const left = data.slice(0, p);
    const right = data.slice(p);
    mergeSort(left, compare);
    mergeSort(right, compare);
    let leftIdx = 0;
    let rightIdx = 0;
    let i = 0;
    while (leftIdx < left.length && rightIdx < right.length) {
      const ret = compare(left[leftIdx], right[rightIdx]);
      if (ret <= 0) {
        data[i++] = left[leftIdx++];
      } else {
        data[i++] = right[rightIdx++];
      }
    }
    while (leftIdx < left.length) {
      data[i++] = left[leftIdx++];
    }
    while (rightIdx < right.length) {
      data[i++] = right[rightIdx++];
    }
    return data;
  }
})(TextDocument || (TextDocument = {}));
class FullTextDocument {
  constructor(uri, languageId, version, content) {
    this._uri = uri;
    this._languageId = languageId;
    this._version = version;
    this._content = content;
    this._lineOffsets = void 0;
  }
  get uri() {
    return this._uri;
  }
  get languageId() {
    return this._languageId;
  }
  get version() {
    return this._version;
  }
  getText(range) {
    if (range) {
      const start = this.offsetAt(range.start);
      const end = this.offsetAt(range.end);
      return this._content.substring(start, end);
    }
    return this._content;
  }
  update(event, version) {
    this._content = event.text;
    this._version = version;
    this._lineOffsets = void 0;
  }
  getLineOffsets() {
    if (this._lineOffsets === void 0) {
      const lineOffsets = [];
      const text = this._content;
      let isLineStart = true;
      for (let i = 0; i < text.length; i++) {
        if (isLineStart) {
          lineOffsets.push(i);
          isLineStart = false;
        }
        const ch = text.charAt(i);
        isLineStart = ch === "\r" || ch === "\n";
        if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
          i++;
        }
      }
      if (isLineStart && text.length > 0) {
        lineOffsets.push(text.length);
      }
      this._lineOffsets = lineOffsets;
    }
    return this._lineOffsets;
  }
  positionAt(offset) {
    offset = Math.max(Math.min(offset, this._content.length), 0);
    const lineOffsets = this.getLineOffsets();
    let low = 0, high = lineOffsets.length;
    if (high === 0) {
      return Position.create(0, offset);
    }
    while (low < high) {
      const mid = Math.floor((low + high) / 2);
      if (lineOffsets[mid] > offset) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    const line = low - 1;
    return Position.create(line, offset - lineOffsets[line]);
  }
  offsetAt(position) {
    const lineOffsets = this.getLineOffsets();
    if (position.line >= lineOffsets.length) {
      return this._content.length;
    } else if (position.line < 0) {
      return 0;
    }
    const lineOffset = lineOffsets[position.line];
    const nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
    return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
  }
  get lineCount() {
    return this.getLineOffsets().length;
  }
}
var Is;
(function(Is2) {
  const toString = Object.prototype.toString;
  function defined(value) {
    return typeof value !== "undefined";
  }
  Is2.defined = defined;
  function undefined2(value) {
    return typeof value === "undefined";
  }
  Is2.undefined = undefined2;
  function boolean(value) {
    return value === true || value === false;
  }
  Is2.boolean = boolean;
  function string(value) {
    return toString.call(value) === "[object String]";
  }
  Is2.string = string;
  function number(value) {
    return toString.call(value) === "[object Number]";
  }
  Is2.number = number;
  function numberRange(value, min, max) {
    return toString.call(value) === "[object Number]" && min <= value && value <= max;
  }
  Is2.numberRange = numberRange;
  function integer2(value) {
    return toString.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
  }
  Is2.integer = integer2;
  function uinteger2(value) {
    return toString.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
  }
  Is2.uinteger = uinteger2;
  function func(value) {
    return toString.call(value) === "[object Function]";
  }
  Is2.func = func;
  function objectLiteral(value) {
    return value !== null && typeof value === "object";
  }
  Is2.objectLiteral = objectLiteral;
  function typedArray(value, check) {
    return Array.isArray(value) && value.every(check);
  }
  Is2.typedArray = typedArray;
})(Is || (Is = {}));


/***/ }),

/***/ "../pyright-internal/package.json":
/*!****************************************!*\
  !*** ../pyright-internal/package.json ***!
  \****************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"name":"pyright-internal","displayName":"pyright","description":"Type checker for the Python language","version":"1.1.359","license":"MIT","private":true,"files":["dist"],"scripts":{"build":"tsc","clean":"shx rm -rf ./dist ./out","webpack:testserver":"webpack --config ./src/tests/lsp/webpack.testserver.config.js --mode=development","webpack:testserver:watch":"npm run clean && webpack --config ./src/tests/lsp/webpack.testserver.config.js --mode development --watch --progress","test":"npm run webpack:testserver && jest --forceExit","test:norebuild":"jest --forceExit","test:coverage":"jest --forceExit --reporters=jest-junit --reporters=default --coverage --coverageReporters=cobertura --coverageReporters=html --coverageReporters=json","test:imports":"jest importResolver.test --forceExit --runInBand"},"dependencies":{"@actions/core":"^1.10.1","@iarna/toml":"2.2.5","@yarnpkg/fslib":"2.10.4","@yarnpkg/libzip":"2.3.0","chalk":"^4.1.2","chokidar":"^3.6.0","command-line-args":"^5.2.1","jsonc-parser":"^3.2.1","leven":"3.1.0","pyright-to-gitlab-ci":"^0.1.3","source-map-support":"^0.5.21","tmp":"^0.2.1","vscode-jsonrpc":"^9.0.0-next.2","vscode-languageserver":"^10.0.0-next.2","vscode-languageserver-textdocument":"1.0.11","vscode-languageserver-types":"^3.17.6-next.3","vscode-uri":"^3.0.8"},"devDependencies":{"@types/command-line-args":"^5.2.3","@types/fs-extra":"^11.0.4","@types/jest":"^29.5.12","@types/lodash":"^4.14.202","@types/node":"^17.0.45","@types/tmp":"^0.2.6","copy-webpack-plugin":"^11.0.0","esbuild-loader":"^3.2.0","jest":"^29.7.0","jest-junit":"^16.0.0","shx":"^0.3.4","ts-jest":"^29.1.2","ts-loader":"^9.5.1","typescript":"~5.2","webpack":"^5.90.1","webpack-cli":"^5.1.4","word-wrap":"1.2.5"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.cs.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.cs.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Vytvořit zástupná procedura typu","createTypeStubFor":"Vytvořit zástupnou proceduru typu pro modul {moduleName}","executingCommand":"Spouští se příkaz","filesToAnalyzeCount":"Počet souborů k analýze: {count}","filesToAnalyzeOne":"1 soubor k analýze","findingReferences":"Hledají se odkazy","organizeImports":"Uspořádat direktivy Import","renameShadowedFile":"Přejmenovat „{oldFile}“ na „{newFile}“"},"Completion":{"autoImportDetail":"Automatický import","indexValueDetail":"Hodnota indexu"},"Diagnostic":{"abstractMethodInvocation":"Metodu „{method}“ nelze volat, protože je abstraktní a neimplementovaná.","annotatedParamCountMismatch":"Počet poznámek parametrů se neshoduje: očekával(o/y) se {expected}, ale přijal(o/y) se {received}.","annotatedTypeArgMissing":"Byl očekáván jeden argument typu a jedna nebo více poznámek pro Annotated","annotationFormatString":"Poznámky typu nemůžou používat formátovací řetězcové literály (f-strings)","annotationNotSupported":"Poznámka typu není pro tento příkaz podporována","annotationSpansStrings":"Poznámky typu nemůžou zahrnovat více řetězcových literálů","annotationStringEscape":"Poznámky typu nemůžou obsahovat řídicí znaky","argAssignment":"Argument typu {argType} není možné přiřadit k parametru typu {paramType}","argAssignmentFunction":"Argument typu {argType} není možné přiřadit k parametru typu {paramType} ve funkci {functionName}","argAssignmentParam":"Argument typu {argType} není možné přiřadit k parametru {paramName} typu {paramType}","argAssignmentParamFunction":"Argument typu {argType} není možné přiřadit k parametru {paramName} typu {paramType} ve funkci {functionName}","argMissingForParam":"Chybí argument pro parametr {name}","argMissingForParams":"Chybí argumenty pro parametry {names}","argMorePositionalExpectedCount":"Očekával se tento počet dalších pozičních argumentů: {expected}","argMorePositionalExpectedOne":"Očekával se 1 další poziční argument","argPositional":"Očekávaný poziční argument","argPositionalExpectedCount":"Očekávaný počet pozičních argumentů: {expected}","argPositionalExpectedOne":"Očekával se 1 poziční argument","argTypePartiallyUnknown":"Typ argumentu je částečně neznámý","argTypeUnknown":"Typ argumentu je neznámý","assertAlwaysTrue":"Výraz Assert se vždy vyhodnotí jako true","assertTypeArgs":"assert_type očekává dva poziční argumenty","assertTypeTypeMismatch":"Neshoda assert_type: očekávalo se {expected}, ale přijalo se {received}","assignmentExprComprehension":"Cíl výrazu přiřazení „{name}“ nemůže používat stejný název jako porozumění cíli","assignmentExprContext":"Výraz přiřazení musí být uvnitř modulu, funkce nebo výrazu lambda","assignmentExprInSubscript":"Výrazy přiřazení v dolním indexu se podporují jenom v Pythonu 3.10 a novějším","assignmentInProtocol":"Proměnné instance nebo třídy v rámci třídy Protocol musí být explicitně deklarovány v těle třídy","assignmentTargetExpr":"Výraz nemůže být cílem přiřazení","asyncNotInAsyncFunction":"Použití „async“ není povolené mimo funkci async","awaitIllegal":"Použití operátoru await vyžaduje Python 3.5 nebo novější","awaitNotAllowed":"Poznámky typu nemůžou používat „await“.","awaitNotInAsync":"Operátor await je povolený jenom v rámci asynchronní funkce","backticksIllegal":"V Pythonu 3.x nejsou podporovány výrazy obklopené zpětnými tečkami; místo toho použijte repr","baseClassCircular":"Třída se nemůže odvozovat od sebe sama","baseClassFinal":"Základní třída {type} je označená jako final a nemůže být podtřídou","baseClassIncompatible":"Základní třídy typu {type} jsou vzájemně nekompatibilní","baseClassInvalid":"Argument třídy musí být základní třída","baseClassMethodTypeIncompatible":"Základní třídy pro třídu {classType} definují metodu {name} nekompatibilním způsobem","baseClassUnknown":"Typ základní třídy je neznámý, co zakrývá typ odvozené třídy","baseClassVariableTypeIncompatible":"Základní třídy pro třídu {classType} definují proměnnou {name} nekompatibilním způsobem","binaryOperationNotAllowed":"Binární operátor není v poznámce typu povolený","bindTypeMismatch":"Nepovedlo se vytvořit vazbu metody „{methodName}“, protože „{type}“ nejde přiřadit k parametru „{paramName}“","breakOutsideLoop":"„break“ se dá použít jenom ve smyčce","callableExtraArgs":"Pro Callable se očekávaly pouze dva argumenty typu","callableFirstArg":"Očekával se seznam typů parametrů nebo ...","callableNotInstantiable":"Není možné vytvořit instanci typu {type}","callableSecondArg":"Očekával se návratový typ jako druhý argument typu pro Callable","casePatternIsIrrefutable":"Nevyvratitelný vzorec je povolený jenom pro poslední výraz velikosti písmen","classAlreadySpecialized":"Typ {type} je už specializovaný","classDecoratorTypeUnknown":"Dekoratér netypové třídy překrývá typ třídy. dekoratér se ignoruje","classDefinitionCycle":"Definice třídy pro „{name}“ závisí sama na sobě","classGetItemClsParam":"Přepsání __class_getitem__ by mělo mít parametr cls","classMethodClsParam":"Metody třídy by měly mít parametr „cls“","classNotRuntimeSubscriptable":"Dolní index pro třídu {name} vygeneruje výjimku modulu runtime; anotaci typu uzavřete do uvozovek","classPatternBuiltInArgPositional":"Vzor třídy přijímá pouze poziční dílčí vzor","classPatternPositionalArgCount":"Příliš mnoho pozičních vzorů pro třídu \\"{type}\\"; očekávalo se {expected}, ale přijalo se {received}","classPatternTypeAlias":"Typ „{type}“ nelze použít ve vzorci třídy, protože se jedná o specializovaný alias typu","classPropertyDeprecated":"Vlastnosti třídy jsou v Pythonu 3.11 zastaralé a v Pythonu 3.13 se nebudou podporovat.","classTypeParametersIllegal":"Syntaxe parametru typu třídy vyžaduje Python 312 nebo novější","classVarFirstArgMissing":"Za ClassVar byl očekáván argument typu","classVarNotAllowed":"ClassVar se v tomto kontextu nepovoluje","classVarOverridesInstanceVar":"Proměnná třídy {name} přepíše proměnnou instance se stejným názvem ve třídě {className}","classVarTooManyArgs":"Za „ClassVar“ byl očekáván pouze jeden argument typu","classVarWithTypeVar":"Typ ClassVar nemůže obsahovat proměnné typu","clsSelfParamTypeMismatch":"Typ parametru „{name}“ musí být nadtyp třídy „{classType}“","codeTooComplexToAnalyze":"Kód je příliš složitý na analýzu; snižte složitost refaktorizací do podprogramů nebo redukcí podmíněných cest kódu","collectionAliasInstantiation":"Nelze vytvořit instanci typu „{type}“. Použijte místo toho „{alias}“","comparisonAlwaysFalse":"Podmínka se vždy vyhodnotí jako False, protože typy {leftType} a {rightType} se nepřekrývají","comparisonAlwaysTrue":"Podmínka se vždy vyhodnotí jako True, protože typy {leftType} a {rightType} se nepřekrývají","comprehensionInDict":"Porozumění není možné použít s jinými položkami slovníku","comprehensionInSet":"Porozumění nelze použít s jinými položkami sady","concatenateContext":"Možnost „Concatenate“ není v tomto kontextu povolená.","concatenateParamSpecMissing":"Poslední argument typu pro „Concatenate“ musí být „ParamSpec“ nebo „...“","concatenateTypeArgsMissing":"Možnost „Concatenate“ vyžaduje alespoň dva argumenty typu","conditionalOperandInvalid":"Neplatný podmíněný operand typu {type}","constantRedefinition":"„{name}“ je konstanta (protože je velkými písmeny) a nedá se předefinovat","constructorNoArgs":"Pro konstruktor {type} nebyly očekávány žádné argumenty","constructorParametersMismatch":"Neshoda mezi signaturou __new__ a __init__ ve třídě“ {classType}“","containmentAlwaysFalse":"Výraz se vždy vyhodnotí jako False, protože typy „{leftType}“ a „{rightType}“ se nepřekrývají","containmentAlwaysTrue":"Výraz se vždy vyhodnotí jako True, protože typy „{leftType}“ a „{rightType}“ se nepřekrývají.","continueInFinally":"continue není možné použít v klauzuli finally","continueOutsideLoop":"continue se dá použít jenom ve smyčce","coroutineInConditionalExpression":"Podmíněný výraz odkazuje na korutinu, která se vždy vyhodnotí jako True.","dataClassBaseClassFrozen":"Nezablokovaná třída nemůže dědit z zmrazené třídy","dataClassBaseClassNotFrozen":"Zablokovaná třída nemůže dědit z třídy, která není zablokovaná","dataClassConverterFunction":"Argument typu {argType} není platný převaděč pro pole {fieldName} typu {fieldType}","dataClassConverterOverloads":"Žádná přetížení {funcName} nejsou platné převaděče pro pole {fieldName} typu {fieldType}","dataClassFieldWithDefault":"Pole bez výchozích hodnot se nemůžou zobrazit po polích s výchozími hodnotami","dataClassFieldWithPrivateName":"Pole datové třídy nemůže používat privátní název","dataClassFieldWithoutAnnotation":"Pole dataclass bez poznámky typu způsobí výjimku modulu runtime","dataClassPostInitParamCount":"Datová třída __post_init__ má nesprávný počet parametrů; počet polí InitVar je {expected}","dataClassPostInitType":"Neshoda typu parametru metody __post_init__ datové třídy pro pole {fieldName}","dataClassSlotsOverwrite":"__slots__ je už ve třídě definovaný","dataClassTransformExpectedBoolLiteral":"Očekával se výraz, který se staticky vyhodnotí jako True nebo False","dataClassTransformFieldSpecifier":"Očekávala se řazená kolekce členů tříd nebo funkcí, ale přijatý typ „{type}“","dataClassTransformPositionalParam":"Všechny argumenty dataclass_transform musí být argumenty klíčových slov","dataClassTransformUnknownArgument":"Argument {name} není v dataclass_transform podporován","dataProtocolInSubclassCheck":"Datové protokoly (které zahrnují atributy bez metody) nejsou ve voláních issubclass povolené.","declaredReturnTypePartiallyUnknown":"Deklarovaný návratový typ {returnType} je částečně neznámý","declaredReturnTypeUnknown":"Deklarovaný návratový typ je neznámý","defaultValueContainsCall":"Volání funkcí a měnitelné objekty nejsou povoleny ve výrazu výchozí hodnoty parametru","defaultValueNotAllowed":"Parametr s * nebo ** nemůže mít výchozí hodnotu","delTargetExpr":"Výraz se nedá odstranit","deprecatedClass":"Třída {name} je zastaralá","deprecatedConstructor":"Konstruktor pro třídu {name} je zastaralý","deprecatedDescriptorDeleter":"Metoda „__delete__“ pro popisovač „{name}“ je zastaralá","deprecatedDescriptorGetter":"Metoda „__get__“ pro popisovač „{name}“ je zastaralá","deprecatedDescriptorSetter":"Metoda „__set__“ pro popisovač „{name}“ je zastaralá","deprecatedFunction":"Funkce {name} je zastaralá.","deprecatedMethod":"Metoda {name} ve třídě {className} je zastaralá.","deprecatedPropertyDeleter":"Odstraňovač pro vlastnost „{name}“ je zastaralý","deprecatedPropertyGetter":"Metoda getter pro vlastnost „{name}“ je zastaralá","deprecatedPropertySetter":"Metoda setter pro vlastnost „{name}“ je zastaralá","deprecatedType":"Tento typ je zastaralý jako Python {version}; místo toho použijte {replacement}","dictExpandIllegalInComprehension":"Rozšíření slovníku není v porozumění povoleno","dictInAnnotation":"Výraz slovníku není v poznámce typu povolený","dictKeyValuePairs":"Položky slovníku musí obsahovat páry klíč/hodnota","dictUnpackIsNotMapping":"Očekávalo se mapování pro operátor rozbalení slovníku","dunderAllSymbolNotPresent":"{name} je zadáno v __all__, ale v modulu se nenachází","duplicateArgsParam":"Je povolený jenom jeden parametr *","duplicateBaseClass":"Duplicitní základní třída není povolena","duplicateCapturePatternTarget":"Cíl zachytávání {name} se v rámci stejného vzoru nemůže vyskytovat více než jednou","duplicateCatchAll":"Je povolena pouze jedna klauzule catch-all except","duplicateEnumMember":"Člen výčtu {name} je už deklarovaný","duplicateGenericAndProtocolBase":"Je povolena pouze jedna základní třída Generic nebo Protocol**","duplicateImport":"Import {importName} je importován více než jednou","duplicateKeywordOnly":"Je povolený jenom jeden oddělovač *","duplicateKwargsParam":"Je povolený jenom jeden parametr **","duplicateParam":"duplicitní parametr {name}","duplicatePositionOnly":"Je povolený jenom jeden parametr „/“","duplicateStarPattern":"V sekvenci vzorů je povolený jenom jeden vzor „*“","duplicateStarStarPattern":"Je povolena pouze jedna položka „**“","duplicateUnpack":"V seznamu je povolena pouze jedna operace rozbalení","ellipsisAfterUnpacked":"„…“ nelze použít s rozbalenou kolekcí TypeVarTuple nebo řazenou kolekcí členů.","ellipsisContext":"„...“ se v tomto kontextu nepovoluje","ellipsisSecondArg":"„...“ je povoleno pouze jako druhý ze dvou argumentů","enumClassOverride":"Třída výčtu {name} je konečná a nemůže být podtřídou","exceptionGroupIncompatible":"Syntaxe skupiny výjimek (except*) vyžaduje Python 3.11 nebo novější","exceptionTypeIncorrect":"„{type}“ se neodvozuje od BaseException","exceptionTypeNotClass":"{type} není platná třída výjimky","exceptionTypeNotInstantiable":"Konstruktor pro výjimku typu {type} vyžaduje jeden nebo více argumentů","expectedAfterDecorator":"Očekávaná deklarace funkce nebo třídy po dekoratéru","expectedArrow":"Byl očekáván znak -> následovaný anotací návratového typu","expectedAsAfterException":"Za typem výjimky byl očekáván znak „as“","expectedAssignRightHandExpr":"Byl očekáván výraz napravo od znaku =","expectedBinaryRightHandExpr":"Očekával se výraz napravo od operátoru","expectedBoolLiteral":"Očekávala se hodnota True nebo False","expectedCase":"Očekával se příkaz case","expectedClassName":"Očekával se název třídy","expectedCloseBrace":"{ nebyla uzavřena","expectedCloseBracket":"[ nebyla uzavřena","expectedCloseParen":"( nebyla uzavřena","expectedColon":"Očekával se znak :","expectedComplexNumberLiteral":"Očekával se komplexní číselný literál pro porovnávání vzorů","expectedDecoratorExpr":"Forma výrazu není podporována pro dekorátor před verzí Python 3.9","expectedDecoratorName":"Očekával se název dekoratéru","expectedDecoratorNewline":"Na konci dekoratéru byl očekáván nový řádek","expectedDelExpr":"Za del se očekával výraz","expectedElse":"Očekávalo se else","expectedEquals":"Očekával se znak =","expectedExceptionClass":"Neplatná třída nebo objekt výjimky","expectedExceptionObj":"Byl očekáván objekt výjimky, třída výjimky nebo None","expectedExpr":"Očekávaný výraz","expectedFunctionAfterAsync":"Očekávaná definice funkce po „async“","expectedFunctionName":"Za def se očekával název funkce","expectedIdentifier":"Očekávaný identifikátor","expectedImport":"Očekával se import","expectedImportAlias":"Za as byl očekáván symbol","expectedImportSymbols":"Po importu se očekával jeden nebo více názvů symbolů","expectedIn":"Očekávalo se in","expectedInExpr":"Za in byl očekáván výraz","expectedIndentedBlock":"Očekával se odsazený blok","expectedMemberName":"Za znakem . byl očekáván název člena","expectedModuleName":"Očekávaný název modulu","expectedNameAfterAs":"Za „as“ se očekával název symbolu","expectedNamedParameter":"Parametr klíčového slova musí následovat za znakem *","expectedNewline":"Očekával se nový řádek","expectedNewlineOrSemicolon":"Příkazy musí být oddělené novými řádky nebo středníky","expectedOpenParen":"Očekával se znak „(“","expectedParamName":"Očekával se název parametru","expectedPatternExpr":"Očekávaný výraz vzoru","expectedPatternSubjectExpr":"Očekávaný výraz předmětu vzoru","expectedPatternValue":"Očekávaný výraz hodnoty vzoru ve formátu a.b","expectedReturnExpr":"Za return se očekával výraz","expectedSliceIndex":"Očekávaný výraz indexu nebo řezu","expectedTypeNotString":"Očekával se typ, ale přijal se řetězcový literál","expectedTypeParameterName":"Očekávaný název parametru typu","expectedYieldExpr":"Očekávaný výraz v příkazu yield","finalClassIsAbstract":"Třída „{type}“ je označená jako konečná a musí implementovat všechny abstraktní symboly","finalContext":"Final se v tomto kontextu nepovoluje","finalMethodOverride":"Metoda {name} nemůže přepsat konečnou metodu definovanou ve třídě {className}","finalNonMethod":"Funkci „{name}“ nelze označit @final, protože se nejedná o metodu.","finalReassigned":"„{name}“ se deklaruje jako Final a nedá se znovu přiřadit","finalRedeclaration":"{name} se dříve deklarovalo jako Final","finalRedeclarationBySubclass":"{name} se nedá deklarovat znovu, protože nadřazená třída {className} ji deklaruje jako final","finalTooManyArgs":"Za Final byl očekáván jeden argument typu","finalUnassigned":"{name} se deklaruje jako final, ale hodnota není přiřazená","formatStringBrace":"Jednoduchá pravá složená závorka není v literálu f-string povolena. použijte dvojitou pravou složenou závorku","formatStringBytes":"Formátovací řetězcové literály (f-strings) nemůžou být binární","formatStringDebuggingIllegal":"Specifikátor ladění F-string „=“ vyžaduje Python 3.8 nebo novější","formatStringEscape":"Řídicí sekvence (zpětné lomítko) není povolená v části výrazu f-string před Python 3.12","formatStringExpectedConversion":"V řetězci f-string byl za znakem ! očekáván specifikátor převodu","formatStringIllegal":"Formátovací řetězcové literály (f-string) vyžadují Python 3.6 nebo novější","formatStringInPattern":"Formátovací řetězec není ve vzoru povolený","formatStringNestedFormatSpecifier":"Příliš hluboko vnořené výrazy v rámci specifikátoru formátovacího řetězce","formatStringNestedQuote":"Řetězce vnořené v řetězci f-string nemůžou používat stejný znak uvozovek jako řetězec f-string před Python 3.12","formatStringUnicode":"Formátovací řetězcové literály (f-strings) nemůžou být unicode","formatStringUnterminated":"Neukončený výraz v f-string; očekává se „}“","functionDecoratorTypeUnknown":"Dekorátor netypové funkce překrývá typ funkce; ignoruje se dekoratér","functionInConditionalExpression":"Podmíněný výraz odkazuje na funkci, která se vždy vyhodnotí jako True","functionTypeParametersIllegal":"Syntaxe parametru typu funkce vyžaduje Python 3.12 nebo novější","futureImportLocationNotAllowed":"Importy z __future__ musí být na začátku souboru","generatorAsyncReturnType":"Návratový typ funkce asynchronního generátoru musí být kompatibilní s typem AsyncGenerator[{yieldType}, Any]","generatorNotParenthesized":"Výrazy generátoru musí být v závorkách, pokud nejsou jediným argumentem","generatorSyncReturnType":"Návratový typ funkce generátoru musí být kompatibilní s Generator[{yieldType}, Any, Any]","genericBaseClassNotAllowed":"Základní třídu „Generic“ nejde použít se syntaxí parametru typu","genericClassAssigned":"Obecný typ třídy není možné přiřadit","genericClassDeleted":"Obecný typ třídy nelze odstranit","genericInstanceVariableAccess":"Přístup k obecné proměnné instance prostřednictvím třídy je nejednoznačný.","genericNotAllowed":"Generic není v tomto kontextu platný","genericTypeAliasBoundTypeVar":"Alias obecného typu v rámci třídy nemůže používat proměnné vázaného typu {names}","genericTypeArgMissing":"Generic vyžaduje alespoň jeden argument typu","genericTypeArgTypeVar":"Argument typu pro Generic musí být proměnná typu","genericTypeArgUnique":"Argumenty typu pro Generic musí být jedinečné","globalReassignment":"{name} je přiřazen před globální deklarací","globalRedefinition":"Název {name} už je deklarován jako globální","implicitStringConcat":"Implicitní zřetězení řetězců není povolené","importCycleDetected":"V řetězci importu byl zjištěn cyklus","importDepthExceeded":"Hloubka řetězu importu překročila {depth}","importResolveFailure":"Import {importName} se nepovedlo vyřešit","importSourceResolveFailure":"Import {importName} se nepovedlo přeložit ze zdroje","importSymbolUnknown":"{name} je neznámý symbol importu","incompatibleMethodOverride":"Metoda {name} přepisuje třídu {className} nekompatibilním způsobem","inconsistentIndent":"Množství zrušeného odsazení neodpovídá předchozímu odsazení","inconsistentTabs":"Nekonzistentní použití tabulátorů a mezer v odsazení","initMustReturnNone":"Návratový typ __init__ musí být None","initSubclassCallFailed":"Nesprávné argumenty klíčového slova pro metodu __init_subclass__","initSubclassClsParam":"Přepsání __init_subclass__ by mělo mít parametr cls","initVarNotAllowed":"InitVar se v tomto kontextu nepovoluje.","instanceMethodSelfParam":"Metody instance by měly mít parametr self","instanceVarOverridesClassVar":"Proměnná instance „{name}“ přepíše proměnnou třídy se stejným názvem ve třídě „{className}“","instantiateAbstract":"Nelze vytvořit instanci abstraktní třídy „{type}“","instantiateProtocol":"Nelze vytvořit instanci třídy protokolu „{type}“","internalBindError":"Při vytváření vazby souboru {file} došlo k vnitřní chybě: {message}","internalParseError":"Při analýze souboru {file} došlo k vnitřní chybě: {message}","internalTypeCheckingError":"Při kontrole typu souboru {file} došlo k vnitřní chybě: {message}","invalidIdentifierChar":"Neplatný znak v identifikátoru","invalidStubStatement":"Příkaz je v souboru zástupné procedury typu bezvýznamný","invalidTokenChars":"Neplatný znak „{text}“ v tokenu","isInstanceInvalidType":"Druhý argument pro „isinstance“ musí být třída nebo řazená kolekce členů tříd","isSubclassInvalidType":"Druhý argument pro issubclass musí být třída nebo řazená kolekce členů tříd","keyValueInSet":"Páry klíč-hodnota nejsou v rámci sady povoleny","keywordArgInTypeArgument":"Argumenty klíčových slov nelze použít v seznamech argumentů typu","keywordOnlyAfterArgs":"Oddělovač argumentů jen pro klíčová slova není povolený za parametrem *","keywordParameterMissing":"Jeden nebo více parametrů klíčového slova musí následovat za parametrem „*“","keywordSubscriptIllegal":"Argumenty klíčových slov v dolních indexech nejsou podporovány","lambdaReturnTypePartiallyUnknown":"Návratový typ lambda {returnType} je částečně neznámý","lambdaReturnTypeUnknown":"Návratový typ výrazu lambda je neznámý","listAssignmentMismatch":"Výraz s typem {type} se nedá přiřadit k cílovému seznamu","listInAnnotation":"Výraz seznamu není v poznámce typu povolený","literalEmptyArgs":"Za literálem se očekával jeden nebo více argumentů typu","literalNotAllowed":"„Literal“ nejde v tomto kontextu použít bez argumentu typu.","literalNotCallable":"Není možné vytvořit instanci typu literálu","literalUnsupportedType":"Argumenty typu pro Literal musí být None, hodnota literálu (int, bool, str nebo bytes) nebo hodnota výčtu","matchIncompatible":"Příkazy match vyžadují Python 3.10 nebo novější","matchIsNotExhaustive":"Případy v rámci příkazu match nezpracovávají kompletně všechny hodnoty","maxParseDepthExceeded":"Byla překročena maximální hloubka analýzy; rozdělte výraz na dílčí výrazy","memberAccess":"Není možné získat přístup ke členu {name} pro typ {type}","memberDelete":"Není možné odstranit člena {name} pro typ {type}","memberSet":"Nelze přiřadit člena „{name}“ pro typ „{type}“","metaclassConflict":"Metatřída odvozené třídy musí být podtřídou metatříd všech jejích základních tříd","metaclassDuplicate":"Je možné zadat pouze jednu metatřídu","metaclassIsGeneric":"Metatřída nemůže být obecná","methodNotDefined":"Metoda {name} není definována","methodNotDefinedOnType":"Metoda {name} není u typu {type} definována","methodOrdering":"Není možné vytvořit konzistentní řazení metod","methodOverridden":"„{name}“ přepisuje metodu se stejným názvem ve třídě „{className}“ s nekompatibilním typem {type}","methodReturnsNonObject":"Metoda {name} nevrací objekt","missingSuperCall":"Metoda {methodName} nevolá metodu se stejným názvem v nadřazené třídě","moduleAsType":"Modul nejde použít jako typ","moduleNotCallable":"Modul není volatelný","moduleUnknownMember":"Člen „{memberName}“ není známým členem modulu „{moduleName}“","namedExceptAfterCatchAll":"Za klauzulí catch-all except se nemůže objevit pojmenovaná klauzule except","namedParamAfterParamSpecArgs":"Parametr klíčového slova {name} se nemůže objevit v signatuře za parametrem argumentů ParamSpec","namedTupleEmptyName":"Názvy v pojmenované řazené kolekci členů nemůžou být prázdné.","namedTupleEntryRedeclared":"{name} nejde přepsat, protože nadřazená třída {className} je pojmenovaná řazená kolekce členů.","namedTupleFirstArg":"Jako první argument byl očekáván název pojmenované třídy řazené kolekce členů","namedTupleMultipleInheritance":"Vícenásobná dědičnost s NamedTuple se nepodporuje","namedTupleNameKeyword":"Názvy polí nemůžou být klíčové slovo.","namedTupleNameType":"Očekávala se řazená kolekce členů se dvěma položkami určující název a typ položky","namedTupleNameUnique":"Názvy v pojmenované řazené kolekci členů musí být jedinečné","namedTupleNoTypes":"namedtuple neposkytuje žádné typy pro položky řazené kolekce členů; místo toho použijte NamedTuple","namedTupleSecondArg":"Jako druhý argument byl očekáván pojmenovaný seznam řazené kolekce členů","newClsParam":"Přepsání __new__ by mělo mít parametr cls","newTypeAnyOrUnknown":"Druhý argument pro NewType musí být známá třída, nikoli Any nebo Unknown.","newTypeBadName":"Prvním argumentem pro NewType musí být řetězcový literál","newTypeLiteral":"Typ NewType není možné použít s typem Literal","newTypeNameMismatch":"Typ NewType musí být přiřazen proměnné se stejným názvem.","newTypeNotAClass":"Očekávaná třída jako druhý argument pro NewType","newTypeParamCount":"NewType vyžaduje dva poziční argumenty","newTypeProtocolClass":"NewType nelze použít se strukturálním typem (protokol nebo třída TypedDict).","noOverload":"Zadaným argumentům neodpovídají žádná přetížení pro {name}","noReturnContainsReturn":"Funkce s deklarovaným návratovým typem NoReturn nemůže obsahovat příkaz return","noReturnContainsYield":"Funkce s deklarovaným návratovým typem NoReturn nemůže obsahovat příkaz yield","noReturnReturnsNone":"Funkce s deklarovaným návratovým typem „NoReturn“ nemůže vrátit „None“.","nonDefaultAfterDefault":"Nevýchozí argument následuje za výchozím argumentem","nonLocalInModule":"Nemístní deklarace není povolená na úrovni modulu","nonLocalNoBinding":"Nenašla se žádná vazba pro nemístní {name}","nonLocalReassignment":"{name} je přiřazeno před nemístní deklarací","nonLocalRedefinition":"{name} již bylo deklarováno jako nemístní","noneNotCallable":"Objekt typu „None“ nelze volat.","noneNotIterable":"Objekt typu None není možné použít jako iterovatelnou hodnotu","noneNotSubscriptable":"Objekt typu “None“ nelze zadat jako dolní index","noneNotUsableWith":"Objekt typu None není možné použít s with","noneOperator":"Operátor {operator} se pro None nepodporuje","noneUnknownMember":"{name} není známým členem None","notRequiredArgCount":"Za NotRequired byl očekáván jeden argument typu","notRequiredNotInTypedDict":"NotRequired není v tomto kontextu povolené","objectNotCallable":"Objekt typu {type} není možné volat","obscuredClassDeclaration":"Deklarace třídy {name} je zakrytá deklarací stejného jména","obscuredFunctionDeclaration":"Deklarace funkce {name} je zakrytá deklarací stejného názvu","obscuredMethodDeclaration":"Deklarace metody {name} je zakrytá deklarací stejného názvu","obscuredParameterDeclaration":"Deklarace parametru {name} je zakrytá deklarací stejného názvu","obscuredTypeAliasDeclaration":"Deklarace aliasu typu {name} je zakrytá deklarací stejného názvu","obscuredVariableDeclaration":"Deklarace {name} je zakrytá deklarací stejného názvu","operatorLessOrGreaterDeprecated":"Operátor <> se v Pythonu 3 nepodporuje; místo toho použijte !=","optionalExtraArgs":"Za nepovinnou hodnotou se očekával jeden argument typu","orPatternIrrefutable":"Nevratný vzor je povolený jenom jako poslední dílčí vzorec ve vzorci „or“","orPatternMissingName":"Všechny dílčí vzory v rámci vzoru or musí cílit na stejné názvy","overlappingKeywordArgs":"Slovník silného typu se překrývá s parametrem klíčového slova: {names}","overlappingOverload":"Přetížení {obscured} pro {name} se nikdy nepoužije, protože jeho parametry se překrývají s přetížením {obscuredBy}","overloadAbstractMismatch":"Přetížené metody musí být všechny abstraktní nebo ne","overloadClassMethodInconsistent":"Přetížení pro {name} používají @classmethod nekonzistentně.","overloadFinalInconsistencyImpl":"Přetížení pro „{name}“ je označené @final ale implementace není","overloadFinalInconsistencyNoImpl":"Přetížení {index} pro „{name}“ je označené @final ale přetížení 1 není","overloadImplementationMismatch":"Přetížená implementace není konzistentní se signaturou přetížení {index}","overloadReturnTypeMismatch":"Přetížení {prevIndex} pro {name} se překrývá s přetížením {newIndex} a vrací nekompatibilní typ","overloadStaticMethodInconsistent":"Přetížení pro {name} používají @staticmethod nekonzistentně.","overloadWithoutImplementation":"„{name}“ je označen(é/o) jako přetížení, ale není zadaná žádná implementace","overriddenMethodNotFound":"Metoda „{name}“ je označená jako přepsání, ale neexistuje žádná základní metoda se stejným názvem","overrideDecoratorMissing":"Metoda „{name}“ není označená jako přepsání, ale přepisuje metodu ve třídě „{className}“","paramAfterKwargsParam":"Parametr nemůže následovat za parametrem „**“","paramAlreadyAssigned":"Parametr {name} je už přiřazený","paramAnnotationMissing":"Chybí poznámka typu pro parametr „{name}“","paramAssignmentMismatch":"Výraz typu „{sourceType}“ nelze přiřadit k parametru typu „{paramType}“","paramNameMissing":"Žádný parametr s názvem {name}","paramSpecArgsKwargsUsage":"Členy argumentů args a kwargs parametru ParamSpec se musí vyskytovat v signatuře funkce","paramSpecArgsMissing":"Chybí argumenty pro parametr ParamSpec {type}","paramSpecArgsUsage":"Člen „args“ parametru ParamSpec je platný jenom v případě, že se používá s parametrem *args","paramSpecAssignedName":"Parametr ParamSpec musí být přiřazen proměnné s názvem {name}","paramSpecContext":"ParamSpec se v tomto kontextu nepovoluje","paramSpecDefaultNotTuple":"Očekávaly se tři tečky, výraz řazené kolekce členů nebo Parametr ParamSpec pro výchozí hodnotu ParamSpec","paramSpecFirstArg":"Očekával se název parametru ParamSpec jako první argument","paramSpecKwargsUsage":"Člen kwargs parametru ParamSpec je platný jenom v případě, že se používá s parametrem **kwargs","paramSpecNotUsedByOuterScope":"Parametr ParamSpec {name} nemá v tomto kontextu žádný význam","paramSpecScopedToReturnType":"Parametr ParamSpec {name} je vymezený na volatelnou proměnnou v rámci návratového typu a nedá se na něj odkazovat v těle funkce jazyka","paramSpecUnknownArg":"Parametr ParamSpec nepodporuje více než jeden argument","paramSpecUnknownMember":"{name} není známý člen ParamSpec","paramSpecUnknownParam":"„{name}“ je neznámý parametr parametru ParamSpec","paramTypeCovariant":"Proměnnou kovariantní typu není možné použít v typu parametru","paramTypePartiallyUnknown":"Typ parametru {paramName} je částečně neznámý","paramTypeUnknown":"Typ parametru {paramName} je neznámý","parenthesizedContextManagerIllegal":"Závorky v příkazu with vyžadují Python 3.9 nebo novější","patternNeverMatches":"Vzor se nikdy nebude shodovat s typem předmětu {type}","positionArgAfterNamedArg":"Poziční argument se nemůže objevit za argumenty klíčového slova","positionOnlyAfterArgs":"Oddělovač parametrů jen pro pozici není povolený za parametrem *.","positionOnlyAfterKeywordOnly":"Parametr / se musí zobrazit před parametrem *","positionOnlyAfterNon":"Parametr jen pro pozici není povolený za parametrem, který není jen pro pozici.","positionOnlyFirstParam":"Oddělovač parametrů jen pro pozici není povolený jako první parametr.","positionOnlyIncompatible":"Oddělovač parametrů jen pro pozici vyžaduje Python 3.8 nebo novější.","privateImportFromPyTypedModule":"{name} se neexportuje z modulu {module}","privateUsedOutsideOfClass":"{name} je privátní a používá se mimo třídu, ve které je deklarovaná","privateUsedOutsideOfModule":"{name} je privátní a používá se mimo modul, ve kterém je deklarován","propertyOverridden":"„{name}“ nesprávně přepíše vlastnost se stejným názvem ve třídě {className}","propertyStaticMethod":"Statické metody nejsou povoleny pro metodu getter, setter nebo deleter vlastnosti","protectedUsedOutsideOfClass":"„{name}“ je chráněn(ý/o/é) a používá se mimo třídu, ve které je deklarovaná","protocolBaseClass":"Třída protokolu „{classType}“ se nemůže odvozovat od třídy,která není protokolem „{baseType}“","protocolBaseClassWithTypeArgs":"Argumenty typu nejsou u třídy Protocol povoleny při použití syntaxe parametru typu","protocolIllegal":"Použití protokolu vyžaduje Python 3.7 nebo novější","protocolNotAllowed":"„Protocol“ nejde v tomto kontextu použít.","protocolUnsafeOverlap":"Třída se nebezpečně překrývá s názvem „{name}“ a může vytvořit shodu při spuštění.","protocolVarianceContravariant":"Proměnná typu „{variable}“ použitá v obecném protokolu „{class}“ by měla být kontravariantní","protocolVarianceCovariant":"Proměnná typu „{variable}“ použitá v obecném protokolu „{class}“ by měla být kovariantní","protocolVarianceInvariant":"Proměnná typu „{variable}“ použitá v obecném protokolu „{class}“ by měla být invariantní","pyrightCommentInvalidDiagnosticBoolValue":"Za direktivou komentářů Pyright musí následovat znak =a hodnota true nebo false","pyrightCommentInvalidDiagnosticSeverityValue":"Za direktivou komentářů Pyright musí následovat = a hodnota true, false, error, warning, information nebo none","pyrightCommentMissingDirective":"Za komentářem Pyright musí následovat direktiva (základní nebo striktní) nebo diagnostické pravidlo","pyrightCommentNotOnOwnLine":"Komentáře Pyright používané k řízení nastavení na úrovni souborů se musí zobrazovat na vlastním řádku","pyrightCommentUnknownDiagnosticRule":"{rule} je neznámé diagnostické pravidlo pro komentář pyright","pyrightCommentUnknownDiagnosticSeverityValue":"{value} je neplatná hodnota pro komentář pyright; očekávalo se true, false, error, warning, information nebo none","pyrightCommentUnknownDirective":"Direktiva {directive} je neznámá direktiva pro komentář pyright; očekávalo se strict nebo basic","readOnlyArgCount":"Za „ReadOnly“ se očekával jeden argument typu","readOnlyNotInTypedDict":"ReadOnly není v tomto kontextu povolené","recursiveDefinition":"Typ „{name}“ nelze určit, protože odkazuje sám na sebe","relativeImportNotAllowed":"Relativní importy se nedají použít s formulářem importu .a; místo toho použijte from . import a","requiredArgCount":"Za povinným argumentem se očekával jeden argument typu","requiredNotInTypedDict":"Required není v tomto kontextu povoleno","returnInAsyncGenerator":"Příkaz Return s hodnotou není v asynchronním generátoru povolený","returnMissing":"Funkce s deklarovaným návratovým typem „{returnType}“ musí vracet hodnotu na všech cestách kódu","returnOutsideFunction":"„return“ se dá použít jenom v rámci funkce","returnTypeContravariant":"Kontravariantní proměnnou typu nejde použít v návratovém typu","returnTypeMismatch":"Výraz typu {exprType} není možné přiřadit k návratového typu {returnType}","returnTypePartiallyUnknown":"Návratový typ {returnType} je částečně neznámý","returnTypeUnknown":"Návratový typ je neznámý","revealLocalsArgs":"Pro volání reveal_locals se neočekávaly žádné argumenty","revealLocalsNone":"V tomto oboru nejsou žádné místní hodnoty","revealTypeArgs":"Pro volání reveal_type byl očekáván jeden poziční argument","revealTypeExpectedTextArg":"Argument „expected_text“ pro funkci „reveal_type“ musí být hodnota literálu str","revealTypeExpectedTextMismatch":"Neshoda typu textu; očekávaný počet: {expected}, počet, který byl přijat: {received}","revealTypeExpectedTypeMismatch":"Neshoda typů; Očekával(o/y) se „{expected}“, ale přijal(o/y) se „{received}“","selfTypeContext":"Self není v tomto kontextu platné","selfTypeMetaclass":"„Self“ nelze použít v rámci metatřídy (podtřídy „type“).","selfTypeWithTypedSelfOrCls":"Self není možné použít ve funkci s parametrem self nebo cls, která má jinou poznámku typu než Self","setterGetterTypeMismatch":"Typ hodnoty metody setter vlastnosti není možné přiřadit návratového typu getter","singleOverload":"{name} je označené jako přetížení, ale chybí další přetížení","slotsAttributeError":"„{name}“ není zadaný v __slots__","slotsClassVarConflict":"{name} je v konfliktu s proměnnou instance deklarovanou v __slots__","starPatternInAsPattern":"Vzor hvězdy se nedá použít s cílem as","starPatternInOrPattern":"Vzor hvězdy nemůže být ORed v jiných vzorech","starStarWildcardNotAllowed":"** není možné použít se zástupným znakem _","staticClsSelfParam":"Statické metody by neměly přijímat parametr self nebo cls","stdlibModuleOverridden":"„{path}“ přepisuje modul stdlib „{name}“","stringNonAsciiBytes":"Znak jiný než ASCII není povolený v bajtech řetězcového literálu","stringNotSubscriptable":"Řetězcový výraz není možné v poznámce typu zadat jako dolní index uzavření celé poznámky do uvozovek","stringUnsupportedEscape":"Nepodporovaná řídicí sekvence v řetězcovém literálu","stringUnterminated":"Řetězcový literál je neukončený","stubFileMissing":"Soubor zástupné procedury pro {importName} se nenašel","stubUsesGetAttr":"Soubor zástupné procedury typu je neúplný; __getattr__ zakrývá typové chyby pro modul","sublistParamsIncompatible":"Parametry podsestavy nejsou v Python 3.x podporované","superCallArgCount":"Pro volání „super“ se očekávaly maximálně dva argumenty","superCallFirstArg":"Jako první argument pro volání super se očekával typ třídy, ale přijal se {type}","superCallSecondArg":"Druhý argument volání super musí být objekt nebo třída odvozená z typu {type}","superCallZeroArgForm":"Forma nulového argumentu „super“ volání je platná pouze v rámci metody.","superCallZeroArgFormStaticMethod":"Forma nulového argumentu „super“ volání není platná v rámci statické metody.","symbolIsPossiblyUnbound":"{name} je pravděpodobně nevázané","symbolIsUnbound":"Název {name} je nevázaný","symbolIsUndefined":"{name} není definované","symbolOverridden":"{name} přepíše symbol stejného názvu ve třídě {className}","ternaryNotAllowed":"Výraz ternary není v poznámce typu povolený.","totalOrderingMissingMethod":"Třída musí definovat jednu z __lt__, __le__, __gt__ nebo __ge__, aby bylo možné používat total_ordering","trailingCommaInFromImport":"Koncová čárka není povolena bez okolních závorek","tryWithoutExcept":"Příkaz Try musí mít alespoň jednu klauzuli except nebo finally","tupleAssignmentMismatch":"Výraz s typem „{type}“ se nedá přiřadit cílové řazené kolekci členů","tupleInAnnotation":"Výraz řazené kolekce členů není v poznámce typu povolený","tupleIndexOutOfRange":"Index {index} je pro typ {type} mimo rozsah","typeAliasIllegalExpressionForm":"Neplatný formulář výrazu pro definici aliasu typu","typeAliasIsRecursiveDirect":"Alias typu „{name}“ nemůže ve své definici používat sám sebe","typeAliasNotInModuleOrClass":"Typ TypeAlias je možné definovat pouze v rámci oboru modulu nebo třídy","typeAliasRedeclared":"{name} se deklaruje jako TypAlias a dá se přiřadit jenom jednou","typeAliasStatementBadScope":"Příkaz type se dá použít jenom v rámci oboru modulu nebo třídy.","typeAliasStatementIllegal":"Příkaz alias typu vyžaduje Python 3.12 nebo novější","typeAliasTypeBaseClass":"Alias typu definovaný v příkazu „typ“ nejde použít jako základní třídu","typeAliasTypeMustBeAssigned":"Typ TypeAliasType musí být přiřazen proměnné se stejným názvem jako alias typu","typeAliasTypeNameArg":"První argument typeAliasType musí být řetězcový literál představující název aliasu typu","typeAliasTypeNameMismatch":"Název aliasu typu se musí shodovat s názvem proměnné, ke které je přiřazená","typeAliasTypeParamInvalid":"Seznam parametrů typu musí být řazená kolekce členů obsahující pouze typeVar, TypeVarTuple nebo ParamSpec","typeAnnotationCall":"Výraz volání není ve výrazu typu povolený","typeAnnotationVariable":"Proměnná není ve výrazu typu povolená","typeAnnotationWithCallable":"Argument typu pro „type“ musí být třída; volatelné objekty se nepodporují.","typeArgListExpected":"Očekával se parametr ParamSpec, tři tečky nebo seznam typů","typeArgListNotAllowed":"Výraz seznamu není pro tento argument typu povolený","typeArgsExpectingNone":"Pro třídu {name} se neočekávaly žádné argumenty typu","typeArgsMismatchOne":"Očekával se jeden argument typu, ale bylo přijato {received}","typeArgsMissingForAlias":"Pro alias obecného typu {name} se očekávaly argumenty typu","typeArgsMissingForClass":"Očekávané argumenty typu pro obecnou třídu „{name}“","typeArgsTooFew":"Pro {name} se zadalo příliš málo argumentů typu. Očekávalo se {expected}, ale přijalo se {received}","typeArgsTooMany":"Pro „{name}“ se zadalo příliš mnoho argumentů typu. Očekával(o/y) se {expected}, ale přijal(o/y) se {received}","typeAssignmentMismatch":"Výraz typu {sourceType} není možné přiřadit deklarovanému typu {destType}","typeAssignmentMismatchWildcard":"Symbol importu {name} má typ {sourceType}, který nejde přiřadit deklarovanému typu {destType}.","typeCallNotAllowed":"Volání type() by se nemělo používat v poznámce typu","typeCheckOnly":"Název {name} je označený jako @type_check_only a dá se použít jenom v poznámkách typu","typeCommentDeprecated":"Použití komentářů typu je zastaralé místo toho použít anotaci typu","typeExpectedClass":"Očekával se výraz typu, ale přijal se {type}","typeGuardArgCount":"Za TypeGuard nebo TypeIs byl očekáván jeden argument typu.","typeGuardParamCount":"Funkce a metody ochrany typů definované uživatelem musí mít alespoň jeden vstupní parametr","typeIsReturnType":"Návratový typ TypeIs ({returnType}) není konzistentní s typem parametru hodnoty ({type}).","typeNotAwaitable":"„{type}“ se nedá očekávat.","typeNotIntantiable":"Není možné vytvořit instanci {type}","typeNotIterable":"{type} není možné iterovat","typeNotSpecializable":"Nepovedlo se specializovat typ „{type}“","typeNotSubscriptable":"Objekt typu {type} není možné zadat jako dolní index","typeNotSupportBinaryOperator":"Operátor „{operator}“ se pro typy „{leftType}“ a „{rightType}“ nepodporuje","typeNotSupportBinaryOperatorBidirectional":"Operátor {operator} není podporován pro typy „{leftType}“ a „{rightType}“, pokud se očekává typ „{expectedType}“","typeNotSupportUnaryOperator":"Operátor {operator} se pro typ {type} nepodporuje","typeNotSupportUnaryOperatorBidirectional":"Operátor {operator} není podporován pro typ {type}, když očekávaný typ je {expectedType}","typeNotUsableWith":"Objekt typu {type} není možné použít s typem with, protože neimplementuje metodu {method}","typeParameterBoundNotAllowed":"Vazbu nebo omezení nelze použít s parametrem variadického typu ani s parametrem ParamSpec","typeParameterConstraintTuple":"Omezení parametru typu musí být řazená kolekce členů dvou nebo více typů","typeParameterExistingTypeParameter":"Parametr typu {name} se už používá","typeParameterNotDeclared":"Parametr typu {name} není zahrnutý v seznamu parametrů typu pro kontejner {container}","typeParametersMissing":"Musí být zadán alespoň jeden parametr typu","typePartiallyUnknown":"Typ {name} je částečně neznámý","typeUnknown":"Typ {name} je neznámý","typeVarAssignedName":"Typ TypeVar musí být přiřazen proměnné s názvem {name}","typeVarAssignmentMismatch":"Typ „{type}“ se nedá přiřadit proměnné typu „{name}“","typeVarBoundAndConstrained":"TypeVar nemůže být současně vázaný i omezený","typeVarBoundGeneric":"Vázaný typ TypeVar nemůže být obecný","typeVarConstraintGeneric":"Typ omezení TypeVar nemůže být obecný","typeVarDefaultBoundMismatch":"Výchozí typ TypeVar musí být podtyp vázaného typu","typeVarDefaultConstraintMismatch":"Výchozí typ TypeVar musí být jeden z omezených typů","typeVarDefaultIllegal":"Výchozí typy proměnných typů vyžadují Python 3.13 nebo novější","typeVarDefaultInvalidTypeVar":"Parametr typu {name} má výchozí typ, který odkazuje na jednu nebo více proměnných typu, které jsou mimo obor","typeVarFirstArg":"Očekával se název TypeVar jako první argument","typeVarNoMember":"TypeVar {type} nemá žádného člena {name}","typeVarNotSubscriptable":"TypeVar {type} není možné zadat jako dolní index","typeVarNotUsedByOuterScope":"Proměnná typu {name} nemá v tomto kontextu žádný význam","typeVarPossiblyUnsolvable":"Proměnná typu „{name}“ může být nevyřešená, pokud volající nezadá žádný argument pro parametr „{param}“","typeVarScopedToReturnType":"Proměnná typu „{name}“ je vymezená na volatelnou proměnnou v rámci návratového typu a nedá se na to odkazovat v těle funkce","typeVarSingleConstraint":"TypeVar musí mít alespoň dva omezené typy","typeVarTupleConstraints":"TypeVarTuple nemůže mít omezení hodnoty","typeVarTupleContext":"TypeVarTuple se v tomto kontextu nepovoluje","typeVarTupleDefaultNotUnpacked":"Výchozí typ TypeVarTuple musí být rozbalený řazená kolekce členů nebo TypeVarTuple","typeVarTupleMustBeUnpacked":"Pro hodnotu TypeVarTuple se vyžaduje operátor rozbalení","typeVarTupleUnknownParam":"{name} je neznámý parametr pro TypeVarTuple","typeVarUnknownParam":"„{name}“ je neznámý parametr pro TypeVar","typeVarUsedByOuterScope":"TypeVar „{name}“ se už používá ve vnějším oboru","typeVarUsedOnlyOnce":"TypeVar {name} se v signatuře obecné funkce zobrazuje jenom jednou","typeVarVariance":"TypeVar nemůže být kovariantní i kontravariantní","typeVarWithDefaultFollowsVariadic":"TypeVar {typeVarName} má výchozí hodnotu a nemůže následovat po typeVarTuple {variadicName}.","typeVarWithoutDefault":"„{name}“ se v seznamu parametrů typu nemůže zobrazit za „{other}“ , protože nemá žádný výchozí typ","typeVarsNotInGenericOrProtocol":"Generic[] nebo Protocol[] musí obsahovat všechny proměnné typu","typedDictAccess":"Nepovedlo se získat přístup k položce v TypedDict","typedDictAssignedName":"TypedDict se musí přiřadit proměnné s názvem „{name}“.","typedDictBadVar":"Třídy TypedDict můžou obsahovat jenom poznámky typu","typedDictBaseClass":"Všechny základní třídy pro třídy TypedDict musí být také třídami TypedDict","typedDictBoolParam":"Očekávalo se, že parametr {name} bude mít hodnotu True nebo False","typedDictClosedExtras":"Základní třída {name} je uzavřená třída TypedDict; Další položky musí být typu {type}.","typedDictClosedNoExtras":"Základní třída {name} je uzavřená hodnota TypedDict; Položky navíc nejsou povolené.","typedDictDelete":"Nepovedlo se odstranit položku v TypedDict","typedDictEmptyName":"Názvy v rámci TypedDict nemůžou být prázdné","typedDictEntryName":"Očekával se řetězcový literál pro název položky slovníku","typedDictEntryUnique":"Názvy ve slovníku musí být jedinečné","typedDictExtraArgs":"Nadbytečné argumenty TypedDict nejsou podporovány","typedDictFieldNotRequiredRedefinition":"Položka TypedDict {name} nejde předefinovat jako NotRequired.","typedDictFieldReadOnlyRedefinition":"Položka TypedDict {name} nejde předefinovat jako ReadOnly.","typedDictFieldRequiredRedefinition":"Položka TypedDict {name} nejde předefinovat jako Required.","typedDictFirstArg":"Jako první argument byl očekáván název třídy TypedDict","typedDictInitsubclassParameter":"TypedDict nepodporuje parametr __init_subclass__ „{name}“.","typedDictNotAllowed":"„TypedDict“ se v tomto kontextu nedá použít.","typedDictSecondArgDict":"Jako druhý parametr se očekával parametr diktování nebo klíčového slova","typedDictSecondArgDictEntry":"Očekávaná jednoduchá položka slovníku","typedDictSet":"Nelze přiřadit položku v TypedDict","unaccessedClass":"Třída „{name}“ není přístupná","unaccessedFunction":"Funkce {name} není přístupná","unaccessedImport":"Import {name} není přístupný","unaccessedSymbol":"{name} není přístupné","unaccessedVariable":"Proměnná {name} není přístupná","unannotatedFunctionSkipped":"Analýza funkce „{name}“ se přeskočila, protože není označená","unaryOperationNotAllowed":"Unární operátor není v poznámce typu povolený.","unexpectedAsyncToken":"Očekávalo se, že za async bude následovat def, with nebo for","unexpectedExprToken":"Neočekávaný token na konci výrazu","unexpectedIndent":"Neočekávané odsazení","unexpectedUnindent":"Neočekává se unindent","unhashableDictKey":"Klíč slovníku musí být hashovatelný","unhashableSetEntry":"Položka sady musí být hashovatelná","uninitializedAbstractVariables":"Proměnné definované v abstraktní základní třídě nejsou inicializovány v konečné třídě {classType}","uninitializedInstanceVariable":"Proměnná instance {name} není inicializována v těle třídy nebo v metodě __init__","unionForwardReferenceNotAllowed":"Syntaxi sjednocení není možné použít s operandem řetězce; použijte uvozovky kolem celého výrazu","unionSyntaxIllegal":"Alternativní syntaxe pro sjednocení vyžaduje Python 3.10 nebo novější","unionTypeArgCount":"Sjednocení vyžaduje dva nebo více argumentů typu","unionUnpackedTuple":"Sjednocení nemůže obsahovat rozbalenou řazenou kolekci členů.","unionUnpackedTypeVarTuple":"Sjednocení nemůže obsahovat rozbalený typ TypeVarTuple.","unnecessaryCast":"Nepotřebné volání„přetypování“; Typ už je „{type}“.","unnecessaryIsInstanceAlways":"Zbytečné volání isinstance; {testType} je vždy instancí třídy {classType}","unnecessaryIsSubclassAlways":"Nepotřebné volání issubclass; „{testType}“ je vždy podtřídou třídy „{classType}“","unnecessaryPyrightIgnore":"Nepotřebný komentář „# pyright: ignore“","unnecessaryPyrightIgnoreRule":"Nepotřebné pravidlo # pyright: ignore: {name}","unnecessaryTypeIgnore":"Nepotřebný komentář „# type: ignore“","unpackArgCount":"Po rozbalení „Unpack“ se očekával jeden argument typu","unpackExpectedTypeVarTuple":"Jako argument typu pro rozbalení byl očekáván typ TypeVarTuple nebo řazená kolekce členů","unpackExpectedTypedDict":"Byl očekáván argument typu TypedDict pro rozbalení Unpack","unpackIllegalInComprehension":"Operace rozbalení není v porozumění povolená","unpackInAnnotation":"V poznámce typu není povolený operátor rozbalení","unpackInDict":"Operace rozbalení není ve slovnících povolena","unpackInSet":"Operátor rozbalení není v sadě povolený","unpackNotAllowed":"Rozbalení se v tomto kontextu nepovoluje","unpackOperatorNotAllowed":"Operace rozbalení není v tomto kontextu povolená","unpackTuplesIllegal":"Operace rozbalení není povolená v řazených kolekcích členů před Pythonem 3.8","unpackedArgInTypeArgument":"Rozbalené argumenty není možné použít v seznamech argumentů typu","unpackedArgWithVariadicParam":"Pro parametr TypeVarTuple nejde použít rozbalený argument","unpackedDictArgumentNotMapping":"Výraz argumentu za ** musí být mapování s typem klíče str","unpackedDictSubscriptIllegal":"Operátor rozbalení slovníku v dolním indexu není povolený","unpackedSubscriptIllegal":"Operátor rozbalení v dolním indexu vyžaduje Python 3.11 nebo novější","unpackedTypeVarTupleExpected":"Byl očekáván rozbalený typ TypeVarTuple; použijte Unpack[{name1}] nebo *{name2}","unpackedTypedDictArgument":"Nepovedlo se spárovat nebalený argument TypedDict s parametry","unreachableCode":"Kód je nedostupný","unreachableExcept":"Klauzule Except je nedosažitelná, protože výjimka je již zpracována","unsupportedDunderAllOperation":"Operace s __all__ se nepodporuje, takže exportovaný seznam symbolů nemusí být správný","unusedCallResult":"Výsledek výrazu volání je typu „{type}“ a nepoužívá se. přiřadit proměnné „_“, pokud je to záměrné","unusedCoroutine":"Výsledek volání asynchronní funkce se nepoužívá; použijte operátor await nebo přiřaďte výsledek proměnné","unusedExpression":"Hodnota výrazu se nepoužívá","varAnnotationIllegal":"Poznámky typu pro proměnné vyžadují Python 3.6 nebo novější; pro kompatibilitu s předchozími verzemi použijte komentáře typu","variableFinalOverride":"Proměnná {name} je označená jako final a přepíše proměnnou non-Final se stejným názvem ve třídě {className}","variadicTypeArgsTooMany":"Seznam argumentů typů může mít maximálně jeden rozbalený typ TypeVarTuple nebo řazenou kolekci členů","variadicTypeParamTooManyAlias":"Alias typu může mít maximálně jeden parametr typu TypeVarTuple, ale přijal několik ({names})","variadicTypeParamTooManyClass":"Obecná třída může mít maximálně jeden parametr typu TypeVarTuple, ale přijala více ({names})","walrusIllegal":"Operátor := vyžaduje Python 3.8 nebo novější","walrusNotAllowed":"Operátor := není v tomto kontextu povolen bez okolních závorek","wildcardInFunction":"Import se zástupnými znaky není v rámci třídy nebo funkce povolen","wildcardLibraryImport":"Import se zástupnými znaky z knihovny není povolený","wildcardPatternTypePartiallyUnknown":"Typ zachycený vzorem se zástupnými znaky je částečně neznámý","wildcardPatternTypeUnknown":"Typ zachycený vzorem se zástupnými znaky je neznámý","yieldFromIllegal":"Použití příkazu yield from vyžaduje Python 3.3 nebo novější","yieldFromOutsideAsync":"yield from není v asynchronní funkci povoleno","yieldOutsideFunction":"„yield“ není povoleno mimo funkci nebo lambdu","yieldWithinListCompr":"yield není povolen uvnitř seznamu porozumění","zeroCaseStatementsFound":"Výraz shody obsahovat alespoň jeden výraz velikosti písmen","zeroLengthTupleNotAllowed":"Řazená kolekce členů s nulovou délkou není v tomto kontextu povolená"},"DiagnosticAddendum":{"annotatedNotAllowed":"Speciální formulář s poznámkami nejde použít s kontrolami instancí a tříd.","argParam":"Argument odpovídá parametru {paramName}","argParamFunction":"Argument odpovídá parametru {paramName} ve funkci {functionName}","argsParamMissing":"Parametr „*{paramName}“ nemá žádný odpovídající parametr","argsPositionOnly":"Neshoda parametrů pouze s pozicí; Očekával(o/y) se {expected}, ale přijal(o/y) se {received}","argumentType":"Typ argumentu je {type}","argumentTypes":"Typy argumentů: ({types})","assignToNone":"Typ není možné přiřadit typu None","asyncHelp":"Měli jste na mysli „async s“?","baseClassIncompatible":"Základní třída {baseClass} není kompatibilní s typem {type}","baseClassIncompatibleSubclass":"Základní třída {baseClass} je odvozená od třídy {subclass}, která není kompatibilní s typem {type}","baseClassOverriddenType":"Základní třída {baseClass} poskytuje typ {type}, který je přepsán","baseClassOverridesType":"Základní třída „{baseClass}“ přepisuje typ „{type}“","bytesTypePromotions":"Pokud chcete povolit chování povýšení typu pro „bytearray“ a „memoryview“, nastavte disableBytesTypePromotions na false","conditionalRequiresBool":"Metoda __bool__ pro typ {operandType} vrací typ {boolReturnType} místo bool","dataClassFieldLocation":"Deklarace pole","dataClassFrozen":"{name} je zablokované","dataProtocolUnsupported":"„{name}“ je datový protokol.","descriptorAccessBindingFailed":"Nepovedlo se vytvořit vazbu metody {name} pro třídu popisovače {className}.","descriptorAccessCallFailed":"Nepovedlo se volat metodu {name} pro třídu popisovače {className}.","finalMethod":"Konečná metoda","functionParamDefaultMissing":"V parametru „{name}“ chybí výchozí argument","functionParamName":"Neshoda názvu parametru: {destName} a {srcName}","functionParamPositionOnly":"Neshoda parametrů pouze s pozicí; Parametr „{name}“ není jen pro pozici.","functionReturnTypeMismatch":"Návratový typ funkce „{sourceType}“ není kompatibilní s typem „{destType}“","functionTooFewParams":"Funkce přijímá příliš málo pozičních parametrů; očekávaný počet: {expected}, počet, který byl přijat: {received}","functionTooManyParams":"Funkce přijímá příliš mnoho pozičních parametrů; očekávaný počet: {expected}, počet, který byl přijat: {received}","genericClassNotAllowed":"Obecný typ s argumenty obecného typu se pro kontroly instancí nebo tříd nepovoluje.","incompatibleDeleter":"Metoda odstranění vlastnosti je nekompatibilní","incompatibleGetter":"Metoda getter vlastnosti je nekompatibilní","incompatibleSetter":"Metoda setter vlastnosti je nekompatibilní","initMethodLocation":"Metoda __init__ je definována ve třídě {type}","initMethodSignature":"Podpis __init__ je {type}","initSubclassLocation":"Metoda __init_subclass__ je definována ve třídě {name}.","invariantSuggestionDict":"Zvažte přepnutí z „diktování“ na „mapování“, které je v typu hodnoty kovariantní","invariantSuggestionList":"Zvažte přepnutí ze „seznamu“ na „sekvenci“, která je kovavariantní","invariantSuggestionSet":"Zvažte přepnutí ze „seznamu“ na „sekvenci“, která je kovavariantní","keyNotRequired":"„{name}! není v typu „{type}“ povinný klíč, takže přístup může vést k výjimce modulu runtime","keyReadOnly":"{name} je klíč jen pro čtení v {type}","keyRequiredDeleted":"{name} je povinný klíč a nedá se odstranit","keyUndefined":"{name} není definovaný klíč v typu {type}","kwargsParamMissing":"Parametr „**{paramName}“ nemá žádný odpovídající parametr","listAssignmentMismatch":"Typ {type} není kompatibilní s cílovým seznamem","literalAssignmentMismatch":"{sourceType} se nedá přiřadit k typu {destType}","matchIsNotExhaustiveHint":"Pokud není zamýšleno vyčerpávající zpracování, přidejte case _: pass","matchIsNotExhaustiveType":"Nezpracovaný typ: {type}","memberAssignment":"Výraz typu „{type}“ nelze přiřadit členu „{name}“ třídy „{classType}“","memberIsAbstract":"„{type}.{name}“ není implementováno.","memberIsAbstractMore":"a tento počet dalších: {count}...","memberIsClassVarInProtocol":"„{name}“ je v protokolu definován jako ClassVar.","memberIsFinalInProtocol":"{name} je v protokolu označený jako Final","memberIsInitVar":"Člen {name} je pole jen pro inicializaci","memberIsInvariant":"{name} je invariantní, protože je proměnlivé","memberIsNotClassVarInClass":"„{name}“ musí být definováno jako ClassVar, aby bylo kompatibilní s protokolem.","memberIsNotClassVarInProtocol":"„{name}“ není v protokolu definován jako ClassVar.","memberIsNotFinalInProtocol":"„{name}“ není v protokolu označeno jako Final","memberIsWritableInProtocol":"{name} se dá zapisovat do protokolu.","memberSetClassVar":"Člen „{name}“ nelze přiřadit prostřednictvím instance třídy, protože se jedná o třídu ClassVar","memberTypeMismatch":"{name} je nekompatibilní typ","memberUnknown":"Člen {name} je neznámý","metaclassConflict":"Metatřída {metaclass1} je v konfliktu s metatřídou {metaclass2}.","missingDeleter":"Chybí metoda odstranění vlastnosti","missingGetter":"Chybí metoda getter vlastnosti","missingSetter":"Chybí metoda nastavovacího kódu vlastnosti","namedParamMissingInDest":"V cíli chybí parametr klíčového slova {name}","namedParamMissingInSource":"Ve zdroji chybí parametr klíčového slova „{name}“","namedParamTypeMismatch":"Parametr klíčového slova {name} typu {sourceType} není možné přiřadit typu {destType}","namedTupleNotAllowed":"NamedTuple se nedá použít pro kontroly instancí nebo tříd.","newMethodLocation":"Metoda __new__ je definována ve třídě {type}","newMethodSignature":"Podpis __new__ je {type}","newTypeClassNotAllowed":"Třídu vytvořenou pomocí newType nelze použít s kontrolami instancí a tříd.","noOverloadAssignable":"Typ {type} neodpovídá žádné přetížené funkci","noneNotAllowed":"Žádné se nedají použít pro kontroly instancí nebo tříd.","orPatternMissingName":"Chybějící názvy: {name}","overloadIndex":"Přetížení {index} je nejbližší shoda.","overloadNotAssignable":"Nejméně jedno přetížení {name} není možné přiřadit","overloadSignature":"Tady je definován podpis přetížení","overriddenMethod":"Přepsaná metoda","overriddenSymbol":"Přepsaný symbol","overrideInvariantMismatch":"Typ přepsání „{overrideType}“není stejný jako základní typ „{baseType}“","overrideIsInvariant":"Proměnná je proměnlivá, takže její typ je invariantní","overrideNoOverloadMatches":"Signatura přetížení v přepsání není kompatibilní se základní metodou","overrideNotClassMethod":"Základní metoda je deklarována jako metoda classmethod, ale přepsání není","overrideNotInstanceMethod":"Základní metoda je deklarována jako instanční metoda, ale přepsání není","overrideNotStaticMethod":"Základní metoda je deklarována jako staticmethod, ale přepsání není","overrideOverloadNoMatch":"Přepsání nezahrnuje všechna přetížení metody základní třídy","overrideOverloadOrder":"Přetížení přepisované metody musí být ve stejném pořadí jako základní metoda","overrideParamKeywordNoDefault":"Neshoda parametru klíčového slova „{name}“: základní parametr má výchozí hodnotu argumentu, parametr pro přepsání ne","overrideParamKeywordType":"Neshoda typu parametru klíčového slova „{name}“: základní parametr je typu „{baseType}“, parametr přepsání je typu „{overrideType}“","overrideParamName":"Neshoda názvu parametru {index}: základní parametr má název „{baseName}“, parametr přepsání má název „{overrideName}“","overrideParamNameExtra":"V základu chybí parametr {name}","overrideParamNameMissing":"V přepsání chybí parametr „{name}“","overrideParamNamePositionOnly":"Neshoda parametru {index}: základní parametr {baseName} je parametr klíčového slova, přepisující parametr je pouze pozice","overrideParamNoDefault":"Neshoda parametru {index}: Základní parametr má výchozí hodnotu argumentu, parametr přepsání se neshoduje.","overrideParamType":"Neshoda typu parametru {index}: Základní parametr je typu „{baseType}“, parametr přepsání je typu „{overrideType}“.","overridePositionalParamCount":"Neshoda počtu pozičních parametrů; Základní metoda má „{baseCount}“, ale přepsání má {overrideCount}","overrideReturnType":"Neshoda návratového typu: Základní metoda vrací typ {baseType}, přepsání vrací typ {overrideType}","overrideType":"Základní třída definuje typ jako {type}","paramAssignment":"Parametr {index}: Typ {sourceType} není možné přiřadit typu {destType}","paramSpecMissingInOverride":"V metodě přepsání chybí parametry ParamSpec","paramType":"Typ parametru je {paramType}","privateImportFromPyTypedSource":"Místo toho importovat z modulu {module}","propertyAccessFromProtocolClass":"Vlastnost definovaná v rámci třídy protokolu není přístupná jako proměnná třídy","propertyMethodIncompatible":"Metoda vlastnosti {name} není kompatibilní","propertyMethodMissing":"V přepsání chybí metoda vlastnosti „{name}“","propertyMissingDeleter":"Vlastnost {name} nemá definovaný odstraňovač","propertyMissingSetter":"Vlastnost {name} nemá definovanou metodu setter","protocolIncompatible":"{sourceType} není kompatibilní s protokolem {destType}","protocolMemberMissing":"{name} není k dispozici","protocolRequiresRuntimeCheckable":"Třída protokolu musí být @runtime_checkable, aby se použila při kontrolách instancí a tříd.","protocolSourceIsNotConcrete":"„{sourceType}“ není konkrétní typ třídy a nedá se přiřadit k typu „{destType}“","protocolUnsafeOverlap":"Atributy „{name}“ mají stejné názvy jako protokol.","pyrightCommentIgnoreTip":"Pokud chcete potlačit diagnostiku pro jeden řádek, použijte # pyright: ignore[<diagnostic rules>]","readOnlyAttribute":"Atribut {name} je jen pro čtení","seeClassDeclaration":"Viz deklarace třídy","seeDeclaration":"Viz deklarace","seeFunctionDeclaration":"Viz deklarace funkce","seeMethodDeclaration":"Viz deklarace metody","seeParameterDeclaration":"Viz deklarace parametru","seeTypeAliasDeclaration":"Zobrazit deklaraci aliasu typu","seeVariableDeclaration":"Zobrazit deklaraci proměnné","tupleAssignmentMismatch":"Typ „{type}“ není kompatibilní s cílovou řazenou kolekcí členů","tupleEntryTypeMismatch":"Položka řazené kolekce členů {entry} je nesprávného typu","tupleSizeIndeterminateSrc":"Neshoda velikosti řazené kolekce členů; Očekávalo se {expected}, ale přijalo se neurčité.","tupleSizeIndeterminateSrcDest":"Neshoda velikosti řazené kolekce členů; Očekávalo se min. {expected}, ale přijalo se neurčité.","tupleSizeMismatch":"Neshoda velikosti řazené kolekce členů; Očekávalo se {expected}, ale přijalo se {received}.","tupleSizeMismatchIndeterminateDest":"Neshoda velikosti řazené kolekce členů; Očekávalo se min. {expected}, ale přijalo se {received}.","typeAliasInstanceCheck":"Alias typu vytvořený pomocí příkazu „typ“ se nedá použít s kontrolami instancí a tříd","typeAssignmentMismatch":"Typ {sourceType} se nedá přiřadit k typu {destType}","typeBound":"Typ {sourceType} je nekompatibilní s vázaným typem {destType} pro proměnnou typu {name}","typeConstrainedTypeVar":"Typ {type} není kompatibilní s proměnnou omezeného typu {name}","typeIncompatible":"{sourceType} není kompatibilní s typem {destType}","typeNotClass":"{type} není třída","typeNotStringLiteral":"„{type}“ není řetězcový literál","typeOfSymbol":"Typ „{name}“ je „{type}“","typeParamSpec":"Typ {type} není kompatibilní s parametrem ParamSpec {name}","typeUnsupported":"Typ {type} není podporován","typeVarDefaultOutOfScope":"Proměnná typu {name} není v oboru","typeVarIsContravariant":"Parametr typu „{name}“ je kontravariantní, ale „{sourceType}“ není nadtyp „{destType}“.","typeVarIsCovariant":"Parametr typu „{name}“ je kovariantní, ale „{sourceType}“ není podtyp „{destType}“.","typeVarIsInvariant":"Parametr typu „{name}“ je invariantní, ale „{sourceType}“ není stejný jako „{destType}“.","typeVarNotAllowed":"TypeVar se pro kontroly instancí nebo tříd nepovoluje.","typeVarTupleRequiresKnownLength":"Typ TypeVarTuple nemůže být vázaný na řazenou kolekci členů neznámé délky","typeVarUnnecessarySuggestion":"Místo toho použijte {type}.","typeVarUnsolvableRemedy":"Zadejte přetížení, které určuje návratový typ, pokud argument není zadán","typeVarsMissing":"Chybějící proměnné typu: {names}","typedDictBaseClass":"Třída „{type}“ není TypedDict.","typedDictClassNotAllowed":"Třída TypedDict není povolená pro kontroly instancí nebo tříd.","typedDictClosedExtraNotAllowed":"Do {name} nejde přidat položku.","typedDictClosedExtraTypeMismatch":"Nelze přidat položku {name} s typem {type}.","typedDictClosedFieldNotRequired":"Nelze přidat položku {name}, protože musí být NotRequired.","typedDictExtraFieldNotAllowed":"{name} není k dispozici v {type}","typedDictExtraFieldTypeMismatch":"Typ {name} není kompatibilní s typem __extra_items__ v typu {type}.","typedDictFieldMissing":"V {type} chybí {name}","typedDictFieldNotReadOnly":"{name} není v {type} jen pro čtení","typedDictFieldNotRequired":"{name} se v typu {type} nevyžaduje","typedDictFieldRequired":"{name} se vyžaduje v {type}","typedDictFieldTypeMismatch":"Typ {type} se nedá přiřadit k položce {name}","typedDictFieldUndefined":"{name} je nedefinovaná položka v typu {type}","typedDictFinalMismatch":"{sourceType} není kompatibilní s {destType} z důvodu neshody @final","typedDictKeyAccess":"Použít [\\"{name}\\"] k odkazování na položku v TypedDict","typedDictNotAllowed":"TypedDict se nedá použít pro kontroly instancí nebo tříd.","unhashableType":"Typ „{type}“ nejde zatřiďovat","uninitializedAbstractVariable":"Proměnná instance {name} je definovaná v abstraktní základní třídě {classType}, ale neinicializovala se","unreachableExcept":"{exceptionType} je podtřídou {parentType}","useDictInstead":"Označte typ slovníku pomocí Dict[T1, T2]","useListInstead":"Použijte List[T] k označení typu seznamu nebo Union[T1, T2] k označení typu sjednocení","useTupleInstead":"Použijte tuple[T1, ..., Tn] k označení typu řazené kolekce členů nebo Union[T1, T2] k označení typu sjednocení","useTypeInstead":"Místo toho použít Type[T]","varianceMismatchForClass":"Odchylka argumentu typu „{typeVarName}“ není kompatibilní se základní třídou „{className}“","varianceMismatchForTypeAlias":"Rozptyl argumentu typu „{typeVarName}“ není kompatibilní s typem „{typeAliasParam}“"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.de.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.de.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Typstub erstellen","createTypeStubFor":"Typstub für \\"{moduleName}\\" erstellen","executingCommand":"Der Befehl wird ausgeführt.","filesToAnalyzeCount":"{count} Dateien zu analysieren","filesToAnalyzeOne":"1 zu analysierende Datei","findingReferences":"Verweise werden gesucht","organizeImports":"Import-Direktiven organisieren","renameShadowedFile":"\\"{oldFile}\\" in \\"{newFile}\\" umbenennen"},"Completion":{"autoImportDetail":"Autoimport","indexValueDetail":"Indexwert"},"Diagnostic":{"abstractMethodInvocation":"Die Methode „{method}“ kann nicht aufgerufen werden, da sie abstrakt und nicht implementiert ist.","annotatedParamCountMismatch":"Nicht übereinstimmende Parameteranmerkungsanzahl: {expected} erwartet, aber {received} empfangen","annotatedTypeArgMissing":"Es wurde ein Typargument und mindestens eine Anmerkung für \\"Annotated\\" erwartet.","annotationFormatString":"Typanmerkungen können keine Formatzeichenfolgenliterale (f-strings) verwenden.","annotationNotSupported":"Typanmerkung wird für diese Anweisung nicht unterstützt.","annotationSpansStrings":"Typanmerkungen dürfen nicht mehrere Zeichenfolgenliterale umfassen.","annotationStringEscape":"Typanmerkungen dürfen keine Escapezeichen enthalten.","argAssignment":"Ein Argument vom Typ \\"{argType}\\" kann dem Parameter vom Typ \\"{paramType}\\" nicht zugewiesen werden.","argAssignmentFunction":"Ein Argument vom Typ \\"{argType}\\" kann dem Parameter vom Typ \\"{paramType}\\" in der Funktion \\"{functionName}\\" nicht zugewiesen werden.","argAssignmentParam":"Ein Argument vom Typ \\"{argType}\\" kann dem Parameter \\"{paramName}\\" vom Typ \\"{paramType}\\" nicht zugewiesen werden.","argAssignmentParamFunction":"Ein Argument vom Typ \\"{argType}\\" kann dem Parameter \\"{paramName}\\" vom Typ \\"{paramType}\\" in der Funktion \\"{functionName}\\" nicht zugewiesen werden.","argMissingForParam":"Für Parameter {name} fehlt ein Argument.","argMissingForParams":"Fehlende Argumente für die Parameter {names}","argMorePositionalExpectedCount":"Es wurden {expected} weitere Positionsargumente erwartet.","argMorePositionalExpectedOne":"Es wurde 1 weiteres Positionsargument erwartet.","argPositional":"Positionsargument erwartet","argPositionalExpectedCount":"Es wurden {expected} Positionsargumente erwartet.","argPositionalExpectedOne":"Es wurde 1 Positionsargument erwartet.","argTypePartiallyUnknown":"Der Argumenttyp ist teilweise unbekannt","argTypeUnknown":"Argumenttyp ist unbekannt","assertAlwaysTrue":"Assertausdruck wird immer als True ausgewertet.","assertTypeArgs":"\\"assert_type\\" erwartet zwei Positionsargumente.","assertTypeTypeMismatch":"\\"assert_type\\" Konflikt: \\"{expected}\\" erwartet, aber \\"{received}\\" empfangen","assignmentExprComprehension":"Ziel des Zuweisungsausdrucks \\"{name}\\" kann nicht denselben Namen wie das Verständnis für das Ziel verwenden.","assignmentExprContext":"Der Zuweisungsausdruck muss sich innerhalb des Moduls, der Funktion oder der Lambdafunktion befinden.","assignmentExprInSubscript":"Zuweisungsausdrücke innerhalb eines Tiefgestellten werden nur in Python 3.10 und höher unterstützt.","assignmentInProtocol":"Instanzen- oder Klassenvariablen innerhalb einer Protokollklasse müssen explizit innerhalb des Klassentexts deklariert werden.","assignmentTargetExpr":"Der Ausdruck kann kein Zuweisungsziel sein.","asyncNotInAsyncFunction":"Die Verwendung von \\"async\\" ist außerhalb einer asynchronen Funktion nicht zulässig.","awaitIllegal":"Die Verwendung von \\"await\\" erfordert Python 3.5 oder höher.","awaitNotAllowed":"Typanmerkungen können „await“ nicht verwenden.","awaitNotInAsync":"\\"await\\" ist nur innerhalb einer asynchronen Funktion zulässig.","backticksIllegal":"Ausdrücke, die von Backticks umgeben sind, werden in Python 3.x nicht unterstützt; verwenden Sie stattdessen repr","baseClassCircular":"Die Klasse kann nicht von sich selbst abgeleitet werden.","baseClassFinal":"Die Basisklasse \\"{type}\\" ist als final gekennzeichnet und kann nicht als Unterklasse verwendet werden.","baseClassIncompatible":"Basisklassen von {type} sind gegenseitig inkompatibel.","baseClassInvalid":"Das Argument für die Klasse muss eine Basisklasse sein.","baseClassMethodTypeIncompatible":"Basisklassen für die Klasse \\"{classType}\\" definieren die Methode \\"{name}\\" auf inkompatible Weise.","baseClassUnknown":"Der Basisklassentyp ist unbekannt, sodass der Typ der abgeleiteten Klasse verdeckt wird.","baseClassVariableTypeIncompatible":"Basisklassen für die Klasse \\"{classType}\\" definieren die Variable \\"{name}\\" auf inkompatible Weise.","binaryOperationNotAllowed":"Binärer Operator in Typanmerkung nicht zulässig","bindTypeMismatch":"Die Methode \\"{methodName}\\" konnte nicht gebunden werden, da \\"{type}\\" dem Parameter \\"{paramName}\\" nicht zugewiesen werden kann.","breakOutsideLoop":"\\"break\\" kann nur innerhalb einer Schleife verwendet werden.","callableExtraArgs":"Es wurden nur zwei Typargumente für \\"Callable\\" erwartet.","callableFirstArg":"Parametertypliste oder \\"...\\" erwartet.","callableNotInstantiable":"Der Typ \\"{type}\\" kann nicht instanziiert werden.","callableSecondArg":"Rückgabetyp als zweites Typargument für \\"Callable\\" erwartet","casePatternIsIrrefutable":"Ein unwiderlegbares Muster ist nur für die letzte case-Anweisung zulässig.","classAlreadySpecialized":"Der Typ \\"{type}\\" ist bereits spezialisiert.","classDecoratorTypeUnknown":"Der nicht typisierte Klassendekorator verdeckt den Typ der Klasse; Decorator wird ignoriert.","classDefinitionCycle":"Die Klassendefinition für \\"{name}\\" hängt von sich selbst ab.","classGetItemClsParam":"__class_getitem__ Außerkraftsetzung sollte einen \\"cls\\"-Parameter annehmen.","classMethodClsParam":"Klassenmethoden sollten einen \\"cls\\"-Parameter verwenden.","classNotRuntimeSubscriptable":"Durch das Tiefstellungsskript für die Klasse \\"{name}\\" wird eine Laufzeitausnahme generiert; schließen Sie die Typanmerkung in Anführungszeichen ein","classPatternBuiltInArgPositional":"Das Klassenmuster akzeptiert nur positionsbezogenes Untermuster.","classPatternPositionalArgCount":"Zu viele Positionsmuster für Klasse \\"{type}\\". Erwartet: {expected}, empfangen: {received}.","classPatternTypeAlias":"\\"{type}\\" kann nicht in einem Klassenmuster verwendet werden, da es sich um einen spezialisierten Typalias handelt.","classPropertyDeprecated":"Klasseneigenschaften sind in Python 3.11 veraltet und werden in Python 3.13 nicht unterstützt.","classTypeParametersIllegal":"Die Syntax des Klassentypparameters erfordert Python 3.12 oder höher.","classVarFirstArgMissing":"Nach \\"ClassVar\\" wurde ein Typargument erwartet.","classVarNotAllowed":"\\"ClassVar\\" ist in diesem Kontext nicht zulässig.","classVarOverridesInstanceVar":"Die Klassenvariable \\"{name}\\" überschreibt die Instanzvariable desselben Namens in der Klasse \\"{className}\\"","classVarTooManyArgs":"Nach \\"ClassVar\\" wird ein Typargument erwartet.","classVarWithTypeVar":"Der Typ \\"ClassVar\\" darf keine Typvariablen enthalten.","clsSelfParamTypeMismatch":"Der Typ des Parameters \\"{name}\\" muss ein Obertyp seiner Klasse \\"{classType}\\" sein","codeTooComplexToAnalyze":"Der Code ist zu komplex für die Analyse; verringern Sie die Komplexität durch Refactoring in Unterroutinen oder durch Reduzieren bedingter Codepfade","collectionAliasInstantiation":"Der Typ \\"{type}\\" kann nicht instanziiert werden, verwenden Sie stattdessen \\"{alias}\\".","comparisonAlwaysFalse":"Die Bedingung wird immer als False ausgewertet, da die Typen \\"{leftType}\\" und \\"{rightType}\\" keine Überlappung aufweisen.","comparisonAlwaysTrue":"Die Bedingung wird immer als True ausgewertet, da die Typen \\"{leftType}\\" und \\"{rightType}\\" keine Überlappung aufweisen.","comprehensionInDict":"Verständnis kann nicht mit anderen Wörterbucheinträgen verwendet werden.","comprehensionInSet":"Verständnis kann nicht mit anderen Satzeinträgen verwendet werden.","concatenateContext":"„Verketten“ ist in diesem Kontext nicht zulässig.","concatenateParamSpecMissing":"Das letzte Typargument für \\"Concatenate\\" muss ein ParamSpec oder \\"...\\" sein.","concatenateTypeArgsMissing":"\\"Verketten\\" erfordert mindestens zwei Typargumente.","conditionalOperandInvalid":"Ungültiger bedingter Operand vom Typ \\"{type}\\"","constantRedefinition":"\\"{name}\\" ist konstant (da es sich um Großbuchstaben handelt) und kann nicht neu definiert werden.","constructorNoArgs":"Es wurden keine Argumente für \\"{type}\\" Konstruktor erwartet.","constructorParametersMismatch":"Keine Übereinstimmung zwischen der Signatur von __new__ und __init__ in der Klasse \\"{classType}\\"","containmentAlwaysFalse":"Der Ausdruck wird immer als False ausgewertet, da die Typen \\"{leftType}\\" und \\"{rightType}\\" keine Überlappung aufweisen.","containmentAlwaysTrue":"Der Ausdruck wird immer als True ausgewertet, da die Typen \\"{leftType}\\" und \\"{rightType}\\" keine Überlappung aufweisen.","continueInFinally":"\\"continue\\" kann nicht innerhalb einer finally-Klausel verwendet werden.","continueOutsideLoop":"\\"continue\\" kann nur innerhalb einer Schleife verwendet werden.","coroutineInConditionalExpression":"Bedingter Ausdruck verweist auf eine Coroutine, die immer zu \\"True\\" ausgewertet wird.","dataClassBaseClassFrozen":"Eine nicht fixierte Klasse kann nicht von einer fixierten Klasse erben.","dataClassBaseClassNotFrozen":"Eine fixierte Klasse kann nicht von einer nicht fixierten Klasse erben.","dataClassConverterFunction":"Das Argument vom Typ \\"{argType}\\" ist kein gültiger Konverter für das Feld \\"{fieldName}\\" vom Typ \\"{fieldType}\\"","dataClassConverterOverloads":"Keine Überladungen von \\"{funcName}\\" sind gültige Konverter für das Feld \\"{fieldName}\\" vom Typ \\"{fieldType}\\"","dataClassFieldWithDefault":"Felder ohne Standardwerte dürfen nicht nach Feldern mit Standardwerten angezeigt werden.","dataClassFieldWithPrivateName":"Das Feld \\"Dataclass\\" kann keinen privaten Namen verwenden.","dataClassFieldWithoutAnnotation":"Datenklassenfeld ohne Typanmerkung verursacht eine Laufzeitausnahme","dataClassPostInitParamCount":"Dataclass __post_init__ falsche Parameteranzahl; Anzahl von InitVar-Feldern ist {expected}","dataClassPostInitType":"Dataclass __post_init__ Methodenparametertypkonflikt für Feld \\"{fieldName}\\"","dataClassSlotsOverwrite":"__slots__ ist bereits in der Klasse definiert.","dataClassTransformExpectedBoolLiteral":"Es wurde ein Ausdruck erwartet, der statisch als True oder False ausgewertet wird.","dataClassTransformFieldSpecifier":"Es wurde ein Tupel von Klassen oder Funktionen erwartet, es wurde jedoch der Typ \\"{type}\\" empfangen","dataClassTransformPositionalParam":"Alle Argumente für \\"dataclass_transform\\" müssen Schlüsselwortargumente sein.","dataClassTransformUnknownArgument":"Argument \\"{name}\\" wird von dataclass_transform nicht unterstützt.","dataProtocolInSubclassCheck":"Datenprotokolle (die Nicht-Methodenattribute enthalten) sind in „issubclass“-Aufrufen nicht zulässig.","declaredReturnTypePartiallyUnknown":"Der deklarierte Rückgabetyp \\"{returnType}\\" ist teilweise unbekannt.","declaredReturnTypeUnknown":"Unbekannter Rückgabetyp deklariert","defaultValueContainsCall":"Funktionsaufrufe und änderbare Objekte sind innerhalb des Parameterstandardwertausdrucks nicht zulässig.","defaultValueNotAllowed":"Ein Parameter mit \\"*\\" oder \\"**\\" darf keinen Standardwert aufweisen.","delTargetExpr":"Der Ausdruck kann nicht gelöscht werden","deprecatedClass":"Die Klasse \\"{name}\\" ist veraltet.","deprecatedConstructor":"Der Konstruktor für die Klasse \\"{name}\\" ist veraltet.","deprecatedDescriptorDeleter":"Die Methode \\"__delete__\\" für den Deskriptor \\"{name}\\" ist veraltet.","deprecatedDescriptorGetter":"Die Methode \\"__get__\\" für den Deskriptor \\"{name}\\" ist veraltet.","deprecatedDescriptorSetter":"Die Methode \\"__set__\\" für den Deskriptor \\"{name}\\" ist veraltet.","deprecatedFunction":"Die Funktion \\"{name}\\" ist veraltet.","deprecatedMethod":"Die Methode \\"{name}\\" in der Klasse \\"{className}\\" ist veraltet.","deprecatedPropertyDeleter":"Der Deleter für die Eigenschaft \\"{name}\\" ist veraltet.","deprecatedPropertyGetter":"Der Getter für die Eigenschaft \\"{name}\\" ist veraltet.","deprecatedPropertySetter":"Der Setter für die Eigenschaft \\"{name}\\" ist veraltet.","deprecatedType":"Dieser Typ ist ab python-{version} veraltet; verwenden Sie stattdessen \\"{replacement}\\"","dictExpandIllegalInComprehension":"Wörterbucherweiterung ist im Verständnis nicht zulässig.","dictInAnnotation":"Ein Wörterbuchausdruck ist in der Typanmerkung nicht zulässig.","dictKeyValuePairs":"Wörterbucheinträge müssen Schlüssel-Wert-Paare enthalten.","dictUnpackIsNotMapping":"Es wird eine Zuordnung für den Operator zum Entpacken des Wörterbuchs erwartet.","dunderAllSymbolNotPresent":"\\"{name}\\" ist in __all__ angegeben, aber nicht im Modul vorhanden.","duplicateArgsParam":"Es ist nur ein \\"*\\"-Parameter zulässig.","duplicateBaseClass":"Doppelte Basisklasse nicht zulässig","duplicateCapturePatternTarget":"\\"{name}\\" des Erfassungsziels darf nicht mehrmals innerhalb desselben Musters vorkommen.","duplicateCatchAll":"Es ist nur eine catch-all except-Klausel zulässig.","duplicateEnumMember":"Der Enumerationsmember \\"{name}\\" wurde bereits deklariert.","duplicateGenericAndProtocolBase":"Es ist nur eine Generic[...]- oder ein Protocol[...]-Basisklasse zulässig.","duplicateImport":"\\"{importName}\\" wurde mehrmals importiert.","duplicateKeywordOnly":"Es ist nur ein \\"*\\"-Trennzeichen zulässig.","duplicateKwargsParam":"Es ist nur ein \\"**\\"-Parameter zulässig.","duplicateParam":"Doppelter Parameter \\"{name}\\"","duplicatePositionOnly":"Es ist nur ein \\"/\\"-Parameter zulässig.","duplicateStarPattern":"In einer Mustersequenz ist nur ein \\"*\\"-Muster zulässig.","duplicateStarStarPattern":"Es ist nur ein \\"**\\"-Eintrag zulässig.","duplicateUnpack":"In der Liste ist nur ein Vorgang zum Entpacken zulässig.","ellipsisAfterUnpacked":"„...“ kann nicht mit einem entpackten „TypeVarTuple“ oder „Tupel“ verwendet werden.","ellipsisContext":"\\"...\\" ist in diesem Kontext nicht zulässig.","ellipsisSecondArg":"\\"...\\" ist nur als zweites von zwei Argumenten zulässig.","enumClassOverride":"Die Enumerationsklasse \\"{name}\\" ist final und kann nicht in eine Unterklasse aufgenommen werden.","exceptionGroupIncompatible":"Die Ausnahmegruppensyntax (\\"except*\\") erfordert Python 3.11 oder höher.","exceptionTypeIncorrect":"\\"{type}\\" ist nicht von BaseException abgeleitet.","exceptionTypeNotClass":"\\"{type}\\" ist keine gültige Ausnahmeklasse.","exceptionTypeNotInstantiable":"Der Konstruktor für den Ausnahmetyp \\"{type}\\" erfordert mindestens ein Argument.","expectedAfterDecorator":"Es wurde eine Funktions- oder Klassendeklaration nach dem Decorator erwartet.","expectedArrow":"\\"->\\" gefolgt von Rückgabetypanmerkung erwartet","expectedAsAfterException":"\\"as\\" nach Ausnahmetyp erwartet","expectedAssignRightHandExpr":"Ausdruck rechts von \\"=\\" erwartet","expectedBinaryRightHandExpr":"Ausdruck rechts vom Operator","expectedBoolLiteral":"\\"True\\" oder \\"False\\" erwartet","expectedCase":"\\"case\\"-Anweisung erwartet","expectedClassName":"Klassenname erwartet","expectedCloseBrace":"\\"{\\" wurde nicht geschlossen.","expectedCloseBracket":"\\"[\\" wurde nicht geschlossen.","expectedCloseParen":"\\"(\\" wurde nicht geschlossen.","expectedColon":"\\":\\" erwartet","expectedComplexNumberLiteral":"Für den Musterabgleich wurde ein komplexes Zahlenliteral erwartet.","expectedDecoratorExpr":"Das Ausdrucksformular wird für den Decorator vor Python 3.9 nicht unterstützt.","expectedDecoratorName":"Decoratorname erwartet","expectedDecoratorNewline":"Am Ende des Decorators wurde eine neue Zeile erwartet.","expectedDelExpr":"Ausdruck nach \\"del\\" erwartet","expectedElse":"Unerwartetes \\"else\\"","expectedEquals":"\\"=\\" erwartet","expectedExceptionClass":"Ungültige Ausnahmeklasse oder ungültiges Objekt.","expectedExceptionObj":"Ausnahmeobjekt, Ausnahmeklasse oder None erwartet","expectedExpr":"Ausdruck erwartet.","expectedFunctionAfterAsync":"Funktionsdefinition nach \\"async\\" erwartet","expectedFunctionName":"Funktionsname nach \\"def\\" erwartet","expectedIdentifier":"Bezeichner erwartet","expectedImport":"\\"import\\" erwartet","expectedImportAlias":"Symbol nach \\"as\\" erwartet","expectedImportSymbols":"Nach dem Import wurde mindestens ein Symbolname erwartet.","expectedIn":"\\"in\\" wurde erwartet.","expectedInExpr":"Ausdruck nach \\"in\\" erwartet","expectedIndentedBlock":"Eingerückter Block erwartet","expectedMemberName":"Membername nach \\".\\" erwartet","expectedModuleName":"Modulname erwartet","expectedNameAfterAs":"Symbolname nach \\"as\\" erwartet","expectedNamedParameter":"Der Schlüsselwortparameter muss auf \\"*\\" folgen.","expectedNewline":"Zeilenumbruch erwartet","expectedNewlineOrSemicolon":"Anweisungen müssen durch Zeilenumbrüche oder Semikolons getrennt werden.","expectedOpenParen":"\\"(\\" erwartet","expectedParamName":"Parametername erwartet","expectedPatternExpr":"Musterausdruck erwartet","expectedPatternSubjectExpr":"Musterbetreffausdruck erwartet","expectedPatternValue":"Es wurde ein Musterwertausdruck im Format \\"a.b\\" erwartet.","expectedReturnExpr":"Ausdruck nach \\"return\\" erwartet","expectedSliceIndex":"Index- oder Sliceausdruck erwartet","expectedTypeNotString":"Typ erwartet, aber Zeichenfolgenliteral empfangen","expectedTypeParameterName":"Name für Typparameter erwartet","expectedYieldExpr":"Ausdruck in yield-Anweisung erwartet","finalClassIsAbstract":"Die Klasse „{type}“ ist als abgeschlossen markiert und muss alle abstrakten Symbole implementieren.","finalContext":"\\"Final\\" ist in diesem Kontext nicht zulässig.","finalMethodOverride":"Die Methode \\"{name}\\" kann die in der Klasse definierte endgültige Methode \\"{className}\\" nicht überschreiben.","finalNonMethod":"Die Funktion „{name}“ kann nicht @final markiert werden, da sie keine Methode ist.","finalReassigned":"\\"{name}\\" ist als \\"Final\\" deklariert und kann nicht neu zugewiesen werden.","finalRedeclaration":"\\"{name}\\" wurde zuvor als \\"Final\\" deklariert.","finalRedeclarationBySubclass":"\\"{name}\\" kann nicht neu deklariert werden, da die übergeordnete Klasse \\"{className}\\" es als Final deklariert.","finalTooManyArgs":"Nach \\"Final\\" wurde ein einzelnes Typargument erwartet.","finalUnassigned":"\\"{name}\\" ist als Final deklariert, aber der Wert ist nicht zugewiesen.","formatStringBrace":"Eine einzelne schließende geschweifte Klammer ist innerhalb des f-string-Literals nicht zulässig; verwenden Sie doppelte schließende geschweifte Klammern.","formatStringBytes":"Formatzeichenfolgenliterale (f-strings) dürfen nicht binär sein.","formatStringDebuggingIllegal":"Der F-String-Debugspezifizierer \\"=\\" erfordert Python 3.8 oder höher.","formatStringEscape":"Escapesequenz (umgekehrter Schrägstrich) ist im Ausdrucksteil der f-Zeichenfolge vor Python 3.12 nicht zulässig.","formatStringExpectedConversion":"Nach \\"!\\" in f-string wurde ein Konvertierungsspezifizierer erwartet.","formatStringIllegal":"Formatzeichenfolgenliterale (f-strings) erfordern Python 3.6 oder höher.","formatStringInPattern":"Die Formatzeichenfolge ist im Muster nicht zulässig.","formatStringNestedFormatSpecifier":"Ausdrücke sind zu tief im Formatzeichenfolgenspezifizierer geschachtelt.","formatStringNestedQuote":"Zeichenfolgen, die in einer f-Zeichenfolge geschachtelt sind, dürfen nicht dasselbe Anführungszeichen wie die f-Zeichenfolge vor Python 3.12 verwenden.","formatStringUnicode":"Formatzeichenfolgenliterale (f-strings) dürfen nicht Unicode sein.","formatStringUnterminated":"Nicht abgeschlossener Ausdruck in f-string; \\"}\\" wird erwartet.","functionDecoratorTypeUnknown":"Ein nicht typisierter Funktionsdekorator verdeckt den Funktionstyp; Decorator wird ignoriert.","functionInConditionalExpression":"Bedingter Ausdruck verweist auf eine Funktion, die immer zu \\"True\\" ausgewertet wird.","functionTypeParametersIllegal":"Die Syntax des Funktionstypparameters erfordert Python 3.12 oder höher.","futureImportLocationNotAllowed":"Importe von __future__ müssen am Anfang der Datei auftreten","generatorAsyncReturnType":"Der Rückgabetyp der asynchronen Generatorfunktion muss mit \\"AsyncGenerator[{yieldType}, Any]\\" kompatibel sein.","generatorNotParenthesized":"Generatorausdrücke müssen in Klammern gesetzt werden, wenn sie nicht das einzige Argument sind.","generatorSyncReturnType":"Der Rückgabetyp der Generatorfunktion muss mit \\"Generator[{yieldType}, Any, Any]\\" kompatibel sein.","genericBaseClassNotAllowed":"Die Basisklasse \\"Generic\\" kann nicht mit der Typparametersyntax verwendet werden.","genericClassAssigned":"Der generische Klassentyp kann nicht zugewiesen werden.","genericClassDeleted":"Der generische Klassentyp kann nicht gelöscht werden.","genericInstanceVariableAccess":"Der Zugriff auf die generische Instanzvariable über die Klasse ist mehrdeutig.","genericNotAllowed":"\\"Generic\\" ist in diesem Kontext nicht gültig.","genericTypeAliasBoundTypeVar":"Der generische Typalias innerhalb der Klasse kann keine gebundenen Typvariablen {names} verwenden.","genericTypeArgMissing":"\\"Generic\\" erfordert mindestens ein Typargument.","genericTypeArgTypeVar":"Das Typargument für \\"Generic\\" muss eine Typvariable sein.","genericTypeArgUnique":"Typargumente für \\"Generic\\" müssen eindeutig sein.","globalReassignment":"\\"{name}\\" wird vor einer globalen Deklaration zugewiesen.","globalRedefinition":"\\"{name}\\" wurde bereits als global deklariert.","implicitStringConcat":"Implizite Zeichenfolgenverkettung nicht zulässig","importCycleDetected":"Zyklus in Importkette erkannt","importDepthExceeded":"Importkettentiefe überschritten {depth}","importResolveFailure":"Import \\"{importName}\\" konnte nicht aufgelöst werden.","importSourceResolveFailure":"Import \\"{importName}\\" konnte aus der Quelle nicht aufgelöst werden.","importSymbolUnknown":"\\"{name}\\" ist ein unbekanntes Importsymbol.","incompatibleMethodOverride":"Die Methode \\"{name}\\" überschreibt die Klasse \\"{className}\\" auf inkompatible Weise.","inconsistentIndent":"Der Betrag für Nichteinzug stimmt nicht mit dem vorherigen Einzug überein.","inconsistentTabs":"Inkonsistente Verwendung von Tabulatoren und Leerzeichen im Einzug.","initMustReturnNone":"Der Rückgabetyp von \\"__init__\\" muss \\"None\\" sein.","initSubclassCallFailed":"Falsche Schlüsselwortargumente für __init_subclass__ Methode.","initSubclassClsParam":"__init_subclass__ Außerkraftsetzung sollte einen \\"cls\\"-Parameter annehmen.","initVarNotAllowed":"„ClassVar“ ist in diesem Kontext nicht zulässig.","instanceMethodSelfParam":"Instanzmethoden sollten einen \\"self\\"-Parameter verwenden.","instanceVarOverridesClassVar":"Die Instanzvariable \\"{name}\\" überschreibt die Klassenvariable desselben Namens in der Klasse \\"{className}\\"","instantiateAbstract":"Abstrakte Klasse \\"{type}\\" kann nicht erstellt werden.","instantiateProtocol":"Die Protokollklasse \\"{type}\\" kann nicht instanziiert werden.","internalBindError":"Interner Fehler beim Binden der Datei \\"{file}\\": {message}","internalParseError":"Interner Fehler beim Parsen der Datei \\"{file}\\": {message}","internalTypeCheckingError":"Interner Fehler bei der Typüberprüfung der Datei \\"{file}\\": {message}","invalidIdentifierChar":"Ungültiges Zeichen in Bezeichner","invalidStubStatement":"Die Anweisung ist innerhalb einer Typstubdatei bedeutungslos.","invalidTokenChars":"Ungültiges Zeichen \\"{text}\\" im Token","isInstanceInvalidType":"Das zweite Argument für \\"isinstance\\" muss eine Klasse oder ein Tupel von Klassen sein.","isSubclassInvalidType":"Das zweite Argument für \\"issubclass\\" muss eine Klasse oder ein Tupel von Klassen sein.","keyValueInSet":"Schlüssel-Wert-Paare sind innerhalb einer Menge nicht zulässig.","keywordArgInTypeArgument":"Schlüsselwortargumente können nicht in Typargumentlisten verwendet werden.","keywordOnlyAfterArgs":"Schlüsselworttrennzeichen ist nach dem Parameter \\"*\\" nicht zulässig.","keywordParameterMissing":"Mindestens ein Schlüsselwortparameter muss dem Parameter \\"*\\" folgen.","keywordSubscriptIllegal":"Schlüsselwortargumente innerhalb von Tiefskripts werden nicht unterstützt.","lambdaReturnTypePartiallyUnknown":"Der Rückgabetyp des Lambdaausdrucks \\"{returnType}\\" ist teilweise unbekannt.","lambdaReturnTypeUnknown":"Der Rückgabetyp der Lambdafunktion ist unbekannt.","listAssignmentMismatch":"Ein Ausdruck vom Typ \\"{type}\\" kann der Zielliste nicht zugewiesen werden.","listInAnnotation":"Ein Listenausdruck ist in der Typanmerkung nicht zulässig.","literalEmptyArgs":"Nach \\"Literal\\" wurde mindestens ein Typargument erwartet.","literalNotAllowed":"\\"Literal\\" kann in diesem Kontext nicht ohne Typargument verwendet werden.","literalNotCallable":"Der Literaltyp kann nicht instanziiert werden.","literalUnsupportedType":"Typargumente für \\"Literal\\" müssen None, ein Literalwert (int, bool, str oder bytes) oder ein Enumerationswert sein.","matchIncompatible":"Übereinstimmungsanweisungen erfordern Python 3.10 oder höher","matchIsNotExhaustive":"Fälle innerhalb der match-Anweisung behandeln nicht umfassend alle Werte.","maxParseDepthExceeded":"Maximale Analysetiefe überschritten; brechen Sie den Ausdruck in kleinere Unterausdrücke um","memberAccess":"Auf Member \\"{name}\\" für Typ \\"{type}\\" kann nicht zugegriffen werden.","memberDelete":"Member \\"{name}\\" für Typ \\"{type}\\" kann nicht gelöscht werden.","memberSet":"Member \\"{name}\\" für Typ \\"{type}\\" kann nicht zugewiesen werden.","metaclassConflict":"Die Metaklasse einer abgeleiteten Klasse muss eine Unterklasse der Metaklassen aller ihrer Basisklassen sein.","metaclassDuplicate":"Es kann nur eine Metaklasse angegeben werden.","metaclassIsGeneric":"Metaklasse kann nicht generisch sein.","methodNotDefined":"\\"{name}\\" Methode nicht definiert","methodNotDefinedOnType":"Die Methode \\"{name}\\" ist für den Typ \\"{type}\\" nicht definiert.","methodOrdering":"Es kann keine konsistente Methodenreihenfolge erstellt werden.","methodOverridden":"\\"{name}\\" überschreibt die Methode mit demselben Namen in der Klasse \\"{className}\\" mit inkompatiblem Typ \\"{type}\\"","methodReturnsNonObject":"Die Methode \\"{name}\\" gibt kein Objekt zurück.","missingSuperCall":"Die Methode \\"{methodName}\\" ruft nicht die Methode mit demselben Namen in der übergeordneten Klasse auf.","moduleAsType":"Das Modul kann nicht als Typ verwendet werden.","moduleNotCallable":"Das Modul kann nicht aufgerufen werden.","moduleUnknownMember":"\\"{memberName}\\" ist kein bekanntes Mitglied des Moduls \\"{moduleName}\\"","namedExceptAfterCatchAll":"Eine benannte except-Klausel darf nicht nach catch-all except-Klausel auftreten.","namedParamAfterParamSpecArgs":"Der Schlüsselwortparameter \\"{name}\\" kann nicht in der Signatur nach dem Parameter \\"ParamSpec args\\" verwendet werden.","namedTupleEmptyName":"Namen innerhalb eines benannten Tupels dürfen nicht leer sein.","namedTupleEntryRedeclared":"\\"{name}\\" kann nicht überschrieben werden, da die übergeordnete Klasse \\"{className}\\" ein benanntes Tupel ist.","namedTupleFirstArg":"Es wird ein benannter Tupelklassenname als erstes Argument erwartet.","namedTupleMultipleInheritance":"Mehrfachvererbung mit NamedTuple wird nicht unterstützt.","namedTupleNameKeyword":"Feldnamen dürfen kein Schlüsselwort sein.","namedTupleNameType":"Es wurde ein Tupel mit zwei Einträgen unter Angabe von Eintragsname und -typ erwartet.","namedTupleNameUnique":"Namen innerhalb eines benannten Tupels müssen eindeutig sein.","namedTupleNoTypes":"\\"namedtuple\\" stellt keine Typen für Tupeleinträge bereit; verwenden Sie stattdessen \\"NamedTuple\\".","namedTupleSecondArg":"Benannte Tupeleintragsliste als zweites Argument erwartet","newClsParam":"__new__ Außerkraftsetzung sollte einen \\"cls\\"-Parameter annehmen.","newTypeAnyOrUnknown":"Das zweite Argument für NewType muss eine bekannte Klasse sein, nicht „Any“ oder „Unknown“.","newTypeBadName":"Das erste Argument für NewType muss ein Zeichenfolgenliteral sein.","newTypeLiteral":"\\"NewType\\" kann nicht mit dem Literaltyp verwendet werden.","newTypeNameMismatch":"NewType muss einer Variablen mit demselben Namen zugewiesen werden.","newTypeNotAClass":"Klasse als zweites Argument für NewType erwartet","newTypeParamCount":"NewType erfordert zwei Positionsargumente.","newTypeProtocolClass":"NewType kann nicht mit strukturellem Typ (Protokoll- oder TypedDict-Klasse) verwendet werden.","noOverload":"Keine Überladungen für \\"{name}\\" stimmen mit den angegebenen Argumenten überein.","noReturnContainsReturn":"Eine Funktion mit dem deklarierten Rückgabetyp \\"NoReturn\\" kann keine return-Anweisung enthalten.","noReturnContainsYield":"Eine Funktion mit dem deklarierten Rückgabetyp \\"NoReturn\\" kann keine yield-Anweisung enthalten.","noReturnReturnsNone":"Eine Funktion mit dem deklarierten Rückgabetyp \\"NoReturn\\" kann nicht \\"None\\" zurückgeben.","nonDefaultAfterDefault":"Das nicht standardmäßige Argument folgt dem Standardargument.","nonLocalInModule":"Nichtlokale Deklaration auf Modulebene nicht zulässig","nonLocalNoBinding":"Es wurde keine Bindung für nichtlokale \\"{name}\\" gefunden.","nonLocalReassignment":"\\"{name}\\" wird vor einer nichtlokalen Deklaration zugewiesen.","nonLocalRedefinition":"\\"{name}\\" wurde bereits als nichtlokal deklariert.","noneNotCallable":"Ein Objekt vom Typ \\"None\\" kann nicht aufgerufen werden.","noneNotIterable":"Ein Objekt vom Typ \\"None\\" kann nicht als iterierbarer Wert verwendet werden.","noneNotSubscriptable":"Das Objekt vom Typ \\"None\\" kann nicht tiefgestellt werden.","noneNotUsableWith":"Ein Objekt vom Typ \\"None\\" kann nicht mit \\"with\\" verwendet werden.","noneOperator":"Der Operator \\"{operator}\\" wird für den \\"{None}\\" nicht unterstützt.","noneUnknownMember":"\\"{name}\\" ist kein bekanntes Element von \\"None\\".","notRequiredArgCount":"Nach \\"NotRequired\\" wurde ein einzelnes Typargument erwartet.","notRequiredNotInTypedDict":"\\"NotRequired\\" ist in diesem Kontext nicht zulässig.","objectNotCallable":"Das Objekt vom Typ \\"{type}\\" kann nicht aufgerufen werden.","obscuredClassDeclaration":"Die Klassendeklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","obscuredFunctionDeclaration":"Die Funktionsdeklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","obscuredMethodDeclaration":"Die Methodendeklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","obscuredParameterDeclaration":"Die Parameterdeklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","obscuredTypeAliasDeclaration":"Die Typaliasdeklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","obscuredVariableDeclaration":"Die Deklaration \\"{name}\\" wird durch eine Deklaration desselben Namens verdeckt.","operatorLessOrGreaterDeprecated":"Der Operator \\"<>\\" wird in Python 3 nicht unterstützt; verwenden Sie stattdessen \\"!=\\".","optionalExtraArgs":"Nach \\"Optional\\" wurde ein Typargument erwartet.","orPatternIrrefutable":"Ein irrefutables Muster ist nur als letztes Unterpattern in einem \\"or\\"-Muster zulässig.","orPatternMissingName":"Alle Teilmuster innerhalb eines \\"or\\"-Musters müssen auf dieselben Namen zielen.","overlappingKeywordArgs":"Typisierte Wörterbuchüberlappungen mit Schlüsselwortparameter: {names}","overlappingOverload":"Überladung {obscured} für \\"{name}\\" wird nie verwendet, da sich die Parameter überlappen, {obscuredBy}","overloadAbstractMismatch":"Überladene Methoden müssen alle abstrakt sein oder nicht.","overloadClassMethodInconsistent":"Überladungen für \\"{name}\\" verwenden @classmethod inkonsistent","overloadFinalInconsistencyImpl":"Die Überladung für „{name}“ ist @final markiert, die Implementierung ist es jedoch nicht.","overloadFinalInconsistencyNoImpl":"Überladung {index} für „{name}“ ist als @final markiert, Überladung 1 ist es jedoch nicht.","overloadImplementationMismatch":"Die überladene Implementierung ist nicht konsistent mit der Signatur der Überladung {index}","overloadReturnTypeMismatch":"Überladung {prevIndex} für \\"{name}\\" überlappt {newIndex} und gibt einen inkompatiblen Typ zurück.","overloadStaticMethodInconsistent":"Überladungen für \\"{name}\\" verwenden @staticmethod inkonsistent","overloadWithoutImplementation":"\\"{name}\\" ist als Überladen markiert, es wurde jedoch keine Implementierung bereitgestellt.","overriddenMethodNotFound":"Die Methode \\"{name}\\" ist als Überschreibung markiert, aber es ist keine Basismethode mit demselben Namen vorhanden.","overrideDecoratorMissing":"Die Methode \\"{name}\\" ist nicht als Überschreibung markiert, überschreibt jedoch eine Methode in der Klasse \\"{className}\\"","paramAfterKwargsParam":"Der Parameter kann nicht auf den Parameter \\"**\\" folgen.","paramAlreadyAssigned":"Der Parameter \\"{name}\\" ist bereits zugewiesen.","paramAnnotationMissing":"Typanmerkung fehlt für Parameter \\"{name}\\"","paramAssignmentMismatch":"Ein Ausdruck vom Typ \\"{sourceType}\\" kann keinem Parameter vom Typ \\"{paramType}\\" zugewiesen werden.","paramNameMissing":"Kein Parameter mit dem Namen \\"{name}\\"","paramSpecArgsKwargsUsage":"Die Member \\"args\\" und \\"kwargs\\" von ParamSpec müssen beide innerhalb einer Funktionssignatur auftreten.","paramSpecArgsMissing":"Argumente für ParamSpec \\"{type}\\" fehlen.","paramSpecArgsUsage":"Das \\"args\\"-Element von ParamSpec ist nur gültig, wenn es mit dem Parameter \\"*args\\" verwendet wird.","paramSpecAssignedName":"ParamSpec muss einer Variablen mit dem Namen \\"{name}\\" zugewiesen werden.","paramSpecContext":"ParamSpec ist in diesem Kontext nicht zulässig.","paramSpecDefaultNotTuple":"Es wurde ein Auslassungszeichen, ein Tupelausdruck oder ParamSpec für den Standardwert von ParamSpec erwartet.","paramSpecFirstArg":"Der Name von ParamSpec wurde als erstes Argument erwartet.","paramSpecKwargsUsage":"Das \\"kwargs\\"-Element von ParamSpec ist nur gültig, wenn es mit dem Parameter **kwargs verwendet wird.","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" hat in diesem Kontext keine Bedeutung.","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" ist auf einen Aufruf innerhalb des Rückgabetyps beschränkt und kann im Funktionstext nicht referenziert werden.","paramSpecUnknownArg":"ParamSpec unterstützt nur ein Argument.","paramSpecUnknownMember":"\\"{name}\\" ist kein bekanntes Element von ParamSpec.","paramSpecUnknownParam":"\\"{name}\\" ist ein unbekannter Parameter für ParamSpec.","paramTypeCovariant":"Eine Variable vom Typ \\"Covariant\\" kann nicht im Parametertyp verwendet werden.","paramTypePartiallyUnknown":"Der Typ des Parameters \\"{paramName}\\" ist teilweise unbekannt.","paramTypeUnknown":"Der Typ des Parameters \\"{paramName}\\" ist unbekannt.","parenthesizedContextManagerIllegal":"Klammern innerhalb der with-Anweisung erfordern Python 3.9 oder höher.","patternNeverMatches":"Das Muster wird für den Antragstellertyp \\"{type}\\" nie abgeglichen","positionArgAfterNamedArg":"Ein Positionsargument darf nicht nach Schlüsselwortargumenten stehen.","positionOnlyAfterArgs":"Das Parametertrennzeichen \\"Nur Position\\" ist nach dem Parameter \\"*\\" nicht zulässig.","positionOnlyAfterKeywordOnly":"Der Parameter \\"/\\" muss vor dem Parameter \\"*\\" stehen.","positionOnlyAfterNon":"Der Parameter \\"Nur Position\\" ist nach einem Parameter, der nicht vom Typ \\"Nur Position\\" ist, nicht zulässig.","positionOnlyFirstParam":"Das Parametertrennzeichen \\"Nur Position\\" ist als erster Parameter nicht zulässig.","positionOnlyIncompatible":"Für das Parametertrennzeichen \\"Nur Position\\" ist Python 3.8 oder höher erforderlich.","privateImportFromPyTypedModule":"\\"{name}\\" wird nicht aus dem Modul \\"{module}\\" exportiert.","privateUsedOutsideOfClass":"\\"{name}\\" ist privat und wird außerhalb der Klasse verwendet, in dem es deklariert ist.","privateUsedOutsideOfModule":"\\"{name}\\" ist privat und wird außerhalb des Moduls verwendet, in dem es deklariert ist.","propertyOverridden":"\\"{name}\\" überschreibt die Eigenschaft desselben Namens in der Klasse \\"{className}\\" nicht ordnungsgemäß","propertyStaticMethod":"Statische Methoden sind für Eigenschaften-Getter, -Setter oder -Deleter nicht zulässig.","protectedUsedOutsideOfClass":"\\"{name}\\" ist geschützt und wird außerhalb der Klasse verwendet, in der es deklariert ist.","protocolBaseClass":"Die Protokollklasse \\"{classType}\\" kann nicht von einer Nichtprotokollklasse \\"{baseType}\\" abgeleitet werden","protocolBaseClassWithTypeArgs":"Typargumente sind mit der Protokollklasse nicht zulässig, wenn die Typparametersyntax verwendet wird.","protocolIllegal":"Die Verwendung von \\"Protocol\\" erfordert Python 3.7 oder höher.","protocolNotAllowed":"\\"Protocol\\" kann in diesem Kontext nicht verwendet werden.","protocolUnsafeOverlap":"Die Klasse überlappt unsicher mit „{name}“ und könnte zur Laufzeit eine Übereinstimmung erzeugen.","protocolVarianceContravariant":"Die Typvariable \\"{variable}\\", die im generischen Protokoll \\"{class}\\" verwendet wird, muss \\"contravariant\\" sein.","protocolVarianceCovariant":"Die Typvariable \\"{variable}\\", die im generischen Protokoll \\"{class}\\" verwendet wird, muss \\"covariant\\" sein.","protocolVarianceInvariant":"Die Typvariable \\"{variable}\\", die im generischen Protokoll \\"{class}\\" verwendet wird, muss \\"invariant\\" sein.","pyrightCommentInvalidDiagnosticBoolValue":"Auf die Pyright-Kommentardirektive muss \\"=\\" und der Wert \\"true\\" oder \\"false\\" folgen.","pyrightCommentInvalidDiagnosticSeverityValue":"Auf die Pyright-Kommentardirektive muss \\"=\\" und der Wert \\"true\\", \\"false\\", \\"error\\", \\"warning\\", \\"information\\" oder \\"none\\" folgen.","pyrightCommentMissingDirective":"Auf einen Pyright-Kommentar muss eine Direktive (basic oder strict) oder eine Diagnoseregel folgen.","pyrightCommentNotOnOwnLine":"Pyright-Kommentare, die zum Steuern von Einstellungen auf Dateiebene verwendet werden, müssen in ihrer eigenen Zeile angezeigt werden.","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" ist eine unbekannte Diagnoseregel für pyright-Kommentar.","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" ist ein ungültiger Wert für den pyright-Kommentar; \\"true\\", \\"false\\", \\"error\\", \\"warning\\", \\"information\\" oder \\"none\\" erwartet.","pyrightCommentUnknownDirective":"\\"{directive}\\" ist eine unbekannte Direktive für pyright-Kommentar; \\"strict\\" oder \\"basic\\" erwartet","readOnlyArgCount":"Nach \\"ReadOnly\\" wurde ein einzelnes Typargument erwartet.","readOnlyNotInTypedDict":"\\"ReadOnly\\" ist in diesem Kontext nicht zulässig.","recursiveDefinition":"Der Typ von \\"{name}\\" konnte nicht bestimmt werden, da er sich auf selbst bezieht.","relativeImportNotAllowed":"Relative Importe können nicht mit dem Formular \\"import .a\\" verwendet werden; verwenden Sie stattdessen \\"from . import a\\"","requiredArgCount":"Nach \\"Required\\" wurde ein einzelnes Typargument erwartet.","requiredNotInTypedDict":"\\"Required\\" ist in diesem Kontext nicht zulässig.","returnInAsyncGenerator":"Eine Return-Anweisung mit einem Wert ist im asynchronen Generator nicht zulässig.","returnMissing":"Die Funktion mit dem deklarierten Rückgabetyp \\"{returnType}\\" muss einen Wert für alle Codepfade zurückgeben.","returnOutsideFunction":"\\"return\\" kann nur innerhalb einer Funktion verwendet werden.","returnTypeContravariant":"Die Variable vom Typ \\"contravariant\\" kann nicht im Rückgabetyp verwendet werden.","returnTypeMismatch":"Ein Ausdruck vom Typ \\"{exprType}\\" kann dem Rückgabetyp \\"{returnType}\\" nicht zugewiesen werden.","returnTypePartiallyUnknown":"Der Rückgabetyp \\"{returnType}\\" ist teilweise unbekannt.","returnTypeUnknown":"Unbekannter Rückgabetyp","revealLocalsArgs":"Es wurden keine Argumente für den Aufruf \\"reveal_locals\\" erwartet.","revealLocalsNone":"Keine lokalen Elemente in diesem Bereich","revealTypeArgs":"Für den Aufruf \\"reveal_type\\" wurde ein einzelnes Positionsargument erwartet.","revealTypeExpectedTextArg":"Das Argument \\"expected_text\\" für die Funktion \\"reveal_type\\" muss ein str-Literalwert sein.","revealTypeExpectedTextMismatch":"Typentextkonflikt; \\"{expected}\\" erwartet, aber \\"{received}\\" empfangen","revealTypeExpectedTypeMismatch":"Typenkonflikt; \\"{expected}\\" erwartet, aber \\"{received}\\" empfangen","selfTypeContext":"\\"Self\\" ist in diesem Kontext ungültig.","selfTypeMetaclass":"„Self“ kann nicht innerhalb einer Metaklasse (einer Unterklasse von „type“) verwendet werden.","selfTypeWithTypedSelfOrCls":"\\"Self\\" kann nicht in einer Funktion mit einem Parameter \\"self\\" oder \\"cls\\" verwendet werden, der eine andere Typanmerkung als \\"Self\\" aufweist.","setterGetterTypeMismatch":"Der Werttyp des Eigenschaftensetters kann dem Rückgabetyp des Getters nicht zugewiesen werden.","singleOverload":"\\"{name}\\" ist als Überladung markiert, aber es fehlen weitere Überladungen.","slotsAttributeError":"\\"{name}\\" ist in __slots__ nicht angegeben.","slotsClassVarConflict":"\\"{name}\\" steht in Konflikt mit Instanzvariablen, die in __slots__ deklariert sind.","starPatternInAsPattern":"Das Sternmuster kann nicht mit dem Ziel \\"as\\" verwendet werden.","starPatternInOrPattern":"Das Sternmuster kann in anderen Mustern nicht ORed sein.","starStarWildcardNotAllowed":"** kann nicht zusammen mit Platzhalter \\"_\\" verwendet werden","staticClsSelfParam":"Statische Methoden dürfen keinen \\"self\\"- oder \\"cls\\"-Parameter annehmen.","stdlibModuleOverridden":"\\"{path}\\" überschreibt das stdlib-Modul \\"{name}\\"","stringNonAsciiBytes":"Ein Nicht-ASCII-Zeichen ist im Zeichenfolgenliteral in Bytes nicht zulässig.","stringNotSubscriptable":"Der Zeichenfolgenausdruck kann nicht in der Typanmerkung tiefgestellt werden; schließen Sie die gesamte Anmerkung in Anführungszeichen ein","stringUnsupportedEscape":"Nicht unterstützte Escapesequenz im Zeichenfolgenliteral.","stringUnterminated":"Das Zeichenfolgenliteral ist nicht beendet.","stubFileMissing":"Die Stubdatei wurde für \\"{importName}\\" nicht gefunden.","stubUsesGetAttr":"Die Typ-Stub-Datei ist unvollständig; \\"__getattr__\\" verdeckt Typfehler für Modul","sublistParamsIncompatible":"Unterlistenparameter werden in Python 3.x nicht unterstützt.","superCallArgCount":"Es werden nicht mehr als zwei Argumente für den Superaufruf erwartet.","superCallFirstArg":"Klassentyp als erstes Argument für super-Aufruf erwartet, aber \\"{type}\\" empfangen","superCallSecondArg":"Das zweite Argument für den \\"super\\"-Aufruf muss ein Objekt oder eine Klasse sein, das bzw. die von \\"{type}\\" abgeleitet wird.","superCallZeroArgForm":"Die Nullargumentform des „Superaufrufs“ ist nur innerhalb einer Methode gültig.","superCallZeroArgFormStaticMethod":"Die Nullargumentform des „Superaufrufs“ ist nicht innerhalb einer statischen Methode gültig.","symbolIsPossiblyUnbound":"\\"{name}\\" ist möglicherweise ungebunden.","symbolIsUnbound":"\\"{name}\\" ist ungebunden.","symbolIsUndefined":"\\"{name}\\" ist nicht definiert.","symbolOverridden":"\\"{name}\\" überschreibt das Symbol desselben Namens in der Klasse \\"{className}\\"","ternaryNotAllowed":"Ternärer Ausdruck in Typanmerkung nicht zulässig","totalOrderingMissingMethod":"Die Klasse muss \\"__lt__\\", \\"__le__\\", \\"__gt__\\" oder \\"__ge__\\" definieren, um total_ordering zu verwenden.","trailingCommaInFromImport":"Nachgestelltes Komma ist ohne umgebende Klammern nicht zulässig.","tryWithoutExcept":"Die try-Anweisung muss mindestens eine except- oder finally-Klausel aufweisen.","tupleAssignmentMismatch":"Ein Ausdruck vom Typ \\"{type}\\" kann dem Zieltupel nicht zugewiesen werden.","tupleInAnnotation":"Ein Tupelausdruck ist in der Typanmerkung nicht zulässig.","tupleIndexOutOfRange":"Der Index {index} liegt für den Typ {type} außerhalb des gültigen Bereichs.","typeAliasIllegalExpressionForm":"Ungültiges Ausdrucksformular für Typaliasdefinition","typeAliasIsRecursiveDirect":"Der Typalias \\"{name}\\" kann sich nicht selbst in seiner Definition verwenden.","typeAliasNotInModuleOrClass":"TypeAlias kann nur innerhalb eines Moduls oder Klassenbereichs definiert werden.","typeAliasRedeclared":"\\"{name}\\" ist als TypeAlias deklariert und kann nur einmal zugewiesen werden.","typeAliasStatementBadScope":"Eine Typanweisung kann nur innerhalb eines Moduls oder Klassenbereichs verwendet werden.","typeAliasStatementIllegal":"Die Typaliasanweisung erfordert Python 3.12 oder höher.","typeAliasTypeBaseClass":"Ein in einer „type“-Anweisung definierter Typalias kann nicht als Basisklasse verwendet werden.","typeAliasTypeMustBeAssigned":"TypeAliasType muss einer Variablen mit dem gleichen Namen wie der Typalias zugewiesen werden.","typeAliasTypeNameArg":"Das erste Argument für TypeAliasType muss ein Zeichenfolgenliteral sein, das den Namen des Typalias darstellt.","typeAliasTypeNameMismatch":"Der Name des Typalias muss mit dem Namen der Variablen übereinstimmen, der er zugewiesen ist.","typeAliasTypeParamInvalid":"Die Typparameterliste muss ein Tupel sein, das nur TypeVar, TypeVarTuple oder ParamSpec enthält.","typeAnnotationCall":"Der Aufrufausdruck ist im Typausdruck nicht zulässig","typeAnnotationVariable":"Variable im Typausdruck nicht zulässig","typeAnnotationWithCallable":"Das Typargument für \\"type\\" muss eine Klasse sein. Aufrufbare Elemente werden nicht unterstützt.","typeArgListExpected":"ParamSpec, Ellipse oder Liste der Typen erwartet","typeArgListNotAllowed":"Der Listenausdruck ist für dieses Typargument nicht zulässig.","typeArgsExpectingNone":"Für die Klasse \\"{name}\\" werden keine Typargumente erwartet.","typeArgsMismatchOne":"Es wurde ein Typargument erwartet, es wurde jedoch {received} empfangen.","typeArgsMissingForAlias":"Für den generischen Typalias \\"{name}\\" werden Typargumente erwartet.","typeArgsMissingForClass":"Für die generische Klasse \\"{name}\\" werden Typargumente erwartet.","typeArgsTooFew":"Für \\"{name}\\" wurden zu wenige Typargumente angegeben; {expected} erwartet, aber {received} empfangen","typeArgsTooMany":"Für \\"{name}\\" wurden zu viele Typargumente angegeben; {expected} erwartet, aber {received} empfangen","typeAssignmentMismatch":"Ein Ausdruck vom Typ \\"{sourceType}\\" kann nicht dem deklarierten Typ \\"{destType}\\" zugewiesen werden.","typeAssignmentMismatchWildcard":"Das Importsymbol \\"{name}\\" weist den Typ \\"{sourceType}\\" auf, der dem deklarierten Typ \\"{destType}\\" nicht zugewiesen werden kann.","typeCallNotAllowed":"Der type()-Aufruf darf nicht in der Typanmerkung verwendet werden.","typeCheckOnly":"\\"{name}\\" ist als @type_check_only markiert und kann nur in Typanmerkungen verwendet werden.","typeCommentDeprecated":"Die Verwendung von Typkommentaren ist veraltet; verwenden Sie stattdessen Typanmerkung","typeExpectedClass":"Typausdruck erwartet, aber \\"{type}\\" empfangen","typeGuardArgCount":"Nach \\"TypeGuard\\" oder \\"TypeIs\\" wurde ein einzelnes Typargument erwartet.","typeGuardParamCount":"Benutzerdefinierte Typenschutzfunktionen und -methoden müssen mindestens einen Eingabeparameter aufweisen.","typeIsReturnType":"Der Rückgabetyp von TypeIs (\\"{returnType}\\") ist nicht konsistent mit dem Wertparametertyp (\\"{type}\\").","typeNotAwaitable":"\\"{type}\\" ist nicht awaitable.","typeNotIntantiable":"\\"{type}\\" kann nicht instanziiert werden.","typeNotIterable":"\\"{type}\\" ist nicht iterierbar.","typeNotSpecializable":"Der Typ \\"{type}\\" konnte nicht spezialisiert werden","typeNotSubscriptable":"Das Objekt vom Typ \\"{type}\\" kann nicht tiefgestellt werden.","typeNotSupportBinaryOperator":"Der Operator \\"{operator}\\" wird für Typen \\"{leftType}\\" und \\"{rightType}\\" nicht unterstützt.","typeNotSupportBinaryOperatorBidirectional":"Der Operator \\"{operator}\\" wird für die Typen \\"{leftType}\\" und \\"{rightType}\\" nicht unterstützt, wenn der erwartete Typ \\"{expectedType}\\" ist.","typeNotSupportUnaryOperator":"Der Operator \\"{operator}\\" wird für den Typ \\"{type}\\" nicht unterstützt.","typeNotSupportUnaryOperatorBidirectional":"Der Operator \\"{operator}\\" wird für den Typ \\"{type}\\" nicht unterstützt, wenn der erwartete Typ \\"{expectedType}\\" ist.","typeNotUsableWith":"Ein Objekt vom Typ \\"{type}\\" kann nicht mit \\"with\\" verwendet werden, da es nicht {method} implementiert.","typeParameterBoundNotAllowed":"\\"Bound\\" oder \\"constraint\\" kann nicht mit einem variadic-Typparameter oder ParamSpec verwendet werden.","typeParameterConstraintTuple":"Die Typparametereinschränkung muss ein Tupel mit mindestens zwei Typen sein.","typeParameterExistingTypeParameter":"Der Typparameter \\"{name}\\" wird bereits verwendet.","typeParameterNotDeclared":"Der Typparameter \\"{name}\\" ist nicht in der Typparameterliste für \\"{container}\\" enthalten.","typeParametersMissing":"Es muss mindestens ein Typparameter angegeben werden.","typePartiallyUnknown":"Der Typ von \\"{name}\\" ist teilweise unbekannt.","typeUnknown":"Der Typ von \\"{name}\\" ist unbekannt.","typeVarAssignedName":"TypeVar muss einer Variablen mit dem Namen \\"{name}\\" zugewiesen werden.","typeVarAssignmentMismatch":"Der Typ \\"{type}\\" kann der Typvariablen \\"{name}\\" nicht zugewiesen werden.","typeVarBoundAndConstrained":"TypeVar kann nicht gleichzeitig gebunden und eingeschränkt sein.","typeVarBoundGeneric":"Der gebundene Typ \\"TypeVar\\" darf nicht generisch sein.","typeVarConstraintGeneric":"Der Typ der TypeVar-Einschränkung darf nicht generisch sein.","typeVarDefaultBoundMismatch":"Der Standardtyp \\"TypeVar\\" muss ein Untertyp des gebundenen Typs sein.","typeVarDefaultConstraintMismatch":"Der Standardtyp \\"TypeVar\\" muss einer der eingeschränkten Typen sein.","typeVarDefaultIllegal":"Für Standardtypen von Typvariablen ist Python 3.13 oder höher erforderlich.","typeVarDefaultInvalidTypeVar":"Der Typparameter \\"{name}\\" weist einen Standardtyp auf, der auf eine oder mehrere Typvariablen verweist, die außerhalb des Gültigkeitsbereichs liegen.","typeVarFirstArg":"Der Name von TypeVar wurde als erstes Argument erwartet.","typeVarNoMember":"TypeVar \\"{type}\\" hat kein Member \\"{name}\\"","typeVarNotSubscriptable":"TypeVar \\"{type}\\" kann nicht tiefgestellt werden.","typeVarNotUsedByOuterScope":"Die Typvariable \\"{name}\\" hat in diesem Kontext keine Bedeutung.","typeVarPossiblyUnsolvable":"Die Typvariable \\"{name}\\" wird möglicherweise nicht aufgelöst, wenn der Aufrufer kein Argument für Parameter \\"{param}\\" bereitstellt","typeVarScopedToReturnType":"Die Typvariable \\"{name}\\" ist auf einen Aufruf innerhalb des Rückgabetyps beschränkt und kann im Funktionstext nicht referenziert werden.","typeVarSingleConstraint":"TypeVar muss mindestens zwei eingeschränkte Typen aufweisen.","typeVarTupleConstraints":"TypeVarTuple darf keine Werteinschränkungen aufweisen.","typeVarTupleContext":"TypeVarTuple ist in diesem Kontext nicht zulässig.","typeVarTupleDefaultNotUnpacked":"Der Standardtyp \\"TypeVarTuple\\" muss ein entpacktes Tupel oder ein TypeVarTuple sein.","typeVarTupleMustBeUnpacked":"Der Entpackungsoperator ist für den TypeVarTuple-Wert erforderlich.","typeVarTupleUnknownParam":"\\"{name}\\" ist ein unbekannter Parameter für TypeVar-Tuple.","typeVarUnknownParam":"\\"{name}\\" ist ein unbekannter Parameter für TypeVar.","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" wird bereits von einem äußeren Bereich verwendet.","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" wird in der generischen Funktionssignatur nur einmal angezeigt.","typeVarVariance":"TypeVar darf nicht gleichzeitig \\"covariant\\" und \\"contravariant\\" sein.","typeVarWithDefaultFollowsVariadic":"TypeVar „{typeVarName}“ weist einen Standardwert auf und kann typeVarTuple „{variadicName}“ nicht folgen.","typeVarWithoutDefault":"\\"{name}\\" kann nicht nach \\"{other}\\" in der Typparameterliste angezeigt werden, da es keinen Standardtyp aufweist.","typeVarsNotInGenericOrProtocol":"Generic[] oder Protocol[] müssen alle Typvariablen enthalten.","typedDictAccess":"Auf das Element in TypedDict konnte nicht zugegriffen werden.","typedDictAssignedName":"TypedDict muss einer Variablen mit dem Namen „{name}“ zugewiesen werden.","typedDictBadVar":"TypedDict-Klassen dürfen nur Typanmerkungen enthalten.","typedDictBaseClass":"Alle Basisklassen für TypedDict-Klassen müssen auch TypedDict-Klassen sein.","typedDictBoolParam":"Es wird erwartet, dass \\"{name}\\" Parameter den Wert \\"True\\" oder \\"False\\" aufweist.","typedDictClosedExtras":"Die Basisklasse „{name}“ ist ein geschlossenes TypedDict; zusätzliche Elemente müssen vom Typ „{type}“ sein.","typedDictClosedNoExtras":"Die Basisklasse „{name}“ ist ein geschlossenes TypedDict; zusätzliche Elemente sind nicht zulässig.","typedDictDelete":"Das Element in TypedDict konnte nicht gelöscht werden.","typedDictEmptyName":"Namen innerhalb eines TypedDict dürfen nicht leer sein.","typedDictEntryName":"Für den Wörterbucheintragsnamen wurde ein Zeichenfolgenliteral erwartet.","typedDictEntryUnique":"Namen innerhalb eines Wörterbuchs müssen eindeutig sein.","typedDictExtraArgs":"Zusätzliche TypedDict-Argumente werden nicht unterstützt.","typedDictFieldNotRequiredRedefinition":"Das TypedDict-Element „{name}“ kann nicht als „NotRequired“ neu definiert werden.","typedDictFieldReadOnlyRedefinition":"Das TypedDict-Element „{name}“ kann nicht als „ReadOnly“ neu definiert werden.","typedDictFieldRequiredRedefinition":"Das TypedDict-Element „{name}“ kann nicht als „Required“ neu definiert werden.","typedDictFirstArg":"Der Klassenname \\"TypedDict\\" wird als erstes Argument erwartet.","typedDictInitsubclassParameter":"TypedDict unterstützt __init_subclass__ Parameter „{name}“ nicht.","typedDictNotAllowed":"\\"TypedDict\\" kann in diesem Kontext nicht verwendet werden.","typedDictSecondArgDict":"Es wird ein dict- oder Schlüsselwortparameter als zweiter Parameter erwartet.","typedDictSecondArgDictEntry":"Einfacher Wörterbucheintrag erwartet","typedDictSet":"Element konnte in TypedDict nicht zugewiesen werden.","unaccessedClass":"Auf die Klasse \\"{name}\\" kann nicht zugegriffen werden.","unaccessedFunction":"Auf die Funktion \\"{name}\\" kann nicht zugegriffen werden.","unaccessedImport":"Auf den Import \\"{name}\\" kann nicht zugegriffen werden.","unaccessedSymbol":"Auf \\"{name}\\" kann nicht zugegriffen werden.","unaccessedVariable":"Auf die Variable \\"{name}\\" kann nicht zugegriffen werden.","unannotatedFunctionSkipped":"Die Analyse der Funktion \\"{name}\\" wird übersprungen, da sie nicht kommentiert wurde.","unaryOperationNotAllowed":"Unärer Operator in Typanmerkung nicht zulässig","unexpectedAsyncToken":"Es wurde erwartet, dass \\"def\\", \\"with\\" oder \\"for\\" auf \\"async\\" folgt.","unexpectedExprToken":"Unerwartetes Token am Ende des Ausdrucks.","unexpectedIndent":"Unerwarteter Einzug","unexpectedUnindent":"\\"Unindent\\" nicht erwartet.","unhashableDictKey":"Der Wörterbuchschlüssel muss hashbar sein.","unhashableSetEntry":"Der Eintrag \\"Set\\" muss hashbar sein.","uninitializedAbstractVariables":"In der abstrakten Basisklasse definierte Variablen sind in der endgültigen Klasse \\"{classType}\\" nicht initialisiert","uninitializedInstanceVariable":"Die Instanzvariable \\"{name}\\" ist im Klassentext oder in der __init__ Methode nicht initialisiert.","unionForwardReferenceNotAllowed":"Die Unionsyntax kann nicht mit einem Zeichenfolgenoperanden verwendet werden; verwenden Sie Anführungszeichen um den gesamten Ausdruck","unionSyntaxIllegal":"Alternative Syntax für Unions erfordert Python 3.10 oder höher.","unionTypeArgCount":"Union erfordert mindestens zwei Typargumente.","unionUnpackedTuple":"Union kann kein entpacktes Tupel enthalten.","unionUnpackedTypeVarTuple":"Die Union kann kein entpacktes TypeVarTuple enthalten.","unnecessaryCast":"Nicht erforderlicher \\"cast\\"-Aufruf; der Typ ist bereits \\"{type}\\".","unnecessaryIsInstanceAlways":"Nicht erforderlicher isinstance-Aufruf; \\"{testType}\\" ist immer eine Instanz von \\"{classType}\\"","unnecessaryIsSubclassAlways":"Nicht erforderlicher issubclass-Aufruf; \\"{testType}\\" ist immer eine Unterklasse von \\"{classType}\\"","unnecessaryPyrightIgnore":"Unnötiger \\"# pyright: ignore\\"-Kommentar","unnecessaryPyrightIgnoreRule":"Unnötiger \\"# pyright: ignore\\"-Regel: \\"{name}\\"","unnecessaryTypeIgnore":"Nicht erforderlicher \\"# type: ignore\\"-Kommentar","unpackArgCount":"Nach \\"Required\\" wurde ein einzelnes Typargument erwartet.","unpackExpectedTypeVarTuple":"„TypeVarTuple“ oder „Tupel“ als Typargument für „Unpack“ erwartet","unpackExpectedTypedDict":"TypedDict-Typargument für Unpack erwartet","unpackIllegalInComprehension":"Der Entpackvorgang ist in Verständnis nicht zulässig.","unpackInAnnotation":"Der Operator zum Entpacken ist in der Typanmerkung nicht zulässig.","unpackInDict":"Der Entpackvorgang ist in Wörterbüchern nicht zulässig.","unpackInSet":"Der Operator zum Entpacken ist innerhalb einer Menge nicht zulässig.","unpackNotAllowed":"\\"Unpack\\" ist in diesem Kontext nicht zulässig.","unpackOperatorNotAllowed":"Der Entpackvorgang ist in diesem Kontext nicht zulässig.","unpackTuplesIllegal":"Der Entpackvorgang ist in Tupeln vor Python 3.8 nicht zulässig.","unpackedArgInTypeArgument":"Ungepackte Argumente können nicht in Typargumentlisten verwendet werden.","unpackedArgWithVariadicParam":"Das nicht gepackte Argument kann nicht für den Parameter \\"TypeVarTuple\\" verwendet werden.","unpackedDictArgumentNotMapping":"Der Argumentausdruck nach ** muss eine Zuordnung mit dem Schlüsseltyp \\"str\\" sein.","unpackedDictSubscriptIllegal":"Der Operator zum Entpacken des Wörterbuchs in tiefgestellten Zeichen ist nicht zulässig.","unpackedSubscriptIllegal":"Das Entpacken des Operators im Tiefstellungsskript erfordert Python 3.11 oder höher.","unpackedTypeVarTupleExpected":"Nicht gepackter TypeVarTuple erwartet; verwenden Sie Unpack[{name1}] oder *{name2}","unpackedTypedDictArgument":"Das entpackte TypedDict-Argument kann nicht mit Parametern abgelichen werden.","unreachableCode":"Der Code ist nicht erreichbar.","unreachableExcept":"Die except-Klausel ist nicht erreichbar, weil die Ausnahme bereits behandelt wird.","unsupportedDunderAllOperation":"Der Vorgang für \\"__all__\\" wird nicht unterstützt, daher ist die exportierte Symbolliste möglicherweise falsch.","unusedCallResult":"Das Ergebnis des Aufrufausdrucks ist vom Typ \\"{type}\\" und wird nicht verwendet; der Variablen \\"_\\" zuweisen, wenn dies beabsichtigt ist","unusedCoroutine":"Das Ergebnis eines asynchronen Funktionsaufrufs wird nicht verwendet; verwenden Sie \\"await\\", oder weisen Sie der Variablen ein Ergebnis zu.","unusedExpression":"Der Ausdruckswert wird nicht verwendet.","varAnnotationIllegal":"Typanmerkungen für Variablen erfordern Python 3.6 oder höher; verwenden Sie den Typkommentar für Kompatibilität mit früheren Versionen","variableFinalOverride":"Die Variable \\"{name}\\" ist als \\"Final\\" gekennzeichnet und überschreibt die Nicht-Final-Variable desselben Namens in der Klasse \\"{className}\\"","variadicTypeArgsTooMany":"Die Liste der Typargumente darf höchstens ein entpacktes „TypeVarTuple“ oder „Tupel“ enthalten.","variadicTypeParamTooManyAlias":"Der Typalias darf höchstens einen TypeVarTuple-Typparameter aufweisen, es wurden jedoch mehrere ({names}) empfangen.","variadicTypeParamTooManyClass":"Die generische Klasse darf höchstens einen TypeVarTuple-Typparameter aufweisen, es wurden jedoch mehrere ({names}) empfangen.","walrusIllegal":"Der Operator \\":=\\" erfordert Python 3.8 oder höher.","walrusNotAllowed":"Der Operator \\":=\\" ist in diesem Kontext ohne umgebende Klammern nicht zulässig.","wildcardInFunction":"Der Platzhalterimport ist innerhalb einer Klasse oder Funktion nicht zulässig.","wildcardLibraryImport":"Der Platzhalterimport aus einer Bibliothek ist nicht zulässig.","wildcardPatternTypePartiallyUnknown":"Der durch das Platzhaltermuster erfasste Typ ist teilweise unbekannt.","wildcardPatternTypeUnknown":"Der durch das Platzhaltermuster erfasste Typ ist unbekannt.","yieldFromIllegal":"Die Verwendung von \\"yield from\\" erfordert Python 3.3 oder höher.","yieldFromOutsideAsync":"\\"yield from\\" ist in einer asynchronen Funktion nicht zulässig.","yieldOutsideFunction":"\\"yield\\" ist außerhalb einer Funktion oder eines Lambdas nicht zulässig.","yieldWithinListCompr":"\\"yield\\" ist innerhalb eines Listenverständnisses nicht zulässig.","zeroCaseStatementsFound":"Die match-Anweisung muss mindestens eine case-Anweisung enthalten","zeroLengthTupleNotAllowed":"Ein Tupel mit der Länge Null ist in diesem Kontext nicht zulässig."},"DiagnosticAddendum":{"annotatedNotAllowed":"Das Sonderformular „Änderungsverlauf eingeblendet“ kann nicht mit Instanz- und Klassenüberprüfungen verwendet werden.","argParam":"Argument entspricht Parameter \\"{paramName}\\"","argParamFunction":"Argument entspricht Parameter \\"{paramName}\\" in Funktion \\"{functionName}\\"","argsParamMissing":"Der Parameter \\"*{paramName}\\" weist keinen entsprechenden Parameter auf.","argsPositionOnly":"Nicht übereinstimmende Parameteranmerkungsanzahl: {expected} erwartet, aber {received} empfangen","argumentType":"Argumenttyp ist \\"{type}\\"","argumentTypes":"Argumenttypen: ({types})","assignToNone":"Der Typ kann nicht dem Typ \\"None\\" zugewiesen werden.","asyncHelp":"Meinten Sie \\"asynchron mit\\"?","baseClassIncompatible":"Die Basisklasse \\"{baseClass}\\" ist nicht mit dem Typ \\"{type}\\" kompatibel.","baseClassIncompatibleSubclass":"Die Basisklasse \\"{baseClass}\\" wird von \\"{subclass}\\" abgeleitet, die mit dem Typ \\"{type}\\" nicht kompatibel ist.","baseClassOverriddenType":"Die Basisklasse \\"{baseClass}\\" stellt einen Typ \\"{type}\\" bereit, der überschrieben wird.","baseClassOverridesType":"Basisklasse \\"{baseClass}\\" überschreibt mit Typ \\"{type}\\"","bytesTypePromotions":"Legen Sie disableBytesTypePromotions auf FALSE fest, um das Typerweiterungsverhalten für \\"bytearray\\" und \\"memoryview\\" zu aktivieren.","conditionalRequiresBool":"Die Methode __bool__ für den Typ \\"{operandType}\\" gibt den Typ \\"{boolReturnType}\\" anstelle von \\"bool\\" zurück","dataClassFieldLocation":"Felddeklaration","dataClassFrozen":"\\"{name}\\" ist fixiert","dataProtocolUnsupported":"„{name}“ ist ein Datenprotokoll.","descriptorAccessBindingFailed":"Fehler beim Binden der Methode „{name}“ für die Deskriptorklasse „{className}“","descriptorAccessCallFailed":"Fehler beim Aufrufen der Methode „{name}“ für die Deskriptorklasse „{className}“","finalMethod":"Endgültige Methode","functionParamDefaultMissing":"Standardargument für Parameter \\"{name}\\" fehlt.","functionParamName":"Parameternamen stimmen nicht überein: \\"{destName}\\" und \\"{srcName}\\"","functionParamPositionOnly":"Nicht übereinstimmender Parameter „nur für Position“. Der Parameter „{name}“ ist nicht „nur für Position“.","functionReturnTypeMismatch":"Der Funktionsrückgabetyp \\"{sourceType}\\" ist nicht mit dem Typ \\"{destType}\\" kompatibel.","functionTooFewParams":"Die Funktion akzeptiert zu wenige Positionsparameter; {expected} erwartet, aber {received} empfangen","functionTooManyParams":"Die Funktion akzeptiert zu viele Positionsparameter; {expected} erwartet, aber {received} empfangen","genericClassNotAllowed":"Ein generischer Typ mit Typargumenten ist für Instanz- oder Klassenprüfungen nicht zulässig.","incompatibleDeleter":"Die Deletermethode der Eigenschaft ist nicht kompatibel.","incompatibleGetter":"Die Gettermethode der Eigenschaft ist nicht kompatibel.","incompatibleSetter":"Die Settermethode der Eigenschaft ist nicht kompatibel.","initMethodLocation":"Die __init__ Methode ist in der Klasse \\"{type}\\" definiert.","initMethodSignature":"Die Signatur von __init__ ist \\"{type}\\".","initSubclassLocation":"Die __init_subclass__ Methode ist in der Klasse \\"{name}\\" definiert.","invariantSuggestionDict":"Erwägen Sie den Wechsel von \\"dict\\" zu \\"Mapping\\" (im Werttyp covariant).","invariantSuggestionList":"Erwägen Sie den Wechsel von \\"list\\" zu \\"Sequence\\" (covariant).","invariantSuggestionSet":"Erwägen Sie den Wechsel von „set“ zu „Container“, der Kovariante ist.","keyNotRequired":"\\"{name}\\" ist kein erforderlicher Schlüssel in \\"{type}\\". Der Zugriff kann daher zu einer Laufzeitausnahme führen.","keyReadOnly":"\\"{name}\\" ist ein schreibgeschützter Schlüssel in \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" ist ein erforderlicher Schlüssel und kann nicht gelöscht werden.","keyUndefined":"\\"{name}\\" ist kein definierter Schlüssel in \\"{type}\\"","kwargsParamMissing":"Der Parameter \\"**{paramName}\\" weist keinen entsprechenden Parameter auf.","listAssignmentMismatch":"Der Typ \\"{type}\\" ist nicht mit der Zielliste kompatibel.","literalAssignmentMismatch":"\\"{sourceType}\\" kann dem Typ \\"{destType}\\" nicht zugewiesen werden.","matchIsNotExhaustiveHint":"Wenn keine ausführliche Behandlung beabsichtigt ist, fügen Sie \\"case _: pass\\" hinzu.","matchIsNotExhaustiveType":"Unbehandelter Typ: \\"{type}\\"","memberAssignment":"Ein Ausdruck vom Typ \\"{type}\\" kann dem Member \\"{name}\\" der Klasse \\"{classType}\\" nicht zugewiesen werden.","memberIsAbstract":"„{type}. {name}“ ist nicht implementiert.","memberIsAbstractMore":"und {count} weitere...","memberIsClassVarInProtocol":"„{name}“ ist als ClassVar im Protokoll definiert.","memberIsFinalInProtocol":"\\"{name}\\" ist im Protokoll als \\"Final\\" gekennzeichnet.","memberIsInitVar":"Das Element \\"{name}\\" ist ein init-only-Feld.","memberIsInvariant":"\\"{name}\\" ist invariant, da es änderbar ist.","memberIsNotClassVarInClass":"„{name}“ muss als ClassVar definiert sein, um mit dem Protokoll kompatibel zu sein.","memberIsNotClassVarInProtocol":"„{name}“ ist nicht als ClassVar im Protokoll definiert.","memberIsNotFinalInProtocol":"\\"{name}\\" ist im Protokoll nicht als \\"Final\\" gekennzeichnet.","memberIsWritableInProtocol":"\\"{name}\\" ist im Protokoll beschreibbar.","memberSetClassVar":"Der Member \\"{name}\\" kann nicht über eine Klasseninstanz zugewiesen werden, da es sich um eine ClassVar handelt.","memberTypeMismatch":"\\"{name}\\" ist ein inkompatibler Typ.","memberUnknown":"Das Member \\"{name}\\" ist unbekannt.","metaclassConflict":"Die Metaklasse \\"{metaclass1}\\" verursacht einen Konflikt mit \\"{metaclass2}\\"","missingDeleter":"Die Eigenschaft-Deleter-Methode fehlt.","missingGetter":"Die Eigenschaft-Getter-Methode fehlt.","missingSetter":"Die Eigenschaft-Setter-Methode fehlt.","namedParamMissingInDest":"Der Schlüsselwortparameter \\"{name}\\" fehlt im Ziel.","namedParamMissingInSource":"Der Schlüsselwortparameter \\"{name}\\" fehlt in der Quelle.","namedParamTypeMismatch":"Der Stichwortparameter \\"{name}\\" vom Typ \\"{sourceType}\\" kann dem Typ \\"{destType}\\" nicht zugewiesen werden.","namedTupleNotAllowed":"NamedTuple kann nicht für Instanzen- oder Klassenüberprüfungen verwendet werden.","newMethodLocation":"Die __new__ Methode ist in der Klasse \\"{type}\\" definiert.","newMethodSignature":"Signatur von __new__ ist \\"{type}\\"","newTypeClassNotAllowed":"Die mit NewType erstellte Klasse kann nicht mit Instanz- und Klassenüberprüfungen verwendet werden.","noOverloadAssignable":"Keine überladene Funktion stimmt mit dem Typ \\"{type}\\" überein.","noneNotAllowed":"\\"None\\" kann nicht für Instanz- oder Klassenprüfungen verwendet werden.","orPatternMissingName":"Fehlende Namen: {name}","overloadIndex":"Überladung \\"{index}\\" ist die nächste Übereinstimmung.","overloadNotAssignable":"Mindestens eine Überladung von \\"{name}\\" kann nicht zugewiesen werden.","overloadSignature":"Die Überladungssignatur ist hier definiert.","overriddenMethod":"Überschriebene Methode","overriddenSymbol":"Außer Kraft gesetztes Symbol","overrideInvariantMismatch":"Der Überschreibungstyp \\"{overrideType}\\" ist nicht identisch mit dem Basistyp \\"{baseType}\\".","overrideIsInvariant":"Die Variable ist veränderlich, sodass ihr Typ unveränderlich ist.","overrideNoOverloadMatches":"Keine Überladungssignatur in Überschreibung ist mit der Basismethode kompatibel.","overrideNotClassMethod":"Die Basismethode ist als Klassenmethode deklariert, die Überschreibung jedoch nicht","overrideNotInstanceMethod":"Die Basismethode ist als Instanz deklariert, die Überschreibung jedoch nicht","overrideNotStaticMethod":"Die Basismethode ist als staticmethod deklariert, die Überschreibung jedoch nicht","overrideOverloadNoMatch":"Außerkraftsetzung behandelt nicht alle Überladungen der Basismethode.","overrideOverloadOrder":"Überladungen für die Überschreibungsmethode müssen in der gleichen Reihenfolge wie die Basismethode vorliegen.","overrideParamKeywordNoDefault":"Konflikt mit Schlüsselwortparameter \\"{name}\\": Der Basisparameter hat einen Standardargumentwert, der Außerkraftsetzungsparameter ist nicht identisch.","overrideParamKeywordType":"Schlüsselwortparameter \\"{name}\\" Typenkonflikt: Basisparameter ist Typ \\"{baseType}\\", Überschreibungsparameter ist Typ \\"{overrideType}\\"","overrideParamName":"Namenskonflikt mit Parameter {index}: Der Basisparameter hat den Namen \\"{baseName}\\", der Außerkraftsetzungsparameter ist \\"{overrideName}\\"","overrideParamNameExtra":"Der Parameter \\"{name}\\" fehlt in der Basis.","overrideParamNameMissing":"Der Parameter \\"{name}\\" fehlt in der Außerkraftsetzung.","overrideParamNamePositionOnly":"Parameter „{index}“ stimmt nicht überein: Basisparameter „{baseName}“ ist Schlüsselwortparameter, Außerkraftsetzungsparameter ist „position-only“.","overrideParamNoDefault":"Konflikt mit Parameter {index}: Der Basisparameter hat einen Standardargumentwert, der Außerkraftsetzungsparameter ist nicht identisch.","overrideParamType":"Parameter {index} Typenkonflikt: Basisparameter ist Typ \\"{baseType}\\", Überschreibungsparameter ist Typ \\"{overrideType}\\"","overridePositionalParamCount":"Anzahl der Positionsparameter stimmt nicht überein; die Basismethode hat {baseCount}, aber die Überschreibung hat {overrideCount}","overrideReturnType":"Rückgabetypkonflikt: Basismethode gibt Typ \\"{baseType}\\" zurück, Überschreibung gibt Typ \\"{overrideType}\\" zurück","overrideType":"Die Basisklasse definiert den Typ als \\"{type}\\"","paramAssignment":"Parameter {index}: Der Typ \\"{sourceType}\\" kann dem Typ \\"{destType}\\" nicht zugewiesen werden.","paramSpecMissingInOverride":"Parameter \\"ParamSpec\\" fehlen in der Überschreibungsmethode.","paramType":"Parametertyp ist \\"{paramType}\\"","privateImportFromPyTypedSource":"Stattdessen aus \\"{module}\\" importieren","propertyAccessFromProtocolClass":"Auf eine in einer Protokollklasse definierte Eigenschaft kann nicht als Klassenvariable zugegriffen werden.","propertyMethodIncompatible":"Die Eigenschaftsmethode \\"{name}\\" ist inkompatibel.","propertyMethodMissing":"Die Eigenschaftsmethode \\"{name}\\" fehlt in der Überschreibung.","propertyMissingDeleter":"Die Eigenschaft \\"{name}\\" hat keinen definierten Deleter.","propertyMissingSetter":"Die Eigenschaft \\"{name}\\" hat keinen definierten Setter.","protocolIncompatible":"\\"{sourceType}\\" ist nicht mit dem Protokoll \\"{destType}\\" kompatibel.","protocolMemberMissing":"\\"{name}\\" ist nicht vorhanden.","protocolRequiresRuntimeCheckable":"Die Protokollklasse muss @runtime_checkable sein, damit sie mit Instanz- und Klassenprüfungen verwendet werden kann.","protocolSourceIsNotConcrete":"\\"{sourceType}\\" ist kein konkreter Klassentyp und kann dem Typ \\"{destType}\\" nicht zugewiesen werden.","protocolUnsafeOverlap":"Attribute von „{name}“ weisen die gleichen Namen wie das Protokoll auf.","pyrightCommentIgnoreTip":"Verwenden Sie \\"# pyright: ignore[<diagnostic rules>]\\", um die Diagnose für eine einzelne Zeile zu unterdrücken.","readOnlyAttribute":"Das Attribut \\"{name}\\" ist schreibgeschützt.","seeClassDeclaration":"Siehe Klassendeklaration","seeDeclaration":"Siehe Deklaration","seeFunctionDeclaration":"Siehe Funktionsdeklaration","seeMethodDeclaration":"Siehe Methodendeklaration","seeParameterDeclaration":"Siehe Parameterdeklaration","seeTypeAliasDeclaration":"Siehe Typaliasdeklaration","seeVariableDeclaration":"Siehe Variablendeklaration","tupleAssignmentMismatch":"Der Typ \\"{type}\\" ist nicht mit dem Zieltupel kompatibel.","tupleEntryTypeMismatch":"Der Tupeleintrag {entry} ist ein falscher Typ.","tupleSizeIndeterminateSrc":"Nicht übereinstimmende Tupelgröße; {expected} erwartet, aber unbestimmt empfangen","tupleSizeIndeterminateSrcDest":"Nicht übereinstimmende Tupelgröße; {expected} oder mehr erwartet, aber „unbestimmt“ empfangen","tupleSizeMismatch":"Nicht übereinstimmende Tupelgröße; {expected} erwartet, aber {received} empfangen","tupleSizeMismatchIndeterminateDest":"Nicht übereinstimmende Tupelgröße; {expected} oder mehr erwartet, aber {received} empfangen","typeAliasInstanceCheck":"Der mit der „type“-Anweisung erstellte Typalias kann nicht mit Instanz- und Klassenüberprüfungen verwendet werden.","typeAssignmentMismatch":"Der Typ \\"{sourceType}\\" kann dem Typ \\"{destType}\\" nicht zugewiesen werden.","typeBound":"Der Typ \\"{sourceType}\\" ist nicht mit dem gebundenen Typ \\"{destType}\\" für die Typvariablen \\"{name}\\" kompatibel.","typeConstrainedTypeVar":"Der Typ \\"{type}\\" ist mit der eingeschränkten Typvariablen nicht kompatibel \\"{name}\\"","typeIncompatible":"\\"{sourceType}\\" ist nicht mit \\"{destType}\\" kompatibel.","typeNotClass":"\\"{type}\\" ist keine Klasse.","typeNotStringLiteral":"\\"{type}\\" ist kein Zeichenfolgenliteral.","typeOfSymbol":"Der Typ von \\"{name}\\" ist \\"{type}\\".","typeParamSpec":"Typ \\"{type}\\" ist nicht mit ParamSpec \\"{name}\\" kompatibel.","typeUnsupported":"Typ \\"{type}\\" wird nicht unterstützt.","typeVarDefaultOutOfScope":"Die Typvariable \\"{name}\\" befindet sich nicht im Bereich.","typeVarIsContravariant":"Der Typparameter \\"{name}\\" ist kontravariant, aber \\"{sourceType}\\" ist kein Supertyp von \\"{destType}\\"","typeVarIsCovariant":"Der Typparameter \\"{name}\\" ist kovariant, aber \\"{sourceType}\\" ist kein Untertyp von \\"{destType}\\"","typeVarIsInvariant":"Der Typparameter \\"{name}\\" ist invariant, \\"{sourceType}\\" ist jedoch nicht identisch mit \\"{destType}\\"","typeVarNotAllowed":"TypeVar ist für Instanz- oder Klassenprüfungen nicht zulässig.","typeVarTupleRequiresKnownLength":"TypeVarTuple kann nicht an ein Tupel unbekannter Länge gebunden werden.","typeVarUnnecessarySuggestion":"Stattdessen {type} verwenden","typeVarUnsolvableRemedy":"Geben Sie eine Überladung an, die den Rückgabetyp angibt, wenn das Argument nicht angegeben ist.","typeVarsMissing":"Fehlende Typvariablen: {names}","typedDictBaseClass":"Die Klasse \\"{type}\\" ist kein TypedDict.","typedDictClassNotAllowed":"Die TypedDict-Klasse ist für Instanz- oder Klassenüberprüfungen nicht zulässig.","typedDictClosedExtraNotAllowed":"Das Element „{name}“ kann nicht hinzugefügt werden.","typedDictClosedExtraTypeMismatch":"Das Element „{name}“ mit dem Typ „{type}“ kann nicht hinzugefügt werden.","typedDictClosedFieldNotRequired":"Das Element „{name}“ kann nicht hinzugefügt werden, da es „NotRequired“ sein muss.","typedDictExtraFieldNotAllowed":"„{name}“ ist in „{type}“ nicht vorhanden.","typedDictExtraFieldTypeMismatch":"Der Typ von „{name}“ ist nicht mit dem Typ „__extra_items__“ in „{type}“ kompatibel.","typedDictFieldMissing":"\\"{name}\\" fehlt in \\"{type}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" ist in \\"{type}\\" nicht schreibgeschützt.","typedDictFieldNotRequired":"\\"{name}\\" ist in \\"{type}\\" nicht erforderlich.","typedDictFieldRequired":"\\"{name}\\" ist in \\"{type}\\" erforderlich.","typedDictFieldTypeMismatch":"Der Typ „{type}“ kann dem Element „{name}“ nicht zugewiesen werden.","typedDictFieldUndefined":"„{name}“ ist ein nicht definiertes Element im Typ „{type}“.","typedDictFinalMismatch":"\\"{sourceType}\\" ist aufgrund eines @final-Konflikts nicht mit \\"{destType}\\" kompatibel.","typedDictKeyAccess":"[\\"{name}\\"] verwenden, um in TypedDict auf ein Element zu verweisen","typedDictNotAllowed":"TypedDict kann nicht für Instanzen- oder Klassenüberprüfungen verwendet werden.","unhashableType":"Der Typ \\"{type}\\" kann nicht mit einem Hash erstellt werden.","uninitializedAbstractVariable":"Die Instanzvariable \\"{name}\\" ist in einer abstrakten Basisklasse \\"{classType}\\" definiert, aber nicht initialisiert.","unreachableExcept":"\\"{exceptionType}\\" ist eine Unterklasse von \\"{parentType}\\"","useDictInstead":"Verwenden Sie Dict[T1, T2], um einen Wörterbuchtyp anzugeben.","useListInstead":"Verwenden Sie List[T], um einen Listentyp anzugeben, oder Union[T1, T2], um einen Vereinigungstyp anzugeben.","useTupleInstead":"Verwenden Sie Tupel[T1, ..., Tn], um einen Tupeltyp anzugeben, oder Union[T1, T2], um einen Union-Typ anzugeben.","useTypeInstead":"Stattdessen Typ[T] verwenden","varianceMismatchForClass":"Die Varianz des Typarguments \\"{typeVarName}\\" ist nicht mit der Basisklasse \\"{className}\\" kompatibel","varianceMismatchForTypeAlias":"Die Varianz des Typarguments \\"{typeVarName}\\" ist nicht mit \\"{typeAliasParam}\\" kompatibel"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.en-us.json":
/*!*******************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.en-us.json ***!
  \*******************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"Diagnostic":{"abstractMethodInvocation":"Method \\"{method}\\" cannot be called because it is abstract and unimplemented","annotatedParamCountMismatch":"Parameter annotation count mismatch: expected {expected} but received {received}","annotatedTypeArgMissing":"Expected one type argument and one or more annotations for \\"Annotated\\"","annotationBytesString":"Type annotations cannot use bytes string literals","annotationFormatString":"Type annotations cannot use format string literals (f-strings)","annotationNotSupported":"Type annotation not supported for this statement","annotationRawString":"Type annotations cannot use raw string literals","annotationSpansStrings":"Type annotations cannot span multiple string literals","annotationStringEscape":"Type annotations cannot contain escape characters","argAssignment":"Argument of type \\"{argType}\\" cannot be assigned to parameter of type \\"{paramType}\\"","argAssignmentFunction":"Argument of type \\"{argType}\\" cannot be assigned to parameter of type \\"{paramType}\\" in function \\"{functionName}\\"","argAssignmentParam":"Argument of type \\"{argType}\\" cannot be assigned to parameter \\"{paramName}\\" of type \\"{paramType}\\"","argAssignmentParamFunction":"Argument of type \\"{argType}\\" cannot be assigned to parameter \\"{paramName}\\" of type \\"{paramType}\\" in function \\"{functionName}\\"","argMissingForParam":"Argument missing for parameter {name}","argMissingForParams":"Arguments missing for parameters {names}","argMorePositionalExpectedCount":"Expected {expected} more positional arguments","argMorePositionalExpectedOne":"Expected 1 more positional argument","argPositional":"Expected positional argument","argPositionalExpectedCount":"Expected {expected} positional arguments","argPositionalExpectedOne":"Expected 1 positional argument","argTypePartiallyUnknown":"Argument type is partially unknown","argTypeUnknown":"Argument type is unknown","argTypeAny":"Argument type is Any","assertAlwaysTrue":"Assert expression always evaluates to true","assertTypeArgs":"\\"assert_type\\" expects two positional arguments","assertTypeTypeMismatch":"\\"assert_type\\" mismatch: expected \\"{expected}\\" but received \\"{received}\\"","assignmentExprContext":"Assignment expression must be within module, function or lambda","assignmentExprComprehension":"Assignment expression target \\"{name}\\" cannot use same name as comprehension for target","assignmentInProtocol":"Instance or class variables within a Protocol class must be explicitly declared within the class body","assignmentExprInSubscript":"Assignment expressions within a subscript are supported only in Python 3.10 and newer","assignmentTargetExpr":"Expression cannot be assignment target","asyncNotInAsyncFunction":"Use of \\"async\\" not allowed outside of async function","awaitIllegal":"Use of \\"await\\" requires Python 3.5 or newer","awaitNotAllowed":"Type annotations cannot use \\"await\\"","awaitNotInAsync":"\\"await\\" allowed only within async function","backticksIllegal":"Expressions surrounded by backticks are not supported in Python 3.x; use repr instead","baseClassCircular":"Class cannot derive from itself","baseClassIncompatible":"Base classes of {type} are mutually incompatible","baseClassFinal":"Base class \\"{type}\\" is marked final and cannot be subclassed","baseClassInvalid":"Argument to class must be a base class","baseClassMethodTypeIncompatible":"Base classes for class \\"{classType}\\" define method \\"{name}\\" in incompatible way","baseClassVariableTypeIncompatible":"Base classes for class \\"{classType}\\" define variable \\"{name}\\" in incompatible way","baseClassUnknown":"Base class type is unknown, obscuring type of derived class","baseClassAny":"Base class type is Any, obscuring type of derived class","binaryOperationNotAllowed":"Binary operator not allowed in type annotation","bindTypeMismatch":"Could not bind method \\"{methodName}\\" because \\"{type}\\" is not assignable to parameter \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" can be used only within a loop","callableExtraArgs":"Expected only two type arguments to \\"Callable\\"","callableFirstArg":"Expected parameter type list or \\"...\\"","callableNotInstantiable":"Cannot instantiate type \\"{type}\\"","callableSecondArg":"Expected return type as second type argument for \\"Callable\\"","casePatternIsIrrefutable":"Irrefutable pattern is allowed only for the last case statement","classAlreadySpecialized":"Type \\"{type}\\" is already specialized","classDecoratorTypeUnknown":"Untyped class decorator obscures type of class; ignoring decorator","classDecoratorTypeAny":"Class decorator obscures type of class because its type is Any","classDefinitionCycle":"Class definition for \\"{name}\\" depends on itself","classGetItemClsParam":"__class_getitem__ override should take a \\"cls\\" parameter","classMethodClsParam":"Class methods should take a \\"cls\\" parameter","classNotRuntimeSubscriptable":"Subscript for class \\"{name}\\" will generate runtime exception; enclose type annotation in quotes","classPatternBuiltInArgPositional":"Class pattern accepts only positional sub-pattern","classPatternPositionalArgCount":"Too many positional patterns for class \\"{type}\\"; expected {expected} but received {received}","classPatternTypeAlias":"\\"{type}\\" cannot be used in a class pattern because it is a specialized type alias","classPropertyDeprecated":"Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13","classTypeParametersIllegal":"Class type parameter syntax requires Python 3.12 or newer","classVarNotAllowed":"\\"ClassVar\\" is not allowed in this context","classVarFirstArgMissing":"Expected a type argument after \\"ClassVar\\"","classVarOverridesInstanceVar":"Class variable \\"{name}\\" overrides instance variable of same name in class \\"{className}\\"","classVarTooManyArgs":"Expected only one type argument after \\"ClassVar\\"","classVarWithTypeVar":"\\"ClassVar\\" type cannot include type variables","clsSelfParamTypeMismatch":"Type of parameter \\"{name}\\" must be a supertype of its class \\"{classType}\\"","codeTooComplexToAnalyze":"Code is too complex to analyze; reduce complexity by refactoring into subroutines or reducing conditional code paths","collectionAliasInstantiation":"Type \\"{type}\\" cannot be instantiated, use \\"{alias}\\" instead","comparisonAlwaysFalse":"Condition will always evaluate to False since the types \\"{leftType}\\" and \\"{rightType}\\" have no overlap","comparisonAlwaysTrue":"Condition will always evaluate to True since the types \\"{leftType}\\" and \\"{rightType}\\" have no overlap","comprehensionInDict":"Comprehension cannot be used with other dictionary entries","comprehensionInSet":"Comprehension cannot be used with other set entries","concatenateContext":"\\"Concatenate\\" is not allowed in this context","concatenateParamSpecMissing":"Last type argument for \\"Concatenate\\" must be a ParamSpec or \\"...\\"","concatenateTypeArgsMissing":"\\"Concatenate\\" requires at least two type arguments","conditionalOperandInvalid":"Invalid conditional operand of type \\"{type}\\"","constantRedefinition":"\\"{name}\\" is constant (because it is uppercase) and cannot be redefined","constructorParametersMismatch":"Mismatch between signature of __new__ and __init__ in class \\"{classType}\\"","containmentAlwaysFalse":"Expression will always evaluate to False since the types \\"{leftType}\\" and \\"{rightType}\\" have no overlap","containmentAlwaysTrue":"Expression will always evaluate to True since the types \\"{leftType}\\" and \\"{rightType}\\" have no overlap","continueInFinally":"\\"continue\\" cannot be used within a finally clause","continueOutsideLoop":"\\"continue\\" can be used only within a loop","constructorNoArgs":"Expected no arguments to \\"{type}\\" constructor","coroutineInConditionalExpression":"Conditional expression references coroutine which always evaluates to True","dataClassBaseClassFrozen":"A non-frozen class cannot inherit from a class that is frozen","dataClassBaseClassNotFrozen":"A frozen class cannot inherit from a class that is not frozen","dataClassConverterFunction":"Argument of type \\"{argType}\\" is not a valid converter for field \\"{fieldName}\\" of type \\"{fieldType}\\"","dataClassConverterOverloads":"No overloads of \\"{funcName}\\" are valid converters for field \\"{fieldName}\\" of type \\"{fieldType}\\"","dataClassFieldInheritedDefault":"\\"{fieldName}\\" overrides a field of the same name but is missing a default value","dataClassFieldWithDefault":"Fields without default values cannot appear after fields with default values","dataClassFieldWithoutAnnotation":"Dataclass field without type annotation will cause runtime exception","dataClassFieldWithPrivateName":"Dataclass field cannot use private name","dataClassPostInitParamCount":"Dataclass __post_init__ incorrect parameter count; number of InitVar fields is {expected}","dataClassPostInitType":"Dataclass __post_init__ method parameter type mismatch for field \\"{fieldName}\\"","dataClassSlotsOverwrite":"__slots__ is already defined in class","dataClassTransformExpectedBoolLiteral":"Expected expression that statically evaluates to True or False","dataClassTransformFieldSpecifier":"Expected tuple of classes or functions but received type \\"{type}\\"","dataClassTransformPositionalParam":"All arguments to \\"dataclass_transform\\" must be keyword arguments","dataClassTransformUnknownArgument":"Argument \\"{name}\\" is not supported by dataclass_transform","dataProtocolInSubclassCheck":"Data protocols (which include non-method attributes) are not allowed in issubclass calls","declaredReturnTypePartiallyUnknown":"Declared return type, \\"{returnType}\\", is partially unknown","declaredReturnTypeUnknown":"Declared return type is unknown","defaultValueContainsCall":"Function calls and mutable objects not allowed within parameter default value expression","defaultValueNotAllowed":"Parameter with \\"*\\" or \\"**\\" cannot have default value","deprecatedClass":"The class \\"{name}\\" is deprecated","deprecatedConstructor":"The constructor for class \\"{name}\\" is deprecated","deprecatedDescriptorDeleter":"The \\"__delete__\\" method for descriptor \\"{name}\\" is deprecated","deprecatedDescriptorGetter":"The \\"__get__\\" method  for descriptor \\"{name}\\" is deprecated","deprecatedDescriptorSetter":"The \\"__set__\\" method  for descriptor \\"{name}\\" is deprecated","deprecatedFunction":"The function \\"{name}\\" is deprecated","deprecatedMethod":"The method \\"{name}\\" in class \\"{className}\\" is deprecated","deprecatedPropertyDeleter":"The deleter for property \\"{name}\\" is deprecated","deprecatedPropertyGetter":"The getter for property \\"{name}\\" is deprecated","deprecatedPropertySetter":"The setter for property \\"{name}\\" is deprecated","deprecatedType":"This type is deprecated as of Python {version}; use \\"{replacement}\\" instead","delTargetExpr":"Expression cannot be deleted","dictExpandIllegalInComprehension":"Dictionary expansion not allowed in comprehension","dictInAnnotation":"Dictionary expression not allowed in type annotation","dictKeyValuePairs":"Dictionary entries must contain key/value pairs","dictUnpackIsNotMapping":"Expected mapping for dictionary unpack operator","dunderAllSymbolNotPresent":"\\"{name}\\" is specified in __all__ but is not present in module","duplicateArgsParam":"Only one \\"*\\" parameter allowed","duplicateBaseClass":"Duplicate base class not allowed","duplicateCatchAll":"Only one catch-all except clause allowed","duplicateEnumMember":"Enum member \\"{name}\\" is already declared","duplicateGenericAndProtocolBase":"Only one Generic[...] or Protocol[...] base class allowed","duplicateImport":"\\"{importName}\\" is imported more than once","duplicateKwargsParam":"Only one \\"**\\" parameter allowed","duplicateKeywordOnly":"Only one \\"*\\" separator allowed","duplicateParam":"Duplicate parameter \\"{name}\\"","duplicateCapturePatternTarget":"Capture target \\"{name}\\" cannot appear more than once within the same pattern","duplicateStarPattern":"Only one \\"*\\" pattern allowed in a pattern sequence","duplicateStarStarPattern":"Only one \\"**\\" entry allowed","duplicatePositionOnly":"Only one \\"/\\" parameter allowed","duplicateUnpack":"Only one unpack operation allowed in list","ellipsisAfterUnpacked":"\\"...\\" cannot be used with an unpacked TypeVarTuple or tuple","ellipsisContext":"\\"...\\" is not allowed in this context","ellipsisSecondArg":"\\"...\\" is allowed only as the second of two arguments","enumClassOverride":"Enum class \\"{name}\\" is final and cannot be subclassed","exceptionGroupIncompatible":"Exception group syntax (\\"except*\\") requires Python 3.11 or newer","exceptionTypeIncorrect":"\\"{type}\\" does not derive from BaseException","exceptionTypeNotClass":"\\"{type}\\" is not a valid exception class","exceptionTypeNotInstantiable":"Constructor for exception type \\"{type}\\" requires one or more arguments","expectedAfterDecorator":"Expected function or class declaration after decorator","expectedArrow":"Expected \\"->\\" followed by return type annotation","expectedAsAfterException":"Expected \\"as\\" after exception type","expectedAssignRightHandExpr":"Expected expression to the right of \\"=\\"","expectedBinaryRightHandExpr":"Expected expression to the right of operator","expectedBoolLiteral":"Expected True or False","expectedCase":"Expected \\"case\\" statement","expectedClassName":"Expected class name","expectedCloseBrace":"\\"{\\" was not closed","expectedCloseBracket":"\\"[\\" was not closed","expectedCloseParen":"\\"(\\" was not closed","expectedColon":"Expected \\":\\"","expectedComplexNumberLiteral":"Expected complex number literal for pattern matching","expectedDecoratorExpr":"Expression form not supported for decorator prior to Python 3.9","expectedDecoratorName":"Expected decorator name","expectedDecoratorNewline":"Expected new line at end of decorator","expectedDelExpr":"Expected expression after \\"del\\"","expectedElse":"Expected \\"else\\"","expectedEquals":"Expected \\"=\\"","expectedExceptionClass":"Invalid exception class or object","expectedExceptionObj":"Expected exception object, exception class or None","expectedExpr":"Expected expression","expectedIdentifier":"Expected identifier","expectedImport":"Expected \\"import\\"","expectedImportAlias":"Expected symbol after \\"as\\"","expectedImportSymbols":"Expected one or more symbol names after import","expectedIndentedBlock":"Expected indented block","expectedInExpr":"Expected expression after \\"in\\"","expectedIn":"Expected \\"in\\"","expectedFunctionAfterAsync":"Expected function definition after \\"async\\"","expectedFunctionName":"Expected function name after \\"def\\"","expectedMemberName":"Expected attribute name after \\".\\"","expectedModuleName":"Expected module name","expectedNameAfterAs":"Expected symbol name after \\"as\\"","expectedNamedParameter":"Keyword parameter must follow \\"*\\"","expectedNewline":"Expected newline","expectedNewlineOrSemicolon":"Statements must be separated by newlines or semicolons","expectedOpenParen":"Expected \\"(\\"","expectedParamName":"Expected parameter name","expectedPatternExpr":"Expected pattern expression","expectedPatternSubjectExpr":"Expected pattern subject expression","expectedPatternValue":"Expected pattern value expression of the form \\"a.b\\"","expectedReturnExpr":"Expected expression after \\"return\\"","expectedSliceIndex":"Expected index or slice expression","expectedTypeNotString":"Expected type but received a string literal","expectedTypeParameterName":"Expected type parameter name","expectedYieldExpr":"Expected expression in yield statement","finalClassIsAbstract":"Class \\"{type}\\" is marked final and must implement all abstract symbols","finalContext":"\\"Final\\" is not allowed in this context","finalMethodOverride":"Method \\"{name}\\" cannot override final method defined in class \\"{className}\\"","finalNonMethod":"Function \\"{name}\\" cannot be marked @final because it is not a method","finalReassigned":"\\"{name}\\" is declared as Final and cannot be reassigned","finalRedeclaration":"\\"{name}\\" was previously declared as Final","finalRedeclarationBySubclass":"\\"{name}\\" cannot be redeclared because parent class \\"{className}\\" declares it as Final","finalTooManyArgs":"Expected a single type argument after \\"Final\\"","finalUnassigned":"\\"{name}\\" is declared Final, but value is not assigned","formatStringBrace":"Single close brace not allowed within f-string literal; use double close brace","formatStringBytes":"Format string literals (f-strings) cannot be binary","formatStringDebuggingIllegal":"F-string debugging specifier \\"=\\" requires Python 3.8 or newer","formatStringEscape":"Escape sequence (backslash) not allowed in expression portion of f-string prior to Python 3.12","formatStringExpectedConversion":"Expected a conversion specifier after \\"!\\" in f-string","formatStringInPattern":"Format string not allowed in pattern","formatStringNestedFormatSpecifier":"Expressions nested too deeply within format string specifier","formatStringNestedQuote":"Strings nested within an f-string cannot use the same quote character as the f-string prior to Python 3.12","formatStringUnicode":"Format string literals (f-strings) cannot be unicode","formatStringIllegal":"Format string literals (f-strings) require Python 3.6 or newer","formatStringUnterminated":"Unterminated expression in f-string; expecting \\"}\\"","functionDecoratorTypeUnknown":"Untyped function decorator obscures type of function; ignoring decorator","functionDecoratorTypeAny":"Function decorator obscures type of function because its type is Any","functionInConditionalExpression":"Conditional expression references function which always evaluates to True","functionTypeParametersIllegal":"Function type parameter syntax requires Python 3.12 or newer","futureImportLocationNotAllowed":"Imports from __future__ must be at the beginning of the file","generatorAsyncReturnType":"Return type of async generator function must be compatible with \\"AsyncGenerator[{yieldType}, Any]\\"","generatorNotParenthesized":"Generator expressions must be parenthesized if not sole argument","generatorSyncReturnType":"Return type of generator function must be compatible with \\"Generator[{yieldType}, Any, Any]\\"","genericBaseClassNotAllowed":"\\"Generic\\" base class cannot be used with type parameter syntax","genericClassAssigned":"Generic class type cannot be assigned","genericClassDeleted":"Generic class type cannot be deleted","genericInstanceVariableAccess":"Access to generic instance variable through class is ambiguous","genericNotAllowed":"\\"Generic\\" is not valid in this context","genericTypeAliasBoundTypeVar":"Generic type alias within class cannot use bound type variables {names}","genericTypeArgMissing":"\\"Generic\\" requires at least one type argument","genericTypeArgTypeVar":"Type argument for \\"Generic\\" must be a type variable","genericTypeArgUnique":"Type arguments for \\"Generic\\" must be unique","globalReassignment":"\\"{name}\\" is assigned before global declaration","globalRedefinition":"\\"{name}\\" was already declared global","implicitStringConcat":"Implicit string concatenation not allowed","importCycleDetected":"Cycle detected in import chain","importDepthExceeded":"Import chain depth exceeded {depth}","importResolveFailure":"Import \\"{importName}\\" could not be resolved","importSourceResolveFailure":"Import \\"{importName}\\" could not be resolved from source","importSymbolUnknown":"\\"{name}\\" is unknown import symbol","incompatibleMethodOverride":"Method \\"{name}\\" overrides class \\"{className}\\" in an incompatible manner","inconsistentIndent":"Unindent amount does not match previous indent","initMustReturnNone":"Return type of \\"__init__\\" must be None","inconsistentTabs":"Inconsistent use of tabs and spaces in indentation","initMethodSelfParamTypeVar":"Type annotation for \\"self\\" parameter of \\"__init__\\" method cannot contain class-scoped type varaiables","initSubclassClsParam":"__init_subclass__ override should take a \\"cls\\" parameter","initSubclassCallFailed":"Incorrect keyword arguments for __init_subclass__ method","initVarNotAllowed":"\\"InitVar\\" is not allowed in this context","instanceMethodSelfParam":"Instance methods should take a \\"self\\" parameter","instanceVarOverridesClassVar":"Instance variable \\"{name}\\" overrides class variable of same name in class \\"{className}\\"","instantiateAbstract":"Cannot instantiate abstract class \\"{type}\\"","instantiateProtocol":"Cannot instantiate protocol class \\"{type}\\"","internalBindError":"An internal error occurred while binding file \\"{file}\\": {message}","internalParseError":"An internal error occurred while parsing file \\"{file}\\": {message}","internalTypeCheckingError":"An internal error occurred while type checking file \\"{file}\\": {message}","invalidIdentifierChar":"Invalid character in identifier","invalidStubStatement":"Statement is meaningless within a type stub file","invalidTokenChars":"Invalid character \\"{text}\\" in token","isInstanceInvalidType":"Second argument to \\"isinstance\\" must be a class or tuple of classes","isSubclassInvalidType":"Second argument to \\"issubclass\\" must be a class or tuple of classes","keyValueInSet":"Key/value pairs are not allowed within a set","keywordArgInTypeArgument":"Keyword arguments cannot be used in type argument lists","keywordOnlyAfterArgs":"Keyword-only argument separator not allowed after \\"*\\" parameter","keywordParameterMissing":"One or more keyword parameters must follow \\"*\\" parameter","keywordSubscriptIllegal":"Keyword arguments within subscripts are not supported","lambdaReturnTypeUnknown":"Return type of lambda is unknown","lambdaReturnTypeAny":"Return type of lambda is Any","lambdaReturnTypePartiallyUnknown":"Return type of lambda, \\"{returnType}\\", is partially unknown","listAssignmentMismatch":"Expression with type \\"{type}\\" cannot be assigned to target list","listInAnnotation":"List expression not allowed in type annotation","literalUnsupportedType":"Type arguments for \\"Literal\\" must be None, a literal value (int, bool, str, or bytes), or an enum value","literalNamedUnicodeEscape":"Named unicode escape sequences are not supported in \\"Literal\\" string annotations","literalEmptyArgs":"Expected one or more type arguments after \\"Literal\\"","literalNotAllowed":"\\"Literal\\" cannot be used in this context without a type argument","literalNotCallable":"Literal type cannot be instantiated","matchIncompatible":"Match statements require Python 3.10 or newer","matchIsNotExhaustive":"Cases within match statement do not exhaustively handle all values","maxParseDepthExceeded":"Maximum parse depth exceeded; break expression into smaller sub-expressions","memberAccess":"Cannot access attribute \\"{name}\\" for class \\"{type}\\"","memberDelete":"Cannot delete attribute \\"{name}\\" for class \\"{type}\\"","memberSet":"Cannot assign to attribute \\"{name}\\" for class \\"{type}\\"","metaclassConflict":"The metaclass of a derived class must be a subclass of the metaclasses of all its base classes","metaclassDuplicate":"Only one metaclass can be provided","metaclassIsGeneric":"Metaclass cannot be generic","methodNotDefined":"\\"{name}\\" method not defined","methodNotDefinedOnType":"\\"{name}\\" method not defined on type \\"{type}\\"","methodOrdering":"Cannot create consistent method ordering","methodOverridden":"\\"{name}\\" overrides method of same name in class \\"{className}\\" with incompatible type \\"{type}\\"","methodReturnsNonObject":"\\"{name}\\" method does not return an object","missingSuperCall":"Method \\"{methodName}\\" does not call the method of the same name in parent class","moduleAsType":"Module cannot be used as a type","moduleNotCallable":"Module is not callable","moduleUnknownMember":"\\"{memberName}\\" is not a known attribute of module \\"{moduleName}\\"","namedExceptAfterCatchAll":"A named except clause cannot appear after catch-all except clause","namedParamAfterParamSpecArgs":"Keyword parameter \\"{name}\\" cannot appear in signature after ParamSpec args parameter","namedTupleEmptyName":"Names within a named tuple cannot be empty","namedTupleMultipleInheritance":"Multiple inheritance with NamedTuple is not supported","namedTupleEntryRedeclared":"Cannot override \\"{name}\\" because parent class \\"{className}\\" is a named tuple","namedTupleFirstArg":"Expected named tuple class name as first argument","namedTupleNameKeyword":"Field names cannot be a keyword","namedTupleNameType":"Expected two-entry tuple specifying entry name and type","namedTupleNameUnique":"Names within a named tuple must be unique","namedTupleNoTypes":"\\"namedtuple\\" provides no types for tuple entries; use \\"NamedTuple\\" instead","namedTupleSecondArg":"Expected named tuple entry list as second argument","newClsParam":"__new__ override should take a \\"cls\\" parameter","newTypeAnyOrUnknown":"The second argument to NewType must be a known class, not Any or Unknown","newTypeBadName":"The first argument to NewType must be a string literal","newTypeLiteral":"NewType cannot be used with Literal type","newTypeNameMismatch":"NewType must be assigned to a variable with the same name","newTypeNotAClass":"Expected class as second argument to NewType","newTypeParamCount":"NewType requires two positional arguments","newTypeProtocolClass":"NewType cannot be used with structural type (a protocol or TypedDict class)","nonDefaultAfterDefault":"Non-default argument follows default argument","noneNotCallable":"Object of type \\"None\\" cannot be called","noneNotIterable":"Object of type \\"None\\" cannot be used as iterable value","noneOperator":"Operator \\"{operator}\\" not supported for \\"None\\"","noneNotSubscriptable":"Object of type \\"None\\" is not subscriptable","noneNotUsableWith":"Object of type \\"None\\" cannot be used with \\"with\\"","noneUnknownMember":"\\"{name}\\" is not a known attribute of \\"None\\"","nonLocalNoBinding":"No binding for nonlocal \\"{name}\\" found","nonLocalReassignment":"\\"{name}\\" is assigned before nonlocal declaration","nonLocalRedefinition":"\\"{name}\\" was already declared nonlocal","nonLocalInModule":"Nonlocal declaration not allowed at module level","noOverload":"No overloads for \\"{name}\\" match the provided arguments","noReturnContainsReturn":"Function with declared return type \\"NoReturn\\" cannot include a return statement","noReturnContainsYield":"Function with declared return type \\"NoReturn\\" cannot include a yield statement","noReturnReturnsNone":"Function with declared return type \\"NoReturn\\" cannot return \\"None\\"","notRequiredArgCount":"Expected a single type argument after \\"NotRequired\\"","notRequiredNotInTypedDict":"\\"NotRequired\\" is not allowed in this context","objectNotCallable":"Object of type \\"{type}\\" is not callable","obscuredClassDeclaration":"Class declaration \\"{name}\\" is obscured by a declaration of the same name","obscuredFunctionDeclaration":"Function declaration \\"{name}\\" is obscured by a declaration of the same name","obscuredMethodDeclaration":"Method declaration \\"{name}\\" is obscured by a declaration of the same name","obscuredParameterDeclaration":"Parameter declaration \\"{name}\\" is obscured by a declaration of the same name","obscuredTypeAliasDeclaration":"Type alias declaration \\"{name}\\" is obscured by a declaration of the same name","obscuredVariableDeclaration":"Declaration \\"{name}\\" is obscured by a declaration of the same name","operatorLessOrGreaterDeprecated":"Operator \\"<>\\" is not supported in Python 3; use \\"!=\\" instead","optionalExtraArgs":"Expected one type argument after \\"Optional\\"","orPatternIrrefutable":"Irrefutable pattern allowed only as the last subpattern in an \\"or\\" pattern","orPatternMissingName":"All subpatterns within an \\"or\\" pattern must target the same names","overlappingKeywordArgs":"Typed dictionary overlaps with keyword parameter: {names}","overlappingOverload":"Overload {obscured} for \\"{name}\\" will never be used because its parameters overlap overload {obscuredBy}","overloadAbstractMismatch":"Overloaded methods must all be abstract or not","overloadClassMethodInconsistent":"Overloads for \\"{name}\\" use @classmethod inconsistently","overloadFinalInconsistencyImpl":"Overload for \\"{name}\\" is marked @final but implementation is not","overloadFinalInconsistencyNoImpl":"Overload {index} for \\"{name}\\" is marked @final but overload 1 is not","overloadImplementationMismatch":"Overloaded implementation is not consistent with signature of overload {index}","overloadReturnTypeMismatch":"Overload {prevIndex} for \\"{name}\\" overlaps overload {newIndex} and returns an incompatible type","overloadStaticMethodInconsistent":"Overloads for \\"{name}\\" use @staticmethod inconsistently","overloadWithoutImplementation":"\\"{name}\\" is marked as overload, but no implementation is provided","overriddenMethodNotFound":"Method \\"{name}\\" is marked as override, but no base method of same name is present","overrideDecoratorMissing":"Method \\"{name}\\" is not marked as override but is overriding a method in class \\"{className}\\"","paramAfterKwargsParam":"Parameter cannot follow \\"**\\" parameter","paramAlreadyAssigned":"Parameter \\"{name}\\" is already assigned","paramAnnotationMissing":"Type annotation is missing for parameter \\"{name}\\"","paramNameMissing":"No parameter named \\"{name}\\"","paramSpecArgsKwargsUsage":"\\"args\\" and \\"kwargs\\" attributes of ParamSpec must both appear within a function signature","paramSpecArgsMissing":"Arguments for ParamSpec \\"{type}\\" are missing","paramSpecArgsUsage":"\\"args\\" attribute of ParamSpec is valid only when used with *args parameter","paramSpecAssignedName":"ParamSpec must be assigned to a variable named \\"{name}\\"","paramSpecContext":"ParamSpec is not allowed in this context","paramSpecDefaultNotTuple":"Expected ellipsis, a tuple expression, or ParamSpec for default value of ParamSpec","paramSpecFirstArg":"Expected name of ParamSpec as first argument","paramSpecKwargsUsage":"\\"kwargs\\" attribute of ParamSpec is valid only when used with **kwargs parameter","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" has no meaning in this context","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" is scoped to a callable within the return type and cannot be referenced in the function body","paramSpecUnknownArg":"ParamSpec does not support more than one argument","paramSpecUnknownMember":"\\"{name}\\" is not a known attribute of ParamSpec","paramSpecUnknownParam":"\\"{name}\\" is unknown parameter to ParamSpec","paramAssignmentMismatch":"Expression of type \\"{sourceType}\\" cannot be assigned to parameter of type \\"{paramType}\\"","paramTypeCovariant":"Covariant type variable cannot be used in parameter type","paramTypeUnknown":"Type of parameter \\"{paramName}\\" is unknown","paramTypeAny":"Type of parameter \\"{paramName}\\" is Any","paramTypePartiallyUnknown":"Type of parameter \\"{paramName}\\" is partially unknown","parenthesizedContextManagerIllegal":"Parentheses within \\"with\\" statement requires Python 3.9 or newer","patternNeverMatches":"Pattern will never be matched for subject type \\"{type}\\"","positionArgAfterNamedArg":"Positional argument cannot appear after keyword arguments","privateImportFromPyTypedModule":"\\"{name}\\" is not exported from module \\"{module}\\"","positionOnlyAfterArgs":"Position-only parameter separator not allowed after \\"*\\" parameter","positionOnlyAfterKeywordOnly":"\\"/\\" parameter must appear before \\"*\\" parameter","positionOnlyAfterNon":"Position-only parameter not allowed after parameter that is not position-only","positionOnlyIncompatible":"Position-only parameter separator requires Python 3.8 or newer","positionOnlyFirstParam":"Position-only parameter separator not allowed as first parameter","privateUsedOutsideOfClass":"\\"{name}\\" is private and used outside of the class in which it is declared","privateUsedOutsideOfModule":"\\"{name}\\" is private and used outside of the module in which it is declared","propertyOverridden":"\\"{name}\\" incorrectly overrides property of same name in class \\"{className}\\"","propertyStaticMethod":"Static methods not allowed for property getter, setter or deleter","protectedUsedOutsideOfClass":"\\"{name}\\" is protected and used outside of the class in which it is declared","protocolBaseClass":"Protocol class \\"{classType}\\" cannot derive from non-protocol class \\"{baseType}\\"","protocolBaseClassWithTypeArgs":"Type arguments are not allowed with Protocol class when using type parameter syntax","protocolIllegal":"Use of \\"Protocol\\" requires Python 3.7 or newer","protocolNotAllowed":"\\"Protocol\\" cannot be used in this context","protocolUnsafeOverlap":"Class overlaps \\"{name}\\" unsafely and could produce a match at runtime","protocolVarianceContravariant":"Type variable \\"{variable}\\" used in generic protocol \\"{class}\\" should be contravariant","protocolVarianceCovariant":"Type variable \\"{variable}\\" used in generic protocol \\"{class}\\" should be covariant","protocolVarianceInvariant":"Type variable \\"{variable}\\" used in generic protocol \\"{class}\\" should be invariant","pyrightCommentInvalidDiagnosticBoolValue":"Pyright comment directive must be followed by \\"=\\" and a value of true or false","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright comment directive must be followed by \\"=\\" and a value of true, false, error, warning, information, or none","pyrightCommentMissingDirective":"Pyright comment must be followed by a directive (basic or strict) or a diagnostic rule","pyrightCommentNotOnOwnLine":"Pyright comments used to control file-level settings must appear on their own line","pyrightCommentUnknownDirective":"\\"{directive}\\" is an unknown directive for pyright comment; expected \\"strict\\" or \\"basic\\"","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" is an unknown diagnostic rule for pyright comment","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" is invalid value for pyright comment; expected true, false, error, warning, information, or none","readOnlyArgCount":"Expected a single type argument after \\"ReadOnly\\"","readOnlyNotInTypedDict":"\\"ReadOnly\\" is not allowed in this context","relativeImportNotAllowed":"Relative imports cannot be used with \\"import .a\\" form; use \\"from . import a\\" instead","recursiveDefinition":"Type of \\"{name}\\" could not be determined because it refers to itself","requiredArgCount":"Expected a single type argument after \\"Required\\"","requiredNotInTypedDict":"\\"Required\\" is not allowed in this context","returnInAsyncGenerator":"Return statement with value is not allowed in async generator","returnOutsideFunction":"\\"return\\" can be used only within a function","returnMissing":"Function with declared return type \\"{returnType}\\" must return value on all code paths","returnTypeContravariant":"Contravariant type variable cannot be used in return type","returnTypeMismatch":"Expression of type \\"{exprType}\\" is incompatible with return type \\"{returnType}\\"","returnTypeUnknown":"Return type is unknown","returnTypeAny":"Return type is Any","returnTypePartiallyUnknown":"Return type, \\"{returnType}\\", is partially unknown","revealLocalsArgs":"Expected no arguments for \\"reveal_locals\\" call","revealLocalsNone":"No locals in this scope","revealTypeArgs":"Expected a single positional argument for \\"reveal_type\\" call","revealTypeExpectedTextArg":"The \\"expected_text\\" argument for function \\"reveal_type\\" must be a str literal value","revealTypeExpectedTextMismatch":"Type text mismatch; expected \\"{expected}\\" but received \\"{received}\\"","revealTypeExpectedTypeMismatch":"Type mismatch; expected \\"{expected}\\" but received \\"{received}\\"","selfTypeContext":"\\"Self\\" is not valid in this context","selfTypeMetaclass":"\\"Self\\" cannot be used within a metaclass (a subclass of \\"type\\")","selfTypeWithTypedSelfOrCls":"\\"Self\\" cannot be used in a function with a `self` or `cls` parameter that has a type annotation other than \\"Self\\"","setterGetterTypeMismatch":"Property setter value type is not assignable to the getter return type","singleOverload":"\\"{name}\\" is marked as overload, but additional overloads are missing","slotsAttributeError":"\\"{name}\\" is not specified in __slots__","slotsClassVarConflict":"\\"{name}\\" conflicts with instance variable declared in __slots__","starPatternInAsPattern":"Star pattern cannot be used with \\"as\\" target","starPatternInOrPattern":"Star pattern cannot be ORed within other patterns","starStarWildcardNotAllowed":"** cannot be used with wildcard \\"_\\"","staticClsSelfParam":"Static methods should not take a \\"self\\" or \\"cls\\" parameter","stdlibModuleOverridden":"\\"{path}\\" is overriding the stdlib module \\"{name}\\"","stringNonAsciiBytes":"Non-ASCII character not allowed in bytes string literal","stringNotSubscriptable":"String expression cannot be subscripted in type annotation; enclose entire annotation in quotes","stringUnsupportedEscape":"Unsupported escape sequence in string literal","stringUnterminated":"String literal is unterminated","stubFileMissing":"Stub file not found for \\"{importName}\\"","stubUsesGetAttr":"Type stub file is incomplete; \\"__getattr__\\" obscures type errors for module","sublistParamsIncompatible":"Sublist parameters are not supported in Python 3.x","superCallArgCount":"Expected no more than two arguments to \\"super\\" call","superCallFirstArg":"Expected class type as first argument to \\"super\\" call but received \\"{type}\\"","superCallSecondArg":"Second argument to \\"super\\" call must be object or class that derives from \\"{type}\\"","superCallZeroArgForm":"Zero-argument form of \\"super\\" call is valid only within a method","superCallZeroArgFormStaticMethod":"Zero-argument form of \\"super\\" call is not valid within a static method","symbolIsUnbound":"\\"{name}\\" is unbound","symbolIsUndefined":"\\"{name}\\" is not defined","symbolIsPossiblyUnbound":"\\"{name}\\" is possibly unbound","symbolOverridden":"\\"{name}\\" overrides symbol of same name in class \\"{className}\\"","ternaryNotAllowed":"Ternary expression not allowed in type annotation","totalOrderingMissingMethod":"Class must define one of \\"__lt__\\", \\"__le__\\", \\"__gt__\\", or \\"__ge__\\" to use total_ordering","trailingCommaInFromImport":"Trailing comma not allowed without surrounding parentheses","tryWithoutExcept":"Try statement must have at least one except or finally clause","tupleAssignmentMismatch":"Expression with type \\"{type}\\" cannot be assigned to target tuple","tupleInAnnotation":"Tuple expression not allowed in type annotation","tupleIndexOutOfRange":"Index {index} is out of range for type {type}","typeAliasIllegalExpressionForm":"Invalid expression form for type alias definition","typeAliasIsRecursiveDirect":"Type alias \\"{name}\\" cannot use itself in its definition","typeAliasNotInModuleOrClass":"A TypeAlias can be defined only within a module or class scope","typeAliasRedeclared":"\\"{name}\\" is declared as a TypeAlias and can be assigned only once","typeAliasStatementIllegal":"Type alias statement requires Python 3.12 or newer","typeAliasStatementBadScope":"A type statement can be used only within a module or class scope","typeAliasTypeBaseClass":"A type alias defined in a \\"type\\" statement cannot be used as a base class","typeAliasTypeMustBeAssigned":"TypeAliasType must be assigned to a variable with the same name as the type alias","typeAliasTypeNameArg":"First argument to TypeAliasType must be a string literal representing the name of the type alias","typeAliasTypeNameMismatch":"Name of type alias must match the name of the variable to which it is assigned","typeAliasTypeParamInvalid":"Type parameter list must be a tuple containing only TypeVar, TypeVarTuple, or ParamSpec","typeArgListExpected":"Expected ParamSpec, ellipsis, or list of types","typeAnnotationCall":"Call expression not allowed in type expression","typeAnnotationVariable":"Variable not allowed in type expression","typeAnnotationWithCallable":"Type argument for \\"type\\" must be a class; callables are not supported","typeArgListNotAllowed":"List expression not allowed for this type argument","typeArgsExpectingNone":"Expected no type arguments for class \\"{name}\\"","typeArgsMismatchOne":"Expected one type argument but received {received}","typeArgsMissingForAlias":"Expected type arguments for generic type alias \\"{name}\\"","typeArgsMissingForClass":"Expected type arguments for generic class \\"{name}\\"","typeArgsTooFew":"Too few type arguments provided for \\"{name}\\"; expected {expected} but received {received}","typeArgsTooMany":"Too many type arguments provided for \\"{name}\\"; expected {expected} but received {received}","typeAssignmentMismatch":"Expression of type \\"{sourceType}\\" is incompatible with declared type \\"{destType}\\"","typeAssignmentMismatchWildcard":"Import symbol \\"{name}\\" has type \\"{sourceType}\\", which is incompatible with declared type \\"{destType}\\"","typeCallNotAllowed":"type() call should not be used in type annotation","typeCheckOnly":"\\"{name}\\" is marked as @type_check_only and can be used only in type annotations","typeCommentDeprecated":"Use of type comments is deprecated; use type annotation instead","typedDictAccess":"Could not access item in TypedDict","typedDictAssignedName":"TypedDict must be assigned to a variable named \\"{name}\\"","typedDictBadVar":"TypedDict classes can contain only type annotations","typedDictBaseClass":"All base classes for TypedDict classes must also be TypedDict classes","typedDictBoolParam":"Expected \\"{name}\\" parameter to have a value of True or False","typedDictClosedExtras":"Base class \\"{name}\\" is a closed TypedDict; extra items must be type \\"{type}\\"","typedDictClosedNoExtras":"Base class \\"{name}\\" is a closed TypedDict; extra items are not allowed","typedDictDelete":"Could not delete item in TypedDict","typedDictEmptyName":"Names within a TypedDict cannot be empty","typedDictEntryName":"Expected string literal for dictionary entry name","typedDictEntryUnique":"Names within a dictionary must be unique","typedDictExtraArgs":"Extra TypedDict arguments not supported","typedDictFieldNotRequiredRedefinition":"TypedDict item \\"{name}\\" cannot be redefined as NotRequired","typedDictFieldReadOnlyRedefinition":"TypedDict item \\"{name}\\" cannot be redefined as ReadOnly","typedDictFieldRequiredRedefinition":"TypedDict item \\"{name}\\" cannot be redefined as Required","typedDictFirstArg":"Expected TypedDict class name as first argument","typedDictInitsubclassParameter":"TypedDict does not support __init_subclass__ parameter \\"{name}\\"","typedDictNotAllowed":"\\"TypedDict\\" cannot be used in this context","typedDictSecondArgDict":"Expected dict or keyword parameter as second parameter","typedDictSecondArgDictEntry":"Expected simple dictionary entry","typedDictSet":"Could not assign item in TypedDict","typeExpectedClass":"Expected type expression but received \\"{type}\\"","typeGuardArgCount":"Expected a single type argument after \\"TypeGuard\\" or \\"TypeIs\\"","typeGuardParamCount":"User-defined type guard functions and methods must have at least one input parameter","typeIsReturnType":"Return type of TypeIs (\\"{returnType}\\") is not consistent with value parameter type (\\"{type}\\")","typeNotAwaitable":"\\"{type}\\" is not awaitable","typeNotIntantiable":"\\"{type}\\" cannot be instantiated","typeNotIterable":"\\"{type}\\" is not iterable","typeNotSpecializable":"Could not specialize type \\"{type}\\"","typeNotSubscriptable":"Object of type \\"{type}\\" is not subscriptable","typeNotUsableWith":"Object of type \\"{type}\\" cannot be used with \\"with\\" because it does not implement {method}","typeNotSupportBinaryOperator":"Operator \\"{operator}\\" not supported for types \\"{leftType}\\" and \\"{rightType}\\"","typeNotSupportBinaryOperatorBidirectional":"Operator \\"{operator}\\" not supported for types \\"{leftType}\\" and \\"{rightType}\\" when expected type is \\"{expectedType}\\"","typeNotSupportUnaryOperator":"Operator \\"{operator}\\" not supported for type \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"Operator \\"{operator}\\" not supported for type \\"{type}\\" when expected type is \\"{expectedType}\\"","typeParameterBoundNotAllowed":"Bound or constraint cannot be used with a variadic type parameter or ParamSpec","typeParameterConstraintTuple":"Type parameter constraint must be a tuple of two or more types","typeParameterExistingTypeParameter":"Type parameter \\"{name}\\" is already in use","typeParametersMissing":"At least one type parameter must be specified","typeParameterNotDeclared":"Type parameter \\"{name}\\" is not included in the type parameter list for \\"{container}\\"","typePartiallyUnknown":"Type of \\"{name}\\" is partially unknown","typeUnknown":"Type of \\"{name}\\" is unknown","typeAny":"Type of \\"{name}\\" is Any","typeVarAssignedName":"TypeVar must be assigned to a variable named \\"{name}\\"","typeVarAssignmentMismatch":"Type \\"{type}\\" cannot be assigned to type variable \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar cannot be both bound and constrained","typeVarBoundGeneric":"TypeVar bound type cannot be generic","typeVarConstraintGeneric":"TypeVar constraint type cannot be generic","typeVarDefaultBoundMismatch":"TypeVar default type must be a subtype of the bound type","typeVarDefaultConstraintMismatch":"TypeVar default type must be one of the constrained types","typeVarDefaultIllegal":"Type variable default types require Python 3.13 or newer","typeVarDefaultInvalidTypeVar":"Type parameter \\"{name}\\" has a default type that refers to one or more type variables that are out of scope","typeVarFirstArg":"Expected name of TypeVar as first argument","typeVarNoMember":"TypeVar \\"{type}\\" has no attribute \\"{name}\\"","typeVarNotSubscriptable":"TypeVar \\"{type}\\" is not subscriptable","typeVarNotUsedByOuterScope":"Type variable \\"{name}\\" has no meaning in this context","typeVarPossiblyUnsolvable":"Type variable \\"{name}\\" may go unsolved if caller supplies no argument for parameter \\"{param}\\"","typeVarScopedToReturnType":"Type variable \\"{name}\\" is scoped to a callable within the return type and cannot be referenced in the function body","typeVarSingleConstraint":"TypeVar must have at least two constrained types","typeVarsNotInGenericOrProtocol":"Generic[] or Protocol[] must include all type variables","typeVarTupleContext":"TypeVarTuple is not allowed in this context","typeVarTupleDefaultNotUnpacked":"TypeVarTuple default type must be an unpacked tuple or TypeVarTuple","typeVarTupleMustBeUnpacked":"Unpack operator is required for TypeVarTuple value","typeVarTupleConstraints":"TypeVarTuple cannot have value constraints","typeVarTupleUnknownParam":"\\"{name}\\" is unknown parameter to TypeVarTuple","typeVarUnknownParam":"\\"{name}\\" is unknown parameter to TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" is already in use by an outer scope","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" appears only once in generic function signature","typeVarVariance":"TypeVar cannot be both covariant and contravariant","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" has a default value and cannot follow TypeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" cannot appear after \\"{other}\\" in type parameter list because it has no default type","unaccessedClass":"Class \\"{name}\\" is not accessed","unaccessedFunction":"Function \\"{name}\\" is not accessed","unaccessedImport":"Import \\"{name}\\" is not accessed","unaccessedSymbol":"\\"{name}\\" is not accessed","unaccessedVariable":"Variable \\"{name}\\" is not accessed","unannotatedFunctionSkipped":"Analysis of function \\"{name}\\" is skipped because it is unannotated","unaryOperationNotAllowed":"Unary operator not allowed in type annotation","unexpectedAsyncToken":"Expected \\"def\\", \\"with\\" or \\"for\\" to follow \\"async\\"","unexpectedExprToken":"Unexpected token at end of expression","unexpectedIndent":"Unexpected indentation","unexpectedUnindent":"Unindent not expected","unhashableDictKey":"Dictionary key must be hashable","unhashableSetEntry":"Set entry must be hashable","unionForwardReferenceNotAllowed":"Union syntax cannot be used with string operand; use quotes around entire expression","unionSyntaxIllegal":"Alternative syntax for unions requires Python 3.10 or newer","unionTypeArgCount":"Union requires two or more type arguments","uninitializedAbstractVariables":"Variables defined in abstract base class are not initialized in final class \\"{classType}\\"","uninitializedInstanceVariable":"Instance variable \\"{name}\\" is not initialized in the class body or __init__ method","unionUnpackedTuple":"Union cannot include an unpacked tuple","unionUnpackedTypeVarTuple":"Union cannot include an unpacked TypeVarTuple","unnecessaryCast":"Unnecessary \\"cast\\" call; type is already \\"{type}\\"","unnecessaryIsInstanceAlways":"Unnecessary isinstance call; \\"{testType}\\" is always an instance of \\"{classType}\\"","unnecessaryIsSubclassAlways":"Unnecessary issubclass call; \\"{testType}\\" is always a subclass of \\"{classType}\\"","unnecessaryPyrightIgnore":"Unnecessary \\"# pyright: ignore\\" comment","unnecessaryPyrightIgnoreRule":"Unnecessary \\"# pyright: ignore\\" rule: \\"{name}\\"","unnecessaryTypeIgnore":"Unnecessary \\"# type: ignore\\" comment","unpackArgCount":"Expected a single type argument after \\"Unpack\\"","unpackedArgInTypeArgument":"Unpacked arguments cannot be used in type argument lists","unpackedArgWithVariadicParam":"Unpacked argument cannot be used for TypeVarTuple parameter","unpackedDictArgumentNotMapping":"Argument expression after ** must be a mapping with a \\"str\\" key type","unpackedDictSubscriptIllegal":"Dictionary unpack operator in subscript is not allowed","unpackedSubscriptIllegal":"Unpack operator in subscript requires Python 3.11 or newer","unpackedTypedDictArgument":"Unable to match unpacked TypedDict argument to parameters","unpackedTypeVarTupleExpected":"Expected unpacked TypeVarTuple; use Unpack[{name1}] or *{name2}","unpackExpectedTypedDict":"Expected TypedDict type argument for Unpack","unpackExpectedTypeVarTuple":"Expected TypeVarTuple or tuple as type argument for Unpack","unpackIllegalInComprehension":"Unpack operation not allowed in comprehension","unpackInAnnotation":"Unpack operator not allowed in type annotation","unpackInDict":"Unpack operation not allowed in dictionaries","unpackInSet":"Unpack operator not allowed within a set","unpackNotAllowed":"Unpack is not allowed in this context","unpackOperatorNotAllowed":"Unpack operation is not allowed in this context","unpackTuplesIllegal":"Unpack operation not allowed in tuples prior to Python 3.8","unreachableCode":"Code is unreachable","unreachableExcept":"Except clause is unreachable because exception is already handled","unsupportedDunderAllOperation":"Operation on \\"__all__\\" is not supported, so exported symbol list may be incorrect","unusedCallResult":"Result of call expression is of type \\"{type}\\" and is not used; assign to variable \\"_\\" if this is intentional","unusedCoroutine":"Result of async function call is not used; use \\"await\\" or assign result to variable","unusedExpression":"Expression value is unused","varAnnotationIllegal":"Type annotations for variables requires Python 3.6 or newer; use type comment for compatibility with previous versions","variableFinalOverride":"Variable \\"{name}\\" is marked Final and overrides non-Final variable of same name in class \\"{className}\\"","variadicTypeArgsTooMany":"Type argument list can have at most one unpacked TypeVarTuple or tuple","variadicTypeParamTooManyAlias":"Type alias can have at most one TypeVarTuple type parameter but received multiple ({names})","variadicTypeParamTooManyClass":"Generic class can have at most one TypeVarTuple type parameter but received multiple ({names})","walrusIllegal":"Operator \\":=\\" requires Python 3.8 or newer","walrusNotAllowed":"Operator \\":=\\" is not allowed in this context without surrounding parentheses","wildcardInFunction":"Wildcard import not allowed within a class or function","wildcardPatternTypeUnknown":"Type captured by wildcard pattern is unknown","wildcardPatternTypeAny":"Type captured by wildcard pattern is Any","wildcardPatternTypePartiallyUnknown":"Type captured by wildcard pattern is partially unknown","wildcardLibraryImport":"Wildcard import from a library not allowed","yieldFromIllegal":"Use of \\"yield from\\" requires Python 3.3 or newer","yieldFromOutsideAsync":"\\"yield from\\" not allowed in an async function","yieldOutsideFunction":"\\"yield\\" not allowed outside of a function or lambda","yieldWithinListCompr":"\\"yield\\" not allowed inside a list comprehension","zeroCaseStatementsFound":"Match statement must include at least one case statement","zeroLengthTupleNotAllowed":"Zero-length tuple is not allowed in this context","pyrightIgnoreCommentWithoutRule":"`pyright: ignore` comment must specify a rule (eg. `# pyright: ignore[ruleName]`)","typeIgnoreCommentWithoutRule":"`type: ignore` comment must specify a rule (eg. `# type: ignore[ruleName]`)","implicitRelativeImport":"Import from `{importName}` is implicitly relative and will not work if this file is imported as a module","invalidCast":"Conversion of type `{fromType}` to type `{toType}` may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to `object` first."},"DiagnosticAddendum":{"annotatedNotAllowed":"\\"Annotated\\" special form cannot be used with instance and class checks","argParam":"Argument corresponds to parameter \\"{paramName}\\"","argParamFunction":"Argument corresponds to parameter \\"{paramName}\\" in function \\"{functionName}\\"","argsParamMissing":"Parameter \\"*{paramName}\\" has no corresponding parameter","argsPositionOnly":"Position-only parameter mismatch; expected {expected} but received {received}","argumentType":"Argument type is \\"{type}\\"","argumentTypes":"Argument types: ({types})","assignToNone":"Type is incompatible with \\"None\\"","asyncHelp":"Did you mean \\"async with\\"?","baseClassIncompatible":"Base class \\"{baseClass}\\" is incompatible with type \\"{type}\\"","baseClassIncompatibleSubclass":"Base class \\"{baseClass}\\" derives from \\"{subclass}\\" which is incompatible with type \\"{type}\\"","baseClassOverriddenType":"Base class \\"{baseClass}\\" provides type \\"{type}\\", which is overridden","baseClassOverridesType":"Base class \\"{baseClass}\\" overrides with type \\"{type}\\"","bytesTypePromotions":"Set disableBytesTypePromotions to false to enable type promotion behavior for \\"bytearray\\" and \\"memoryview\\"","conditionalRequiresBool":"Method __bool__ for type \\"{operandType}\\" returns type \\"{boolReturnType}\\" rather than \\"bool\\"","dataClassFieldLocation":"Field declaration","dataProtocolUnsupported":"\\"{name}\\" is a data protocol","descriptorAccessBindingFailed":"Failed to bind method \\"{name}\\" for descriptor class \\"{className}\\"","descriptorAccessCallFailed":"Failed to call method \\"{name}\\" for descriptor class \\"{className}\\"","dataClassFrozen":"\\"{name}\\" is frozen","finalMethod":"Final method","functionParamDefaultMissing":"Parameter \\"{name}\\" is missing default argument","functionParamName":"Parameter name mismatch: \\"{destName}\\" versus \\"{srcName}\\"","functionParamPositionOnly":"Position-only parameter mismatch; parameter \\"{name}\\" is not position-only","functionReturnTypeMismatch":"Function return type \\"{sourceType}\\" is incompatible with type \\"{destType}\\"","functionTooFewParams":"Function accepts too few positional parameters; expected {expected} but received {received}","functionTooManyParams":"Function accepts too many positional parameters; expected {expected} but received {received}","genericClassNotAllowed":"Generic type with type arguments not allowed for instance or class checks","keyNotRequired":"\\"{name}\\" is not a required key in \\"{type}\\", so access may result in runtime exception","keyReadOnly":"\\"{name}\\" is a read-only key in \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" is a required key and cannot be deleted","keyUndefined":"\\"{name}\\" is not a defined key in \\"{type}\\"","incompatibleGetter":"Property getter method is incompatible","incompatibleSetter":"Property setter method is incompatible","initMethodLocation":"The __init__ method is defined in class \\"{type}\\"","incompatibleDeleter":"Property deleter method is incompatible","initMethodSignature":"Signature of __init__ is \\"{type}\\"","initSubclassLocation":"The __init_subclass__ method is defined in class \\"{name}\\"","invariantSuggestionDict":"Consider switching from \\"dict\\" to \\"Mapping\\" which is covariant in the value type","invariantSuggestionList":"Consider switching from \\"list\\" to \\"Sequence\\" which is covariant","invariantSuggestionSet":"Consider switching from \\"set\\" to \\"Container\\" which is covariant","kwargsParamMissing":"Parameter \\"**{paramName}\\" has no corresponding parameter","listAssignmentMismatch":"Type \\"{type}\\" is incompatible with target list","literalAssignmentMismatch":"\\"{sourceType}\\" is incompatible with type \\"{destType}\\"","matchIsNotExhaustiveType":"Unhandled type: \\"{type}\\"","matchIsNotExhaustiveHint":"If exhaustive handling is not intended, add \\"case _: pass\\"","memberSetClassVar":"Attribute \\"{name}\\" cannot be assigned through a class instance because it is a ClassVar","memberAssignment":"Expression of type \\"{type}\\" cannot be assigned to attribute \\"{name}\\" of class \\"{classType}\\"","memberIsAbstract":"\\"{type}.{name}\\" is not implemented","memberIsAbstractMore":"and {count} more...","memberIsClassVarInProtocol":"\\"{name}\\" is defined as a ClassVar in protocol","memberIsFinalInProtocol":"\\"{name}\\" is marked Final in protocol","memberIsInitVar":"\\"{name}\\" is an init-only field","memberIsInvariant":"\\"{name}\\" is invariant because it is mutable","memberIsNotClassVarInClass":"\\"{name}\\" must be defined as a ClassVar to be compatible with protocol","memberIsNotClassVarInProtocol":"\\"{name}\\" is not defined as a ClassVar in protocol","memberIsNotFinalInProtocol":"\\"{name}\\" is not marked Final in protocol","memberIsWritableInProtocol":"\\"{name}\\" is writable in protocol","memberTypeMismatch":"\\"{name}\\" is an incompatible type","memberUnknown":"Attribute \\"{name}\\" is unknown","metaclassConflict":"Metaclass \\"{metaclass1}\\" conflicts with \\"{metaclass2}\\"","missingGetter":"Property getter method is missing","missingSetter":"Property setter method is missing","missingDeleter":"Property deleter method is missing","namedParamMissingInDest":"Keyword parameter \\"{name}\\" is missing in destination","namedParamMissingInSource":"Keyword parameter \\"{name}\\" is missing in source","namedParamTypeMismatch":"Keyword parameter \\"{name}\\" of type \\"{sourceType}\\" is incompatible with type \\"{destType}\\"","namedTupleNotAllowed":"NamedTuple cannot be used for instance or class checks","newMethodLocation":"The __new__ method is defined in class \\"{type}\\"","newMethodSignature":"Signature of __new__ is \\"{type}\\"","newTypeClassNotAllowed":"Class created with NewType cannot be used with instance and class checks","noneNotAllowed":"None cannot be used for instance or class checks","noOverloadAssignable":"No overloaded function matches type \\"{type}\\"","orPatternMissingName":"Missing names: {name}","overloadIndex":"Overload {index} is the closest match","overloadSignature":"Overload signature is defined here","overloadNotAssignable":"One or more overloads of \\"{name}\\" is not assignable","overriddenMethod":"Overridden method","overriddenSymbol":"Overridden symbol","overrideIsInvariant":"Variable is mutable so its type is invariant","overrideInvariantMismatch":"Override type \\"{overrideType}\\" is not the same as base type \\"{baseType}\\"","overrideNoOverloadMatches":"No overload signature in override is compatible with base method","overrideNotClassMethod":"Base method is declared as a classmethod but override is not","overrideNotInstanceMethod":"Base method is declared as an instance method but override is not","overrideNotStaticMethod":"Base method is declared as a staticmethod but override is not","overrideOverloadNoMatch":"Override does not handle all overloads of base method","overrideOverloadOrder":"Overloads for override method must be in the same order as the base method","overrideParamKeywordNoDefault":"Keyword parameter \\"{name}\\" mismatch: base parameter has default argument value, override parameter does not","overrideParamKeywordType":"Keyword parameter \\"{name}\\" type mismatch: base parameter is type \\"{baseType}\\", override parameter is type \\"{overrideType}\\"","overrideParamName":"Parameter {index} name mismatch: base parameter is named \\"{baseName}\\", override parameter is named \\"{overrideName}\\"","overrideParamNameExtra":"Parameter \\"{name}\\" is missing in base","overrideParamNameMissing":"Parameter \\"{name}\\" is missing in override","overrideParamNamePositionOnly":"Parameter {index} mismatch: base parameter \\"{baseName}\\" is keyword parameter, override parameter is position-only","overrideParamNoDefault":"Parameter {index} mismatch: base parameter has default argument value, override parameter does not","overrideParamType":"Parameter {index} type mismatch: base parameter is type \\"{baseType}\\", override parameter is type \\"{overrideType}\\"","overridePositionalParamCount":"Positional parameter count mismatch; base method has {baseCount}, but override has {overrideCount}","overrideReturnType":"Return type mismatch: base method returns type \\"{baseType}\\", override returns type \\"{overrideType}\\"","overrideType":"Base class defines type as \\"{type}\\"","paramAssignment":"Parameter {index}: type \\"{sourceType}\\" is incompatible with type \\"{destType}\\"","paramSpecMissingInOverride":"ParamSpec parameters are missing in override method","paramType":"Parameter type is \\"{paramType}\\"","privateImportFromPyTypedSource":"Import from \\"{module}\\" instead","propertyAccessFromProtocolClass":"A property defined within a protocol class cannot be accessed as a class variable","propertyMethodIncompatible":"Property method \\"{name}\\" is incompatible","propertyMethodMissing":"Property method \\"{name}\\" is missing in override","propertyMissingDeleter":"Property \\"{name}\\" has no defined deleter","propertyMissingSetter":"Property \\"{name}\\" has no defined setter","protocolIncompatible":"\\"{sourceType}\\" is incompatible with protocol \\"{destType}\\"","protocolMemberMissing":"\\"{name}\\" is not present","protocolRequiresRuntimeCheckable":"Protocol class must be @runtime_checkable to be used with instance and class checks","protocolSourceIsNotConcrete":"\\"{sourceType}\\" is not a concrete class type and cannot be assigned to type \\"{destType}\\"","protocolUnsafeOverlap":"Attributes of \\"{name}\\" have the same names as the protocol","pyrightCommentIgnoreTip":"Use \\"# pyright: ignore[<diagnostic rules>] to suppress diagnostics for a single line","readOnlyAttribute":"Attribute \\"{name}\\" is read-only","seeDeclaration":"See declaration","seeClassDeclaration":"See class declaration","seeFunctionDeclaration":"See function declaration","seeMethodDeclaration":"See method declaration","seeParameterDeclaration":"See parameter declaration","seeTypeAliasDeclaration":"See type alias declaration","seeVariableDeclaration":"See variable declaration","tupleEntryTypeMismatch":"Tuple entry {entry} is incorrect type","tupleAssignmentMismatch":"Type \\"{type}\\" is incompatible with target tuple","tupleSizeIndeterminateSrc":"Tuple size mismatch; expected {expected} but received indeterminate","tupleSizeIndeterminateSrcDest":"Tuple size mismatch; expected {expected} or more but received indeterminate","tupleSizeMismatch":"Tuple size mismatch; expected {expected} but received {received}","tupleSizeMismatchIndeterminateDest":"Tuple size mismatch; expected {expected} or more but received {received}","typeAliasInstanceCheck":"Type alias created with \\"type\\" statement cannot be used with instance and class checks","typeAssignmentMismatch":"Type \\"{sourceType}\\" is incompatible with type \\"{destType}\\"","typeBound":"Type \\"{sourceType}\\" is incompatible with bound type \\"{destType}\\" for type variable \\"{name}\\"","typeConstrainedTypeVar":"Type \\"{type}\\" is incompatible with constrained type variable \\"{name}\\"","typedDictBaseClass":"Class \\"{type}\\" is not a TypedDict","typedDictClassNotAllowed":"TypedDict class not allowed for instance or class checks","typedDictExtraFieldNotAllowed":"\\"{name}\\" is not present in \\"{type}\\"","typedDictExtraFieldTypeMismatch":"Type of \\"{name}\\" is incompatible with type of \\"__extra_items__\\" in \\"{type}\\"","typedDictFieldMissing":"\\"{name}\\" is missing from \\"{type}\\"","typedDictClosedExtraNotAllowed":"Cannot add item \\"{name}\\"","typedDictClosedExtraTypeMismatch":"Cannot add item \\"{name}\\" with type \\"{type}\\"","typedDictClosedFieldNotRequired":"Cannot add item \\"{name}\\" because it must be NotRequired","typedDictFieldNotReadOnly":"\\"{name}\\" is not read-only in \\"{type}\\"","typedDictFieldNotRequired":"\\"{name}\\" is not required in \\"{type}\\"","typedDictFieldRequired":"\\"{name}\\" is required in \\"{type}\\"","typedDictFieldTypeMismatch":"Type \\"{type}\\" is not assignable to item \\"{name}\\"","typedDictFieldUndefined":"\\"{name}\\" is an undefined item in type \\"{type}\\"","typedDictFinalMismatch":"\\"{sourceType}\\" is incompatible with \\"{destType}\\" because of a @final mismatch","typedDictKeyAccess":"Use [\\"{name}\\"] to reference item in TypedDict","typedDictNotAllowed":"TypedDict cannot be used for instance or class checks","typeIncompatible":"\\"{sourceType}\\" is incompatible with \\"{destType}\\"","typeNotClass":"\\"{type}\\" is not a class","typeParamSpec":"Type \\"{type}\\" is incompatible with ParamSpec \\"{name}\\"","typeNotStringLiteral":"\\"{type}\\" is not a string literal","typeOfSymbol":"Type of \\"{name}\\" is \\"{type}\\"","typeUnsupported":"Type \\"{type}\\" is unsupported","typeVarDefaultOutOfScope":"Type variable \\"{name}\\" is not in scope","typeVarIsContravariant":"Type parameter \\"{name}\\" is contravariant, but \\"{sourceType}\\" is not a supertype of \\"{destType}\\"","typeVarIsCovariant":"Type parameter \\"{name}\\" is covariant, but \\"{sourceType}\\" is not a subtype of \\"{destType}\\"","typeVarIsInvariant":"Type parameter \\"{name}\\" is invariant, but \\"{sourceType}\\" is not the same as \\"{destType}\\"","typeVarNotAllowed":"TypeVar not allowed for instance or class checks","typeVarUnnecessarySuggestion":"Use {type} instead","typeVarUnsolvableRemedy":"Provide an overload that specifies the return type when the argument is not supplied","typeVarsMissing":"Missing type variables: {names}","typeVarTupleRequiresKnownLength":"TypeVarTuple cannot be bound to a tuple of unknown length","unhashableType":"Type \\"{type}\\" is not hashable","uninitializedAbstractVariable":"Instance variable \\"{name}\\" is defined in abstract base class \\"{classType}\\" but not initialized","unreachableExcept":"\\"{exceptionType}\\" is a subclass of \\"{parentType}\\"","useDictInstead":"Use Dict[T1, T2] to indicate a dictionary type","useListInstead":"Use List[T] to indicate a list type or Union[T1, T2] to indicate a union type","useTupleInstead":"Use tuple[T1, ..., Tn] to indicate a tuple type or Union[T1, T2] to indicate a union type","useTypeInstead":"Use Type[T] instead","varianceMismatchForClass":"Variance of type argument \\"{typeVarName}\\" is incompatible with base class \\"{className}\\"","varianceMismatchForTypeAlias":"Variance of type argument \\"{typeVarName}\\" is incompatible with \\"{typeAliasParam}\\"","explicitRelativeImportSuggestion":"Use a relative import from `.{importName}` instead","fullPathImportSuggestion":"or specify the full module path: `{importName}`"},"CodeAction":{"createTypeStub":"Create Type Stub","createTypeStubFor":"Create Type Stub For \\"{moduleName}\\"","executingCommand":"Executing command","filesToAnalyzeOne":"1 file to analyze","filesToAnalyzeCount":"{count} files to analyze","findingReferences":"Finding references","organizeImports":"Organize Imports","renameShadowedFile":"Rename \\"{oldFile}\\" to \\"{newFile}\\""},"Completion":{"autoImportDetail":"Auto-import","indexValueDetail":"Index value"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.es.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.es.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Crear Tipo Stub","createTypeStubFor":"Crear Tipo Stub Para \\"{moduleName}\\"","executingCommand":"Ejecutando el comando","filesToAnalyzeCount":"{count} archivos para analizar","filesToAnalyzeOne":"1 archivo para analizar","findingReferences":"Buscando referencias","organizeImports":"Organizar Importaciones","renameShadowedFile":"Cambie el nombre de \\"{oldFile}\\" a \\"{newFile}\\""},"Completion":{"autoImportDetail":"Importación automática","indexValueDetail":"Valor de índice"},"Diagnostic":{"abstractMethodInvocation":"No se puede llamar al método \\"{method}\\" porque es abstracto y no se ha implementado.","annotatedParamCountMismatch":"El recuento de anotaciones del parámetro no coincide: se esperaba {expected}, pero se recibió {received}","annotatedTypeArgMissing":"Se espera un argumento de tipo y una o más anotaciones para \\"Anotado\\".","annotationFormatString":"Las anotaciones de tipo no pueden utilizar literales de cadena de formato (cadenas f)","annotationNotSupported":"No se admite la anotación de tipo para esta declaración","annotationSpansStrings":"Las anotaciones de tipo no pueden abarcar varios literales de cadena","annotationStringEscape":"Las anotaciones de tipo no pueden contener caracteres de escape","argAssignment":"Argumento de tipo \\"{argType}\\" no puede ser asignado a parámetro de tipo \\"{paramType}\\"","argAssignmentFunction":"El argumento de tipo \\"{argType}\\" no puede ser asignado a parámetro de tipo \\"{paramType}\\" en función \\"{functionName}\\"","argAssignmentParam":"Argumento de tipo \\"{argType}\\" no puede ser asignado a parámetro \\"{paramName}\\" de tipo \\"{paramType}\\"","argAssignmentParamFunction":"Argumento de tipo \\"{argType}\\" no puede ser asignado a parámetro \\"{paramName}\\" de tipo \\"{paramType}\\" en función \\"{functionName}\\"","argMissingForParam":"Falta el argumento para el parámetro {name}","argMissingForParams":"Faltan argumentos para los parámetros {names}","argMorePositionalExpectedCount":"Más argumentos posicionales {expected} esperados","argMorePositionalExpectedOne":"Se espera 1 argumento posicional más","argPositional":"Argumento posicional esperado","argPositionalExpectedCount":"Argumentos posicionales esperados {expected}","argPositionalExpectedOne":"Se espera 1 argumento posicional","argTypePartiallyUnknown":"El tipo de argumento es parcialmente desconocido","argTypeUnknown":"Tipo de argumento desconocido","assertAlwaysTrue":"La expresión Assert siempre se evalúa como verdadero","assertTypeArgs":"\\"assert_type\\" espera dos argumentos posicionales","assertTypeTypeMismatch":"Error de coincidencia \\"assert_type\\": se esperaba \\"{expected}\\" pero se ha recibido \\"{received}\\"","assignmentExprComprehension":"El destino de la expresión de asignación \\"{name}\\" no puede usar el mismo nombre que la comprensión para el destino","assignmentExprContext":"La expresión de asignación debe estar dentro de un módulo, función o lambda","assignmentExprInSubscript":"Las expresiones de asignación dentro de un subíndice solo se admiten en Python 3.10 y versiones posteriores.","assignmentInProtocol":"Las variables de instancia o clase dentro de una clase Protocol deben declararse explícitamente en el cuerpo de la clase.","assignmentTargetExpr":"La expresión no puede ser objetivo de asignación","asyncNotInAsyncFunction":"No se permite el uso de \\"async\\" fuera de la función asincrónica","awaitIllegal":"El uso de \\"await\\" requiere Python 3.5 o posterior.","awaitNotAllowed":"Las anotaciones de tipo no pueden usar \\"await\\"","awaitNotInAsync":"\\"await\\" solo se permite dentro de una función async","backticksIllegal":"En Python 3.x no se admiten expresiones rodeadas de puntos suspensivos; utilice repr en su lugar.","baseClassCircular":"La clase no se puede derivar de sí misma","baseClassFinal":"La clase base \\"{type}\\" está marcada como final y no puede ser subclasificada","baseClassIncompatible":"Las clases base de {type} son mutuamente incompatibles","baseClassInvalid":"El argumento de la clase debe ser una clase base","baseClassMethodTypeIncompatible":"Las clases base para la clase \\"{classType}\\" definen el método \\"{name}\\" de forma incompatible","baseClassUnknown":"Se desconoce el tipo de la clase base, lo que oculta el tipo de la clase derivada.","baseClassVariableTypeIncompatible":"Las clases base para la clase \\"{classType}\\" definen la variable \\"{name}\\" de forma incompatible","binaryOperationNotAllowed":"Operador binario no permitido en la anotación de tipo","bindTypeMismatch":"No se pudo enlazar el método \\"{methodName}\\" porque \\"{type}\\" no se puede asignar al parámetro \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" solo se puede usar dentro de un bucle","callableExtraArgs":"Se esperaban solo dos argumentos de tipo para \\"Exigible\\".","callableFirstArg":"Lista de tipos de parámetros esperados o \\"...\\"","callableNotInstantiable":"No se puede instanciar el tipo \\"{type}\\"","callableSecondArg":"Tipo de retorno esperado como segundo argumento de tipo para \\"Exigible\\"","casePatternIsIrrefutable":"El patrón irrefutable solo se permite para la última instrucción case","classAlreadySpecialized":"El tipo \\"{type}\\" ya está especializado","classDecoratorTypeUnknown":"El decorador de clase sin tipo oculta el tipo de clase; omitiendo el elemento Decorator","classDefinitionCycle":"La definición de clase para \\"{name}\\" depende de sí misma.","classGetItemClsParam":"__class_getitem__ debe tomar un parámetro \\"cls\\"","classMethodClsParam":"Los métodos de clase deben tomar un parámetro \\"cls\\"","classNotRuntimeSubscriptable":"El subíndice para la clase \\"{name}\\" generará una excepción en tiempo de ejecución; encierre la anotación de tipo entre comillas","classPatternBuiltInArgPositional":"El patrón de clase solo acepta subpatrones posicionales","classPatternPositionalArgCount":"Demasiados patrones posicionales para la clase \\"{type}\\"; esperado {expected} pero recibido {received}","classPatternTypeAlias":"\\"{type}\\" no se puede usar en un patrón de clase porque es un alias de tipo especializado","classPropertyDeprecated":"Las propiedades de clase están en desuso en Python 3.11 y no se admitirán en Python 3.13.","classTypeParametersIllegal":"La sintaxis de los parámetros de tipo de clase requiere Python 3.12 o posterior.","classVarFirstArgMissing":"Se esperaba un argumento de tipo después de \\"ClassVar\\"","classVarNotAllowed":"\\"ClassVar\\" no está permitido en este contexto","classVarOverridesInstanceVar":"La variable de clase \\"{name}\\" anula la variable de instancia del mismo nombre en la clase \\"{className}\\"","classVarTooManyArgs":"Solo se esperaba un argumento de tipo después de \\"ClassVar\\"","classVarWithTypeVar":"El tipo \\"ClassVar\\" no puede incluir variables de tipo","clsSelfParamTypeMismatch":"El tipo de parámetro \\"{name}\\" debe ser un supertipo de su clase \\"{classType}\\"","codeTooComplexToAnalyze":"El código es demasiado complejo para analizarlo; reduzca la complejidad refactorizándolo en subrutinas o reduciendo las rutas de código condicional.","collectionAliasInstantiation":"No se puede crear una instancia del tipo \\"{type}\\"; use \\"{alias}\\" en su lugar.","comparisonAlwaysFalse":"La condición siempre se evaluará como Falso, ya que los tipos \\"{leftType}\\" y \\"{rightType}\\" no se superponen.","comparisonAlwaysTrue":"La condición siempre se evaluará como Verdadero, ya que los tipos \\"{leftType}\\" y \\"{rightType}\\" no se superpone.","comprehensionInDict":"La comprensión no puede utilizarse con otras entradas del diccionario","comprehensionInSet":"La comprensión no se puede usar con otras entradas de conjunto","concatenateContext":"\\"Concatenar\\" no se permite en este contexto","concatenateParamSpecMissing":"El último argumento de tipo para \\"Concatenatar\\" debe ser un ParamSpec o \\"...\\"","concatenateTypeArgsMissing":"\\"Concatenar\\" requiere al menos dos argumentos de tipo","conditionalOperandInvalid":"Operando condicional no válido de tipo \\"{type}\\"","constantRedefinition":"\\"{name}\\" es constante (porque está en mayúsculas) y no se puede volver a definir","constructorNoArgs":"No se esperaban argumentos para el constructor \\"{type}\\"","constructorParametersMismatch":"Error de coincidencia entre la firma de __new__ y __init__ en la clase \\"{classType}\\"","containmentAlwaysFalse":"La expresión siempre se evaluará como False, ya que los tipos \\"{leftType}\\" y \\"{rightType}\\" no tienen superposición","containmentAlwaysTrue":"La expresión siempre se evaluará como True, ya que los tipos \\"{leftType}\\" y \\"{rightType}\\" no tienen superposición","continueInFinally":"\\"continue\\" no puede utilizarse dentro de una cláusula finally","continueOutsideLoop":"\\"continue\\" solo puede utilizarse dentro de un bucle","coroutineInConditionalExpression":"La expresión condicional hace referencia a una corrutina que siempre se evalúa como Verdadero","dataClassBaseClassFrozen":"Una clase no inmovilizada no puede heredar de una clase inmovilizada","dataClassBaseClassNotFrozen":"Una clase congelada no puede heredar de una clase que no esté congelada","dataClassConverterFunction":"Argumento de tipo \\"{argType}\\" no es un convertidor válido para el campo \\"{fieldName}\\" de tipo \\"{fieldType}\\"","dataClassConverterOverloads":"No hay sobrecargas de \\"{funcName}\\" que sean convertidores válidos para el campo \\"{fieldName}\\" de tipo \\"{fieldType}\\"","dataClassFieldWithDefault":"Los campos sin valores predeterminados no pueden aparecer después de los campos con valores predeterminados","dataClassFieldWithPrivateName":"El campo Dataclass no puede utilizar un nombre privado","dataClassFieldWithoutAnnotation":"El campo Dataclass sin anotación de tipo provocará una excepción en tiempo de ejecución","dataClassPostInitParamCount":"Dataclass __post_init__ recuento de parámetros incorrecto; el número de campos InitVar es {expected}.","dataClassPostInitType":"El tipo de parámetro del método __post_init__ de la clase de datos no coincide con el del campo \\"{fieldName}\\".","dataClassSlotsOverwrite":"__slots__ ya está definido en la clase","dataClassTransformExpectedBoolLiteral":"Expresión esperada que se evalúa estáticamente como True o False","dataClassTransformFieldSpecifier":"Se esperaba una tupla de clases o funciones, pero se recibió el tipo \\"{type}\\"","dataClassTransformPositionalParam":"Todos los argumentos de \\"dataclass_transform\\" deben ser argumentos de palabra clave","dataClassTransformUnknownArgument":"El argumento \\"{name}\\" no es compatible con dataclass_transform","dataProtocolInSubclassCheck":"No se permiten protocolos de datos (que incluyen atributos que no son de método) en llamadas issubclass","declaredReturnTypePartiallyUnknown":"El tipo de retorno declarado, \\"{returnType}\\", es parcialmente desconocido","declaredReturnTypeUnknown":"El tipo de retorno declarado es desconocido","defaultValueContainsCall":"No se permiten llamadas de función y objetos mutables dentro de la expresión de valor predeterminado del parámetro","defaultValueNotAllowed":"Los parámetros con \\"*\\" o \\"**\\" no pueden tener valor por defecto","delTargetExpr":"No se puede eliminar la expresión","deprecatedClass":"La clase \\"{name}\\" está en desuso","deprecatedConstructor":"El constructor de la clase \\"{name}\\" está obsoleto","deprecatedDescriptorDeleter":"El método \\"__delete__\\" para el \\"{name}\\" de descriptor está en desuso","deprecatedDescriptorGetter":"El método \\"__get__\\" para el \\"{name}\\" de descriptor está en desuso","deprecatedDescriptorSetter":"El método \\"__set__\\" para el \\"{name}\\" de descriptor está en desuso","deprecatedFunction":"La función \\"{name}\\" está obsoleta","deprecatedMethod":"El método \\"{name}\\" en la clase \\"{className}\\" está en desuso","deprecatedPropertyDeleter":"El eliminador de la propiedad \\"{name}\\" está en desuso","deprecatedPropertyGetter":"El captador de la propiedad \\"{name}\\" está en desuso","deprecatedPropertySetter":"El establecedor de la propiedad \\"{name}\\" está en desuso","deprecatedType":"Este tipo está obsoleto a partir de la {version} de Python; utilice en su lugar \\"{replacement}\\".","dictExpandIllegalInComprehension":"No se permite la ampliación del diccionario en la comprensión","dictInAnnotation":"Expresión de diccionario no permitida en anotación de tipo","dictKeyValuePairs":"Las entradas del diccionario deben contener pares clave/valor","dictUnpackIsNotMapping":"Asignación esperada para el operador de desempaquetado del diccionario","dunderAllSymbolNotPresent":"\\"{name}\\" se especifica en __all__ pero no está presente en el módulo","duplicateArgsParam":"Solo se permite un parámetro \\"*\\".","duplicateBaseClass":"Clase base duplicada no permitida","duplicateCapturePatternTarget":"El destino de captura \\"{name}\\" no puede aparecer más de una vez dentro del mismo patrón","duplicateCatchAll":"Solo se permite una cláusula de excepción","duplicateEnumMember":"El miembro Enum \\"{name}\\" ya está declarado","duplicateGenericAndProtocolBase":"Solo se permite una clase base Genérica[...] o Protocolar[...].","duplicateImport":"\\"{importName}\\" se importa más de una vez","duplicateKeywordOnly":"Solo se permite un separador \\"*\\".","duplicateKwargsParam":"Solo se permite un parámetro \\"**\\".","duplicateParam":"Parámetro duplicado \\"{name}\\"","duplicatePositionOnly":"Solo se permite un parámetro \\"/\\"","duplicateStarPattern":"Solo se permite un patrón \\"*\\" en una secuencia de patrones","duplicateStarStarPattern":"Solo se permite una entrada \\"**\\"","duplicateUnpack":"Solo se permite una operación de desempaquetado en la lista","ellipsisAfterUnpacked":"\\"...\\" no se puede usar con una TypeVarTuple o tupla sin empaquetar","ellipsisContext":"\\"...\\" no está permitido en este contexto","ellipsisSecondArg":"\\"...\\" está permitido sólo como el segundo de dos argumentos","enumClassOverride":"La clase Enum \\"{name}\\" es final y no puede ser subclasificada","exceptionGroupIncompatible":"La sintaxis de grupo de excepciones (\\"except*\\") requiere Python 3.11 o posterior.","exceptionTypeIncorrect":"\\"{type}\\" no se deriva de BaseException","exceptionTypeNotClass":"\\"{type}\\" no es una clase de excepción válida","exceptionTypeNotInstantiable":"El constructor para el tipo de excepción \\"{type}\\" requiere uno o más argumentos","expectedAfterDecorator":"Se esperaba una declaración de función o clase después del decorador","expectedArrow":"Se esperaba \\"->\\" seguido de una anotación de tipo de retorno","expectedAsAfterException":"Se esperaba \\"as\\" después del tipo de excepción","expectedAssignRightHandExpr":"Expresión esperada a la derecha de \\"=\\"","expectedBinaryRightHandExpr":"Expresión esperada a la derecha del operador","expectedBoolLiteral":"Se esperaba True o False","expectedCase":"Declaración \\"case\\" esperada","expectedClassName":"Nombre de clase esperado","expectedCloseBrace":"\\"{\\" no estaba cerrado","expectedCloseBracket":"\\"[\\" no estaba cerrado","expectedCloseParen":"\\"(\\" no estaba cerrado","expectedColon":"Se esperaba \\":\\"","expectedComplexNumberLiteral":"Número complejo literal esperado para la concordancia de patrones","expectedDecoratorExpr":"Forma de expresión no compatible con Decorator anterior a Python 3.9","expectedDecoratorName":"Nombre esperado del Decorator","expectedDecoratorNewline":"Nueva línea esperada al final de Decorator","expectedDelExpr":"Expresión esperada después de \\"del\\"","expectedElse":"Se espera \\"else\\"","expectedEquals":"Se esperaba \\"=\\"","expectedExceptionClass":"Clase o objeto de excepción no válido","expectedExceptionObj":"Objeto de excepción esperado, clase de excepción o Ninguno","expectedExpr":"Se esperaba una expresión","expectedFunctionAfterAsync":"Definición de función esperada después de \\"async\\"","expectedFunctionName":"Se esperaba nombre de la función luego de \\"def\\"","expectedIdentifier":"Identificador esperado","expectedImport":"Se espera \\"import\\"","expectedImportAlias":"Símbolo esperado después de \\"como\\"","expectedImportSymbols":"Se esperan uno o más nombres de símbolos tras la importación","expectedIn":"Se esperaba \\"in\\"","expectedInExpr":"Expresión esperada después de \\"in\\"","expectedIndentedBlock":"Bloque con sangría previsto","expectedMemberName":"Nombre de miembro esperado después de \\".\\"","expectedModuleName":"Nombre de módulo esperado","expectedNameAfterAs":"Se esperaba un nombre de símbolo después de \\"as\\"","expectedNamedParameter":"El parámetro de palabra clave debe ir después de \\"*\\".","expectedNewline":"Nueva línea esperada","expectedNewlineOrSemicolon":"Las declaraciones deben ir separadas por nuevas líneas o punto y coma","expectedOpenParen":"Se espera \\"(\\"","expectedParamName":"Nombre esperado del parámetro","expectedPatternExpr":"Expresión del patrón esperado","expectedPatternSubjectExpr":"Expresión de asunto de patrón esperada","expectedPatternValue":"Expresión de valor de patrón esperada de la forma \\"a.b\\"","expectedReturnExpr":"Expresión esperada después de \\"return\\"","expectedSliceIndex":"Expresión de índice o segmento esperada","expectedTypeNotString":"Se esperaba un tipo pero se ha recibido una cadena literal","expectedTypeParameterName":"Nombre de parámetro de tipo esperado","expectedYieldExpr":"Expresión esperada en la instrucción yield","finalClassIsAbstract":"La clase \\"{type}\\" está marcada como final y debe implementar todos los símbolos abstractos","finalContext":"\\"Final\\" no está permitido en este contexto","finalMethodOverride":"El método \\"{name}\\" no puede anular el método final definido en la clase \\" {className}\\"","finalNonMethod":"La función \\"{name}\\" no se puede marcar @final porque no es un método","finalReassigned":"\\"{name}\\" se declara como Final y no se puede reasignar","finalRedeclaration":"\\"{name}\\" se declaró anteriormente como Final","finalRedeclarationBySubclass":"\\"{name}\\" no puede ser redeclarado porque la clase padre \\"{className}\\" lo declara como Final","finalTooManyArgs":"Se esperaba un único argumento de tipo después de \\"Final\\".","finalUnassigned":"\\"{name}\\" se declara Final, pero no se asigna valor","formatStringBrace":"No se permite una llave de cierre única dentro del literal de cadena f; usar llave de cierre doble","formatStringBytes":"Los literales de cadena de formato (f-strings) no pueden ser binarios","formatStringDebuggingIllegal":"El especificador de depuración de cadena F \\"=\\" requiere Python 3.8 o posterior","formatStringEscape":"Secuencia de escape (barra diagonal inversa) no permitida en la parte de expresión de f-string anterior a Python 3.12","formatStringExpectedConversion":"Se esperaba un especificador de conversión después de \\"!\\" en f-string","formatStringIllegal":"Los literales de cadena de formato (f-strings) requieren Python 3.6 o posterior","formatStringInPattern":"Cadena de formato no permitida en el patrón","formatStringNestedFormatSpecifier":"Expresiones anidadas demasiado profundamente dentro del especificador de cadena de formato","formatStringNestedQuote":"Las cadenas anidadas dentro de una cadena f no pueden usar el mismo carácter de comillas que la cadena f anterior a Python 3.12","formatStringUnicode":"Los literales de cadena de formato (cadenas f) no pueden ser unicode","formatStringUnterminated":"Expresión sin terminar en f-string; se esperaba \\"}\\"","functionDecoratorTypeUnknown":"Un decorator de función no tipificado oculta el tipo de función; ignorar el decorator","functionInConditionalExpression":"La expresión condicional hace referencia a una función que siempre se evalúa como Verdadero","functionTypeParametersIllegal":"La sintaxis del parámetro de tipo de función requiere Python 3.12 o posterior","futureImportLocationNotAllowed":"Las importaciones desde __future__ deben estar al principio del fichero","generatorAsyncReturnType":"El tipo de retorno de la función generadora asíncrona debe ser compatible con \\"AsyncGenerator[{yieldType}, Any]\\"","generatorNotParenthesized":"Las expresiones del generador deben ir entre paréntesis si no son el único argumento","generatorSyncReturnType":"El tipo de retorno de la función generadora debe ser compatible con \\"Generator[{yieldType}, Any, Any]\\"","genericBaseClassNotAllowed":"La clase base \\"Generic\\" no se puede usar con la sintaxis de parámetro de tipo","genericClassAssigned":"No se puede asignar un tipo de clase genérico","genericClassDeleted":"No se puede eliminar el tipo de clase genérica","genericInstanceVariableAccess":"El acceso a la variable de instancia genérica a través de la clase es ambiguo","genericNotAllowed":"\\"Generic\\" no es válido en este contexto","genericTypeAliasBoundTypeVar":"Los alias de tipo genérico dentro de una clase no pueden utilizar variables de tipo vinculadas {names}.","genericTypeArgMissing":"\\"Generic\\" requiere al menos un argumento de tipo","genericTypeArgTypeVar":"El argumento de tipo para \\"Generic\\" debe ser una variable de tipo","genericTypeArgUnique":"Los argumentos de tipo para \\"Generic\\" deben ser únicos","globalReassignment":"\\"{name}\\" se asigna antes de la declaración global","globalRedefinition":"\\"{name}\\" ya ha sido declarado global","implicitStringConcat":"No se permite la concatenación implícita de cadenas","importCycleDetected":"Ciclo detectado en la cadena de importación","importDepthExceeded":"La profundidad de la cadena de importación superó {depth}","importResolveFailure":"No se ha podido resolver la importación \\"{importName}\\".","importSourceResolveFailure":"La importación \\"{importName}\\" no se ha podido resolver desde el origen","importSymbolUnknown":"\\"{name}\\" es un símbolo de importación desconocido","incompatibleMethodOverride":"El método \\"{name}\\" sobrescribe la clase \\"{className}\\" de forma incompatible","inconsistentIndent":"La cantidad sin sangría no coincide con la sangría anterior","inconsistentTabs":"Uso incoherente de tabuladores y espacios en la sangría","initMustReturnNone":"El tipo de retorno de \\"__init__\\" debe ser None","initSubclassCallFailed":"Argumentos de palabra clave incorrectos para el método __init_subclass__","initSubclassClsParam":"__init_subclass__ debe tomar un parámetro \\"cls\\"","initVarNotAllowed":"\\"InitVar\\" no se permite en este contexto","instanceMethodSelfParam":"Los métodos de instancia deben tomar un parámetro \\"auto\\"","instanceVarOverridesClassVar":"La variable de instancia \\"{name}\\" invalida la variable de clase del mismo nombre en la clase \\"{className}\\"","instantiateAbstract":"No se puede instanciar la clase abstracta \\"{type}\\"","instantiateProtocol":"No se puede crear una instancia de la clase de protocolo \\"{type}\\"","internalBindError":"Se ha producido un error interno al vincular el archivo \\"{file}\\": {message}","internalParseError":"Se ha producido un error interno al procesar el archivo \\"{file}\\": {message}","internalTypeCheckingError":"Se ha producido un error interno al comprobar el tipo de archivo \\"{file}\\":{message}","invalidIdentifierChar":"Carácter no válido en el identificador","invalidStubStatement":"La declaración no tiene sentido dentro de un archivo de tipo stub","invalidTokenChars":"Carácter \\"{text}\\" no válido en el token","isInstanceInvalidType":"El segundo argumento de \\"isinstance\\" debe ser una clase o tupla de clases","isSubclassInvalidType":"El segundo argumento de \\"issubclass\\" debe ser una clase o tupla de clases","keyValueInSet":"No se permiten pares de clave/valor dentro de un conjunto","keywordArgInTypeArgument":"No se pueden usar argumentos de palabra clave en listas de argumentos de tipo","keywordOnlyAfterArgs":"No se permite el separador de argumentos por palabra clave después del parámetro \\"*\\".","keywordParameterMissing":"Uno o varios parámetros de palabra clave deben seguir el parámetro \\"*\\"","keywordSubscriptIllegal":"No se admiten argumentos de palabra clave dentro de subíndices","lambdaReturnTypePartiallyUnknown":"El tipo de retorno de la lambda \\"{returnType}\\" es parcialmente desconocido.","lambdaReturnTypeUnknown":"Se desconoce el tipo de retorno de la lambda","listAssignmentMismatch":"La expresión con el tipo \\"{type}\\" no puede asignarse a la lista de destino","listInAnnotation":"Expresión de lista no permitida en anotación de tipo","literalEmptyArgs":"Se esperaban uno o varios argumentos de tipo después de \\"Literal\\"","literalNotAllowed":"\\"Literal\\" no se puede usar en este contexto sin un argumento de tipo","literalNotCallable":"El tipo literal no puede instanciarse","literalUnsupportedType":"Los argumentos de tipo para \\"Literal\\" deben ser None, un valor literal (int, bool, str, o bytes), o un valor enum","matchIncompatible":"Las declaraciones de coincidencia requieren Python 3.10 o posterior","matchIsNotExhaustive":"Los casos dentro de la declaración de coincidencia no tratan exhaustivamente todos los valores","maxParseDepthExceeded":"Se ha superado la profundidad máxima de análisis; divida la expresión en subexpresiones más pequeñas.","memberAccess":"No se puede acceder al miembro \\"{name}\\" para el tipo \\" {type} \\"","memberDelete":"No se puede eliminar el miembro \\"{name}\\" para el tipo \\"{type}\\"","memberSet":"No se puede asignar el miembro \\"{name}\\" para el tipo \\"{type}\\"","metaclassConflict":"La metaclase de una clase derivada debe ser una subclase de las metaclases de todas sus clases base","metaclassDuplicate":"Solo se puede proporcionar una metaclase","metaclassIsGeneric":"La metaclase no puede ser genérica","methodNotDefined":"Método \\"{name}\\" no definido","methodNotDefinedOnType":"Método \\"{name}\\" no definido en el tipo \\"{type}\\"","methodOrdering":"No se puede crear una ordenación coherente de los métodos","methodOverridden":"\\"{name}\\" invalida el método del mismo nombre en la clase \\"{className}\\" con el tipo incompatible \\"{type}\\"","methodReturnsNonObject":"El método \\"{name}\\" no devuelve un objeto","missingSuperCall":"El método \\"{methodName}\\" no llama al método del mismo nombre en la clase principal.","moduleAsType":"El módulo no se puede usar como tipo.","moduleNotCallable":"No se puede llamar al módulo","moduleUnknownMember":"\\"{memberName}\\" no es un miembro conocido del módulo \\"{moduleName}\\"","namedExceptAfterCatchAll":"Una cláusula except con nombre no puede aparecer después de la cláusula catch-all except","namedParamAfterParamSpecArgs":"El parámetro de palabra clave \\"{name}\\" no puede aparecer en la firma después del parámetro ParamSpec args","namedTupleEmptyName":"Los nombres de una tupla con nombre no pueden estar vacíos","namedTupleEntryRedeclared":"No se puede invalidar \\"{name}\\" porque la clase primaria \\"{className}\\" es una tupla con nombre","namedTupleFirstArg":"Nombre de clase de tupla como primer argumento","namedTupleMultipleInheritance":"No se admite la herencia múltiple con NamedTuple","namedTupleNameKeyword":"Los nombres de campo no pueden ser una palabra clave","namedTupleNameType":"Tupla de dos entradas esperada que especifica el nombre y el tipo de entrada","namedTupleNameUnique":"Los nombres dentro de una tupla con nombre deben ser únicos","namedTupleNoTypes":"\\"namedtuple\\" no proporciona tipos para las entradas de tupla; utilice en su lugar \\"NamedTuple\\".","namedTupleSecondArg":"Lista de entradas de tupla con nombre esperada como segundo argumento","newClsParam":"__new__ debe tomar un parámetro \\"cls\\"","newTypeAnyOrUnknown":"El segundo argumento de NewType debe ser una clase conocida, no Cualquiera ni Desconocido","newTypeBadName":"El primer argumento de NewType debe ser una cadena literal","newTypeLiteral":"NewType no se puede usar con el tipo Literal","newTypeNameMismatch":"NewType debe asignarse a una variable con el mismo nombre","newTypeNotAClass":"Clase esperada como segundo argumento de NewType","newTypeParamCount":"NewType requiere dos argumentos posicionales","newTypeProtocolClass":"NewType no se puede usar con un tipo estructural (un protocolo o una clase TypedDict)","noOverload":"Ninguna sobrecarga para \\"{name}\\" coincide con los argumentos proporcionados","noReturnContainsReturn":"La función con tipo de retorno declarado \\"NoReturn\\" no puede incluir una sentencia volver","noReturnContainsYield":"La función con tipo de retorno declarado \\"NoReturn\\" no puede incluir una instrucción yield","noReturnReturnsNone":"La función con el tipo de valor devuelto declarado \\"NoReturn\\" no puede devolver \\"None\\"","nonDefaultAfterDefault":"El argumento no predeterminado sigue al argumento predeterminado","nonLocalInModule":"Declaración no local no permitida a nivel de módulo","nonLocalNoBinding":"No se ha encontrado ningún enlace para \\"{name}\\" no local.","nonLocalReassignment":"\\"{name}\\" se asigna antes de la declaración no local","nonLocalRedefinition":"\\"{name}\\" ya fue declarado no local","noneNotCallable":"No se puede llamar al objeto de tipo \\"None\\"","noneNotIterable":"No se puede utilizar un objeto de tipo \\"Ninguno\\" como valor iterable","noneNotSubscriptable":"El objeto de tipo \\"None\\" no se puede suscribir","noneNotUsableWith":"El objeto de tipo \\"None\\" no puede utilizarse con \\"with\\".","noneOperator":"El operador \\"{operator}\\" no es compatible con \\"None\\".","noneUnknownMember":"\\"{name}\\" no es un miembro conocido de \\"None\\"","notRequiredArgCount":"Se esperaba un único argumento de tipo después de \\"NotRequired\\".","notRequiredNotInTypedDict":"\\"NotRequired\\" no está permitido en este contexto","objectNotCallable":"El objeto de tipo \\"{type}\\" no es invocable","obscuredClassDeclaration":"La declaración de clase \\"{name}\\" queda oculta por una declaración del mismo nombre","obscuredFunctionDeclaration":"La declaración de función \\"{name}\\" queda oculta por una declaración del mismo nombre","obscuredMethodDeclaration":"La declaración de método \\"{name}\\" queda oculta por una declaración del mismo nombre","obscuredParameterDeclaration":"La declaración de parámetro \\"{name}\\" queda oculta por una declaración del mismo nombre","obscuredTypeAliasDeclaration":"La declaración de alias de tipo \\"{name}\\" queda oculta por una declaración del mismo nombre","obscuredVariableDeclaration":"La declaración \\"{name}\\" está oculta por una declaración del mismo nombre","operatorLessOrGreaterDeprecated":"El operador \\"<>\\" no es admitido en Python 3; utilice en su lugar \\"!=\\".","optionalExtraArgs":"Se esperaba un argumento de tipo después de \\"Optional\\"","orPatternIrrefutable":"El patrón irrefutable solo se permite como el último subpatrón en un patrón \\"or\\".","orPatternMissingName":"Todos los subpatrones de un patrón \\"o\\" deben tener los mismos nombres","overlappingKeywordArgs":"El diccionario escrito se superpone con el parámetro de palabra clave: {names}","overlappingOverload":"La sobrecarga {obscured} para \\"{name}\\" nunca se utilizará porque sus parámetros se superpone con la sobrecarga {obscuredBy}.","overloadAbstractMismatch":"Todos los métodos sobrecargados deben ser abstractos o no","overloadClassMethodInconsistent":"Las sobrecargas de \\"{name}\\" usan @classmethod de forma incoherente","overloadFinalInconsistencyImpl":"La sobrecarga de \\"{name}\\" está marcada @final pero la implementación no","overloadFinalInconsistencyNoImpl":"La sobrecarga {index} para \\"{name}\\" está marcada @final pero la sobrecarga 1 no lo está.","overloadImplementationMismatch":"La implementación de la sobrecarga no es consistente con la firma de la sobrecarga {index}","overloadReturnTypeMismatch":"La sobrecarga {prevIndex} para \\" {name}\\" se superpone con la sobrecarga {newIndex} y devuelve un tipo incompatible","overloadStaticMethodInconsistent":"Las sobrecargas de \\"{name}\\" usan @staticmethod de forma incoherente","overloadWithoutImplementation":"\\"{name}\\" está marcado como sobrecarga, pero no se proporciona ninguna implementación.","overriddenMethodNotFound":"El método \\"{name}\\" está marcado como invalidación, pero no existe ningún método base con el mismo nombre","overrideDecoratorMissing":"El método \\"{name}\\" no está marcado como invalidación, pero está reemplazando un método de la clase \\"{className}\\"","paramAfterKwargsParam":"El parámetro no puede seguir el parámetro \\"**\\"","paramAlreadyAssigned":"El parámetro \\"{name}\\" ya está asignado","paramAnnotationMissing":"Falta la anotación de tipo para el parámetro \\"{name}\\"","paramAssignmentMismatch":"La expresión de tipo \\"{sourceType}\\" no se puede asignar al parámetro de tipo \\"{paramType}\\"","paramNameMissing":"Ningún parámetro llamado \\"{name}\\"","paramSpecArgsKwargsUsage":"Los miembros \\"args\\" y \\"kwargs\\" de ParamSpec deben aparecer ambos dentro de una firma de función","paramSpecArgsMissing":"Faltan argumentos para ParamSpec \\"{type}\\".","paramSpecArgsUsage":"El miembro \\"args\\" de ParamSpec solo es válido cuando se usa con el parámetro *args.","paramSpecAssignedName":"ParamSpec debe asignarse a una variable llamada \\"{name} \\"","paramSpecContext":"ParamSpec no está permitido en este contexto","paramSpecDefaultNotTuple":"Se esperaban puntos suspensivos, una expresión de tupla o ParamSpec para el valor predeterminado de ParamSpec","paramSpecFirstArg":"Se esperaba el nombre de ParamSpec como primer argumento","paramSpecKwargsUsage":"El miembro \\"kwargs\\" de ParamSpec solo es válido cuando se utiliza con el parámetro **kwargs","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" no tiene significado en este contexto","paramSpecScopedToReturnType":"El ámbito de ParamSpec \\"{name}\\" es un ámbito al que se puede llamar dentro del tipo de valor devuelto y no se puede hacer referencia a él en el cuerpo de la función.","paramSpecUnknownArg":"ParamSpec no admite más de un argumento","paramSpecUnknownMember":"\\"{name}\\" no es un miembro conocido de ParamSpec","paramSpecUnknownParam":"\\"{name}\\" es un parámetro desconocido para ParamSpec","paramTypeCovariant":"La variable de tipo covariante no puede utilizarse en el tipo de parámetro","paramTypePartiallyUnknown":"El tipo de parámetro \\"{paramName}\\" es parcialmente desconocido","paramTypeUnknown":"Se desconoce el tipo del parámetro \\"{paramName}\\".","parenthesizedContextManagerIllegal":"Los paréntesis dentro de la instrucción \\"with\\" requieren Python 3.9 o posterior","patternNeverMatches":"El patrón nunca coincidirá para el tipo de asunto \\"{type}\\"","positionArgAfterNamedArg":"El argumento posicional no puede aparecer después de los argumentos de palabra clave","positionOnlyAfterArgs":"No se permite el separador de parámetros de un solo puesto después del parámetro \\"*\\".","positionOnlyAfterKeywordOnly":"El parámetro \\"/\\" debe aparecer antes del parámetro \\"*\\".","positionOnlyAfterNon":"Parámetro de un solo puesto no permitido después del parámetro que no es de solo posición","positionOnlyFirstParam":"Separador parámetros de solo un puesto no permitido como primer parámetro","positionOnlyIncompatible":"El separador de parámetros de un solo puesto requiere Python 3.8 o posterior","privateImportFromPyTypedModule":"\\"{name}\\" no se exporta desde el módulo \\"{module}\\"","privateUsedOutsideOfClass":"\\"{name}\\" es privado y se utiliza fuera de la clase en la que se declara","privateUsedOutsideOfModule":"\\"{name}\\" es privado y se utiliza fuera del módulo en el que se declara","propertyOverridden":"\\"{name}\\" invalida incorrectamente la propiedad del mismo nombre en la clase \\"{className}\\"","propertyStaticMethod":"Métodos estáticos no permitidos para los valores getter, setter o deleter de propiedades","protectedUsedOutsideOfClass":"\\"{name}\\" está protegido y se usa fuera de la clase en la que se declara","protocolBaseClass":"La clase de protocolo \\"{classType}\\" no se puede derivar de la clase que no es de protocolo \\"{baseType}\\"","protocolBaseClassWithTypeArgs":"No se permiten argumentos de tipo con la clase Protocol cuando se usa la sintaxis de parámetro de tipo","protocolIllegal":"El uso de \\"Protocolo\\" requiere Python 3.7 o posterior.","protocolNotAllowed":"\\"Protocolo\\" no puede utilizarse en este contexto","protocolUnsafeOverlap":"La clase se superpone \\"{name}\\" de forma no segura y podría producir una coincidencia en tiempo de ejecución","protocolVarianceContravariant":"La variable de tipo \\"{variable}\\" usada en el protocolo genérico \\"{class}\\" debe ser contravariante.","protocolVarianceCovariant":"La variable de tipo \\"{variable}\\" usada en el protocolo genérico \\"{class}\\" debe ser covariante","protocolVarianceInvariant":"La variable de tipo \\"{variable}\\" usada en el protocolo genérico \\"{class}\\" debe ser invariable.","pyrightCommentInvalidDiagnosticBoolValue":"La directiva de comentario Pyright debe ir seguida de \\"=\\" y un valor de true o false","pyrightCommentInvalidDiagnosticSeverityValue":"La directiva de comentario Pyright debe ir seguida de \\"=\\" y un valor de verdadero, falso, error, advertencia, información o ninguno.","pyrightCommentMissingDirective":"El comentario de copyright debe ir seguido de una directiva (básica o estricta) o de una regla de diagnóstico","pyrightCommentNotOnOwnLine":"Los comentarios de copyright utilizados para controlar los ajustes a nivel de archivo deben aparecer en su propia línea","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" es una regla de diagnóstico desconocida para el comentario pyright","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" es un valor no válido para el comentario pyright; se espera verdadero, falso, error, advertencia, información o ninguno.","pyrightCommentUnknownDirective":"\\"{directive}\\" es una directiva desconocida para el comentario pyright; se esperaba \\"strict\\" o \\"basic\\".","readOnlyArgCount":"Se esperaba un único argumento de tipo después de \\"ReadOnly\\"","readOnlyNotInTypedDict":"\\"ReadOnly\\" no está permitido en este contexto","recursiveDefinition":"No se pudo determinar el tipo de \\"{name}\\" porque hace referencia a sí mismo.","relativeImportNotAllowed":"Las importaciones relativas no pueden utilizarse con la forma \\"import .a\\"; utilice en su lugar \\"from . import a\\"","requiredArgCount":"Se esperaba un único argumento de tipo después de \\"Required\\"","requiredNotInTypedDict":"\\"Required\\" no está permitido en este contexto","returnInAsyncGenerator":"No se permite la instrucción Return con valor en el generador asincrónico","returnMissing":"La función con el tipo de valor devuelto declarado \\"{returnType}\\" debe devolver un valor en todas las rutas de acceso del código.","returnOutsideFunction":"\\"return\\" solo se puede usar dentro de una función","returnTypeContravariant":"La variable de tipo contravariante no se puede usar en el tipo de valor devuelto","returnTypeMismatch":"La expresión del tipo \\"{exprType}\\" no puede asignarse al tipo de retorno \\"{returnType}\\"","returnTypePartiallyUnknown":"El tipo de retorno, \\"{returnType}\\", es parcialmente desconocido","returnTypeUnknown":"Tipo de retorno desconocido","revealLocalsArgs":"No se esperaba ningún argumento para la llamada \\"reveal_locals\\"","revealLocalsNone":"No hay locales en este ámbito","revealTypeArgs":"Se esperaba un único argumento posicional para la llamada \\"reveal_type\\"","revealTypeExpectedTextArg":"El argumento \\"expected_text\\" de la función \\"reveal_type\\" debe ser un valor literal str.","revealTypeExpectedTextMismatch":"El tipo de texto no coincide; se esperaba \\"{expected}\\" pero se ha recibido \\"{received}\\".","revealTypeExpectedTypeMismatch":"Error de coincidencia de tipos; se esperaba \\"{expected}\\", pero se recibió \\"{received}\\"","selfTypeContext":"\\"Self\\" no es válido en este contexto","selfTypeMetaclass":"\\"Self\\" no se puede usar dentro de una metaclase (una subclase de \\"type\\")","selfTypeWithTypedSelfOrCls":"\\"Auto\\" no puede utilizarse en una función con un parámetro `self` o `cls` que tenga una anotación de tipo distinta de \\"Auto\\".","setterGetterTypeMismatch":"El tipo de valor setter de propiedad no se puede asignar al tipo devuelto por el valor setter","singleOverload":"\\"{name}\\" está marcado como sobrecarga, pero faltan sobrecargas adicionales","slotsAttributeError":"\\"{name}\\" no se especificó en __slots__","slotsClassVarConflict":"\\"{name}\\" entra en conflicto con la variable de instancia declarada en __slots__","starPatternInAsPattern":"El patrón estrella no puede utilizarse con el objetivo \\"as\\"","starPatternInOrPattern":"El patrón de estrella no puede unirse a otros patrones","starStarWildcardNotAllowed":"** no puede utilizarse con el comodín \\"_\\".","staticClsSelfParam":"Los métodos estáticos no deben tomar un parámetro \\"auto\\" o \\"cls\\".","stdlibModuleOverridden":"\\"{path}\\" está reemplazando el módulo stdlib \\"{name}\\"","stringNonAsciiBytes":"Carácter no ASCII no permitido en el literal de cadena de bytes","stringNotSubscriptable":"La expresión de cadena no puede ir entre comillas en la anotación de tipo; encierre toda la anotación entre comillas.","stringUnsupportedEscape":"Secuencia de escape no admitida en el literal de cadena","stringUnterminated":"La cadena literal no está terminada","stubFileMissing":"Archivo Stub no encontrado para \\"{importName}\\"","stubUsesGetAttr":"El archivo stub de tipo está incompleto; \\"__getattr__\\" oculta errores de tipo para el módulo","sublistParamsIncompatible":"Los parámetros de sublista no están soportados en Python 3.x","superCallArgCount":"No se esperaban más de dos argumentos para la llamada \\"super\\"","superCallFirstArg":"Se esperaba el tipo de clase como primer argumento de la llamada a \\"super\\" pero se recibió \\"{type}\\"","superCallSecondArg":"El segundo argumento de la llamada a \\"super\\" debe ser un objeto o clase que derive de \\"{type}\\"","superCallZeroArgForm":"La forma sin argumentos de la llamada \\"super\\" sólo es válida dentro de un método","superCallZeroArgFormStaticMethod":"La forma sin argumentos de la llamada \\"super\\" no es válida en un método estático","symbolIsPossiblyUnbound":"\\"{name}\\" está posiblemente desvinculado","symbolIsUnbound":"\\"{name}\\" está sin consolidar","symbolIsUndefined":"\\"{name}\\" no está definido","symbolOverridden":"\\"{name}\\" anula el símbolo del mismo nombre en la clase \\"{className}\\"","ternaryNotAllowed":"No se permite la expresión ternaria en la anotación de tipo","totalOrderingMissingMethod":"La clase debe definir uno de \\"__lt__\\", \\"__le__\\", \\"__gt__\\", o \\"__ge__\\" para utilizar total_ordering","trailingCommaInFromImport":"No se permite la coma final sin paréntesis alrededor","tryWithoutExcept":"La instrucción Try debe tener al menos una cláusula except o finally","tupleAssignmentMismatch":"La expresión con el tipo \\"{type}\\" no se puede asignar a la tupla de destino","tupleInAnnotation":"No se permite la expresión de tupla en la anotación de tipo","tupleIndexOutOfRange":"El índice {index} está fuera de rango para el tipo {type}.","typeAliasIllegalExpressionForm":"Forma de expresión no válida para la definición de alias de tipo","typeAliasIsRecursiveDirect":"El alias de tipo \\"{name}\\" no puede usarse a sí mismo en su definición","typeAliasNotInModuleOrClass":"Un TypeAlias solo puede definirse en el ámbito de un módulo o de una clase","typeAliasRedeclared":"\\"{name}\\" se declara como TypeAlias y solo puede asignarse una vez","typeAliasStatementBadScope":"Una instrucción de tipo solo se puede usar en el ámbito de un módulo o de una clase","typeAliasStatementIllegal":"La sentencia Type alias requiere Python 3.12 o posterior","typeAliasTypeBaseClass":"Un alias de tipo definido en una instrucción \\"type\\" no se puede usar como clase base","typeAliasTypeMustBeAssigned":"TypeAliasType debe asignarse a una variable con el mismo nombre que el alias de tipo","typeAliasTypeNameArg":"El primer argumento de TypeAliasType debe ser un literal de cadena que represente el nombre del alias de tipo","typeAliasTypeNameMismatch":"El nombre del alias de tipo debe coincidir con el nombre de la variable a la que se asigna","typeAliasTypeParamInvalid":"La lista de parámetros de tipo debe ser una tupla que contenga solo TypeVar, TypeVarTuple o ParamSpec.","typeAnnotationCall":"No se permite la expresión de llamada en la expresión de tipo","typeAnnotationVariable":"Variable no permitida en la expresión de tipo","typeAnnotationWithCallable":"El argumento de tipo para \\"type\\" debe ser una clase; no se admiten invocables","typeArgListExpected":"ParamSpec esperado, elipsis o lista de tipos","typeArgListNotAllowed":"Expresión de lista no permitida para este argumento de tipo","typeArgsExpectingNone":"No se esperaban argumentos de tipo para la clase \\"{name}\\"","typeArgsMismatchOne":"Se esperaba un argumento de tipo pero ha recibido {received}","typeArgsMissingForAlias":"Argumentos de tipo esperados para el alias de tipo genérico \\"{name}\\"","typeArgsMissingForClass":"Se esperaban argumentos de tipo para la clase genérica \\"{name}\\"","typeArgsTooFew":"Se han proporcionado muy pocos argumentos de tipo para \\"{name}\\"; se esperaba {expected} pero se ha recibido {received}.","typeArgsTooMany":"Se proporcionaron demasiados argumentos de tipo para \\"{name}\\"; se esperaba {expected}, pero se recibieron {received}","typeAssignmentMismatch":"La expresión del tipo \\"{sourceType}\\" no puede asignarse al tipo declarado \\"{destType}\\"","typeAssignmentMismatchWildcard":"El símbolo de importación \\"{name}\\" tiene el tipo \\"{sourceType}\\", que no se puede asignar al tipo declarado \\"{destType}\\"","typeCallNotAllowed":"la llamada a type() no debe utilizarse en la anotación de tipo","typeCheckOnly":"\\"{name}\\" está marcado como @type_check_only y solo se puede usar en anotaciones de tipo","typeCommentDeprecated":"El uso de comentarios de tipo está obsoleto; utilice en su lugar anotaciones de tipo.","typeExpectedClass":"Se esperaba una expresión de tipo pero se ha recibido \\"{type}\\"","typeGuardArgCount":"Se esperaba un único argumento de tipo después de \\"TypeGuard\\" o \\"TypeIs\\"","typeGuardParamCount":"Las funciones y métodos de protección de tipo definidos por el usuario deben tener al menos un parámetro de entrada","typeIsReturnType":"El tipo de valor devuelto de TypeIs (\\"{returnType}\\") no es coherente con el tipo de parámetro de valor (\\"{type}\\")","typeNotAwaitable":"\\"{type}\\" no se puede esperar","typeNotIntantiable":"\\"{type}\\" no puede crear instancias","typeNotIterable":"\\"{type}\\" no es iterable","typeNotSpecializable":"No se pudo especializar el tipo \\"{type}\\"","typeNotSubscriptable":"Objeto de tipo \\"{type}\\" no es subscriptible","typeNotSupportBinaryOperator":"El operador \\"{operator}\\" no se admite para los tipos \\"{leftType}\\" y \\"{rightType}\\"","typeNotSupportBinaryOperatorBidirectional":"No se admite el operador \\"{operator}\\" para los tipos \\"{leftType}\\" y \\"{rightType}\\" cuando el tipo esperado es \\"{expectedType}\\"","typeNotSupportUnaryOperator":"El operador \\"{operator}\\" no se admite para el tipo \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"Operador \\"{operator}\\" no admitido para el tipo \\"{type}\\" cuando el tipo esperado es \\"{expectedType}\\"","typeNotUsableWith":"El objeto de tipo \\"{type}\\" no puede utilizarse con \\"con\\" porque no implementa {method}.","typeParameterBoundNotAllowed":"No se pueden usar límites o restricciones con un parámetro de tipo variádico o ParamSpec","typeParameterConstraintTuple":"La restricción del parámetro de tipo debe ser una tupla de dos o más tipos","typeParameterExistingTypeParameter":"El parámetro de tipo \\"{name}\\" ya está en uso","typeParameterNotDeclared":"El parámetro de tipo \\"{name}\\" no está incluido en la lista de parámetros de tipo para \\"{container}\\"","typeParametersMissing":"Debe especificarse al menos un parámetro de tipo","typePartiallyUnknown":"El tipo de \\"{name}\\" es parcialmente desconocido","typeUnknown":"El tipo de \\"{name} \\" es desconocido","typeVarAssignedName":"TypeVar debe asignarse a una variable llamada \\"{name}\\"","typeVarAssignmentMismatch":"No se puede asignar el tipo \\"{type}\\" a la variable de tipo \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar no puede estar ligado y restringido a la vez","typeVarBoundGeneric":"El tipo vinculado TypeVar no puede ser genérico","typeVarConstraintGeneric":"El tipo de restricción TypeVar no puede ser genérico","typeVarDefaultBoundMismatch":"El tipo predeterminado TypeVar debe ser un subtipo del tipo enlazado.","typeVarDefaultConstraintMismatch":"El tipo predeterminado TypeVar debe ser uno de los tipos restringidos.","typeVarDefaultIllegal":"Los tipos predeterminados de variable de tipo requieren Python 3.13 o posterior","typeVarDefaultInvalidTypeVar":"El parámetro de tipo \\"{name}\\" tiene un tipo por defecto que hace referencia a una o más variables de tipo que están fuera de ámbito.","typeVarFirstArg":"Nombre esperado de TypeVar como primer argumento","typeVarNoMember":"TypeVar \\"{type}\\" no tiene miembro \\"{name}\\"","typeVarNotSubscriptable":"TypeVar \\"{type}\\" no es subscribible","typeVarNotUsedByOuterScope":"La variable de tipo \\"{name}\\" no tiene ningún significado en este contexto","typeVarPossiblyUnsolvable":"La variable de tipo \\"{name}\\" puede quedar sin resolver si el autor de la llamada no proporciona ningún argumento para el parámetro \\"{param}\\"","typeVarScopedToReturnType":"La variable de tipo \\"{name}\\" tiene como ámbito una llamada dentro del tipo de valor devuelto y no se puede hacer referencia a ella en el cuerpo de la función.","typeVarSingleConstraint":"TypeVar debe tener al menos dos tipos restringidos","typeVarTupleConstraints":"TypeVarTuple no puede tener restricciones de valor","typeVarTupleContext":"TypeVarTuple no está permitido en este contexto","typeVarTupleDefaultNotUnpacked":"El tipo predeterminado TypeVarTuple debe ser una tupla desempaquetada o TypeVarTuple","typeVarTupleMustBeUnpacked":"Se requiere el operador Unpack para el valor TypeVarTuple.","typeVarTupleUnknownParam":"\\"{name}\\" es un parámetro desconocido para TypeVarTuple","typeVarUnknownParam":"\\"{name}\\" es un parámetro desconocido para TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" ya está en uso por un ámbito externo","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" solo aparece una vez en la firma de la función genérica","typeVarVariance":"TypeVar no puede ser covariante y contravariante","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" tiene un valor predeterminado y no puede seguir a TypeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" no puede aparecer después de \\"{other}\\" en la lista de parámetros de tipo porque no tiene ningún tipo predeterminado","typeVarsNotInGenericOrProtocol":"Generic[] o Protocol[] deben incluir todas las variables de tipo","typedDictAccess":"No se ha podido acceder al elemento en TypedDict","typedDictAssignedName":"TypedDict debe asignarse a una variable denominada \\"{name}\\"","typedDictBadVar":"Las clases TypedDict solo pueden contener anotaciones de tipo","typedDictBaseClass":"Todas las clases base de las clases TypedDict deben ser también clases TypedDict","typedDictBoolParam":"Se esperaba que el parámetro \\"{name}\\" tuviera un valor de Verdadero o Falso.","typedDictClosedExtras":"La clase base \\"{name}\\" es un TypedDict cerrado; los elementos adicionales deben ser de tipo \\"{type}\\"","typedDictClosedNoExtras":"La clase base \\"{name}\\" es un TypedDict cerrado; no se permiten elementos adicionales","typedDictDelete":"No se puede eliminar un elemento en TypedDict","typedDictEmptyName":"Los nombres de un TypedDict no pueden estar vacíos","typedDictEntryName":"Cadena literal esperada para el nombre de la entrada del diccionario","typedDictEntryUnique":"Los nombres dentro de un diccionario deben ser únicos","typedDictExtraArgs":"No se admiten argumentos TypedDict adicionales","typedDictFieldNotRequiredRedefinition":"El elemento TypedDict \\"{name}\\" no se puede redefinir como NotRequired","typedDictFieldReadOnlyRedefinition":"El elemento TypedDict \\"{name}\\" no se puede redefinir como ReadOnly","typedDictFieldRequiredRedefinition":"El elemento TypedDict \\"{name}\\" no se puede redefinir como Requerido","typedDictFirstArg":"Nombre de clase TypedDict esperado como primer argumento","typedDictInitsubclassParameter":"TypedDict no admite __init_subclass__ parámetro \\"{name}\\"","typedDictNotAllowed":"\\"TypedDict\\" no puede utilizarse en este contexto","typedDictSecondArgDict":"Parámetro dict o palabra clave esperado como segundo parámetro","typedDictSecondArgDictEntry":"Entrada de diccionario simple esperada","typedDictSet":"No se pudo asignar el elemento en TypedDict","unaccessedClass":"No se accede a la clase \\"{name}\\"","unaccessedFunction":"No se accede a la función \\"{name}","unaccessedImport":"No se accede a la importación \\"{name}","unaccessedSymbol":"No se accede a \\"{name}\\"","unaccessedVariable":"No se accede a la variable \\"{name} \\".","unannotatedFunctionSkipped":"Se omite el análisis de la función \\"{name}\\" porque no está anotada","unaryOperationNotAllowed":"Operador unario no permitido en la anotación de tipo","unexpectedAsyncToken":"Se esperaba que \\"def\\", \\"with\\" o \\"for\\" siguieran a \\"async\\".","unexpectedExprToken":"Token inesperado al final de la expresión","unexpectedIndent":"sangSangría inesperadaría inesperada","unexpectedUnindent":"No se espera sangría","unhashableDictKey":"La clave del diccionario debe ser hash","unhashableSetEntry":"La entrada del conjunto debe ser hashable","uninitializedAbstractVariables":"Las variables definidas en la clase base abstracta no se inicializan en la clase final \\"{classType}\\"","uninitializedInstanceVariable":"La variable de instancia \\"{name}\\" no está inicializada en el cuerpo de la clase o en el método __init__.","unionForwardReferenceNotAllowed":"Union syntax cannot be used with string operand; use quotes around entire expression","unionSyntaxIllegal":"La sintaxis alternativa para las uniones requiere Python 3.10 o posterior.","unionTypeArgCount":"La unión requiere dos o más argumentos de tipo","unionUnpackedTuple":"La unión no puede incluir una tupla desempaquetada","unionUnpackedTypeVarTuple":"La unión no puede incluir un TypeVarTuple desempaquetado","unnecessaryCast":"Llamada \\"cast\\" innecesaria; el tipo ya es \\"{type}\\"","unnecessaryIsInstanceAlways":"Llamada isinstance innecesaria; \\"{testType}\\" es siempre una instancia de \\"{classType}\\"","unnecessaryIsSubclassAlways":"Llamada de issubclass innecesaria; \\"{testType}\\" siempre es una subclase de \\"{classType}\\"","unnecessaryPyrightIgnore":"Comentario \\"# pyright: ignore\\" innecesario","unnecessaryPyrightIgnoreRule":"Regla innecesaria \\"# pyright: ignore\\": \\"{name}\\"","unnecessaryTypeIgnore":"Comentario \\"# type: ignore\\" innecesario","unpackArgCount":"Se esperaba un único argumento de tipo después de \\"Desempaquetar\\"","unpackExpectedTypeVarTuple":"Se esperaba TypeVarTuple o tupla como argumento de tipo para desempaquetar","unpackExpectedTypedDict":"Se esperaba un argumento de tipo TypedDict para Unpack","unpackIllegalInComprehension":"Operación de desempaquetado no permitida en la comprensión","unpackInAnnotation":"No se permite el operador desempaquetado en la anotación de tipo","unpackInDict":"Operación de desempaquetado no permitida en diccionarios","unpackInSet":"No se permite el operador Unpack dentro de un conjunto","unpackNotAllowed":"El desempaquetado no está permitido en este contexto","unpackOperatorNotAllowed":"La operación de desempaquetado no está permitida en este contexto","unpackTuplesIllegal":"Operación de desempaquetado no permitida en tuplas anteriores a Python 3.8","unpackedArgInTypeArgument":"Los argumentos sin empaquetar no pueden utilizarse en listas de argumentos de tipo","unpackedArgWithVariadicParam":"No se puede usar un argumento desempaquetado para el parámetro TypeVarTuple","unpackedDictArgumentNotMapping":"La expresión del argumento después de ** debe ser un mapeo con un tipo de clave \\"str\\".","unpackedDictSubscriptIllegal":"El operador de desempaquetado del diccionario en el subíndice no está permitido","unpackedSubscriptIllegal":"El operador de desempaquetado en el subíndice requiere Python 3.11 o posterior.","unpackedTypeVarTupleExpected":"Se espera un TypeVarTuple desempaquetado; use Unpack[{name1}] o *{name2}","unpackedTypedDictArgument":"No se puede emparejar el argumento TypedDict desempaquetado con los parámetros","unreachableCode":"El código es inalcanzable","unreachableExcept":"La cláusula Excepto es inalcanzable porque la excepción ya está administrada","unsupportedDunderAllOperation":"No se admite la operación en \\"__all__\\", por lo que la lista de símbolos exportada puede ser incorrecta.","unusedCallResult":"El resultado de la expresión de llamada es de tipo \\"{type}\\" y no se usa; asignar a la variable \\"_\\" si esto es intencionado","unusedCoroutine":"El resultado de la llamada a una función asíncrona no se utiliza; utilice \\"await\\" o asigne el resultado a una variable.","unusedExpression":"El valor de expresión no se usa","varAnnotationIllegal":"Las anotaciones de tipo para variables requieren Python 3.6 o posterior; utilice el comentario de tipo para la compatibilidad con versiones anteriores.","variableFinalOverride":"La variable \\"{name}\\" está marcada como Final y anula la variable no Final del mismo nombre en la clase \\"{className}\\".","variadicTypeArgsTooMany":"La lista de argumentos de tipo puede tener como máximo una TypeVarTuple o tupla desempaquetada","variadicTypeParamTooManyAlias":"Los alias de tipo pueden tener como máximo un parámetro de tipo TypeVarTuple, pero reciben varios ({names})","variadicTypeParamTooManyClass":"La clase genérica puede tener como máximo un parámetro de tipo TypeVarTuple pero recibió múltiples ({names})","walrusIllegal":"El operador \\":=\\" requiere Python 3.8 o posterior","walrusNotAllowed":"El operador \\":=\\" no está permitido en este contexto sin paréntesis alrededor","wildcardInFunction":"No se permite la importación de comodines dentro de una clase o función","wildcardLibraryImport":"No se permite la importación de caracteres comodín desde una biblioteca","wildcardPatternTypePartiallyUnknown":"El tipo capturado por el patrón comodín es parcialmente desconocido","wildcardPatternTypeUnknown":"Se desconoce el tipo capturado por el patrón de caracteres comodín","yieldFromIllegal":"El uso de \\"yield\\" requiere Python 3.3 o posterior.","yieldFromOutsideAsync":"\\"yield from\\" no permitido en una función asincrónica","yieldOutsideFunction":"\\"yield\\" no se permite fuera de una función o lambda","yieldWithinListCompr":"\\"yield\\" no está permitido dentro de una comprensión de lista","zeroCaseStatementsFound":"La instrucción Match debe incluir al menos una instrucción case","zeroLengthTupleNotAllowed":"La tupla de longitud cero no está permitida en este contexto"},"DiagnosticAddendum":{"annotatedNotAllowed":"El formulario especial \\"Anotado\\" no se puede usar con comprobaciones de instancia y clase","argParam":"El argumento corresponde al parámetro \\"{paramName}\\"","argParamFunction":"El argumento corresponde al parámetro \\"{paramName}\\" en la función \\"{functionName}\\"","argsParamMissing":"El parámetro \\"*{paramName}\\" no tiene ningún parámetro correspondiente","argsPositionOnly":"Error de coincidencia del parámetro de solo posición; se esperaba {expected}, pero se recibieron {received}","argumentType":"El tipo de argumento es \\"{type}\\"","argumentTypes":"Tipos de argumento: ({types})","assignToNone":"El tipo no puede asignarse al tipo \\"None\\"","asyncHelp":"¿Quería decir \\"async with\\"?","baseClassIncompatible":"La clase base \\"{baseClass}\\" no es compatible con el tipo \\"{type}\\"","baseClassIncompatibleSubclass":"La clase base \\"{baseClass}\\" deriva de \\"{subclass}\\", que no es compatible con el tipo \\"{type}\\"","baseClassOverriddenType":"La clase base \\"{baseClass}\\" proporciona el tipo \\"{type}\\", que se sobrescribe","baseClassOverridesType":"Invalidaciones de clase base \\"{baseClass}\\" con el tipo \\"{type}\\"","bytesTypePromotions":"Establezca disableBytesTypePromotions en falso para activar el comportamiento de promoción de tipos para \\"bytearray\\" y \\"memoryview\\".","conditionalRequiresBool":"El método __bool__ para el tipo \\"{operandType}\\" devuelve el tipo \\"{boolReturnType}\\" en lugar de \\"bool\\"","dataClassFieldLocation":"en declaración de campo","dataClassFrozen":"\\"{name}\\" está congelado","dataProtocolUnsupported":"\\"{name}\\" es un protocolo de datos","descriptorAccessBindingFailed":"No se pudo enlazar el método \\"{name}\\" para la clase de descriptor \\"{className}\\"","descriptorAccessCallFailed":"No se pudo llamar al método \\"{name}\\" para la clase de descriptor \\"{className}\\"","finalMethod":"Método final","functionParamDefaultMissing":"Falta el argumento predeterminado en el parámetro \\"{name}\\"","functionParamName":"Nombre de parámetro no coincidente: \\"{destName}\\" frente a \\"{srcName}\\"","functionParamPositionOnly":"Error de coincidencia del parámetro de solo posición; el parámetro \\"{name}\\" no es de solo posición","functionReturnTypeMismatch":"El tipo de valor devuelto de la función \\"{sourceType}\\" no es compatible con el tipo \\"{destType}\\"","functionTooFewParams":"La función acepta muy pocos parámetros posicionales; esperado {expected} pero recibido {received}","functionTooManyParams":"La función acepta demasiados parámetros posicionales; esperado {expected} pero recibido {received}","genericClassNotAllowed":"Tipo genérico con argumentos de tipo no permitidos para comprobaciones de instancia o clase","incompatibleDeleter":"El método de eliminación de propiedades no es compatible","incompatibleGetter":"El método captador de propiedad no es compatible","incompatibleSetter":"El método setter de la propiedad no es compatible","initMethodLocation":"El método __init__ se define en la clase \\"{type}\\"","initMethodSignature":"La firma de __init__ es \\"{type}\\"","initSubclassLocation":"El método __init_subclass__ se define en la clase \\"{name}\\"","invariantSuggestionDict":"Considere cambiar de \\"predicción\\" a \\" Asignación\\" que es covariante en el tipo de valor","invariantSuggestionList":"Considere la posibilidad de cambiar de \\"lista\\" a \\"Secuencia\\" que es covariante","invariantSuggestionSet":"Considere la posibilidad de cambiar de \\"conjunto\\" a \\"Contenedor\\" que es covariante","keyNotRequired":"\\"{name}\\" no es una clave necesaria en \\"{type}\\", por lo que el acceso puede dar lugar a una excepción en tiempo de ejecución","keyReadOnly":"\\"{name}\\" es una clave de solo lectura en \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" es una clave necesaria y no se puede eliminar","keyUndefined":"\\"{name}\\" no es una clave definida en \\"{type}\\"","kwargsParamMissing":"El parámetro \\"**{paramName}\\" no tiene ningún parámetro correspondiente.","listAssignmentMismatch":"El tipo \\"{type}\\" es incompatible con la lista de objetivos","literalAssignmentMismatch":"\\"{sourceType}\\" no puede asignarse al tipo \\"{destType}\\"","matchIsNotExhaustiveHint":"Si no se pretende un tratamiento exhaustivo, agregue \\"case _: pass\\"","matchIsNotExhaustiveType":"Tipo no manejado: \\"{type}\\"","memberAssignment":"La expresión de tipo \\"{type}\\" no se puede asignar al miembro \\"{name}\\" de la clase \\"{classType}\\"","memberIsAbstract":"\\"{type}. {name}\\" no está implementado","memberIsAbstractMore":"y {count} más","memberIsClassVarInProtocol":"\\"{name}\\" se define como ClassVar en el protocolo","memberIsFinalInProtocol":"\\"{name}\\" está marcado como Final en el protocolo","memberIsInitVar":"El miembro \\"{name}\\" es un campo solo de inicialización","memberIsInvariant":"\\"{name}\\" es invariable porque es mutable","memberIsNotClassVarInClass":"\\"{name}\\" debe definirse como ClassVar para que sea compatible con el protocolo","memberIsNotClassVarInProtocol":"\\"{name}\\" no está definido como ClassVar en el protocolo","memberIsNotFinalInProtocol":"\\"{name}\\" no está marcado como Final en el protocolo","memberIsWritableInProtocol":"\\"{name}\\" se puede escribir en el protocolo","memberSetClassVar":"El miembro \\"{name}\\" no se puede asignar a través de una instancia de clase porque es un ClassVar.","memberTypeMismatch":"\\"{name}\\" es un tipo incompatible","memberUnknown":"El miembro \\"{name}\\" es desconocido","metaclassConflict":"La metaclase \\"{metaclass1}\\" entra en conflicto con \\"{metaclass2}\\"","missingDeleter":"Falta el método de eliminación de propiedades","missingGetter":"Falta el método Getter de la propiedad","missingSetter":"Falta el método establecedor de propiedades","namedParamMissingInDest":"Falta el parámetro de palabra clave \\"{name}\\" en el destino","namedParamMissingInSource":"Falta el parámetro de palabra clave \\"{name}\\" en el origen","namedParamTypeMismatch":"El parámetro de palabra clave \\"{name}\\" del tipo \\"{sourceType}\\" no puede asignarse al tipo \\"{destType}\\"","namedTupleNotAllowed":"No se puede usar NamedTuple para comprobaciones de instancia o clase","newMethodLocation":"El método __new__ está definido en la clase \\"{type}\\"","newMethodSignature":"La firma de __new__ es \\"{type}\\"","newTypeClassNotAllowed":"La clase creada con NewType no se puede usar con comprobaciones de instancia y clase","noOverloadAssignable":"Ninguna función sobrecargada coincide con el tipo \\"{type}\\"","noneNotAllowed":"No se puede usar ninguno para comprobaciones de instancia o clase","orPatternMissingName":"Nombres que faltan: {name}","overloadIndex":"La sobrecarga {index} es la coincidencia más cercana","overloadNotAssignable":"Una o más sobrecargas de \\"{name}\\" no es asignable","overloadSignature":"Aquí se define la firma de la sobrecarga","overriddenMethod":"Método reemplazado","overriddenSymbol":"Símbolo anulado","overrideInvariantMismatch":"El tipo de invalidación “{overrideType}” no es el mismo que el tipo básico “{baseType}”","overrideIsInvariant":"La variable es mutable, por lo que su tipo es invariable","overrideNoOverloadMatches":"Ninguna firma de sobrecarga en anulación es compatible con el método base","overrideNotClassMethod":"El método base se declara como Método de clase pero el Reemplazar no","overrideNotInstanceMethod":"El método base se declara como método de instancia, pero la invalidación no","overrideNotStaticMethod":"El método base se declara como staticmethod pero el reemplazo no","overrideOverloadNoMatch":"La invalidación no controla todas las sobrecargas del método base","overrideOverloadOrder":"Las sobrecargas para el método de anulación deben estar en el mismo orden que el método base","overrideParamKeywordNoDefault":"El parámetro de palabra clave \\"{name}\\" no coincide: el parámetro base tiene el valor de argumento predeterminado, el parámetro de invalidación no","overrideParamKeywordType":"El parámetro de palabra clave \\"{name}\\" no coincide: el parámetro base es de tipo \\"{baseType}\\", el parámetro de invalidación es de tipo \\"{overrideType}\\"","overrideParamName":"El nombre del parámetro {index} no coincide: el parámetro base se denomina \\"{baseName}\\", el parámetro de invalidación se denomina \\"{overrideName}\\"","overrideParamNameExtra":"Falta el parámetro \\"{name}\\" en la base","overrideParamNameMissing":"Falta el parámetro \\"{name}\\" en la invalidación","overrideParamNamePositionOnly":"El parámetro {index} no coincide: el parámetro base \\"{baseName}\\" es un parámetro de palabra clave, el parámetro de invalidación es de solo posición","overrideParamNoDefault":"El parámetro {index} no coincide: el parámetro base tiene un valor de argumento predeterminado, el parámetro de invalidación no","overrideParamType":"El parámetro {index} no coincide: el parámetro base es de tipo \\"{baseType}\\", el parámetro de invalidación es de tipo \\"{overrideType}\\"","overridePositionalParamCount":"El recuento de parámetros posicionales no coincide; el método base tiene {baseCount}, pero la invalidación tiene {overrideCount}","overrideReturnType":"Error de tipo de retorno: el método base devuelve el tipo \\"{baseType}\\", el reemplazo devuelve el tipo \\"{overrideType}\\".","overrideType":"La clase base define el tipo como \\"{type}\\"","paramAssignment":"Parámetro {index}: el tipo \\"{sourceType}\\" no puede asignarse al tipo \\"{destType}\\"","paramSpecMissingInOverride":"Faltan parámetros ParamSpec en el método de invalidación","paramType":"El tipo de parámetro es \\"{paramType}\\"","privateImportFromPyTypedSource":"Importar desde \\"{module}\\" en su lugar","propertyAccessFromProtocolClass":"No se puede tener acceso a una propiedad definida dentro de una clase de protocolo como variable de clase","propertyMethodIncompatible":"El método de propiedad \\"{name}\\" no es compatible","propertyMethodMissing":"Falta el método de propiedad \\"{name}\\" en la invalidación","propertyMissingDeleter":"La propiedad \\"{name}\\" no tiene un supresor definido","propertyMissingSetter":"La propiedad \\"{name}\\" no tiene el valor setter definido","protocolIncompatible":"\\"{sourceType}\\" no es compatible con el protocolo \\"{destType}\\"","protocolMemberMissing":"\\"{name}\\" no está presente.","protocolRequiresRuntimeCheckable":"La clase de protocolo debe ser @runtime_checkable para usarse con comprobaciones de instancia y clase","protocolSourceIsNotConcrete":"\\"{sourceType}\\" no es un tipo de clase concreto y no se puede asignar al tipo \\"{destType}\\"","protocolUnsafeOverlap":"Los atributos de \\"{name}\\" tienen los mismos nombres que el protocolo","pyrightCommentIgnoreTip":"Utilice \\"# pyright: ignore[<diagnostic rules>] para suprimir el diagnóstico de una sola línea","readOnlyAttribute":"El atributo \\"{name}\\" es de solo lectura","seeClassDeclaration":"Ver declaración de clase","seeDeclaration":"Ver declaración","seeFunctionDeclaration":"Ver declaración de función","seeMethodDeclaration":"Consulte la declaración del métodoa","seeParameterDeclaration":"Declaración de parámetro","seeTypeAliasDeclaration":"Véase la declaración de alias de tipo","seeVariableDeclaration":"declaración de variable out","tupleAssignmentMismatch":"El tipo \\"{type}\\" no es compatible con la tupla de destino","tupleEntryTypeMismatch":"La entrada {entry} de la tupla es de tipo incorrecto","tupleSizeIndeterminateSrc":"El tamaño de la tupla no coincide; se esperaba {expected} pero se recibió uno indeterminado","tupleSizeIndeterminateSrcDest":"El tamaño de la tupla no coincide; se esperaba {expected} o más, pero se recibió uno indeterminado","tupleSizeMismatch":"El tamaño de la tupla no coincide; se esperaba {expected} pero se recibió {received}","tupleSizeMismatchIndeterminateDest":"El tamaño de la tupla no coincide; se esperaba {expected} o más, pero se recibió {received}","typeAliasInstanceCheck":"El alias de tipo creado con la instrucción \\"type\\" no se puede usar con comprobaciones de instancia y clase","typeAssignmentMismatch":"El tipo \\"{sourceType}\\" no puede asignarse al tipo \\"{destType}\\"","typeBound":"El tipo \\"{sourceType}\\" es incompatible con el tipo \\"{destType}\\" vinculado para la variable de tipo \\"{name}\\"","typeConstrainedTypeVar":"El tipo \\"{type}\\" no es compatible con la variable de tipo restringido \\"{name}\\"","typeIncompatible":"\\"{sourceType}\\" no es compatible con \\"{destType}\\"","typeNotClass":"\\"{type}\\" no es una clase","typeNotStringLiteral":"\\"{type}\\" no es un literal de cadena","typeOfSymbol":"El tipo de \\"{name}\\" es \\"{type}\\"","typeParamSpec":"El tipo \\"{type}\\" no es compatible con ParamSpec \\"{name}\\"","typeUnsupported":"El tipo \\"{type}\\" no es compatible","typeVarDefaultOutOfScope":"La variable de tipo \\"{name} \\" no está en el ámbito de aplicación","typeVarIsContravariant":"El parámetro de tipo \\"{name}\\" es contravariante, pero \\"{sourceType}\\" no es un supertipo de \\"{destType}\\"","typeVarIsCovariant":"El parámetro de tipo \\"{name}\\" es covariante, pero \\"{sourceType}\\" no es un subtipo de \\"{destType}\\"","typeVarIsInvariant":"El parámetro de tipo \\"{name}\\" es invariable, pero \\"{sourceType}\\" no es el mismo que \\"{destType}\\"","typeVarNotAllowed":"TypeVar no se permite para comprobaciones de instancia o clase","typeVarTupleRequiresKnownLength":"TypeVarTuple no se puede enlazar a una tupla de longitud desconocida","typeVarUnnecessarySuggestion":"Usar {type} en su lugar","typeVarUnsolvableRemedy":"Proporciona una sobrecarga que especifica el tipo de retorno cuando no se proporciona el argumento","typeVarsMissing":"Faltan variables de tipo: {names}","typedDictBaseClass":"La clase “{type}” no es un TypeDict","typedDictClassNotAllowed":"No se permite la clase TypedDict para comprobaciones de instancia o clase","typedDictClosedExtraNotAllowed":"No se puede agregar el elemento \\"{name}\\"","typedDictClosedExtraTypeMismatch":"No se puede agregar el elemento \\"{name}\\" con el tipo \\"{type}\\"","typedDictClosedFieldNotRequired":"No se puede agregar el elemento \\"{name}\\" porque debe ser NotRequired.","typedDictExtraFieldNotAllowed":"\\"{name}\\" no está presente en \\"{type}\\"","typedDictExtraFieldTypeMismatch":"El tipo de \\"{name}\\" no es compatible con el tipo de \\"__extra_items__\\" en \\"{type}\\"","typedDictFieldMissing":"\\"{name}\\" falta en \\"{type}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" no es de solo lectura en \\"{type}\\"","typedDictFieldNotRequired":"\\"{name}\\" no es obligatorio en \\"{type}\\"","typedDictFieldRequired":"\\"{name}\\" es obligatorio en \\"{type}\\"","typedDictFieldTypeMismatch":"El tipo \\"{type}\\" no se puede asignar al elemento \\"{name}\\"","typedDictFieldUndefined":"\\"{name}\\" es un elemento no definido en el tipo \\"{type}\\"","typedDictFinalMismatch":"\\"{sourceType}\\" no es compatible con \\"{destType}\\" debido a una discrepancia @final","typedDictKeyAccess":"Utilizar [\\"{name}\\"] para hacer referencia al elemento en TypedDict","typedDictNotAllowed":"No se puede usar TypedDict para comprobaciones de instancia o clase","unhashableType":"El tipo \\"{type}\\" no admite hash","uninitializedAbstractVariable":"La variable de instancia \\"{name}\\" está definida en la clase base abstracta \\"{classType} \\" pero no inicializada.","unreachableExcept":"\\"{exceptionType}\\" es una subclase de \\"{parentType}\\"","useDictInstead":"Usar Dict[T1, T2] para indicar un tipo de diccionario","useListInstead":"Usar List[T] para indicar un tipo de lista o Union[T1, T2] para indicar un tipo de unión","useTupleInstead":"Utilice Tupla[T1, ..., Tn] para indicar un tipo de tupla o Union[T1, T2] para indicar un tipo de unión.","useTypeInstead":"Utilice Type[T] en su lugar","varianceMismatchForClass":"La varianza del argumento de tipo \\"{typeVarName}\\" no es compatible con la clase base \\"{className}\\"","varianceMismatchForTypeAlias":"La varianza del argumento de tipo \\"{typeVarName}\\" no es compatible con \\"{typeAliasParam}\\""}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.fr.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.fr.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Créer un stub de type","createTypeStubFor":"Créer un stub de type pour « {moduleName} »","executingCommand":"Exécution de la commande","filesToAnalyzeCount":"{count} fichiers à analyser","filesToAnalyzeOne":"1 fichier à analyser","findingReferences":"Recherche de références","organizeImports":"Organiser les importations","renameShadowedFile":"Renommez \\"{oldFile}\\" en \\"{newFile}\\""},"Completion":{"autoImportDetail":"Importation automatique","indexValueDetail":"Valeur de l\'indice"},"Diagnostic":{"abstractMethodInvocation":"Désolé, nous n’avons pas pu appeler la méthode « {method} », car elle est abstraite et non implémentée","annotatedParamCountMismatch":"Non-concordance du nombre d\'annotations de paramètre : attendu {expected} mais reçu {received}","annotatedTypeArgMissing":"Un argument de type et une ou plusieurs annotations sont attendus pour « Annotation »","annotationFormatString":"Les annotations de type ne peuvent pas utiliser de littéraux de chaîne de format (f-strings)","annotationNotSupported":"Annotation de type non prise en charge pour cette instruction","annotationSpansStrings":"Les annotations de type ne peuvent pas s\'étendre sur plusieurs littéraux de chaîne","annotationStringEscape":"Les annotations de type ne peuvent pas contenir de caractères d\'échappement","argAssignment":"Impossible d’affecter l’argument de type « {argType} » au paramètre de type « {paramType} »","argAssignmentFunction":"Impossible d’affecter l’argument de type « {argType} » au paramètre de type « {paramType} » dans la fonction « {functionName} »","argAssignmentParam":"Impossible d’affecter l’argument de type « {argType} » au paramètre « {paramName} » de type « {paramType} »","argAssignmentParamFunction":"Impossible d’affecter l’argument de type « {argType} » au paramètre « {paramName} » de type « {paramType} » dans la fonction « {functionName} »","argMissingForParam":"Argument manquant pour le paramètre {name}","argMissingForParams":"Arguments manquants pour les paramètres {names}","argMorePositionalExpectedCount":"{expected} arguments positionnels supplémentaires attendus","argMorePositionalExpectedOne":"1 argument positionnel supplémentaire attendu","argPositional":"Argument positionnel attendu","argPositionalExpectedCount":"Arguments positionnels {expected} attendus","argPositionalExpectedOne":"1 argument positionnel attendu","argTypePartiallyUnknown":"Le type d\'argument est partiellement inconnu","argTypeUnknown":"Le type d’argument est inconnu","assertAlwaysTrue":"L’expression Assert prend toujours la valeur true","assertTypeArgs":"« assert_type » attend deux arguments positionnels","assertTypeTypeMismatch":"Non-concordance de « assert_type » : « {expected} » attendu, mais « {received} »","assignmentExprComprehension":"La cible d\'expression d\'affectation \\"{name}\\" ne peut pas utiliser le même nom que la compréhension pour la cible","assignmentExprContext":"L’expression d’assignation doit se trouver dans le module, la fonction ou l’expression lambda","assignmentExprInSubscript":"Les expressions d’assignation dans un indice sont prises en charge uniquement dans Python 3.10 et versions ultérieures","assignmentInProtocol":"Les variables d\'instance ou de classe au sein d\'une classe Protocol doivent être explicitement déclarées dans le corps de la classe","assignmentTargetExpr":"L’expression ne peut pas être une cible d’assignation","asyncNotInAsyncFunction":"L\'utilisation de \\"async\\" n\'est pas autorisée en dehors de la fonction async","awaitIllegal":"L’utilisation de « await » nécessite Python 3.5 ou version ultérieure","awaitNotAllowed":"Les annotations de type ne peuvent pas utiliser « await »","awaitNotInAsync":"« await » autorisé uniquement dans la fonction asynchrone","backticksIllegal":"Les expressions entourées de accents inverses ne sont pas prises en charge dans Python 3.x; utiliser repr à la place","baseClassCircular":"La classe ne peut pas dériver d\'elle-même","baseClassFinal":"La classe de base « {type} » est marquée comme finale et ne peut pas être sous-classée","baseClassIncompatible":"Les classes de base de {type} sont mutuellement incompatibles","baseClassInvalid":"L’argument pour la classe doit être une classe de base","baseClassMethodTypeIncompatible":"Les classes de base de la classe « {classType} » définissent la méthode « {name} » de manière incompatible","baseClassUnknown":"Le type de classe de base est inconnu, ce qui masque le type de classe dérivée","baseClassVariableTypeIncompatible":"Les classes de base de la classe « {classType} » définissent la variable « {name} » de manière incompatible","binaryOperationNotAllowed":"Opérateur binaire non autorisé dans l’annotation de type","bindTypeMismatch":"Impossible de lier la méthode \\"{methodName}\\" car \\"{type}\\" n\'est pas attribuable au paramètre \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" ne peut être utilisé qu\'à l\'intérieur d\'une boucle","callableExtraArgs":"Seuls deux arguments de type sont attendus pour « Joignable »","callableFirstArg":"Liste de types de paramètres attendue ou « ... »","callableNotInstantiable":"Impossible d’instancier le type « {type} »","callableSecondArg":"Type de retour attendu en tant que deuxième argument de type pour « Joignable »","casePatternIsIrrefutable":"Le motif irréfutable n\'est autorisé que pour la dernière instruction case","classAlreadySpecialized":"Le type « {type} » est déjà spécialisé","classDecoratorTypeUnknown":"Le décorateur de classe non typé masque le type de classe ; décorateur ignorant","classDefinitionCycle":"La définition de classe pour \\"{name}\\" dépend d\'elle-même","classGetItemClsParam":"__class_getitem__ remplacement doit prendre un paramètre « cls »","classMethodClsParam":"Les méthodes de classe doivent prendre un paramètre \\"cls\\"","classNotRuntimeSubscriptable":"L’indice de la classe « {name} » génère une exception d’exécution ; placer l’annotation de type entre guillemets","classPatternBuiltInArgPositional":"Le modèle de classe accepte uniquement le sous-modèle positionnel","classPatternPositionalArgCount":"Trop de modèles positionnels pour les \\"{type}\\" de classe ; {expected} attendue mais {received} reçues","classPatternTypeAlias":"\\"{type}\\" ne peut pas être utilisé dans un modèle de classe car il s\'agit d\'un alias de type spécialisé","classPropertyDeprecated":"Les propriétés de classe sont obsolètes dans Python 3.11 et ne seront pas prises en charge dans Python 3.13","classTypeParametersIllegal":"La syntaxe du paramètre de type de classe nécessite Python 3.12 ou version ultérieure","classVarFirstArgMissing":"Attendu un argument de type après \\"ClassVar\\"","classVarNotAllowed":"« ClassVar » n’est pas autorisé dans ce contexte","classVarOverridesInstanceVar":"La variable de classe « {name} » remplace la variable d’instance du même nom dans la classe « {className} »","classVarTooManyArgs":"Attendu un seul argument de type après \\"ClassVar\\"","classVarWithTypeVar":"Le type \\"ClassVar\\" ne peut pas inclure de variables de type","clsSelfParamTypeMismatch":"Le type de paramètre \\"{name}\\" doit être un supertype de sa classe \\"{classType}\\"","codeTooComplexToAnalyze":"Le code est trop complexe à analyser ; réduire la complexité en refactorisant en sous-routines ou en réduisant les chemins de code conditionnels","collectionAliasInstantiation":"Le type \\"{type}\\" ne peut pas être instancié, utilisez \\"{alias}\\" à la place","comparisonAlwaysFalse":"La condition prend toujours la valeur False, car les types « {leftType} » et « {rightType} » ne se chevauchent pas","comparisonAlwaysTrue":"La condition prend toujours la valeur True, car les types « {leftType} » et « {rightType} » ne se chevauchent pas","comprehensionInDict":"La compréhension ne peut pas être utilisée avec d’autres entrées de dictionnaire","comprehensionInSet":"La compréhension ne peut pas être utilisée avec d\'autres entrées définies","concatenateContext":"« Concatenate » n’est pas autorisé dans ce contexte","concatenateParamSpecMissing":"Le dernier argument de type pour « Concatener » doit être un ParamSpec ou bien « ... »","concatenateTypeArgsMissing":"\\"Concaténation\\" nécessite au moins deux arguments de type","conditionalOperandInvalid":"Opérande conditionnel non valide de type \\"{type}\\"","constantRedefinition":"\\"{name}\\" est constant (car il est en majuscule) et ne peut pas être redéfini","constructorNoArgs":"Aucun argument attendu pour le constructeur « {type} »","constructorParametersMismatch":"Non-concordance entre la signature de __new__ et __init__ dans la classe \\"{classType}\\"","containmentAlwaysFalse":"L\'expression sera toujours évaluée à False car les types \\"{leftType}\\" et \\"{rightType}\\" ne se chevauchent pas","containmentAlwaysTrue":"L\'expression sera toujours évaluée à True puisque les types \\"{leftType}\\" et \\"{rightType}\\" ne se chevauchent pas","continueInFinally":"« continuer » ne peut pas être utilisé dans une clause finally","continueOutsideLoop":"« continuer » ne peut être utilisé qu’au sein d’une boucle","coroutineInConditionalExpression":"L\'expression conditionnelle fait référence à une coroutine qui est toujours évaluée à True","dataClassBaseClassFrozen":"Une classe non gelée ne peut pas hériter d\'une classe gelée","dataClassBaseClassNotFrozen":"Une classe figée ne peut pas hériter d’une classe qui n’est pas figée","dataClassConverterFunction":"L’argument de type « {argType} » n’est pas un convertisseur valide pour le champ « {fieldName} » de type « {fieldType} »","dataClassConverterOverloads":"Aucune surcharge de « {funcName} » n’est valide pour le champ « {fieldName} » de type « {fieldType} »","dataClassFieldWithDefault":"Les champs sans valeurs par défaut ne peuvent pas apparaître après les champs avec des valeurs par défaut","dataClassFieldWithPrivateName":"Le champ Dataclass ne peut pas utiliser de nom privé","dataClassFieldWithoutAnnotation":"Le champ Dataclass sans annotation de type provoquera une exception d\'exécution","dataClassPostInitParamCount":"La classe de données __post_init__ nombre de paramètres incorrect ; le nombre de champs InitVar est {expected}","dataClassPostInitType":"Incompatibilité du type de paramètre de méthode __post_init__ Dataclass pour le champ « {fieldName} »","dataClassSlotsOverwrite":"__slots__ est déjà défini dans la classe","dataClassTransformExpectedBoolLiteral":"Expression attendue qui prend statiquement la valeur True ou False","dataClassTransformFieldSpecifier":"Tuple attendu de classes ou de fonctions mais type reçu \\"{type}\\"","dataClassTransformPositionalParam":"Tous les arguments de « dataclass_transform » doivent être des arguments de mot clé","dataClassTransformUnknownArgument":"L’argument « {name} » n’est pas pris en charge par dataclass_transform","dataProtocolInSubclassCheck":"Les protocoles de données (qui incluent des attributs non méthode) ne sont pas autorisés dans les appels de sous-classe","declaredReturnTypePartiallyUnknown":"Le type de retour déclaré « {returnType} » est partiellement inconnu","declaredReturnTypeUnknown":"Le type de retour déclaré est inconnu","defaultValueContainsCall":"Les appels de fonction et les objets mutables ne sont pas autorisés dans l\'expression de la valeur par défaut du paramètre","defaultValueNotAllowed":"Le paramètre avec « * » ou « ** » ne peut pas avoir de valeur par défaut","delTargetExpr":"L\'expression ne peut pas être supprimée","deprecatedClass":"La classe \\"{name}\\" est obsolète","deprecatedConstructor":"Le constructeur de la classe « {name} » est déconseillé","deprecatedDescriptorDeleter":"La méthode « __delete__ » du descripteur « {name} » est déconseillée","deprecatedDescriptorGetter":"La méthode « __get__ » du descripteur « {name} » est déconseillée","deprecatedDescriptorSetter":"La méthode « __set__ » du descripteur « {name} » est déconseillée","deprecatedFunction":"La fonction \\"{name}\\" est obsolète","deprecatedMethod":"La méthode \\"{name}\\" dans la classe \\"{className}\\" est obsolète","deprecatedPropertyDeleter":"Le deleter de la propriété « {name} » est déconseillé","deprecatedPropertyGetter":"Le getter de la propriété « {name} » est déconseillé","deprecatedPropertySetter":"Le setter de la propriété « {name} » est déconseillé","deprecatedType":"Ce type est déconseillé à compter de Python {version}; utiliser « {replacement} » à la place","dictExpandIllegalInComprehension":"Expansion du dictionnaire non autorisée dans la compréhension","dictInAnnotation":"Expression de dictionnaire non autorisée dans l’annotation de type","dictKeyValuePairs":"Les entrées de dictionnaire doivent contenir des paires clé/valeur","dictUnpackIsNotMapping":"Mappage attendu pour l’opérateur de décompression de dictionnaire","dunderAllSymbolNotPresent":"« {name} » est spécifié dans __all__ mais n’est pas présent dans le module","duplicateArgsParam":"Un seul paramètre « * » est autorisé","duplicateBaseClass":"Classe de base en double non autorisée","duplicateCapturePatternTarget":"La cible Capture \\"{name}\\" ne peut pas apparaître plus d\'une fois dans le même modèle","duplicateCatchAll":"Une seule clause catch-all sauf autorisée","duplicateEnumMember":"Le membre enum « {name} » est déjà déclaré","duplicateGenericAndProtocolBase":"Une seule classe de base Generic[...] ou Protocol[...] autorisée","duplicateImport":"« {importName} » est importé plusieurs fois","duplicateKeywordOnly":"Un seul séparateur « * » autorisé","duplicateKwargsParam":"Un seul paramètre « ** » est autorisé","duplicateParam":"Dupliquer le paramètre « {name} »","duplicatePositionOnly":"Un seul paramètre \\"/\\" autorisé","duplicateStarPattern":"Un seul motif \\"*\\" autorisé dans une séquence de motifs","duplicateStarStarPattern":"Une seule entrée \\"**\\" autorisée","duplicateUnpack":"Une seule opération de décompression autorisée dans la liste","ellipsisAfterUnpacked":"\\"...\\" ne peut pas être utilisé avec un TypeVarTuple ou un tuple décompressé","ellipsisContext":"« ... » n’est pas autorisé dans ce contexte","ellipsisSecondArg":"« ... » n’est autorisé qu’en tant que second des deux arguments","enumClassOverride":"La classe Enum « {name} » est finale et ne peut pas être sous-classée","exceptionGroupIncompatible":"La syntaxe du groupe d’exceptions (« except* ») nécessite Python 3.11 ou version ultérieure","exceptionTypeIncorrect":"\\"{type}\\" ne dérive pas de BaseException","exceptionTypeNotClass":"« {type} » n’est pas une classe d’exception valide","exceptionTypeNotInstantiable":"Le constructeur pour le type d’exception « {type} » requiert un ou plusieurs arguments","expectedAfterDecorator":"Fonction attendue ou déclaration de classe après le décorateur","expectedArrow":"« -> » attendu suivi d’une annotation de type de retour","expectedAsAfterException":"\\"comme\\" attendu après le type d\'exception","expectedAssignRightHandExpr":"Expression attendue à droite de « = »","expectedBinaryRightHandExpr":"Expression attendue à droite de l’opérateur","expectedBoolLiteral":"Attendu vrai ou faux","expectedCase":"Instruction « case » attendue","expectedClassName":"Nom de classe attendu","expectedCloseBrace":"« { » n’a pas été fermé","expectedCloseBracket":"« [ » n’a pas été fermé","expectedCloseParen":"« ( » n’a pas été fermé","expectedColon":"« : » attendu","expectedComplexNumberLiteral":"Littéral de nombre complexe attendu pour la correspondance de modèle","expectedDecoratorExpr":"Formulaire d’expression non pris en charge pour l’élément décoratif antérieur à Python 3.9","expectedDecoratorName":"Nom de l’élément décoratif attendu","expectedDecoratorNewline":"Nouvelle ligne attendue à la fin de l’élément décoratif","expectedDelExpr":"Expression attendue après « del »","expectedElse":"« else » attendu","expectedEquals":"« = » attendu","expectedExceptionClass":"Classe ou objet d\'exception non valide","expectedExceptionObj":"Objet d’exception attendu, classe d’exception ou Aucun","expectedExpr":"Expression attendue","expectedFunctionAfterAsync":"Définition de fonction attendue après \\"async\\"","expectedFunctionName":"Nom de fonction attendu après « def »","expectedIdentifier":"Identifiant attendu","expectedImport":"« importation » attendue","expectedImportAlias":"Symbole attendu après « as »","expectedImportSymbols":"Un ou plusieurs noms de symboles attendus après l’importation","expectedIn":"« in » attendu","expectedInExpr":"Expression attendue après « in »","expectedIndentedBlock":"Bloc en retrait attendu","expectedMemberName":"Nom de membre attendu après « . »","expectedModuleName":"Nom de module attendu","expectedNameAfterAs":"Nom de symbole attendu après \\"as\\"","expectedNamedParameter":"Le paramètre de mot clé doit suivre « * »","expectedNewline":"Nouvelle ligne attendue","expectedNewlineOrSemicolon":"Les instructions doivent être séparées par des nouvelles lignes ou des points-virgules","expectedOpenParen":"Attendu \\"(\\"","expectedParamName":"Nom du paramètre attendu","expectedPatternExpr":"Expression de modèle attendue","expectedPatternSubjectExpr":"Expression du sujet du modèle attendu","expectedPatternValue":"Expression de valeur de modèle attendue sous la forme « a.b »","expectedReturnExpr":"Expression attendue après « return »","expectedSliceIndex":"Expression d\'index ou de tranche attendue","expectedTypeNotString":"Type attendu mais réception d’un littéral de chaîne","expectedTypeParameterName":"Nom de paramètre de type attendu","expectedYieldExpr":"Expression attendue dans l\'instruction yield","finalClassIsAbstract":"La classe « {type} » est marquée comme finale et doit implémenter toutes les symboles abstraits","finalContext":"« Final » n’est pas autorisé dans ce contexte","finalMethodOverride":"La méthode « {name} » ne peut pas remplacer la méthode finale définie dans la classe « {className} »","finalNonMethod":"La fonction « {name} » ne peut pas être marquée @final, car il ne s’agit pas d’une méthode","finalReassigned":"\\"{name}\\" est déclaré final et ne peut pas être réaffecté","finalRedeclaration":"« {name} » a été déclaré comme final","finalRedeclarationBySubclass":"« {name} » ne peut pas être redéclaré, car la classe parente « {className} » la déclare final","finalTooManyArgs":"Argument de type unique attendu après « Final »","finalUnassigned":"« {name} » est déclaré Final, mais la valeur n’est pas affectée","formatStringBrace":"Accolade fermante unique non autorisée dans le littéral f-string ; utiliser une double accolade fermée","formatStringBytes":"Les littéraux de chaîne de format (chaînes f) ne peuvent pas être binaires","formatStringDebuggingIllegal":"Le spécificateur de débogage de chaîne F \\"=\\" nécessite Python 3.8 ou une version plus récente","formatStringEscape":"Séquence d\'échappement (barre oblique inverse) non autorisée dans la partie expression de la chaîne f avant Python 3.12","formatStringExpectedConversion":"Spécificateur de conversion attendu après « ! » dans f-string","formatStringIllegal":"Les littéraux de chaîne de format (chaînes f) nécessitent Python 3.6 ou une version plus récente","formatStringInPattern":"Chaîne de format non autorisée dans le modèle","formatStringNestedFormatSpecifier":"Expressions imbriqués trop profondément dans le spécificateur de chaîne de format","formatStringNestedQuote":"Les chaînes imbriquées dans une chaîne f ne peuvent pas utiliser le même guillemet que la chaîne f avant Python 3.12","formatStringUnicode":"Les littéraux de chaîne de format (f-strings) ne peuvent pas être unicode","formatStringUnterminated":"Expression non terminée dans f-string ; attendant \\"}\\"","functionDecoratorTypeUnknown":"Le décorateur de fonction non typé masque le type de fonction ; élément décoratif ignoré","functionInConditionalExpression":"L’expression conditionnelle fait référence à une fonction qui prend toujours la valeur True","functionTypeParametersIllegal":"La syntaxe des paramètres de type de fonction nécessite Python 3.12 ou une version plus récente","futureImportLocationNotAllowed":"Les importations à partir de __future__ doivent se trouver au début du fichier","generatorAsyncReturnType":"Le type de retour de la fonction de générateur asynchrone doit être compatible avec « AsyncGenerator[{yieldType}, Any] »","generatorNotParenthesized":"Les expressions de générateur doivent être entre parenthèses si elles ne sont pas uniquement des arguments","generatorSyncReturnType":"Le type de retour de la fonction de générateur doit être compatible avec « Generator[{yieldType}, Any, Any] »","genericBaseClassNotAllowed":"La classe de base \\"générique\\" ne peut pas être utilisée avec la syntaxe de paramètre de type","genericClassAssigned":"Impossible d’attribuer le type de classe générique","genericClassDeleted":"Le type de classe générique ne peut pas être supprimé","genericInstanceVariableAccess":"L’accès à une variable d’instance générique via une classe est ambigu","genericNotAllowed":"« Générique » n’est pas valide dans ce contexte","genericTypeAliasBoundTypeVar":"L’alias de type générique dans la classe ne peut pas utiliser les variables de type lié {names}","genericTypeArgMissing":"« Générique » nécessite au moins un argument de type","genericTypeArgTypeVar":"L’argument de type pour « Generic » doit être une variable de type","genericTypeArgUnique":"Les arguments de type pour « Generic » doivent être uniques","globalReassignment":"« {name} » est attribué avant la déclaration globale","globalRedefinition":"« {name} » a déjà été déclaré global","implicitStringConcat":"Concaténation implicite de chaînes non autorisée","importCycleDetected":"Cycle détecté dans la chaîne d\'importation","importDepthExceeded":"La profondeur de la chaîne d\'importation a dépassé {depth}","importResolveFailure":"Impossible de résoudre l’importation « {importName} »","importSourceResolveFailure":"Impossible de résoudre l’importation « {importName} » à partir de la source","importSymbolUnknown":"« {name} » est un symbole d’importation inconnu","incompatibleMethodOverride":"La méthode « {name} » remplace la classe « {className} » de manière incompatible","inconsistentIndent":"Le montant du retrait ne correspond pas au retrait précédent","inconsistentTabs":"Utilisation incohérente des onglets et des espaces dans la mise en retrait","initMustReturnNone":"Le type de retour de « __init__ » doit être None","initSubclassCallFailed":"Arguments de mot clé incorrects pour la méthode __init_subclass__","initSubclassClsParam":"__init_subclass__ remplacement doit prendre un paramètre « cls »","initVarNotAllowed":"« InitVar » n’est pas autorisé dans ce contexte","instanceMethodSelfParam":"Les méthodes d’instance doivent prendre un paramètre « self »","instanceVarOverridesClassVar":"La variable d\'instance \\"{name}\\" remplace la variable de classe du même nom dans la classe \\"{className}\\"","instantiateAbstract":"Impossible d\'instancier la classe abstraite \\"{type}\\"","instantiateProtocol":"Impossible d\'instancier la classe de protocole \\"{type}\\"","internalBindError":"Une erreur interne s’est produite lors de la liaison du fichier « {file} » : {message}","internalParseError":"Une erreur interne s’est produite lors de l’analyse du fichier « {file} » : {message}","internalTypeCheckingError":"Une erreur interne s’est produite lors de la vérification de type du fichier « {file} » : {message}","invalidIdentifierChar":"Caractère invalide dans l\'identifiant","invalidStubStatement":"L’instruction n’a aucun sens dans un fichier stub de type","invalidTokenChars":"Caractère non valide \\"{text}\\" dans le jeton","isInstanceInvalidType":"Le deuxième argument de \\"isinstance\\" doit être une classe ou un tuple de classes","isSubclassInvalidType":"Le deuxième argument de « issubclass » doit être une classe ou un tuple de classes","keyValueInSet":"Les paires clé/valeur ne sont pas autorisées dans un ensemble","keywordArgInTypeArgument":"Les arguments de mot-clé ne peuvent pas être utilisés dans les listes d\'arguments de type","keywordOnlyAfterArgs":"Séparateur d’arguments mot clé uniquement non autorisé après le paramètre « * »","keywordParameterMissing":"Un ou plusieurs paramètres de mot-clé doivent suivre le paramètre \\"*\\"","keywordSubscriptIllegal":"Les arguments de mot-clé dans les indices ne sont pas pris en charge","lambdaReturnTypePartiallyUnknown":"Le type de retour de lambda, « {returnType} », est partiellement inconnu","lambdaReturnTypeUnknown":"Le type de retour de lambda est inconnu","listAssignmentMismatch":"Impossible d’affecter l’expression de type « {type} » à la liste cible","listInAnnotation":"Expression de liste non autorisée dans l’annotation de type","literalEmptyArgs":"Attendu un ou plusieurs arguments de type après \\"Literal\\"","literalNotAllowed":"\\"Littéral\\" ne peut pas être utilisé dans ce contexte sans argument de type","literalNotCallable":"Impossible d’instancier le type littéral","literalUnsupportedType":"Les arguments de type pour « Literal » doivent être None, une valeur littérale (int, bool, str ou bytes) ou une valeur enum","matchIncompatible":"Les instructions de correspondance nécessitent Python 3.10 ou version ultérieure","matchIsNotExhaustive":"Les cas dans l’instruction match ne gèrent pas toutes les valeurs de manière exhaustive","maxParseDepthExceeded":"Profondeur d’analyse maximale dépassée ; scinder l’expression en sous-expressions plus petites","memberAccess":"Impossible d’accéder au membre « {name} » pour le type « {type} »","memberDelete":"Impossible de supprimer le membre « {name} » pour le type « {type} »","memberSet":"Impossible d\'affecter le membre \\"{name}\\" pour le type \\"{type}\\"","metaclassConflict":"La métaclasse d’une classe dérivée doit être une sous-classe des métaclasses de toutes ses classes de base","metaclassDuplicate":"Une seule métaclasse peut être fournie","metaclassIsGeneric":"La métaclasse ne peut pas être générique","methodNotDefined":"Méthode « {name} » non définie","methodNotDefinedOnType":"Méthode « {name} » non définie sur le type « {type} »","methodOrdering":"Impossible de créer un classement de méthode cohérent","methodOverridden":"\\"{name}\\" remplace la méthode du même nom dans la classe \\"{className}\\" avec un type incompatible \\"{type}\\"","methodReturnsNonObject":"La méthode « {name} » ne retourne pas d’objet","missingSuperCall":"La méthode « {methodName} » n’appelle pas la méthode du même nom dans la classe parente","moduleAsType":"Le module ne peut pas être utilisé comme type","moduleNotCallable":"Le module ne peut pas être appelé","moduleUnknownMember":"\\"{memberName}\\" n\'est pas un membre connu du module \\"{moduleName}\\"","namedExceptAfterCatchAll":"Une clause except nommée ne peut pas apparaître après une clause except fourre-tout","namedParamAfterParamSpecArgs":"Le paramètre de mot clé « {name} » ne peut pas apparaître dans la signature après le paramètre ParamSpec args","namedTupleEmptyName":"Les noms dans un tuple nommé ne peuvent pas être vides","namedTupleEntryRedeclared":"Impossible de remplacer « {name} », car la classe parente « {className} » est un tuple nommé","namedTupleFirstArg":"Nom de classe de tuple nommé attendu en tant que premier argument","namedTupleMultipleInheritance":"L’héritage multiple avec NamedTuple n’est pas pris en charge","namedTupleNameKeyword":"Les noms de champs ne peuvent pas être un mot-clé","namedTupleNameType":"Tuple à deux entrées attendu spécifiant le nom et le type de l’entrée","namedTupleNameUnique":"Les noms dans un tuple nommé doivent être uniques","namedTupleNoTypes":"« namedtuple » ne fournit aucun type pour les entrées de tuple ; utilisez « NamedTuple » à la place","namedTupleSecondArg":"Liste d’entrées de tuple nommée attendue en tant que deuxième argument","newClsParam":"__new__ remplacement doit prendre un paramètre « cls »","newTypeAnyOrUnknown":"Le deuxième argument de NewType doit être une classe connue, et non Any ou Unknown","newTypeBadName":"Le premier argument de NewType doit être un littéral de chaîne","newTypeLiteral":"Impossible d’utiliser NewType avec le type Literal","newTypeNameMismatch":"NewType doit être affecté à une variable portant le même nom","newTypeNotAClass":"Classe attendue comme deuxième argument de NewType","newTypeParamCount":"NewType requiert deux arguments positionnels","newTypeProtocolClass":"Désolé, nous n’avons pas pu utiliser NewType avec un type structurelle (un protocole ou une classe TypedDict)","noOverload":"Aucune surcharge pour « {name} » ne correspond aux arguments fournis","noReturnContainsReturn":"La fonction avec le type de retour déclaré « NoReturn » ne peut pas inclure d’instruction de retour","noReturnContainsYield":"La fonction avec le type de retour déclaré « NoReturn » ne peut pas inclure d’instruction yield","noReturnReturnsNone":"La fonction avec le type de retour déclaré \\"NoReturn\\" ne peut pas renvoyer \\"None\\"","nonDefaultAfterDefault":"L’argument autre que l’argument par défaut suit l’argument par défaut","nonLocalInModule":"Déclaration non locale non autorisée au niveau du module","nonLocalNoBinding":"Aucune liaison pour le « {name} » non local trouvé","nonLocalReassignment":"« {name} » est attribué avant la déclaration non locale","nonLocalRedefinition":"« {name} » a déjà été déclaré non local","noneNotCallable":"L\'objet de type \\"Aucun\\" ne peut pas être appelé","noneNotIterable":"L’objet de type « None » ne peut pas être utilisé en tant que valeur itérable","noneNotSubscriptable":"L\'objet de type \\"Aucun\\" n\'est pas inscriptible","noneNotUsableWith":"L’objet de type « None » ne peut pas être utilisé avec « with »","noneOperator":"L’opérateur « {operator} » n’est pas pris en charge pour « None »","noneUnknownMember":"« {name} » n’est pas un membre connu de « None »","notRequiredArgCount":"Argument de type unique attendu après « NotRequired »","notRequiredNotInTypedDict":"« NotRequired » n’est pas autorisé dans ce contexte","objectNotCallable":"L’objet de type « {type} » n’est pas appelant","obscuredClassDeclaration":"La déclaration de classe « {name} » est masquée par une déclaration du même nom","obscuredFunctionDeclaration":"La déclaration de fonction « {name} » est masquée par une déclaration du même nom","obscuredMethodDeclaration":"La déclaration de méthode « {name} » est masquée par une déclaration du même nom","obscuredParameterDeclaration":"La déclaration de paramètre « {name} » est masquée par une déclaration du même nom","obscuredTypeAliasDeclaration":"La déclaration d’alias de type « {name} » est masquée par une déclaration du même nom","obscuredVariableDeclaration":"La déclaration « {name} » est masquée par une déclaration du même nom","operatorLessOrGreaterDeprecated":"L’opérateur « <> » n’est pas pris en charge dans Python 3 ; utilisez « != » à la place","optionalExtraArgs":"Attendu un argument de type après \\"Facultatif\\"","orPatternIrrefutable":"Modèle irréfutable autorisé uniquement en tant que dernier sous-modèle dans un modèle \\"ou\\"","orPatternMissingName":"Tous les sous-modèles d’un modèle « or » doivent cibler les mêmes noms","overlappingKeywordArgs":"Le dictionnaire tapé chevauche avec le mot clé paramètre : {names}","overlappingOverload":"La surcharge {obscured} pour « {name} » ne sera jamais utilisée, car ses paramètres chevauchent la surcharge {obscuredBy}","overloadAbstractMismatch":"Les méthodes surchargées doivent toutes être abstraites ou non","overloadClassMethodInconsistent":"Les surcharges pour « {name} » utilisent @classmethod de manière incohérente","overloadFinalInconsistencyImpl":"La surcharge pour « {name} » est marquée @final, mais l’implémentation ne l’est pas","overloadFinalInconsistencyNoImpl":"La surcharge {index} pour « {name} » est marquée @final mais la surcharge 1 n’est pas","overloadImplementationMismatch":"L’implémentation surchargée n’est pas cohérente avec la signature de la surcharge {index}","overloadReturnTypeMismatch":"La surcharge {prevIndex} pour « {name} » chevauche la surcharge {newIndex} et retourne un type incompatible","overloadStaticMethodInconsistent":"Les surcharges pour « {name} » utilisent @staticmethod de manière incohérente","overloadWithoutImplementation":"\\"{name}\\" est marqué comme surcharge, mais aucune implémentation n\'est fournie","overriddenMethodNotFound":"La méthode \\"{name}\\" est marquée comme prioritaire, mais aucune méthode de base du même nom n\'est présente","overrideDecoratorMissing":"La méthode \\"{name}\\" n\'est pas marquée comme override mais remplace une méthode dans la classe \\"{className}\\"","paramAfterKwargsParam":"Le paramètre ne peut pas suivre le paramètre \\"**\\"","paramAlreadyAssigned":"Le paramètre « {name} » est déjà affecté","paramAnnotationMissing":"L\'annotation de type est manquante pour le paramètre \\"{name}\\"","paramAssignmentMismatch":"L\'expression de type \\"{sourceType}\\" ne peut pas être affectée au paramètre de type \\"{paramType}\\"","paramNameMissing":"Aucun paramètre nommé « {name} »","paramSpecArgsKwargsUsage":"Les membres « args » et « kwargs » de ParamSpec doivent apparaître tous les deux dans une signature de fonction","paramSpecArgsMissing":"Les arguments pour ParamSpec « {type} » sont manquants","paramSpecArgsUsage":"Le membre \\"args\\" de ParamSpec n\'est valide que lorsqu\'il est utilisé avec le paramètre *args","paramSpecAssignedName":"ParamSpec doit être affecté à une variable nommée « {name} »","paramSpecContext":"ParamSpec n’est pas autorisé dans ce contexte","paramSpecDefaultNotTuple":"Points de suspension attendus, expression de tuple ou ParamSpec pour la valeur par défaut de ParamSpec","paramSpecFirstArg":"Nom attendu de ParamSpec comme premier argument","paramSpecKwargsUsage":"Le membre « configurrgs » de ParamSpec n’est valide qu’en cas d’utilisation avec le paramètre **rgs","paramSpecNotUsedByOuterScope":"ParamSpec « {name} » n’a aucune signification dans ce contexte","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" est limité à un appelable dans le type de retour et ne peut pas être référencé dans le corps de la fonction","paramSpecUnknownArg":"ParamSpec ne prend pas en charge plus d\'un argument","paramSpecUnknownMember":"« {name} » n’est pas un membre connu de ParamSpec","paramSpecUnknownParam":"\\"{name}\\" est un paramètre inconnu pour ParamSpec","paramTypeCovariant":"Impossible d’utiliser la variable de type Covariant dans le type de paramètre","paramTypePartiallyUnknown":"Le type du paramètre « {paramName} » est partiellement inconnu","paramTypeUnknown":"Le type de paramètre « {paramName} » est inconnu","parenthesizedContextManagerIllegal":"Les parenthèses dans l\'instruction \\"with\\" nécessitent Python 3.9 ou une version plus récente","patternNeverMatches":"Le modèle ne sera jamais mis en correspondance pour le type d’objet « {type} »","positionArgAfterNamedArg":"L’argument positionnel ne peut pas apparaître après les arguments de mot clé","positionOnlyAfterArgs":"Séparateur de paramètres de position seule non autorisé après le paramètre « * »","positionOnlyAfterKeywordOnly":"Le paramètre « / » doit apparaître avant le paramètre « * »","positionOnlyAfterNon":"Paramètre de position seule non autorisé après un paramètre qui n’est pas en position seule","positionOnlyFirstParam":"Séparateur de paramètres de position seule non autorisé en tant que premier paramètre","positionOnlyIncompatible":"Le séparateur de paramètres de position seule requiert Python 3.8 ou version ultérieure","privateImportFromPyTypedModule":"« {name} » n’est pas exporté à partir du module « {module} »","privateUsedOutsideOfClass":"« {name} » est privé et utilisé en dehors de la classe dans laquelle il est déclaré","privateUsedOutsideOfModule":"« {name} » est privé et utilisé en dehors du module dans lequel il est déclaré","propertyOverridden":"\\"{name}\\" remplace à tort la propriété du même nom dans la classe \\"{className}\\"","propertyStaticMethod":"Méthodes statiques non autorisées pour la propriété getter, setter ou deleter","protectedUsedOutsideOfClass":"\\"{name}\\" est protégé et utilisé en dehors de la classe dans laquelle il est déclaré","protocolBaseClass":"La classe de protocole \\"{classType}\\" ne peut pas dériver de la classe non protocolaire \\"{baseType}\\"","protocolBaseClassWithTypeArgs":"Les arguments de type ne sont pas autorisés avec la classe Protocol lors de l\'utilisation de la syntaxe des paramètres de type","protocolIllegal":"L’utilisation de « Protocole » nécessite Python 3.7 ou une version plus récente","protocolNotAllowed":"\\"Protocole\\" ne peut pas être utilisé dans ce contexte","protocolUnsafeOverlap":"La classe chevauche « {name} » de manière non sécurisée et peut produire une correspondance au moment de l’exécution","protocolVarianceContravariant":"La variable de type \\"{variable}\\" utilisée dans le protocole générique \\"{class}\\" doit être contravariante","protocolVarianceCovariant":"La variable de type \\"{variable}\\" utilisée dans le protocole générique \\"{class}\\" doit être covariante","protocolVarianceInvariant":"La variable de type \\"{variable}\\" utilisée dans le protocole générique \\"{class}\\" doit être invariante","pyrightCommentInvalidDiagnosticBoolValue":"La directive de commentaire Deight doit être suivie de « = » et d’une valeur true ou false","pyrightCommentInvalidDiagnosticSeverityValue":"La directive de commentaire Deright doit être suivie de « = » et avoir la valeur true, false, error, warning, information ou none","pyrightCommentMissingDirective":"Le commentaire Pyright doit être suivi d’une directive (de base ou stricte) ou d’une règle de diagnostic","pyrightCommentNotOnOwnLine":"Les commentaires Ensight utilisés pour contrôler les paramètres au niveau du fichier doivent apparaître sur leur propre ligne","pyrightCommentUnknownDiagnosticRule":"« {rule} » est une règle de diagnostic inconnue pour le commentaire deight","pyrightCommentUnknownDiagnosticSeverityValue":"« {value} \\" n’est pas valide pour le commentaire deight ; true, false, erreur, avertissement, informations ou aucun attendu","pyrightCommentUnknownDirective":"« {directive} » est une directive inconnue pour le commentaire deight; « strict » ou « de base » attendu","readOnlyArgCount":"Attendu un seul argument de type après \\"ReadOnly\\"","readOnlyNotInTypedDict":"« ReadOnly » n’est pas autorisé dans ce contexte","recursiveDefinition":"Le type de \\"{name}\\" n\'a pas pu être déterminé car il fait référence à lui-même","relativeImportNotAllowed":"Les importations relatives ne peuvent pas être utilisées avec le formulaire « import .a » ; utiliser « à partir de . importer a » à la place","requiredArgCount":"Attendu un argument de type unique après \\"Required\\"","requiredNotInTypedDict":"« Obligatoire » n’est pas autorisé dans ce contexte","returnInAsyncGenerator":"L\'instruction de retour avec valeur n\'est pas autorisée dans le générateur asynchrone","returnMissing":"La fonction avec le type de retour déclaré \\"{returnType}\\" doit renvoyer une valeur sur tous les chemins de code","returnOutsideFunction":"\\"return\\" ne peut être utilisé que dans une fonction","returnTypeContravariant":"La variable de type contravariant ne peut pas être utilisée dans le type de retour","returnTypeMismatch":"Impossible d’affecter l’expression de type « {exprType} » pour retourner le type « {returnType} »","returnTypePartiallyUnknown":"Le type de retour « {returnType} » est partiellement inconnu","returnTypeUnknown":"Le type de retour est inconnu","revealLocalsArgs":"Aucun argument attendu pour l\'appel \\"reveal_locals\\"","revealLocalsNone":"Aucun élément local dans cette étendue","revealTypeArgs":"Argument positionnel unique attendu pour l’appel « reveal_type »","revealTypeExpectedTextArg":"L\'argument \\"expected_text\\" pour la fonction \\"reveal_type\\" doit être une valeur littérale str","revealTypeExpectedTextMismatch":"Incompatibilité de texte de type ; « {expected} » attendu, mais a reçu « {received} »","revealTypeExpectedTypeMismatch":"Incompatibilité de type; attendu \\"{expected}\\" mais reçu \\"{received}\\"","selfTypeContext":"« Self » n’est pas valide dans ce contexte","selfTypeMetaclass":"« Self » ne peut pas être utilisé dans une métaclasse (une sous-classe de « type »)","selfTypeWithTypedSelfOrCls":"« Self » ne peut pas être utilisé dans une fonction avec un paramètre « self » ou « cls » qui a une annotation de type autre que « Self »","setterGetterTypeMismatch":"Le type valeur setter de propriété n’est pas assignable au type de retour getter","singleOverload":"« {name} » est marqué comme surcharge, mais des surcharges supplémentaires sont manquantes","slotsAttributeError":"\\"{name}\\" n\'est pas spécifié dans __slots__","slotsClassVarConflict":"\\"{name}\\" est en conflit avec la variable d\'instance déclarée dans __slots__","starPatternInAsPattern":"Le modèle d’étoile ne peut pas être utilisé avec la cible « as »","starPatternInOrPattern":"Le modèle d’étoile ne peut pas être supprimé dans d’autres modèles","starStarWildcardNotAllowed":"** ne peut pas être utilisé avec le caractère générique « _ »","staticClsSelfParam":"Les méthodes statiques ne doivent pas prendre de paramètre « self » ou « cls »","stdlibModuleOverridden":"\\"{path}\\" remplace le module stdlib \\"{name}\\"","stringNonAsciiBytes":"Caractère non-ASCII non autorisé dans le littéral de chaîne d\'octets","stringNotSubscriptable":"L’expression de chaîne ne peut pas être en indice dans l’annotation de type ; placer l’annotation entière entre guillemets","stringUnsupportedEscape":"Séquence d\'échappement non prise en charge dans le littéral de chaîne","stringUnterminated":"Le littéral de chaîne n’est pas spécifié","stubFileMissing":"Fichier stub introuvable pour « {importName} »","stubUsesGetAttr":"Le fichier stub de type est incomplet ; « __getattr__ » masque les erreurs de type pour le module","sublistParamsIncompatible":"Les paramètres de sous-liste ne sont pas pris en charge dans Python 3.x","superCallArgCount":"Pas plus de deux arguments attendus pour l\'appel \\"super\\"","superCallFirstArg":"Type de classe attendu en tant que premier argument de l’appel « super », mais « {type} » reçu","superCallSecondArg":"Le deuxième argument de l’appel « super » doit être un objet ou une classe dérivé de « {type} »","superCallZeroArgForm":"La forme sans argument d\'appel \\"super\\" n\'est valide que dans une méthode","superCallZeroArgFormStaticMethod":"La forme à zéro argument de l’appel « super » n’est pas valide dans une méthode statique","symbolIsPossiblyUnbound":"« {name} » est peut-être indépendant","symbolIsUnbound":"« {name} » est indépendant","symbolIsUndefined":"« {name} » n’est pas défini","symbolOverridden":"« {name} » remplace le symbole du même nom dans la classe « {className} »","ternaryNotAllowed":"Expression ternaire non autorisée dans l’annotation de type","totalOrderingMissingMethod":"La classe doit définir « __lt__ », « __le__ », « __gt__ » ou « __ge__ » pour utiliser total_ordering","trailingCommaInFromImport":"Virgule de fin non autorisée sans parenthèses adjacentes","tryWithoutExcept":"L\'instruction try doit avoir au moins une clause except ou finally","tupleAssignmentMismatch":"L\'expression avec le type \\"{type}\\" ne peut pas être assignée au tuple cible","tupleInAnnotation":"Expression de tuple non autorisée dans l\'annotation de type","tupleIndexOutOfRange":"L’index {index} est hors limites pour le type {type}","typeAliasIllegalExpressionForm":"Formulaire d’expression non valide pour la définition d’alias de type","typeAliasIsRecursiveDirect":"L\'alias de type \\"{name}\\" ne peut pas s\'utiliser lui-même dans sa définition","typeAliasNotInModuleOrClass":"Un TypeAlias ne peut être défini qu’au sein d’un module ou d’une étendue de classe","typeAliasRedeclared":"« {name} » est déclaré en tant que TypeAlias et ne peut être attribué qu’une seule fois","typeAliasStatementBadScope":"Une instruction de type ne peut être utilisée que dans une étendue de module ou de classe","typeAliasStatementIllegal":"L’instruction d’alias de type nécessite Python 3.12 ou version ultérieure","typeAliasTypeBaseClass":"Un alias de type défini dans une instruction « type » ne peut pas être utilisé en tant que classe de base","typeAliasTypeMustBeAssigned":"TypeAliasType doit être affecté à une variable portant le même nom que l\'alias de type","typeAliasTypeNameArg":"Le premier argument de TypeAliasType doit être un littéral de chaîne représentant le nom de l\'alias de type","typeAliasTypeNameMismatch":"Le nom de l’alias de type doit correspondre au nom de la variable à laquelle il est affecté","typeAliasTypeParamInvalid":"La liste de paramètres de type doit être un tuple contenant uniquement TypeVar, TypeVarTuple ou ParamSpec","typeAnnotationCall":"Expression d\'appel non autorisée dans l\'expression de type","typeAnnotationVariable":"Variable non autorisée dans l\'expression de type","typeAnnotationWithCallable":"L\'argument de type pour \\"type\\" doit être une classe ; les callables ne sont pas pris en charge","typeArgListExpected":"ParamSpec, ellipse ou liste de types attendue","typeArgListNotAllowed":"Expression de liste non autorisée pour cet argument de type","typeArgsExpectingNone":"Aucun argument de type attendu pour la classe « {name} »","typeArgsMismatchOne":"Argument de type attendu mais {received} reçu","typeArgsMissingForAlias":"Arguments de type attendus pour l’alias de type générique « {name} »","typeArgsMissingForClass":"Arguments de type attendus pour la classe générique \\"{name}\\"","typeArgsTooFew":"Trop peu d’arguments de type fournis pour « {name} » ; {expected} attendu, mais {received} reçu","typeArgsTooMany":"Trop d\'arguments de type fournis pour \\"{name}\\" ; attendu {expected} mais reçu {received}","typeAssignmentMismatch":"Impossible d’affecter l’expression de type « {sourceType} » au type déclaré « {destType} »","typeAssignmentMismatchWildcard":"Le symbole d’importation « {name} » a le type « {sourceType} », qui ne peut pas être affecté au type déclaré « {destType} »","typeCallNotAllowed":"l’appel type() ne doit pas être utilisé dans l’annotation de type","typeCheckOnly":"\\"{name}\\" est marqué comme @type_check_only et ne peut être utilisé que dans les annotations de type","typeCommentDeprecated":"L’utilisation de commentaires de type est déconseillée ; utiliser l’annotation de type à la place","typeExpectedClass":"Expression de type attendue mais « {type} » reçue","typeGuardArgCount":"Argument de type unique attendu après « TypeGuard » ou « Typels »","typeGuardParamCount":"Les méthodes et fonctions de protection de type définies par l’utilisateur doivent avoir au moins un paramètre d’entrée","typeIsReturnType":"Le type de retour des TypesIs (« {returnType} ») n’est pas cohérent avec le type de paramètre de valeur (« {type} »)","typeNotAwaitable":"\\"{type}\\" n\'est pas attendu","typeNotIntantiable":"« {type} » ne peut pas être instancié","typeNotIterable":"« {type} » n’est pas itérable","typeNotSpecializable":"Impossible de spécialiser le type \\"{type}\\"","typeNotSubscriptable":"L’objet de type « {type} » n’est pas sous-scriptible","typeNotSupportBinaryOperator":"Opérateur \\"{operator}\\" non pris en charge pour les types \\"{leftType}\\" et \\"{rightType}\\"","typeNotSupportBinaryOperatorBidirectional":"L\'opérateur \\"{operator}\\" n\'est pas pris en charge pour les types \\"{leftType}\\" et \\"{rightType}\\" lorsque le type attendu est \\"{expectedType}\\"","typeNotSupportUnaryOperator":"L\'opérateur \\"{operator}\\" n\'est pas pris en charge pour le type \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"L’opérateur « {operator} » n’est pas pris en charge pour le type « {type} » quand le type attendu est « {expectedType} »","typeNotUsableWith":"L’objet de type \\"{type}\\" ne peut pas être utilisé avec « with », car il n’implémente pas {method}","typeParameterBoundNotAllowed":"La limite ou la contrainte ne peut pas être utilisée avec un paramètre de type variadique ou ParamSpec","typeParameterConstraintTuple":"La contrainte de paramètre de type doit être un tuple de plusieurs types","typeParameterExistingTypeParameter":"Le paramètre de type « {name} » est déjà utilisé","typeParameterNotDeclared":"Le paramètre de type « {name} » n’est pas inclus dans la liste des paramètres de type pour « {container} »","typeParametersMissing":"Au moins un paramètre de type doit être spécifié","typePartiallyUnknown":"Le type de « {name} » est partiellement inconnu","typeUnknown":"Le type de « {name} » est inconnu","typeVarAssignedName":"TypeVar doit être affecté à une variable nommée « {name} »","typeVarAssignmentMismatch":"Le type \\"{type}\\" ne peut pas être affecté à la variable de type \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar ne peut pas être à la fois lié et contraint","typeVarBoundGeneric":"Le type lié TypeVar ne peut pas être générique","typeVarConstraintGeneric":"Le type de contrainte TypeVar ne peut pas être générique","typeVarDefaultBoundMismatch":"Le type par défaut TypeVar doit être un sous-type du type lié","typeVarDefaultConstraintMismatch":"Le type par défaut TypeVar doit être l\'un des types contraints","typeVarDefaultIllegal":"Les types de variables de type par défaut nécessitent Python 3.13 ou une version plus récente","typeVarDefaultInvalidTypeVar":"Le paramètre de type « {name} » a un type par défaut qui fait référence à une ou plusieurs variables de type hors de portée","typeVarFirstArg":"Nom attendu de TypeVar comme premier argument","typeVarNoMember":"TypeVar « {type} » n’a pas de membre « {name} »","typeVarNotSubscriptable":"TypeVar « {type} » n’est pas subscriptible","typeVarNotUsedByOuterScope":"La variable de type « {name} » n’a aucune signification dans ce contexte","typeVarPossiblyUnsolvable":"La variable de type \\"{name}\\" peut rester non résolue si l\'appelant ne fournit aucun argument pour le paramètre \\"{param}\\"","typeVarScopedToReturnType":"La variable de type \\"{name}\\" est limitée à un appelable dans le type de retour et ne peut pas être référencée dans le corps de la fonction","typeVarSingleConstraint":"TypeVar doit avoir au moins deux types contraints","typeVarTupleConstraints":"TypeVarTuple ne peut pas avoir de contraintes de valeur","typeVarTupleContext":"TypeVarTuple n’est pas autorisé dans ce contexte","typeVarTupleDefaultNotUnpacked":"Le type par défaut TypeVarTuple doit être un tuple décompressé ou TypeVarTuple","typeVarTupleMustBeUnpacked":"L\'opérateur Unpack est requis pour la valeur TypeVarTuple","typeVarTupleUnknownParam":"« {name} » est un paramètre inconnu de TypeVarTuple","typeVarUnknownParam":"\\"{name}\\" est un paramètre inconnu pour TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" est déjà utilisé par une portée externe","typeVarUsedOnlyOnce":"TypeVar « {name} » n’apparaît qu’une seule fois dans la signature de fonction générique","typeVarVariance":"TypeVar ne peut pas être à la fois covariant et contravariant","typeVarWithDefaultFollowsVariadic":"TypeVar « {typeVarName} » a une valeur par défaut et ne peut pas suivre TypeVarTuple « {variadicName} »","typeVarWithoutDefault":"\\"{name}\\" ne peut pas apparaître après \\"{other}\\" dans la liste des paramètres de type car il n\'a pas de type par défaut","typeVarsNotInGenericOrProtocol":"Generic[] ou Protocol[] doit inclure toutes les variables de type","typedDictAccess":"Impossible d’accéder à l’élément dans TypedDict","typedDictAssignedName":"TypedDict doit être affecté à une variable nommée « {name} »","typedDictBadVar":"Les classes TypedDict ne peuvent contenir que des annotations de type","typedDictBaseClass":"Toutes les classes de base pour les classes TypedDict doivent également être des classes TypedDict","typedDictBoolParam":"Paramètre « {name} » attendu avec la valeur True ou False","typedDictClosedExtras":"La classe de base « {name} » est un TypedDict fermé, les éléments supplémentaires doivent être de type « {type} »","typedDictClosedNoExtras":"La classe de base « {name} » est un TypedDict fermé, les éléments supplémentaires ne sont pas autorisés","typedDictDelete":"Impossible de supprimer l’élément dans TypedDict","typedDictEmptyName":"Les noms dans un TypedDict ne peuvent pas être vides","typedDictEntryName":"Littéral de chaîne attendu pour le nom d’entrée du dictionnaire","typedDictEntryUnique":"Les noms dans un dictionnaire doivent être uniques","typedDictExtraArgs":"Arguments TypedDict supplémentaires non pris en charge","typedDictFieldNotRequiredRedefinition":"L’élément TypedDict « {name} » ne peut pas être redéfini comme étant Non requis","typedDictFieldReadOnlyRedefinition":"L’élément TypedDict « {name} » ne peut pas être redéfini comme état En lecture seule","typedDictFieldRequiredRedefinition":"L’élément TypedDict « {name} » ne peut pas être redéfini comme étant Requis","typedDictFirstArg":"Nom de classe TypedDict attendu comme premier argument","typedDictInitsubclassParameter":"TypedDict ne prend pas en charge __init_subclass__ paramètre « {name} »","typedDictNotAllowed":"\\"TypedDict\\" ne peut pas être utilisé dans ce contexte","typedDictSecondArgDict":"Paramètre de mot clé ou de dict attendu en tant que deuxième paramètre","typedDictSecondArgDictEntry":"Entrée de dictionnaire simple attendue","typedDictSet":"Impossible d\'attribuer l\'élément dans TypedDict","unaccessedClass":"La classe \\"{name}\\" n\'est pas accessible","unaccessedFunction":"La fonction « {name} » n’est pas accessible","unaccessedImport":"L’importation « {name} » n’est pas accessible","unaccessedSymbol":"« {name} » n’est pas accessible","unaccessedVariable":"La variable « {name} » n’est pas accessible","unannotatedFunctionSkipped":"L\'analyse de la fonction \\"{name}\\" est ignorée car elle n\'est pas annotée","unaryOperationNotAllowed":"Opérateur unaire non autorisé dans l’annotation de type","unexpectedAsyncToken":"« def », « with » ou « for » attendu pour suivre « async »","unexpectedExprToken":"Jeton inattendu à la fin de l’expression","unexpectedIndent":"Retrait inattendu","unexpectedUnindent":"Unindent non attendu","unhashableDictKey":"La clé du dictionnaire doit être hachable","unhashableSetEntry":"L’entrée set doit être hachable","uninitializedAbstractVariables":"Les variables définies dans la classe de base abstraite ne sont pas initialisées dans la classe finale « {classType} »","uninitializedInstanceVariable":"La variable d’instance « {name} » n’est pas initialisée dans le corps de la classe ou dans la méthode __init__","unionForwardReferenceNotAllowed":"La syntaxe Union ne peut pas être utilisée avec l’opérande de chaîne ; utiliser des guillemets autour de l’expression entière","unionSyntaxIllegal":"Une autre syntaxe pour les unions nécessite Python 3.10 ou une version plus récente","unionTypeArgCount":"L’union requiert au moins deux arguments de type","unionUnpackedTuple":"Union ne peut pas inclure un tuple décompressé","unionUnpackedTypeVarTuple":"Union ne peut pas inclure un TypeVarTuple décompressé","unnecessaryCast":"Appel \\"cast\\" inutile ; le type est déjà \\"{type}\\"","unnecessaryIsInstanceAlways":"Appel d’isinstance inutile ; « {testType} » est toujours une instance de « {classType} »","unnecessaryIsSubclassAlways":"Appel issubclass inutile ; \\"{testType}\\" est toujours une sous-classe de \\"{classType}\\"","unnecessaryPyrightIgnore":"Commentaire \\"# pyright: ignore\\" inutile","unnecessaryPyrightIgnoreRule":"Règle inutile « #ightight: ignore » : « {name} »","unnecessaryTypeIgnore":"Commentaire \\"# type: ignore\\" inutile","unpackArgCount":"Attendu un seul argument de type après \\"Unpack\\"","unpackExpectedTypeVarTuple":"TypeVarTuple ou tuple attendu en tant qu’argument de type pour décompresser","unpackExpectedTypedDict":"Argument de type TypedDict attendu pour Unpack","unpackIllegalInComprehension":"Opération de décompression non autorisée dans la compréhension","unpackInAnnotation":"Opérateur de décompression non autorisé dans l’annotation de type","unpackInDict":"Opération de décompression non autorisée dans les dictionnaires","unpackInSet":"Opérateur de déballage non autorisé dans un ensemble","unpackNotAllowed":"Le décompression n’est pas autorisé dans ce contexte","unpackOperatorNotAllowed":"L’opération de décompression n’est pas autorisée dans ce contexte","unpackTuplesIllegal":"Opération de décompression non autorisée dans les tuples avant Python 3.8","unpackedArgInTypeArgument":"Les arguments décompressés ne peuvent pas être utilisés dans les listes d’arguments de type","unpackedArgWithVariadicParam":"L\'argument décompressé ne peut pas être utilisé pour le paramètre TypeVarTuple","unpackedDictArgumentNotMapping":"L’expression d’argument après ** doit être un mappage avec un type de clé « str »","unpackedDictSubscriptIllegal":"L’opérateur de décompression de dictionnaire dans l’indice n’est pas autorisé","unpackedSubscriptIllegal":"L’opérateur de décompression en indice requiert Python 3.11 ou version ultérieure","unpackedTypeVarTupleExpected":"TypeVarTuple décompressé attendu ; utiliser Unpack[{name1}] ou *{name2}","unpackedTypedDictArgument":"Impossible de faire correspondre l’argument TypedDict décompressé aux paramètres","unreachableCode":"Le code est inaccessible","unreachableExcept":"La clause Except est inaccessible, car l’exception est déjà gérée","unsupportedDunderAllOperation":"L’opération sur « __all__ » n’est pas prise en charge. Par conséquent, la liste de symboles exportée peut être incorrecte","unusedCallResult":"Le résultat de l\'expression d\'appel est de type \\"{type}\\" et n\'est pas utilisé ; affecter à la variable \\"_\\" si c\'est intentionnel","unusedCoroutine":"Le résultat de l’appel de fonction asynchrone n’est pas utilisé ; utiliser « await » ou affecter le résultat à la variable","unusedExpression":"La valeur de l\'expression n\'est pas utilisée","varAnnotationIllegal":"Les annotations de type pour les variables nécessitent Python 3.6 ou une version ultérieure ; utiliser le commentaire de type pour la compatibilité avec les versions précédentes","variableFinalOverride":"La variable « {name} » est marquée comme finale et remplace la variable non finale du même nom dans la classe « {className} »","variadicTypeArgsTooMany":"La liste d’arguments de type peut avoir au plus un TypeVarTuple ou tuple décompressé","variadicTypeParamTooManyAlias":"L’alias de type peut avoir au plus un paramètre de type TypeVarTuple, mais a reçu plusieurs ({names})","variadicTypeParamTooManyClass":"La classe générique peut avoir au plus un paramètre de type TypeVarTuple, mais en a reçu plusieurs ({names})","walrusIllegal":"L’opérateur « := » nécessite Python 3.8 ou version ultérieure","walrusNotAllowed":"L’opérateur « := » n’est pas autorisé dans ce contexte sans parenthèses adjacentes","wildcardInFunction":"Importation de caractères génériques non autorisée dans une classe ou une fonction","wildcardLibraryImport":"Importation de caractères génériques à partir d\'une bibliothèque non autorisée","wildcardPatternTypePartiallyUnknown":"Le type capturé par le modèle générique est partiellement inconnu","wildcardPatternTypeUnknown":"Le type capturé par le modèle générique est inconnu","yieldFromIllegal":"L’utilisation de « yield from » nécessite Python 3.3 ou version ultérieure","yieldFromOutsideAsync":"« yield from » non autorisé dans une fonction asynchrone","yieldOutsideFunction":"\\"rendement\\" non autorisé en dehors d\'une fonction ou d\'un lambda","yieldWithinListCompr":"« yield » non autorisé dans une compréhension de liste","zeroCaseStatementsFound":"L\'instruction de correspondance doit inclure au moins une instruction case","zeroLengthTupleNotAllowed":"Le tuple de longueur nulle n’est pas autorisé dans ce contexte"},"DiagnosticAddendum":{"annotatedNotAllowed":"Impossible d’utiliser le formulaire spécial « Annoté » avec les vérifications d’instance et de classe","argParam":"L’argument correspond au paramètre « {paramName} »","argParamFunction":"L’argument correspond au paramètre « {paramName} » dans la fonction « {functionName} »","argsParamMissing":"Le paramètre \\"*{paramName}\\" n\'a pas de paramètre correspondant","argsPositionOnly":"Non-concordance des paramètres de position uniquement ; attendu {expected} mais reçu {received}","argumentType":"Le type d’argument est « {type} »","argumentTypes":"Types d\'argument : ({types})","assignToNone":"Le type ne peut pas être affecté au type « None »","asyncHelp":"Vouliez-vous dire \\"asynchrone avec\\" ?","baseClassIncompatible":"La classe de base « {baseClass} » n’est pas compatible avec le type « {type} »","baseClassIncompatibleSubclass":"La classe de base « {baseClass} » dérive de « {subclass} » qui est incompatible avec le type « {type} »","baseClassOverriddenType":"La classe de base « {baseClass} » fournit le type « {type} », qui est remplacé","baseClassOverridesType":"La classe de base \\"{baseClass}\\" remplace le type \\"{type}\\"","bytesTypePromotions":"Définir disableBytesTypePromotions sur false pour activer le comportement de promotion de type pour « bytearray » et « memoryview »","conditionalRequiresBool":"La méthode __bool__ pour le type « {operandType} » retourne le type « {boolReturnType} » plutôt que « bool »","dataClassFieldLocation":"Déclaration de champ","dataClassFrozen":"« {name} » est figé","dataProtocolUnsupported":"« {name} » est un protocole de données","descriptorAccessBindingFailed":"Échec de la liaison du « {name} » de méthode pour la classe de descripteur « {className} »","descriptorAccessCallFailed":"Échec de l’appel du « {name} » de méthode pour la classe de descripteur « {className} »","finalMethod":"Méthode finale","functionParamDefaultMissing":"Le paramètre \\"{name}\\" n\'a pas d\'argument par défaut","functionParamName":"Incompatibilité de nom de paramètre : « {destName} » et « {srcName} »","functionParamPositionOnly":"Non-correspondance des paramètres position uniquement ; le paramètre « {name} » n’est pas en position seule","functionReturnTypeMismatch":"Le type de retour de fonction \\"{sourceType}\\" est incompatible avec le type \\"{destType}\\"","functionTooFewParams":"La fonction accepte trop peu de paramètres positionnels ; {expected} attendu, mais {received} reçu","functionTooManyParams":"La fonction accepte trop de paramètres positionnels ; {expected} attendu, mais {received} reçu","genericClassNotAllowed":"Type générique avec des arguments de type non autorisé pour les vérifications d’instance ou de classe","incompatibleDeleter":"La méthode du deleter de propriété n’est pas compatible","incompatibleGetter":"La méthode de récupération de propriété est incompatible","incompatibleSetter":"La méthode setter de propriété n’est pas compatible","initMethodLocation":"La méthode __init__ est définie dans la classe « {type} »","initMethodSignature":"La signature de __init__ est « {type} »","initSubclassLocation":"La méthode __init_subclass__ est définie dans la classe « {name} »","invariantSuggestionDict":"Envisagez de passer de « dict » à « Mapping », qui est covariant dans le type valeur","invariantSuggestionList":"Envisagez de passer de « list » à « Sequence » qui est covariant","invariantSuggestionSet":"Pensez à passer de \\"set\\" à \\"Container\\" qui est covariant","keyNotRequired":"\\"{name}\\" n\'est pas une clé requise dans \\"{type}\\", donc l\'accès peut entraîner une exception d\'exécution","keyReadOnly":"« {name} » est une clé en lecture seule dans « {type} »","keyRequiredDeleted":"« {name} » est une clé obligatoire et ne peut pas être supprimée","keyUndefined":"« {name} » n’est pas une clé définie dans « {type} »","kwargsParamMissing":"Le paramètre \\"**{paramName}\\" n\'a pas de paramètre correspondant","listAssignmentMismatch":"Le type « {type} » n’est pas compatible avec la liste cible","literalAssignmentMismatch":"« {sourceType} » ne peut pas être affecté au type « {destType} »","matchIsNotExhaustiveHint":"Si la gestion exhaustive n’est pas prévue, ajoutez « case _: pass »","matchIsNotExhaustiveType":"Type non géré : « {type} »","memberAssignment":"L\'expression de type \\"{type}\\" ne peut pas être attribuée au membre \\"{name}\\" de la classe \\"{classType}\\"","memberIsAbstract":"« {type}.{name} » n’est pas implémenté","memberIsAbstractMore":"et {count} autres...","memberIsClassVarInProtocol":"« {name} » est défini en tant que ClassVar dans le protocole","memberIsFinalInProtocol":"« {name} » est marqué final dans le protocole","memberIsInitVar":"Le membre « {name} » est un champ d’initialisation uniquement","memberIsInvariant":"« {name} » est invariant, car il est mutable","memberIsNotClassVarInClass":"« {name} » doit être défini en tant que ClassVar pour être compatible avec le protocole","memberIsNotClassVarInProtocol":"« {name} » n’est pas défini en tant que ClassVar dans le protocole","memberIsNotFinalInProtocol":"\\"{name}\\" n\'est pas marqué Final dans le protocole","memberIsWritableInProtocol":"« {name} » est accessible en écriture dans le protocole","memberSetClassVar":"Le membre \\"{name}\\" ne peut pas être attribué via une instance de classe car il s\'agit d\'une ClassVar","memberTypeMismatch":"« {name} » est un type incompatible","memberUnknown":"Le membre « {name} » est inconnu","metaclassConflict":"La métaclasse « {metaclass1} » est en conflit avec « {metaclass2} »","missingDeleter":"La méthode de suppression de propriétés est manquante","missingGetter":"La méthode getter de propriété est manquante","missingSetter":"La méthode de définition de propriété est manquante","namedParamMissingInDest":"Le paramètre de mot clé « {name} » est manquant dans la destination","namedParamMissingInSource":"Le paramètre de mot-clé \\"{name}\\" est manquant dans la source","namedParamTypeMismatch":"Impossible d’affecter le paramètre de mot clé « {name} » de type « {sourceType} » au type « {destType} »","namedTupleNotAllowed":"NamedTuple ne peut pas être utilisé pour les vérifications d’instance ou de classe","newMethodLocation":"La méthode __new__ est définie dans la classe « {type} »","newMethodSignature":"La signature de __new__ est « {type} »","newTypeClassNotAllowed":"La classe créée avec NewType ne peut pas être utilisée avec des vérifications de instance et de classe","noOverloadAssignable":"Aucune fonction surchargée ne correspond au type « {type} »","noneNotAllowed":"Aucun ne peut être utilisé pour les vérifications de instance ou de classe","orPatternMissingName":"Noms manquants : {name}","overloadIndex":"La surcharge {index} est la correspondance la plus proche","overloadNotAssignable":"Une ou plusieurs surcharges de « {name} » ne sont pas assignables","overloadSignature":"La signature de surcharge est définie ici","overriddenMethod":"Méthode substituée","overriddenSymbol":"Symbole substitué","overrideInvariantMismatch":"Le type de remplacement \\"{overrideType}\\" n\'est pas le même que le type de base \\"{baseType}\\"","overrideIsInvariant":"La variable est mutable donc son type est invariant","overrideNoOverloadMatches":"Aucune signature de surcharge dans le remplacement n’est compatible avec la méthode de base","overrideNotClassMethod":"La méthode de base est déclarée en tant que classmethod, mais la substitution n’est pas","overrideNotInstanceMethod":"La méthode de base est déclarée en tant que méthode d\'instance mais la substitution n\'est pas","overrideNotStaticMethod":"La méthode de base est déclarée comme staticmethod, mais la substitution n’est pas","overrideOverloadNoMatch":"Le remplacement ne gère pas toutes les surcharges de la méthode de base","overrideOverloadOrder":"Les surcharges pour la méthode de remplacement doivent être dans le même ordre que la méthode de base","overrideParamKeywordNoDefault":"Non-concordance du paramètre de mot-clé \\"{name}\\" : le paramètre de base a une valeur d\'argument par défaut, le paramètre de remplacement n\'en a pas","overrideParamKeywordType":"Incompatibilité de type du paramètre de mot clé \\"{name}\\" : le paramètre de base est de type \\"{baseType}\\", le paramètre de remplacement est de type \\"{overrideType}\\"","overrideParamName":"Incompatibilité de nom de paramètre {index} : le paramètre de base est nommé \\"{baseName}\\", le paramètre de remplacement est nommé \\"{overrideName}\\"","overrideParamNameExtra":"Le paramètre « {name} » est manquant dans la base","overrideParamNameMissing":"Le paramètre \\"{name}\\" est manquant dans le remplacement","overrideParamNamePositionOnly":"Incompatibilité du paramètre {index} : le paramètre de base \\"{baseName}\\" est un paramètre de mot-clé, le paramètre de remplacement est uniquement de position","overrideParamNoDefault":"Non-concordance du paramètre {index} : le paramètre de base a une valeur d\'argument par défaut, le paramètre de remplacement n\'en a pas","overrideParamType":"Incompatibilité de type de paramètre {index} : le paramètre de base est de type \\"{baseType}\\", le paramètre de remplacement est de type \\"{overrideType}\\"","overridePositionalParamCount":"Non-concordance du nombre de paramètres positionnels ; la méthode de base a {baseCount}, mais la substitution a {overrideCount}","overrideReturnType":"Incompatibilité de type de retour : la méthode de base retourne le type « {baseType} », la substitution retourne le type « {overrideType} »","overrideType":"La classe de base définit le type comme « {type} »","paramAssignment":"Paramètre {index} : impossible d’affecter le type « {sourceType} » au type « {destType} »","paramSpecMissingInOverride":"Les paramètres ParamSpec sont manquants dans la méthode de remplacement","paramType":"Le type de paramètre est « {paramType} »","privateImportFromPyTypedSource":"Importer à partir de « {module} » à la place","propertyAccessFromProtocolClass":"Une propriété définie dans une classe de protocole n\'est pas accessible en tant que variable de classe","propertyMethodIncompatible":"La méthode de propriété « {name} » n’est pas compatible","propertyMethodMissing":"La méthode de propriété \\"{name}\\" est manquante dans le remplacement","propertyMissingDeleter":"La propriété « {name} » n’a pas de deleter défini","propertyMissingSetter":"La propriété « {name} » n’a pas de méthode setter définie","protocolIncompatible":"\\"{sourceType}\\" est incompatible avec le protocole \\"{destType}\\"","protocolMemberMissing":"« {name} » n’est pas présent","protocolRequiresRuntimeCheckable":"La classe de protocole doit être @runtime_checkable à utiliser avec des vérifications d’instance et de classe","protocolSourceIsNotConcrete":"\\"{sourceType}\\" n\'est pas un type de classe concret et ne peut pas être affecté au type \\"{destType}\\"","protocolUnsafeOverlap":"Les attributs de « {name} » ont les mêmes noms que le protocole","pyrightCommentIgnoreTip":"Utilisez « #ight: ignore[<diagnostic rules>] pour supprimer les diagnostics pour une seule ligne","readOnlyAttribute":"L’attribut « {name} » est en lecture seule","seeClassDeclaration":"Voir la déclaration de classe","seeDeclaration":"Voir la déclaration","seeFunctionDeclaration":"Voir la déclaration de fonction","seeMethodDeclaration":"Voir la déclaration de méthode","seeParameterDeclaration":"Voir la déclaration des paramètres","seeTypeAliasDeclaration":"Voir la déclaration d’alias de type","seeVariableDeclaration":"Voir déclaration de variable","tupleAssignmentMismatch":"Le type \\"{type}\\" est incompatible avec le tuple cible","tupleEntryTypeMismatch":"Le type de l’entrée de tuple {entry} est incorrect","tupleSizeIndeterminateSrc":"Incompatibilité de taille de tuple ; attendu {expected} mais reçu pour une durée indéterminée","tupleSizeIndeterminateSrcDest":"Incompatibilité de taille de tuple : attente de {expected} ou plus, mais réception indéterminée","tupleSizeMismatch":"Incompatibilité de taille de tuple ; attendu {expected} mais reçu {received}","tupleSizeMismatchIndeterminateDest":"Incompatibilité de taille de tuple : attente de {expected} ou plus, mais réception de {received}","typeAliasInstanceCheck":"L’alias de type créé avec l’instruction « type » ne peut pas être utilisé avec des vérifications d’instance et de classe","typeAssignmentMismatch":"Impossible d’affecter le type « {sourceType} » au type « {destType} »","typeBound":"Le type « {sourceType} » n’est pas compatible avec le type lié « {destType} » pour la variable de type « {name} »","typeConstrainedTypeVar":"Le «{type}» de type n’est pas compatible avec les «{name}» de variable de type contrainte","typeIncompatible":"« {sourceType} » n’est pas compatible avec « {destType} »","typeNotClass":"« {type} » n’est pas une classe","typeNotStringLiteral":"\\"{type}\\" n\'est pas un littéral de chaîne","typeOfSymbol":"Le type de \\"{name}\\" est \\"{type}\\"","typeParamSpec":"Le type « {type} » n’est pas compatible avec ParamSpec « {name} »","typeUnsupported":"Le type « {type} » n’est pas pris en charge","typeVarDefaultOutOfScope":"La variable de type « {name} » n’est pas dans l’étendue","typeVarIsContravariant":"Le paramètre de type \\"{name}\\" est contravariant, mais \\"{sourceType}\\" n\'est pas un supertype de \\"{destType}\\"","typeVarIsCovariant":"Le paramètre de type \\"{name}\\" est covariant, mais \\"{sourceType}\\" n\'est pas un sous-type de \\"{destType}\\"","typeVarIsInvariant":"Le paramètre de type \\"{name}\\" est invariant, mais \\"{sourceType}\\" n\'est pas le même que \\"{destType}\\"","typeVarNotAllowed":"TypeVar non autorisé pour les vérifications d’instance ou de classe","typeVarTupleRequiresKnownLength":"TypeVarTuple ne peut pas être lié à un tuple de longueur inconnue","typeVarUnnecessarySuggestion":"Utilisez plutôt {type}","typeVarUnsolvableRemedy":"Fournir une surcharge qui spécifie le type de retour lorsque l’argument n’est pas fourni","typeVarsMissing":"Variables de type manquantes : {names}","typedDictBaseClass":"La classe \\"{type}\\" n\'est pas un TypedDict","typedDictClassNotAllowed":"Classe TypedDict non autorisée pour les vérifications d’instance ou de classe","typedDictClosedExtraNotAllowed":"Impossible d’ajouter l’élément « {name} »","typedDictClosedExtraTypeMismatch":"Impossible d’ajouter l’élément « {name} » avec le type « {type} »","typedDictClosedFieldNotRequired":"Impossible d’ajouter l’élément « {name} », car il doit être Non requis","typedDictExtraFieldNotAllowed":"« {name} » n’est pas présent dans « {type} »","typedDictExtraFieldTypeMismatch":"Le type de « {name} » est incompatible avec le type « __extra_items__ » dans « {type} »","typedDictFieldMissing":"« {name} » est manquant dans « {type} »","typedDictFieldNotReadOnly":"« {name} » n’est pas en lecture seule dans « {type} »","typedDictFieldNotRequired":"« {name} » n’est pas obligatoire dans « {type} »","typedDictFieldRequired":"« {name} » est obligatoire dans « {type} »","typedDictFieldTypeMismatch":"Le type « {type} » n\'est pas attribuable à l’élément « {name} »","typedDictFieldUndefined":"« {name} » est un élément non défini dans le type « {type} »","typedDictFinalMismatch":"« {sourceType} » n’est pas compatible avec « {destType} » en raison d’une incompatibilité de @final","typedDictKeyAccess":"Utilisez [« {name} »] pour référencer l’élément dans TypedDict","typedDictNotAllowed":"TypedDict ne peut pas être utilisé pour les vérifications d’instance ou de classe","unhashableType":"Le type \\"{type}\\" n\'est pas hachable","uninitializedAbstractVariable":"La variable d’instance « {name} » est définie dans la classe de base abstraite « {classType} » mais n’est pas initialisée","unreachableExcept":"« {exceptionType} » est une sous-classe de « {parentType} »","useDictInstead":"Utilisez Dict[T1, T2] pour indiquer un type de dictionnaire","useListInstead":"Utilisez List[T] pour indiquer un type de liste ou Union[T1, T2] pour indiquer un type d\'union","useTupleInstead":"Utiliser tuple[T1, ..., Tn] pour indiquer un type de tuple ou Union[T1, T2] pour indiquer un type d’union","useTypeInstead":"Utiliser le type[T] à la place","varianceMismatchForClass":"La variance de l\'argument de type \\"{typeVarName}\\" est incompatible avec la classe de base \\"{className}\\"","varianceMismatchForTypeAlias":"La variance de l\'argument de type \\"{typeVarName}\\" est incompatible avec \\"{typeAliasParam}\\""}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.it.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.it.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Crea stub di tipo","createTypeStubFor":"Crea stub di tipo per \\"{moduleName}\\"","executingCommand":"Esecuzione del comando","filesToAnalyzeCount":"{count} file da analizzare","filesToAnalyzeOne":"1 file da analizzare","findingReferences":"Ricerca dei riferimenti in corso","organizeImports":"Organizza importazioni","renameShadowedFile":"Rinomina \\"{oldFile}\\" in \\"{newFile}\\""},"Completion":{"autoImportDetail":"Importazione automatica","indexValueDetail":"Valore dell’indice"},"Diagnostic":{"abstractMethodInvocation":"Impossibile chiamare il metodo \\"{method}\\" perché è astratto e non implementato","annotatedParamCountMismatch":"Numero di annotazioni dei parametro non corrispondente: previsto {expected} ma ricevuto {received}","annotatedTypeArgMissing":"Previsto un argomento di tipo e una o più annotazioni per \\"Annotato\\"","annotationFormatString":"Le annotazioni di tipo non possono usare valori letterali stringa di formato (stringhe f)","annotationNotSupported":"Annotazione di tipo non supportata per questa istruzione","annotationSpansStrings":"Le annotazioni di tipo non possono estendersi su più valori letterali stringa","annotationStringEscape":"Le annotazioni di tipo non possono contenere caratteri di escape","argAssignment":"Non è possibile assegnare l\'argomento di tipo \\"{argType}\\" al parametro di tipo \\"{paramType}\\"","argAssignmentFunction":"Non è possibile assegnare l\'argomento di tipo \\"{argType}\\" al parametro di tipo \\"{paramType}\\" nella funzione \\"{functionName}\\"","argAssignmentParam":"Non è possibile assegnare l\'argomento di tipo \\"{argType}\\" al parametro \\"{paramName}\\" di tipo \\"{paramType}\\"","argAssignmentParamFunction":"Non è possibile assegnare l\'argomento di tipo \\"{argType}\\" al parametro \\"{paramName}\\" di tipo \\"{paramType}\\" nella funzione \\"{functionName}\\"","argMissingForParam":"Manca l\'argomento per il parametro {name}","argMissingForParams":"Argomenti mancanti per i parametri {names}","argMorePositionalExpectedCount":"Sono previsti {expected} altri argomenti posizionali","argMorePositionalExpectedOne":"Previsto 1 altro argomento posizionale","argPositional":"Argomento posizionale previsto","argPositionalExpectedCount":"Sono previsti {expected} argomenti posizionali","argPositionalExpectedOne":"Previsto 1 argomento posizionale","argTypePartiallyUnknown":"Tipo di argomento parzialmente sconosciuto","argTypeUnknown":"Il tipo di argomento è sconosciuto","assertAlwaysTrue":"L\'espressione assert restituisce sempre true","assertTypeArgs":"\\"assert_type\\" prevede due argomenti posizionali","assertTypeTypeMismatch":"\\"assert_type\\" non corrispondente: previsto \\"{expected}\\" ma ricevuto \\"{received}\\"","assignmentExprComprehension":"La destinazione dell\'espressione di assegnazione \\"{name}\\" non può usare lo stesso nome della comprensione per la destinazione","assignmentExprContext":"L\'espressione di assegnazione deve essere all\'interno di modulo, funzione o lambda","assignmentExprInSubscript":"Le espressioni di assegnazione all\'interno di un pedice sono supportate solo in Python 3.10 e versioni successive","assignmentInProtocol":"Le variabili di istanza o di classe all\'interno di una classe Protocollo devono essere dichiarate esplicitamente nel corpo della classe","assignmentTargetExpr":"L\'espressione non può essere una destinazione di assegnazione","asyncNotInAsyncFunction":"L\'uso di \\"async\\" non è consentito al di fuori della funzione asincrona","awaitIllegal":"L\'uso di \\"await\\" richiede Python 3.5 o versione successiva","awaitNotAllowed":"Le annotazioni di tipo non possono usare \\"await\\"","awaitNotInAsync":"\\"await\\" consentito solo all\'interno della funzione asincrona","backticksIllegal":"Le espressioni racchiuse tra backticks non sono supportate in Python 3.x; usare la reimpostazione","baseClassCircular":"La classe non può derivare da se stessa","baseClassFinal":"La classe di base \\"{type}\\" è contrassegnata come finale e non può essere sottoclassata","baseClassIncompatible":"Le classi di base di {type} sono incompatibili tra di loro","baseClassInvalid":"L\'argomento della classe deve essere una classe base","baseClassMethodTypeIncompatible":"Le classi di base per la classe \\"{classType}\\" definiscono il metodo \\"{name}\\" in modo incompatibile","baseClassUnknown":"Il tipo della classe di base è sconosciuto. È in corso il tentativo di determinare il tipo della classe derivata","baseClassVariableTypeIncompatible":"Le classi di base per la classe \\"{classType}\\" definiscono la variabile \\"{name}\\" in modo incompatibile","binaryOperationNotAllowed":"Operatore binario non consentito nell\'annotazione di tipo","bindTypeMismatch":"Non è stato possibile associare il metodo \\"{methodName}\\" perché non è possibile assegnare\\"{type}\\" al parametro \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" può essere usato solo all\'interno di un ciclo","callableExtraArgs":"Sono previsti solo due argomenti di tipo per \\"Callable\\"","callableFirstArg":"Previsto elenco dei tipi di parametro o \\"...\\"","callableNotInstantiable":"Non è possibile creare un\'istanza del tipo \\"{type}\\"","callableSecondArg":"È previsto un tipo restituito come secondo argomento di tipo per \\"Callable\\"","casePatternIsIrrefutable":"Il criterio inconfutabile è consentito solo per l\'ultima istruzione case","classAlreadySpecialized":"Il tipo \\"{type}\\" è già specializzato","classDecoratorTypeUnknown":"L\'elemento Decorator di classe non tipizzato nasconde il tipo di classe. l\'elemento Decorator verrà ignorato","classDefinitionCycle":"La definizione della classe per \\"{name}\\" dipende da se stessa","classGetItemClsParam":"__class_getitem__ override deve accettare un parametro \\"cls\\"","classMethodClsParam":"I metodi di classe devono accettare un parametro \\"cls\\"","classNotRuntimeSubscriptable":"Il pedice per la classe \\"{name}\\" genererà un\'eccezione di runtime; racchiudere l\'annotazione di tipo tra virgolette","classPatternBuiltInArgPositional":"Il modello di classe accetta solo un sotto pattern posizionale","classPatternPositionalArgCount":"Troppi modelli posizionale per la classe \\"{type}\\"; previsto {expected} ma ottenuto {received}","classPatternTypeAlias":"\\"{type}\\" non può essere usato in uno schema di classe, perché è un alias di tipo specializzato","classPropertyDeprecated":"Le proprietà della classe sono deprecate in Python 3.11 e non saranno supportate in Python 3.13","classTypeParametersIllegal":"La sintassi del parametro del tipo di classe richiede Python 3.12 o versione successiva","classVarFirstArgMissing":"È previsto un argomento tipo dopo \\"ClassVar\\"","classVarNotAllowed":"\\"ClassVar\\" non consentito in questo contesto","classVarOverridesInstanceVar":"La variabile di classe \\"{name}\\" esegue l\'override della variabile di istanza con lo stesso nome nella classe \\"{className}\\"","classVarTooManyArgs":"Previsto un solo argomento tipo dopo \\"ClassVar\\"","classVarWithTypeVar":"Il tipo \\"ClassVar\\" non può includere variabili di tipo","clsSelfParamTypeMismatch":"Il tipo di parametro \\"{name}\\" deve essere un supertipo della relativa classe \\"{classType}\\"","codeTooComplexToAnalyze":"Il codice è troppo complesso per l\'analisi. ridurre la complessità eseguendo il refactoring in subroutine o riducendo i percorsi del codice condizionale","collectionAliasInstantiation":"Non è possibile creare un\'istanza del tipo \\"{type}\\". In alternativa, usare \\"{alias}\\"","comparisonAlwaysFalse":"La condizione restituisce sempre False perché i tipi \\"{leftType}\\" e \\"{rightType}\\" non si sovrappongono","comparisonAlwaysTrue":"La condizione restituisce sempre True perché i tipi \\"{leftType}\\" e \\"{rightType}\\" non si sovrappongono","comprehensionInDict":"Non è possibile usare la comprensione con altre voci del dizionario","comprehensionInSet":"Non è possibile usare la comprensione con altre voci del set","concatenateContext":"“Concatena” non è consentito in questo contesto","concatenateParamSpecMissing":"L\'ultimo argomento di tipo per \\"Concatenate\\" deve essere un ParamSpec o \\"...\\"","concatenateTypeArgsMissing":"\\"Concatena\\" richiede almeno due argomenti tipo","conditionalOperandInvalid":"Operando condizionale non valido di tipo \\"{type}\\"","constantRedefinition":"\\"{name}\\" è costante (perché è in maiuscolo) e non può essere ridefinita","constructorNoArgs":"Nessun argomento previsto per il costruttore \\"{type}\\"","constructorParametersMismatch":"Mancata corrispondenza tra firma di __new__ e __init__ nella classe \\"{classType}\\"","containmentAlwaysFalse":"L\'espressione restituisce sempre False perché i tipi \\"{leftType}\\" e \\"{rightType}\\" non si sovrappongono","containmentAlwaysTrue":"L\'espressione restituisce sempre True perché i tipi \\"{leftType}\\" e \\"{rightType}\\" non si sovrappongono","continueInFinally":"Non è possibile usare \\"continue\\" all\'interno di una clausola finally","continueOutsideLoop":"\\"continue\\" può essere usato solo all\'interno di un ciclo","coroutineInConditionalExpression":"L\'espressione condizionale fa riferimento a una coroutine che restituisce sempre True","dataClassBaseClassFrozen":"Una classe non bloccata non può ereditare da una classe bloccata","dataClassBaseClassNotFrozen":"Una classe bloccata non può ereditare da una classe non bloccata","dataClassConverterFunction":"L\'argomento di tipo \\"{argType}\\" non è un convertitore valido per il campo \\"{fieldName}\\" di tipo \\"{fieldType}\\"","dataClassConverterOverloads":"Nessun overload di \\"{funcName}\\" è un convertitore valido per il campo \\"{fieldName}\\" di tipo \\"{fieldType}\\"","dataClassFieldWithDefault":"I campi senza valori predefiniti non possono essere visualizzati dopo i campi con valori predefiniti","dataClassFieldWithPrivateName":"Il campo dataclass non può usare un nome privato","dataClassFieldWithoutAnnotation":"Il campo dataclass senza annotazione del tipo causerà un\'eccezione di runtime","dataClassPostInitParamCount":"Dataclass __post_init__ conteggio dei parametri non corretto; il numero di campi InitVar è {expected}","dataClassPostInitType":"Dataclass __post_init__ tipo di parametro del metodo non corrispondente per il campo \\"{fieldName}\\"","dataClassSlotsOverwrite":"__slots__ è già definito nella classe","dataClassTransformExpectedBoolLiteral":"Espressione prevista che restituisce in modo statico True o False","dataClassTransformFieldSpecifier":"È prevista una tupla di classi o funzioni ma è stato ricevuto il tipo \\"{type}\\"","dataClassTransformPositionalParam":"Tutti gli argomenti di \\"dataclass_transform\\" devono essere argomenti di parole chiave","dataClassTransformUnknownArgument":"Argomento \\"{name}\\" non supportato da dataclass_transform","dataProtocolInSubclassCheck":"I protocolli dati (che includono attributi non di metodo) non sono consentiti nelle chiamate issubclass","declaredReturnTypePartiallyUnknown":"Il tipo restituito dichiarato \\"{returnType}\\" è parzialmente sconosciuto","declaredReturnTypeUnknown":"Il tipo restituito dichiarato è sconosciuto","defaultValueContainsCall":"Chiamate di funzione e oggetti modificabili non consentiti all\'interno dell\'espressione del valore predefinito del parametro","defaultValueNotAllowed":"Il parametro con \\"*\\" o \\"**\\" non può avere un valore predefinito","delTargetExpr":"Non è possibile eliminare l\'espressione","deprecatedClass":"La classe \\"{name}\\" è deprecata","deprecatedConstructor":"Il costruttore per la classe \\"{name}\\" è deprecato","deprecatedDescriptorDeleter":"Il metodo \\"__delete__\\" per il descrittore \\"{name}\\" è deprecato","deprecatedDescriptorGetter":"Il metodo \\"__get__\\" per il descrittore \\"{name}\\" è deprecato","deprecatedDescriptorSetter":"Il metodo \\"__set__\\" per il descrittore \\"{name}\\" è deprecato","deprecatedFunction":"La funzione \\"{name}\\" è deprecata","deprecatedMethod":"Il metodo \\"{name}\\" nella classe \\"{className}\\" è deprecato","deprecatedPropertyDeleter":"Il deleter per la proprietà \\"{name}\\" è deprecato","deprecatedPropertyGetter":"Il getter per la proprietà \\"{name}\\" è deprecato","deprecatedPropertySetter":"Il setter per la proprietà \\"{name}\\" è deprecato","deprecatedType":"Questo tipo è deprecato a partire da Python {version}; usa \\"{replacement}\\"","dictExpandIllegalInComprehension":"Espansione del dizionario non consentita nella comprensione","dictInAnnotation":"Espressione dizionario non consentita nell\'annotazione di tipo","dictKeyValuePairs":"Le voci del dizionario devono contenere coppie chiave-valore","dictUnpackIsNotMapping":"Mapping previsto per l\'operatore di decompressione del dizionario","dunderAllSymbolNotPresent":"\\"{name}\\" è specificato in __all__ ma non è presente nel modulo","duplicateArgsParam":"È consentito un solo parametro \\"*\\"","duplicateBaseClass":"Classe di base duplicata non consentita","duplicateCapturePatternTarget":"La destinazione di acquisizione \\"{name}\\" non può comparire più di una volta all\'interno dello stesso schema","duplicateCatchAll":"È consentita una sola clausola catch-all tranne","duplicateEnumMember":"Il membro di enumerazione \\"{name}\\" è già dichiarato","duplicateGenericAndProtocolBase":"È consentita una sola classe di base Generic(...) o Protocol[...]","duplicateImport":"\\"{importName}\\" è stato importato più di una volta","duplicateKeywordOnly":"È consentito un solo separatore \\"*\\"","duplicateKwargsParam":"È consentito un solo parametro \\"**\\"","duplicateParam":"“{name}\\" parametro duplicato","duplicatePositionOnly":"È consentito un solo parametro \\"/\\"","duplicateStarPattern":"In una sequenza di criteri è consentito un solo criterio \\"*\\"","duplicateStarStarPattern":"È consentita una sola voce \\"**\\"","duplicateUnpack":"Nell\'elenco è consentita una sola operazione di decompressione","ellipsisAfterUnpacked":"\\"...\\" non può essere usato con una tupla o una tupla o TypeVarTuple non compressa","ellipsisContext":"\\"...\\" non è consentito in questo contesto","ellipsisSecondArg":"\\"...\\" è consentito solo come secondo di due argomenti","enumClassOverride":"La classe di enumerazione \\"{name}\\" è finale e non può essere sottoclassata","exceptionGroupIncompatible":"La sintassi del gruppo di eccezioni (\\"except*\\") richiede Python 3.11 o versione successiva","exceptionTypeIncorrect":"\\"{type}\\" non deriva da BaseException","exceptionTypeNotClass":"\\"{type}\\" non è una classe di eccezione valida","exceptionTypeNotInstantiable":"Il costruttore per il tipo di eccezione \\"{type}\\" richiede uno o più argomenti","expectedAfterDecorator":"Dichiarazione di funzione o classe prevista dopo l’elemento Decorator","expectedArrow":"Previsto \\"->\\" seguito da un\'annotazione di tipo restituito","expectedAsAfterException":"Previsto \\"as\\" dopo il tipo di eccezione","expectedAssignRightHandExpr":"Espressione prevista a destra di \\"=\\"","expectedBinaryRightHandExpr":"Espressione prevista a destra dell\'operatore","expectedBoolLiteral":"È previsto True o False","expectedCase":"Prevista istruzione \\"case\\"","expectedClassName":"Nome classe previsto","expectedCloseBrace":"\\"{\\" non è stato chiuso","expectedCloseBracket":"\\"[\\" non è stato chiuso","expectedCloseParen":"\\"(\\" non è stato chiuso","expectedColon":"Previsto \\":\\"","expectedComplexNumberLiteral":"È previsto un valore letterale di numero complesso per i criteri di ricerca","expectedDecoratorExpr":"Il modulo dell\'espressione non è supportato per l\'elemento Decorator precedente a Python 3.9","expectedDecoratorName":"È previsto un nome di elemento Decorator","expectedDecoratorNewline":"Prevista nuova riga alla fine dell\'elemento Decorator","expectedDelExpr":"Espressione prevista dopo \\"del\\"","expectedElse":"Previsto \\"else\\"","expectedEquals":"Previsto \\"=\\"","expectedExceptionClass":"Classe od oggetto di eccezione non valido","expectedExceptionObj":"Previsto oggetto eccezione, classe eccezione o Nessuno","expectedExpr":"Espressione prevista","expectedFunctionAfterAsync":"Prevista definizione di funzione dopo \\"async\\"","expectedFunctionName":"È previsto un nome di funzione dopo \\"def\\"","expectedIdentifier":"Identificatore previsto","expectedImport":"Previsto \\"import\\"","expectedImportAlias":"Simbolo previsto dopo \\"as\\"","expectedImportSymbols":"Sono previsti uno o più nomi di simboli dopo l\'importazione","expectedIn":"previsto \'in\'","expectedInExpr":"Espressione prevista dopo \\"in\\"","expectedIndentedBlock":"Previsto un blocco rientrato","expectedMemberName":"È previsto un nome di membro dopo \\".\\"","expectedModuleName":"Nome del modulo previsto","expectedNameAfterAs":"È previsto il nome del simbolo dopo \\"as\\"","expectedNamedParameter":"Il parametro della parola chiave deve seguire \\"*\\"","expectedNewline":"Prevista nuova riga","expectedNewlineOrSemicolon":"Le istruzioni devono essere separate da nuove righe o punti e virgola","expectedOpenParen":"Previsto \\"(\\"","expectedParamName":"Nome del parametro previsto","expectedPatternExpr":"Espressione del criterio prevista","expectedPatternSubjectExpr":"Prevista espressione del soggetto del criterio","expectedPatternValue":"Espressione del valore del criterio prevista nel formato \\"a.b\\"","expectedReturnExpr":"Espressione prevista dopo \\"return\\"","expectedSliceIndex":"Prevista espressione di indice o sezione","expectedTypeNotString":"È previsto un tipo ma è stato ricevuto un valore letterale stringa","expectedTypeParameterName":"Nome del parametro del tipo previsto","expectedYieldExpr":"Espressione prevista nell\'istruzione yield","finalClassIsAbstract":"La classe \\"{type}\\" è contrassegnata come finale e deve implementare tutti i simboli astratti","finalContext":"\\"Finale\\" non è consentito in questo contesto","finalMethodOverride":"Il metodo \\"{name}\\" non può eseguire l\'override del metodo finale definito nella classe \\"{className}\\"","finalNonMethod":"Impossibile contrassegnare la funzione “{name}” @final perché non è un metodo","finalReassigned":"\\"{name}\\" è dichiarato come Finale e non può essere riassegnato","finalRedeclaration":"\\"{name}\\" è stato dichiarato in precedenza come Finale","finalRedeclarationBySubclass":"Non è possibile ridichiarare \\"{name}\\" perché la classe padre \\"{className}\\" la dichiara come Finale","finalTooManyArgs":"Previsto un singolo argomento tipo dopo \\"Final\\"","finalUnassigned":"\\"{name}\\" è dichiarato Final, ma il valore non è assegnato","formatStringBrace":"Parentesi graffa di chiusura singola non consentita all\'interno del valore letterale f-string; usa parentesi graffa chiusa doppia","formatStringBytes":"I valori letterali stringa di formato (f-string) non possono essere binari","formatStringDebuggingIllegal":"L’identificatore di debug delle stringhe F \\"=\\" richiede Python 3.8 o versione successiva","formatStringEscape":"Sequenza di escape (barra rovesciata) non consentita nella porzione di espressione di f-string prima di Python 3.12","formatStringExpectedConversion":"È previsto un identificatore di conversione dopo \\"!\\" in f-string","formatStringIllegal":"I valori letterali stringa di formato (f-string) richiedono Python 3.6 o versione successiva","formatStringInPattern":"Stringa di formato non consentita nel criterio","formatStringNestedFormatSpecifier":"Espressioni annidate troppo in profondità nell\'identificatore di stringa di formato","formatStringNestedQuote":"Le stringhe annidate all\'interno di una stringa f non possono usare lo stesso carattere virgolette della stringa f prima di Python 3.12","formatStringUnicode":"I valori letterali stringa di formato (f-string) non possono essere unicode","formatStringUnterminated":"Espressione senza terminazione in f-string; previsto \\"}\\".","functionDecoratorTypeUnknown":"L\'elemento Decorator della funzione non tipizzato nasconde il tipo di funzione; l\'elemento Decorator verrà ignorato","functionInConditionalExpression":"L\'espressione condizionale fa riferimento a una funzione che restituisce sempre True","functionTypeParametersIllegal":"La sintassi del parametro del tipo di funzione richiede Python 3.12 o versione successiva","futureImportLocationNotAllowed":"Le importazioni da __future__ devono trovarsi all\'inizio del file","generatorAsyncReturnType":"Il tipo restituito della funzione del generatore asincrono deve essere compatibile con \\"AsyncGenerator[{yieldType}, Any]\\"","generatorNotParenthesized":"Le espressioni del generatore devono essere racchiuse tra parentesi se non è l\'unico argomento","generatorSyncReturnType":"Il tipo restituito della funzione del generatore deve essere compatibile con \\"Generator[{yieldType}, Any, Any]\\"","genericBaseClassNotAllowed":"Non è possibile usare la classe di base \\"Generic\\" con la sintassi del parametro di tipo","genericClassAssigned":"Non è possibile assegnare il tipo di classe generico","genericClassDeleted":"Non è possibile eliminare il tipo di classe generico","genericInstanceVariableAccess":"L\'accesso alla variabile di istanza generica tramite la classe è ambiguo","genericNotAllowed":"\\"Generic\\" non valido in questo contesto","genericTypeAliasBoundTypeVar":"L\'alias di tipo generico all\'interno della classe non può usare variabili di tipo associate {names}","genericTypeArgMissing":"\\"Generico\\" richiede almeno un argomento di tipo","genericTypeArgTypeVar":"L\'argomento di tipo per \\"Generic\\" deve essere una variabile di tipo","genericTypeArgUnique":"Gli argomenti di tipo per \\"Generic\\" devono essere univoci","globalReassignment":"\\"{name}\\" è assegnato prima della dichiarazione globale","globalRedefinition":"\\"{name}\\" è già stato dichiarato globale","implicitStringConcat":"Concatenazione implicita di stringhe non consentita","importCycleDetected":"Ciclo rilevato nella catena di importazione","importDepthExceeded":"La profondità della catena di importazione ha superato {depth}","importResolveFailure":"Non è stato possibile risolvere l\'importazione \\"{importName}\\"","importSourceResolveFailure":"Non è stato possibile risolvere l\'importazione \\"{importName}\\" dall’origine","importSymbolUnknown":"\\"{name}\\" è un simbolo di importazione sconosciuto","incompatibleMethodOverride":"Il metodo \\"{name}\\" esegue l\'override della classe \\"{className}\\" in modo incompatibile","inconsistentIndent":"Il valore dell\'annullamento del rientro non corrisponde al rientro precedente","inconsistentTabs":"Uso incoerente di tabulazioni e spazi nel rientro","initMustReturnNone":"Il tipo restituito di \\"__init__\\" deve essere None","initSubclassCallFailed":"Argomenti di parola chiave non corretti per il metodo __init_subclass__","initSubclassClsParam":"__init_subclass__ override deve accettare un parametro \\"cls\\"","initVarNotAllowed":"\\"InitVar\\" non consentito in questo contesto","instanceMethodSelfParam":"I metodi di istanza devono accettare un parametro \\"self\\"","instanceVarOverridesClassVar":"La variabile di istanza \\"{name}\\" esegue l\'override della variabile di classe con lo stesso nome nella classe \\"{className}\\"","instantiateAbstract":"Non è possibile creare un\'istanza di classe astratta \\"{type}\\"","instantiateProtocol":"Non è possibile creare un\'istanza della classe di protocollo \\"{type}\\"","internalBindError":"Errore interno durante l\'associazione del file \\"{file}\\": {message}","internalParseError":"Si è verificato un errore interno durante l\'analisi del file \\"{file}\\": {message}","internalTypeCheckingError":"Errore interno durante il controllo del tipo del file \\"{file}\\": {message}","invalidIdentifierChar":"Carattere non valido nell\'identificatore","invalidStubStatement":"L\'istruzione non ha significato all\'interno di un file stub di tipo","invalidTokenChars":"Carattere non valido \\"{text}\\" nel token","isInstanceInvalidType":"Il secondo argomento di \\"isinstance\\" deve essere una classe o una tupla di classi","isSubclassInvalidType":"Il secondo argomento di \\"issubclass\\" deve essere una classe o una tupla di classi","keyValueInSet":"Le coppie chiave-valore non sono consentite all\'interno di un set","keywordArgInTypeArgument":"Gli argomenti delle parole chiave non possono essere usati negli elenchi di argomenti tipo","keywordOnlyAfterArgs":"Separatore di argomenti solo parola chiave non consentito dopo il parametro \\"*\\"","keywordParameterMissing":"Uno o più parametri di parole chiave devono seguire il parametro \\"*\\"","keywordSubscriptIllegal":"Gli argomenti delle parole chiave all\'interno di pedici non sono supportati","lambdaReturnTypePartiallyUnknown":"Il tipo restituito dell\'espressione lambda \\"{returnType}\\" è parzialmente sconosciuto","lambdaReturnTypeUnknown":"Il tipo restituito di lambda è sconosciuto","listAssignmentMismatch":"Non è possibile assegnare l\'espressione con tipo \\"{type}\\" all\'elenco di destinazione","listInAnnotation":"Espressione elenco non consentita nell\'annotazione di tipo","literalEmptyArgs":"Previsto uno o più argomenti tipo dopo \\"Valore letterale\\"","literalNotAllowed":"Non è possibile usare \\"Literal\\" in questo contesto senza un argomento tipo","literalNotCallable":"Non è possibile creare un\'istanza del tipo letterale","literalUnsupportedType":"Gli argomenti di tipo per \\"Literal\\" devono essere None, un valore letterale (int, bool, str o bytes) o un valore di enumerazione","matchIncompatible":"Le istruzioni match richiedono Python 3.10 o versione successiva","matchIsNotExhaustive":"I case all\'interno dell\'istruzione match non gestiscono in modo completo tutti i valori","maxParseDepthExceeded":"È stata superata la profondità massima di analisi; suddividere l\'espressione in sottoespressioni più piccole","memberAccess":"Non è possibile accedere al membro \\"{name}\\" per il tipo \\"{type}\\"","memberDelete":"Non è possibile eliminare il membro \\"{name}\\" per il tipo \\"{type}\\"","memberSet":"Non è possibile assegnare il membro \\"{name}\\" per il tipo \\"{type}\\"","metaclassConflict":"La metaclasse di una classe derivata deve essere una sottoclasse delle metaclassi di tutte le relative classi di base","metaclassDuplicate":"È possibile specificare una sola metaclasse","metaclassIsGeneric":"La metaclasse non può essere generica","methodNotDefined":"Metodo \\"{name}\\" non definito","methodNotDefinedOnType":"\\"{name}\\" metodo non definito nel tipo \\"{type}\\"","methodOrdering":"Non è possibile creare un ordinamento coerente del metodo","methodOverridden":"\\"{name}\\" esegue l\'override del metodo con lo stesso nome nella classe \\"{className}\\" con un tipo non compatibile \\"{type}\\".","methodReturnsNonObject":"Il metodo \\"{name}\\" non restituisce un oggetto","missingSuperCall":"Il metodo \\"{methodName}\\" non chiama il metodo con lo stesso nome nella classe padre","moduleAsType":"Il modulo non può essere usato come tipo","moduleNotCallable":"Modulo non chiamabile","moduleUnknownMember":"\\"{memberName}\\" non è un membro noto del modulo \\"{moduleName}\\"","namedExceptAfterCatchAll":"Una clausola except denominata non può trovarsi dopo la clausola catch-all except","namedParamAfterParamSpecArgs":"Il parametro della parola chiave \\"{name}\\" non può essere visualizzato nella firma dopo il parametro ParamSpec args","namedTupleEmptyName":"I nomi all\'interno di una tupla denominata non possono essere vuoti","namedTupleEntryRedeclared":"Non è possibile eseguire l\'override di \\"{name}\\" perché la classe padre \\"{className}\\" è una tupla denominata","namedTupleFirstArg":"Previsto nome della classe di tupla denominata come primo argomento","namedTupleMultipleInheritance":"L\'ereditarietà multipla con NamedTuple non è supportata","namedTupleNameKeyword":"I nomi dei campi non possono essere una parola chiave","namedTupleNameType":"Prevista tupla a due voci che specifica il nome e il tipo della voce","namedTupleNameUnique":"I nomi all\'interno di una tupla denominata devono essere univoci","namedTupleNoTypes":"\\"namedtuple\\" non fornisce tipi per le voci di tupla; usare invece \\"NamedTuple\\"","namedTupleSecondArg":"È previsto un elenco di voci di tupla denominate come secondo argomento","newClsParam":"__new__ override deve accettare un parametro \\"cls\\"","newTypeAnyOrUnknown":"Il secondo argomento di NewType deve essere una classe nota, non Any o Unknown","newTypeBadName":"Il primo argomento di NewType deve essere un valore letterale stringa","newTypeLiteral":"Non è possibile usare NewType con il tipo Literal","newTypeNameMismatch":"NewType deve essere assegnato a una variabile con lo stesso nome","newTypeNotAClass":"Classe prevista come secondo argomento di NewType","newTypeParamCount":"NewType richiede due argomenti posizionali","newTypeProtocolClass":"Non è possibile usare NewType con il tipo strutturale (un protocollo o una classe TypedDict)","noOverload":"Nessun overload per \\"{name}\\" corrisponde agli argomenti specificati","noReturnContainsReturn":"La funzione con tipo restituito dichiarato \\"NoReturn\\" non può includere un\'istruzione return","noReturnContainsYield":"La funzione con il tipo restituito dichiarato \\"NoReturn\\" non può includere un\'istruzione yield","noReturnReturnsNone":"La funzione con tipo restituito dichiarato \\"NoReturn\\" non può restituire \\"None\\"","nonDefaultAfterDefault":"L\'argomento non predefinito segue l\'argomento predefinito","nonLocalInModule":"Dichiarazione non locale non consentita a livello di modulo","nonLocalNoBinding":"Non è stata trovata alcuna associazione per \\"{name}\\" non locale","nonLocalReassignment":"\\"{name}\\" è assegnato prima della dichiarazione non locale","nonLocalRedefinition":"\\"{name}\\" è già stato dichiarato non locale","noneNotCallable":"Non è possibile chiamare l\'oggetto di tipo \\"None\\"","noneNotIterable":"Impossibile utilizzare l\'oggetto di tipo \\"None\\" come valore iterabile","noneNotSubscriptable":"L\'oggetto di tipo \\"Nessuno\\" non è sottoponibile a pedice","noneNotUsableWith":"Impossibile utilizzare l\'oggetto di tipo \\"None\\" con \\"with\\"","noneOperator":"Operatore \\"{operator}\\" non supportato per \\"None\\"","noneUnknownMember":"\\"{name}\\" non è un membro noto di \\"None\\"","notRequiredArgCount":"Previsto un singolo argomento tipo dopo \\"NotRequired\\"","notRequiredNotInTypedDict":"\\"NotRequired\\" non è consentito in questo contesto","objectNotCallable":"L\'oggetto di tipo \\"{type}\\" non è chiamabile","obscuredClassDeclaration":"La dichiarazione di classe \\"{name}\\" è oscurata da una dichiarazione con lo stesso nome","obscuredFunctionDeclaration":"La dichiarazione della funzione \\"{name}\\" è oscurata da una dichiarazione con lo stesso nome","obscuredMethodDeclaration":"La dichiarazione del metodo \\"{name}\\" è oscurata da una dichiarazione con lo stesso nome","obscuredParameterDeclaration":"La dichiarazione del parametro \\"{name}\\" è oscurata da una dichiarazione con lo stesso nome","obscuredTypeAliasDeclaration":"La dichiarazione dell\'alias di tipo \\"{name}\\" è nascosta da una dichiarazione con lo stesso nome","obscuredVariableDeclaration":"La dichiarazione \\"{name}\\" è oscurata da una dichiarazione con lo stesso nome","operatorLessOrGreaterDeprecated":"L\'operatore \\"<>\\" non è supportato in Python 3. Usare invece \\"!=\\"","optionalExtraArgs":"Previsto un argomento tipo dopo \\"Facoltativo\\"","orPatternIrrefutable":"Criterio inconfutabile consentito solo come ultimo criterio secondario in un criterio \\"o\\"","orPatternMissingName":"Tutti i criteri secondari all\'interno di un criterio \\"or\\" devono avere come destinazione gli stessi nomi","overlappingKeywordArgs":"Il dizionario tipizzato si sovrappone al parametro della parola chiave: {names}","overlappingOverload":"L\'overload {obscured} per \\"{name}\\" non verrà mai usato perché i parametri si sovrappongono all\'overload {obscuredBy}","overloadAbstractMismatch":"I metodi di overload devono essere tutti astratti o no","overloadClassMethodInconsistent":"Gli overload per \\"{name}\\" usano @classmethod in modo incoerente","overloadFinalInconsistencyImpl":"L\'overload per “{name}” è contrassegnato @final ma l\'implementazione non lo è","overloadFinalInconsistencyNoImpl":"L\'overload {index} per “{name}” è contrassegnato @final ma l\'overload 1 non lo è","overloadImplementationMismatch":"L\'implementazione di overload non è coerente con la firma dell\'overload {index}","overloadReturnTypeMismatch":"L\'overload {prevIndex} per \\"{name}\\" si sovrappone all\'overload {newIndex} e restituisce un tipo incompatibile","overloadStaticMethodInconsistent":"Gli overload per \\"{name}\\" usano @staticmethod in modo incoerente","overloadWithoutImplementation":"\\"{name}\\" è contrassegnato come overload, ma non viene fornita alcuna implementazione","overriddenMethodNotFound":"Il metodo \\"{name}\\" è contrassegnato come override, ma non è presente alcun metodo di base con lo stesso nome","overrideDecoratorMissing":"Il metodo \\"{name}\\" non è contrassegnato come override, ma esegue l\'override di un metodo nella classe \\"{className}\\"","paramAfterKwargsParam":"Il parametro non può seguire il parametro \\"**\\"","paramAlreadyAssigned":"Il parametro \\"{name}\\" è già assegnato","paramAnnotationMissing":"Annotazione di tipo mancante per il parametro \\"{name}\\"","paramAssignmentMismatch":"Non è possibile assegnare l\'espressione di tipo \\"{sourceType}\\" al parametro di tipo \\"{paramType}\\"","paramNameMissing":"Nessun parametro denominato \\"{name}\\"","paramSpecArgsKwargsUsage":"I membri \\"args\\" e \\"kwargs\\" di ParamSpec devono essere entrambi visualizzati all\'interno di una firma di funzione","paramSpecArgsMissing":"Gli argomenti per ParamSpec \\"{type}\\" sono mancanti","paramSpecArgsUsage":"Il membro \\"args\\" di ParamSpec è valido solo se usato con il parametro *args","paramSpecAssignedName":"ParamSpec deve essere assegnato a una variabile denominata \\"{name}\\"","paramSpecContext":"ParamSpec non è consentito in questo contesto","paramSpecDefaultNotTuple":"Sono previsti puntini di sospensione, un\'espressione di tupla o ParamSpec per il valore predefinito di ParamSpec","paramSpecFirstArg":"Nome previsto di ParamSpec come primo argomento","paramSpecKwargsUsage":"Il membro \\"kwargs\\" di ParamSpec è valido solo se usato con il parametro **kwargs","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" non ha significato in questo contesto","paramSpecScopedToReturnType":"L’ambito ParamSpec \\"{name}\\" è un elemento richiamabile all\'interno del tipo restituito e non può essere usato come riferimento nel corpo della funzione","paramSpecUnknownArg":"ParamSpec non supporta più di un argomento","paramSpecUnknownMember":"\\"{name}\\" non è un membro noto di ParamSpec","paramSpecUnknownParam":"\\"{name}\\" è un parametro sconosciuto per ParamSpec","paramTypeCovariant":"Non è possibile usare la variabile di tipo covariante nel tipo di parametro","paramTypePartiallyUnknown":"Tipo di parametro \\"{paramName}\\" parzialmente sconosciuto","paramTypeUnknown":"Tipo di parametro \\"{paramName}\\" sconosciuto","parenthesizedContextManagerIllegal":"Le parentesi all\'interno dell\'istruzione \\"con\\" richiedono Python 3.9 o versione successiva","patternNeverMatches":"Il criterio non verrà mai confrontato per il tipo di oggetto \\"{type}\\"","positionArgAfterNamedArg":"L\'argomento posizionale non può essere visualizzato dopo gli argomenti della parola chiave","positionOnlyAfterArgs":"Separatore di parametri di sola posizione non consentito dopo il parametro \\"*\\"","positionOnlyAfterKeywordOnly":"Il parametro \\"/\\" deve essere visualizzato prima del parametro \\"*\\"","positionOnlyAfterNon":"Il parametro di sola posizione non è consentito dopo un parametro che non è di sola posizione","positionOnlyFirstParam":"Separatore di argomenti di sola posizione non consentito come primo parametro","positionOnlyIncompatible":"Il separatore di parametri di sola posizione richiede Python 3.8 o versione successiva","privateImportFromPyTypedModule":"\\"{name}\\" non è esportato dal modulo \\"{module}\\"","privateUsedOutsideOfClass":"\\"{name}\\" è privato e utilizzato all\'esterno del modulo in cui è dichiarato","privateUsedOutsideOfModule":"\\"{name}\\" è privato e utilizzato all\'esterno del modulo in cui è dichiarato","propertyOverridden":"\\"{name}\\" esegue erroneamente l’override di una proprietà con lo stesso nome nella classe \\"{className}\\"","propertyStaticMethod":"Metodi statici non consentiti per getter, setter o deleter di proprietà","protectedUsedOutsideOfClass":"\\"{name}\\" è protetto e usato al di fuori della classe in cui è dichiarato","protocolBaseClass":"La classe di protocollo \\"{classType}\\" non può derivare dalla classe non di protocollo \\"{baseType}\\".","protocolBaseClassWithTypeArgs":"Gli argomenti tipo non sono consentiti con la classe Protocollo quando si usa la sintassi dei parametri tipo","protocolIllegal":"L\'uso del \\"protocollo\\" richiede Python 3.7 o versione successiva","protocolNotAllowed":"\\"Protocol\\" non può essere usato in questo contesto","protocolUnsafeOverlap":"La classe si sovrappone a \\"{name}\\" in modo non sicuro e può produrre una corrispondenza in fase di esecuzione","protocolVarianceContravariant":"La variabile di tipo \\"{variable}\\" usata nel protocollo generico \\"{class}\\" deve essere controvariante","protocolVarianceCovariant":"La variabile di tipo \\"{variable}\\" usata nel protocollo generico \\"{class}\\" deve essere covariante","protocolVarianceInvariant":"La variabile di tipo \\"{variable}\\" usata nel protocollo generico \\"{class}\\" deve essere invariabile","pyrightCommentInvalidDiagnosticBoolValue":"La direttiva di commento Pyright deve essere seguita da \\"=\\" e da un valore true o false","pyrightCommentInvalidDiagnosticSeverityValue":"La direttiva di commento Pyright deve essere seguita da \\"=\\" e da un valore true, false, error, warning, information o none","pyrightCommentMissingDirective":"Il commento pyright deve essere seguito da una direttiva (di base o restrittiva) o da una regola di diagnostica","pyrightCommentNotOnOwnLine":"I commenti Pyright usati per controllare le impostazioni a livello di file devono essere visualizzati nella propria riga","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" è una regola di diagnostica sconosciuta per il commento pyright","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" non è un valore valido per il commento pyright; previsto true, false, error, warning, information o none","pyrightCommentUnknownDirective":"\\"{directive}\\" è una direttiva sconosciuta per il commento pyright; previsto \\"strict\\" o \\"basic\\"","readOnlyArgCount":"Previsto un singolo argomento tipo dopo \\"ReadOnly\\"","readOnlyNotInTypedDict":"\\"ReadOnly\\" non consentito in questo contesto","recursiveDefinition":"Non è stato possibile determinare il tipo di \\"{name}\\" perché fa riferimento a se stesso","relativeImportNotAllowed":"Le importazioni relative non possono essere usate con il modulo \\"import .a\\". Usare invece \\"from . import a\\"","requiredArgCount":"Previsto un singolo argomento tipo dopo \\"Obbligatorio\\"","requiredNotInTypedDict":"\\"Required\\" non è consentito in questo contesto","returnInAsyncGenerator":"L’istruzione return con valore non è consentita nel generatore asincrono","returnMissing":"La funzione con tipo restituito dichiarato \\"{returnType}\\" deve restituire un valore in tutti i percorsi di codice","returnOutsideFunction":"\\"return\\" può essere usata solo all\'interno di una funzione.","returnTypeContravariant":"Non è possibile usare la variabile di tipo controvariante nel tipo restituito","returnTypeMismatch":"Non è possibile assegnare l\'espressione di tipo \\"{exprType}\\" al tipo restituito \\"{returnType}\\"","returnTypePartiallyUnknown":"Il tipo restituito \\"{returnType}\\" è parzialmente sconosciuto","returnTypeUnknown":"Il tipo restituito è sconosciuto","revealLocalsArgs":"Non è previsto alcun argomento per la chiamata \\"reveal_locals\\"","revealLocalsNone":"Non sono presenti variabili locali in questo ambito","revealTypeArgs":"Previsto un singolo argomento posizionale per la chiamata \\"reveal_type\\"","revealTypeExpectedTextArg":"L\'argomento \\"expected_text\\" per la funzione \\"reveal_type\\" deve essere un valore letterale str","revealTypeExpectedTextMismatch":"Testo di tipo non corrispondente; previsto \\"{expected}\\" ma ricevuto \\"{received}\\"","revealTypeExpectedTypeMismatch":"Tipo non corrispondente; previsto \\"{expected}\\" ma ricevuto \\"{received}\\"","selfTypeContext":"\\"Self\\" non è valido in questo contesto","selfTypeMetaclass":"Impossibile utilizzare “Self” all\'interno di una metaclasse (una sottoclasse di “type”)","selfTypeWithTypedSelfOrCls":"Non è possibile usare \\"Self\\" in una funzione con un parametro \'self\' o \'cls\' con un\'annotazione di tipo diversa da \\"Self\\"","setterGetterTypeMismatch":"Il tipo di valore del setter di proprietà non è assegnabile al tipo restituito del getter","singleOverload":"\\"{name}\\" è contrassegnato come overload, ma mancano altri overload","slotsAttributeError":"\\"{name}\\" non è specificato in __slots__","slotsClassVarConflict":"\\"{name}\\" è in conflitto con la variabile di istanza dichiarata in __slots__","starPatternInAsPattern":"Il modello a stella non può essere usato con la destinazione \\"as\\"","starPatternInOrPattern":"Il modello a stella non può essere ORed all\'interno di altri modelli","starStarWildcardNotAllowed":"** non può essere usato con il carattere jolly \\"_\\"","staticClsSelfParam":"I metodi statici non devono accettare un parametro \\"self\\" o \\"cls\\"","stdlibModuleOverridden":"\\"{path}\\" sta eseguendo l\'override del modulo stdlib \\"{name}\\"","stringNonAsciiBytes":"Carattere non ASCII non consentito nel valore letterale stringa dei byte","stringNotSubscriptable":"L\'espressione stringa non può essere in pedice nell\'annotazione di tipo. Racchiudere l\'intera annotazione tra virgolette","stringUnsupportedEscape":"Sequenza di escape non supportata nel valore letterale stringa","stringUnterminated":"Il valore letterale stringa non è terminato","stubFileMissing":"File di stub non trovato per \\"{importName}\\"","stubUsesGetAttr":"Il file dello stub di tipo è incompleto; \\"__getattr__\\" nasconde gli errori di tipo per il modulo","sublistParamsIncompatible":"I parametri dell’elenco secondario non sono supportati in Python 3.x","superCallArgCount":"Non sono previsti più di due argomenti per la chiamata \\"super\\".","superCallFirstArg":"È previsto un tipo di classe come primo argomento della chiamata \\"super\\", ma è stato ricevuto \\"{type}\\"","superCallSecondArg":"Il secondo argomento della chiamata \\"super\\" deve essere un oggetto o una classe che deriva da \\"{type}\\"","superCallZeroArgForm":"Il modulo zero-argument della chiamata \\"super\\" è valido solo all\'interno di un metodo","superCallZeroArgFormStaticMethod":"Il modulo zero-argument della chiamata \\"super\\" non è valido all\'interno di un metodo statico","symbolIsPossiblyUnbound":"\\"{name}\\" potrebbe non essere associato","symbolIsUnbound":"\\"{name}\\" non associato","symbolIsUndefined":"\\"{name}\\" non è definito","symbolOverridden":"\\"{name}\\" esegue l\'override del simbolo con lo stesso nome nella classe \\"{className}\\"","ternaryNotAllowed":"Espressione ternaria non consentita nell\'annotazione di tipo","totalOrderingMissingMethod":"La classe deve definire uno dei valori di \\"__lt__\\", \\"__le__\\", \\"__gt__\\" o \\"__ge__\\" per usare total_ordering","trailingCommaInFromImport":"Virgola finale non consentita senza parentesi circostanti","tryWithoutExcept":"L\'istruzione Try deve contenere almeno una clausola except or finally","tupleAssignmentMismatch":"Non è possibile assegnare l\'espressione con tipo \\"{type}\\" alla tupla di destinazione","tupleInAnnotation":"Espressione di tupla non consentita nell\'annotazione di tipo","tupleIndexOutOfRange":"L\'indice {index} non è compreso nell\'intervallo per il tipo {type}","typeAliasIllegalExpressionForm":"Modulo di espressione non valido per la definizione dell\'alias di tipo","typeAliasIsRecursiveDirect":"L\'alias di tipo \\"{name}\\" non può usare se stesso nella relativa definizione","typeAliasNotInModuleOrClass":"TypeAlias può essere definito solo all\'interno di un modulo o di una classe","typeAliasRedeclared":"\\"{name}\\" è dichiarato come TypeAlias e può essere assegnato una sola volta","typeAliasStatementBadScope":"Un\'istruzione Tipo può essere usata solo all\'interno di un modulo o di un ambito della classe","typeAliasStatementIllegal":"L\'istruzione alias di tipo richiede Python 3.12 o versione successiva","typeAliasTypeBaseClass":"Impossibile utilizzare come classe di base un alias di tipo definito in un\'istruzione \\"type\\"","typeAliasTypeMustBeAssigned":"TypeAliasType deve essere assegnato a una variabile con lo stesso nome dell\'alias di tipo","typeAliasTypeNameArg":"Il primo argomento di TypeAliasType deve essere un valore letterale stringa che rappresenta il nome dell\'alias di tipo","typeAliasTypeNameMismatch":"Il nome dell\'alias di tipo deve corrispondere al nome della variabile a cui è assegnato","typeAliasTypeParamInvalid":"L\'elenco dei parametri del tipo deve essere una tupla contenente solo TypeVar, TypeVarTuple o ParamSpec.","typeAnnotationCall":"Espressione di chiamata non consentita nell\'espressione di tipo","typeAnnotationVariable":"Variabile non consentita nell\'espressione di tipo","typeAnnotationWithCallable":"L\'argomento di tipo per \\"type\\" deve essere una classe. I callable non sono supportati","typeArgListExpected":"Previsto ParamSpec, puntini di sospensione o elenco di tipi","typeArgListNotAllowed":"Espressione di elenco non consentita per questo argomento tipo","typeArgsExpectingNone":"Non sono previsti argomenti di tipo per la classe \\"{name}\\"","typeArgsMismatchOne":"Previsto un argomento di tipo, ricevuto {received}","typeArgsMissingForAlias":"Sono previsti argomenti di tipo per l\'alias di tipo generico \\"{name}\\"","typeArgsMissingForClass":"Argomenti tipo previsti per la classe generica \\"{name}\\"","typeArgsTooFew":"Troppo pochi argomenti tipo forniti per \\"{name}\\"; previsto {expected} ma ricevuto {received}","typeArgsTooMany":"Troppi argomenti tipo forniti per \\"{name}\\"; previsto {expected} ma ricevuto {received}","typeAssignmentMismatch":"Impossibile assegnare l\'espressione di tipo \\"{sourceType}\\" al tipo dichiarato \\"{destType}\\"","typeAssignmentMismatchWildcard":"Il simbolo di importazione \\"{name}\\" ha il tipo \\"{sourceType}\\", che non può essere assegnato al tipo dichiarato \\"{destType}\\"","typeCallNotAllowed":"la chiamata type() non deve essere usata nell\'annotazione di tipo","typeCheckOnly":"\\"{name}\\" è contrassegnato come @type_check_only e può essere utilizzato solo nelle annotazioni tipo","typeCommentDeprecated":"L\'uso dei commenti di tipo è deprecato. Usare l\'annotazione di tipo","typeExpectedClass":"È prevista un\'espressione di tipo ma è stato ricevuto \\"{type}\\"","typeGuardArgCount":"È previsto un singolo argomento di tipo dopo \\"TypeGuard\\" o \\"TypeIs\\"","typeGuardParamCount":"Le funzioni e i metodi di protezione dei tipi definiti dall\'utente devono avere almeno un parametro di input","typeIsReturnType":"Il tipo restituito di TypeIs (\\"{returnType}\\") non è coerente con il tipo di parametro di valore (\\"{type}\\")","typeNotAwaitable":"\\"{type}\\" non è awaitable","typeNotIntantiable":"Non è possibile creare un\'istanza di \\"{type}\\"","typeNotIterable":"\\"{type}\\" non è iterabile","typeNotSpecializable":"Non è stato possibile specializzare il tipo \\"{type}\\"","typeNotSubscriptable":"L\'oggetto di tipo \\"{type}\\" non è sottoponibile a script","typeNotSupportBinaryOperator":"L\'operatore \\"{operator}\\" non è supportato per i tipi \\"{leftType}\\" e \\"{rightType}\\".","typeNotSupportBinaryOperatorBidirectional":"L\'operatore \\"{operator}\\" non è supportato per i tipi \\"{leftType}\\" e \\"{rightType}\\" quando il tipo previsto è \\"{expectedType}\\"","typeNotSupportUnaryOperator":"Operatore \\"{operator}\\" non supportato per il tipo \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"L\'operatore \\"{operator}\\" non è supportato per il tipo \\"{type}\\" quando il tipo previsto è \\"{expectedType}\\"","typeNotUsableWith":"Impossibile utilizzare l\'oggetto di tipo \\"{type}\\" con \\"with\\" perché non implementa {method}","typeParameterBoundNotAllowed":"Il vincolo o il binding non possono essere usati con un parametro di tipo variadic o ParamSpec","typeParameterConstraintTuple":"Il vincolo del parametro di tipo deve essere una tupla di due o più tipi","typeParameterExistingTypeParameter":"Il parametro di tipo \\"{name}\\" è già in uso","typeParameterNotDeclared":"Il parametro di tipo \\"{name}\\" non è incluso nell\'elenco dei parametri di tipo per \\"{container}\\"","typeParametersMissing":"È necessario specificare almeno un parametro di tipo","typePartiallyUnknown":"Tipo di \\"{name}\\" parzialmente sconosciuto","typeUnknown":"Il tipo di \\"{name}\\" è sconosciuto","typeVarAssignedName":"TypeVar deve essere assegnato a una variabile denominata \\"{name}\\"","typeVarAssignmentMismatch":"Non è possibile assegnare il tipo \\"{type}\\" alla variabile di tipo \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar non può essere contemporaneamente associato e vincolato","typeVarBoundGeneric":"Il tipo associato a TypeVar non può essere generico","typeVarConstraintGeneric":"Il tipo di vincolo TypeVar non può essere generico","typeVarDefaultBoundMismatch":"Il tipo predefinito TypeVar deve essere un sottotipo del tipo associato","typeVarDefaultConstraintMismatch":"Il tipo predefinito TypeVar deve essere uno dei tipi vincolati","typeVarDefaultIllegal":"I tipi predefiniti delle variabili di tipo richiedono Python 3.13 o versione successiva","typeVarDefaultInvalidTypeVar":"Il parametro di tipo \\"{name}\\" ha un tipo predefinito che fa riferimento a una o più variabili di tipo non compreso nell\'ambito","typeVarFirstArg":"Nome previsto di TypeVar come primo argomento","typeVarNoMember":"TypeVar \\"{type}\\" non ha membri \\"{name}\\"","typeVarNotSubscriptable":"TypeVar \\"{type}\\" non sottoponibile a script","typeVarNotUsedByOuterScope":"La variabile di tipo \\"{name}\\" non ha significato in questo contesto","typeVarPossiblyUnsolvable":"La variabile di tipo \\"{name}\\" potrebbe non essere risolta se il chiamante non fornisce alcun argomento per il parametro \\"{param}\\"","typeVarScopedToReturnType":"La variabile di tipo \\"{name}\\" ha come ambito un elemento richiamabile all\'interno del tipo restituito e non può essere usato come riferimento nel corpo della funzione","typeVarSingleConstraint":"TypeVar deve contenere almeno due tipi vincolati","typeVarTupleConstraints":"TypeVarTuple non può avere vincoli di valore","typeVarTupleContext":"TypeVarTuple non è consentito in questo contesto","typeVarTupleDefaultNotUnpacked":"Il tipo predefinito TypeVarTuple deve essere una tupla non compressa o TypeVarTuple","typeVarTupleMustBeUnpacked":"L\'operatore Decomprimi è obbligatorio per il valore TypeVarTuple","typeVarTupleUnknownParam":"\\"{name}\\" è un parametro sconosciuto per TypeVar","typeVarUnknownParam":"\\"{name}\\" è un parametro sconosciuto per TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" già in uso da un ambito esterno","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" viene visualizzato una sola volta nella firma della funzione generica","typeVarVariance":"TypeVar non può essere covariante e controvariante","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" ha un valore predefinito e non può seguire TypeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" non può essere visualizzato dopo \\"{other}\\" nell\'elenco dei parametri del tipo, perché non ha un tipo predefinito","typeVarsNotInGenericOrProtocol":"Generic[] o Protocol[] deve includere tutte le variabili di tipo","typedDictAccess":"Non è stato possibile accedere all\'elemento in TypedDict","typedDictAssignedName":"TypedDict deve essere assegnato a una variabile denominata \\"{name}\\"","typedDictBadVar":"Le classi TypedDict possono contenere solo annotazioni di tipo","typedDictBaseClass":"Anche tutte le classi di base per le classi TypedDict devono essere classi TypedDict","typedDictBoolParam":"È previsto che il parametro \\"{name}\\" abbia il valore True o False","typedDictClosedExtras":"La classe di base \\"{name}\\" è un TypedDict chiuso; gli elementi aggiuntivi devono essere di tipo \\"{type}\\"","typedDictClosedNoExtras":"La classe di base \\"{name}\\" è un TypedDict chiuso; elementi aggiuntivi non consentiti","typedDictDelete":"Non è stato possibile eliminare l\'elemento in TypedDict","typedDictEmptyName":"I nomi all\'interno di un TypedDict non possono essere vuoti","typedDictEntryName":"Valore letterale stringa previsto per il nome della voce del dizionario","typedDictEntryUnique":"I nomi all\'interno di un dizionario devono essere univoci","typedDictExtraArgs":"Argomenti TypedDict aggiuntivi non supportati","typedDictFieldNotRequiredRedefinition":"Non è possibile ridefinire il campo TypedDict \\"{name}\\" come Non obbligatorio","typedDictFieldReadOnlyRedefinition":"Non è possibile ridefinire l’elemento TypedDict \\"{name}\\" come Sola lettura","typedDictFieldRequiredRedefinition":"Non è possibile ridefinire il campo TypedDict \\"{name}\\" come Obbligatorio","typedDictFirstArg":"È previsto il nome della classe TypedDict come primo argomento","typedDictInitsubclassParameter":"TypedDict non supporta __init_subclass__ parametro “{name}”","typedDictNotAllowed":"\\"TypedDict\\" non può essere usato in questo contesto","typedDictSecondArgDict":"Previsto parametro dict o keyword come secondo parametro","typedDictSecondArgDictEntry":"Voce di dizionario semplice prevista","typedDictSet":"Non è stato possibile assegnare l\'elemento in TypedDict","unaccessedClass":"La classe \\"{name}\\" non è accessibile","unaccessedFunction":"La classe \\"{name}\\" non è accessibile","unaccessedImport":"Non è possibile accedere all\'importazione \\"{name}\\"","unaccessedSymbol":"Non è possibile accedere a \\"{name}\\"","unaccessedVariable":"La variabile \\"{name}\\" non è accessibile","unannotatedFunctionSkipped":"L\'analisi della funzione \\"{name}\\" è stata ignorata perché non è annotata","unaryOperationNotAllowed":"Operatore unario non consentito nell\'annotazione di tipo","unexpectedAsyncToken":"È previsto che \\"def\\", \\"with\\" o \\"for\\" seguano \\"async\\"","unexpectedExprToken":"Token imprevisto alla fine dell\'espressione","unexpectedIndent":"Rientro imprevisto","unexpectedUnindent":"Riduci rientro non previsto","unhashableDictKey":"La chiave del dizionario deve essere hashable","unhashableSetEntry":"La voce set deve essere hashable","uninitializedAbstractVariables":"Le variabili definite nella classe di base astratta non vengono inizializzate nella classe finale \\"{classType}\\"","uninitializedInstanceVariable":"La variabile di istanza \\"{name}\\" non è inizializzata nel corpo della classe o nel metodo __init__","unionForwardReferenceNotAllowed":"Impossibile utilizzare la sintassi di unione con l\'operando stringa. Usare virgolette intorno all\'intera espressione","unionSyntaxIllegal":"La sintassi alternativa per le unioni richiede Python 3.10 o versione successiva","unionTypeArgCount":"L\'unione richiede due o più argomenti di tipo","unionUnpackedTuple":"L\'unione non può includere una tupla decompressa","unionUnpackedTypeVarTuple":"L\'unione non può includere un TypeVarTuple non compresso","unnecessaryCast":"Chiamata \\"cast\\" non necessaria; il tipo è già \\"{type}\\"","unnecessaryIsInstanceAlways":"Chiamata isinstance non necessaria; \\"{testType}\\" è sempre un\'istanza di \\"{classType}\\"","unnecessaryIsSubclassAlways":"Chiamata issubclass non necessaria; \\"{testType}\\" è sempre una sottoclasse di \\"{classType}\\"","unnecessaryPyrightIgnore":"Commento \\"# pyright: ignore\\" non necessario","unnecessaryPyrightIgnoreRule":"Regola \\"# pyright: ignore\\" non necessaria: \\"{name}\\"","unnecessaryTypeIgnore":"Commento \\"# tipo: ignora\\" non necessario","unpackArgCount":"Previsto un singolo argomento tipo dopo \\"Decomprimi\\"","unpackExpectedTypeVarTuple":"È previsto TypeVarTuple o tupla come argomento di tipo per Unpack","unpackExpectedTypedDict":"Previsto argomento di tipo TypedDict per Decomprimi","unpackIllegalInComprehension":"Operazione di decompressione non consentita nella comprensione","unpackInAnnotation":"Operatore di decompressione non consentito nell\'annotazione di tipo","unpackInDict":"Operazione di decompressione non consentita nei dizionari","unpackInSet":"Operatore di decompressione non consentito all’interno di un set","unpackNotAllowed":"La decompressione non è consentita in questo contesto","unpackOperatorNotAllowed":"L’operazione di decompressione non è consentita in questo contesto","unpackTuplesIllegal":"L\'operazione di decompressione non è consentita nelle tuple precedenti a Python 3.8","unpackedArgInTypeArgument":"Gli argomenti non compressi non possono essere usati negli elenchi di argomenti tipo","unpackedArgWithVariadicParam":"Non è possibile usare l\'argomento decompresso per il parametro TypeVarTuple","unpackedDictArgumentNotMapping":"L\'espressione dell\'argomento dopo ** deve essere un mapping con un tipo di chiave \\"str\\"","unpackedDictSubscriptIllegal":"L\'operatore di decompressione del dizionario nel pedice non è consentito","unpackedSubscriptIllegal":"L\'operatore di decompressione nel pedice richiede Python 3.11 o versione successiva","unpackedTypeVarTupleExpected":"Previsto TypeVarTuple decompresso; usa Unpack[{name1}] o *{name2}","unpackedTypedDictArgument":"Impossibile trovare una corrispondenza tra l\'argomento TypedDict non compresso e i parametri","unreachableCode":"Il codice non è raggiungibile","unreachableExcept":"La clausola Except non è raggiungibile perché l\'eccezione è già gestita","unsupportedDunderAllOperation":"L\'operazione su \\"__all__\\" non è supportata, di conseguenza l\'elenco dei simboli esportati potrebbe non essere corretto","unusedCallResult":"Il risultato dell\'espressione di chiamata è di tipo \\"{type}\\" e non è usato. Assegnare alla variabile \\"_\\" se è intenzionale","unusedCoroutine":"Il risultato della chiamata di funzione asincrona non viene usato. usare \\"await\\" o assegnare il risultato alla variabile","unusedExpression":"Il valore dell\'espressione non è utilizzato","varAnnotationIllegal":"Le annotazioni di tipo per le variabili richiedono Python 3.6 o versione successiva. Usare il commento di tipo per compatibilità con le versioni precedenti","variableFinalOverride":"La variabile \\"{name}\\" è contrassegnata come Final ed esegue l\'override della variabile non Final con lo stesso nome nella classe \\"{className}\\"","variadicTypeArgsTooMany":"L\'elenco di argomenti di tipo può contenere al massimo una tupla o TypeVarTuple non compressa","variadicTypeParamTooManyAlias":"L\'alias di tipo può avere al massimo un parametro di tipo TypeVarTuple, ma ne ha ricevuti più ({names})","variadicTypeParamTooManyClass":"La classe generica può avere al massimo un parametro di tipo TypeVarTuple, ma ne ha ricevuti più ({names})","walrusIllegal":"L\'operatore \\":=\\" richiede Python 3.8 o versione successiva","walrusNotAllowed":"L\'operatore \\":=\\" non è consentito in questo contesto senza parentesi circostanti","wildcardInFunction":"Importazione di caratteri jolly non consentita all\'interno di una classe o di una funzione","wildcardLibraryImport":"Importazione di caratteri jolly da una libreria non consentita","wildcardPatternTypePartiallyUnknown":"Il tipo acquisito dal modello con caratteri jolly è parzialmente sconosciuto","wildcardPatternTypeUnknown":"Il tipo acquisito dal criterio con caratteri jolly è sconosciuto","yieldFromIllegal":"L\'uso di \\"yield from\\" richiede Python 3.3 o versione successiva","yieldFromOutsideAsync":"\\"yield from\\" non consentito in una funzione asincrona","yieldOutsideFunction":"\\"yield\\" non consentito all\'esterno di una funzione o di un\'espressione lambda","yieldWithinListCompr":"\\"yield\\" non consentito all\'interno di una comprensione di elenco","zeroCaseStatementsFound":"L’istruzione Match deve includere almeno un’istruzione case","zeroLengthTupleNotAllowed":"Tupla di lunghezza zero non è consentita in questo contesto"},"DiagnosticAddendum":{"annotatedNotAllowed":"Non è possibile usare il modulo speciale \\"Annotato\\" con controlli di istanza e classe","argParam":"L\'argomento corrisponde al parametro \\"{paramName}\\"","argParamFunction":"L\'argomento corrisponde al parametro \\"{paramName}\\" nella funzione \\"{functionName}\\"","argsParamMissing":"Il parametro \\"*{paramName}\\" non ha un parametro corrispondente","argsPositionOnly":"Parametro di sola posizione non corrispondente; previsto {expected} ma ricevuto {received}","argumentType":"Il tipo di argomento è \\"{type}\\"","argumentTypes":"Tipi di argomento: ({types})","assignToNone":"Non è possibile assegnare il tipo al tipo \\"None\\"","asyncHelp":"Intendevi \\"async con\\"?","baseClassIncompatible":"La classe base \\"{baseClass}\\" non è compatibile con il tipo \\"{type}\\"","baseClassIncompatibleSubclass":"La classe base \\"{baseClass}\\" deriva da \\"{subclass}\\", che non è compatibile con il tipo \\"{type}\\"","baseClassOverriddenType":"La classe di base \\"{baseClass}\\" fornisce il tipo \\"{type}\\", di cui viene eseguito l\'override","baseClassOverridesType":"Override della classe base \\"{baseClass}\\" con tipo \\"{type}\\"","bytesTypePromotions":"Imposta disableBytesTypePromotions su false per abilitare il comportamento di innalzamento di livello del tipo per \\"bytearray\\" e \\"memoryview\\"","conditionalRequiresBool":"Il metodo __bool__ per il tipo \\"{operandType}\\" restituisce il tipo \\"{boolReturnType}\\" anziché \\"bool\\"","dataClassFieldLocation":"Dichiarazione di campo","dataClassFrozen":"\\"{name}\\" è bloccato","dataProtocolUnsupported":"“{name}” è un protocollo dati","descriptorAccessBindingFailed":"Impossibile associare il metodo \\"{name}\\" per la classe descrittore \\"{className}\\"","descriptorAccessCallFailed":"Impossibile chiamare il metodo \\"{name}\\" per la classe descrittore \\"{className}\\"","finalMethod":"Metodo finale","functionParamDefaultMissing":"Nel parametro \\"{name}\\" manca un argomento predefinito","functionParamName":"Nome del parametro non corrispondente: \\"{destName}\\" rispetto a \\"{srcName}\\"","functionParamPositionOnly":"Parametro di sola posizione non corrispondente; il parametro “{name}” non è di sola posizione","functionReturnTypeMismatch":"Il tipo restituito della funzione\\"{sourceType}\\" non è compatibile con il tipo \\"{destType}\\"","functionTooFewParams":"La funzione accetta un numero insufficiente di parametri posizionale. Previsto {expected} ma ricevuto {received}","functionTooManyParams":"La funzione accetta un numero eccessivo di parametri posizionale. Previsto {expected} ma ricevuto {received}","genericClassNotAllowed":"Tipo generico con argomenti di tipo non consentiti per i controlli di istanza o classe","incompatibleDeleter":"Il metodo di eliminazione delle proprietà non è compatibile","incompatibleGetter":"Il metodo getter della proprietà non è compatibile","incompatibleSetter":"Il metodo setter di proprietà non è compatibile","initMethodLocation":"Il metodo __init__ è definito nella classe \\"{type}\\"","initMethodSignature":"Firma del __init__ \\"{type}\\"","initSubclassLocation":"Il metodo __init_subclass__ è definito nella classe \\"{name}\\"","invariantSuggestionDict":"Prova a passare da \\"dict\\" a \\"Mapping\\", che è covariante nel tipo di valore","invariantSuggestionList":"Prova a passare da \\"list\\" a \\"Sequence\\", che è covariante","invariantSuggestionSet":"Provare a passare da \\"ste\\" a \\"contenitore\\" che è covariante","keyNotRequired":"\\"{name}\\" non è una chiave obbligatoria in \\"{type}\\", quindi l\'accesso potrebbe causare un\'eccezione di runtime","keyReadOnly":"\\"{name}\\" è una chiave di sola lettura in \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" è una chiave obbligatoria e non può essere eliminata","keyUndefined":"\\"{name}\\" non è una chiave definita in \\"{type}\\"","kwargsParamMissing":"Il parametro \\"**{paramName}\\" non ha un parametro corrispondente","listAssignmentMismatch":"Il tipo \\"{type}\\" non è compatibile con l\'elenco di destinazione","literalAssignmentMismatch":"impossibile assegnare \\"{sourceType}\\" al tipo \\"{destType}\\"","matchIsNotExhaustiveHint":"Se la gestione completa non è prevista, aggiungere \\"case _: pass\\"","matchIsNotExhaustiveType":"Tipo non gestito: \\"{type}\\"","memberAssignment":"L\'espressione di tipo \\"{type}\\" non può essere assegnata al membro \\"{name}\\" della classe \\"{classType}\\".","memberIsAbstract":"\\"{type}.{name}\\" non implementato","memberIsAbstractMore":"e {{count}} altro...","memberIsClassVarInProtocol":"“{name}” è definito come ClassVar nel protocollo","memberIsFinalInProtocol":"\\"{name}\\" è contrassegnato come Finale nel protocollo","memberIsInitVar":"Il membro \\"{name}\\" è un campo solo init","memberIsInvariant":"\\"{name}\\" è invariante perché modificabile","memberIsNotClassVarInClass":"\\"{name}\\" deve essere definito come ClassVar per essere compatibile con il protocollo","memberIsNotClassVarInProtocol":"“{name}” non è definito come ClassVar nel protocollo","memberIsNotFinalInProtocol":"\\"{name}\\" non è contrassegnato come Finale nel protocollo","memberIsWritableInProtocol":"\\"{name}\\" è scrivibile nel protocollo","memberSetClassVar":"Non è possibile assegnare il membro \\"{name}\\" tramite un\'istanza di classe perché è una ClassVar","memberTypeMismatch":"\\"{name}\\" è un tipo non compatibile","memberUnknown":"Il membro \\"{name}\\" è sconosciuto","metaclassConflict":"La metaclasse \\"{metaclass1}\\" è in conflitto con \\"{metaclass2}\\"","missingDeleter":"Manca il metodo di eliminazione delle proprietà","missingGetter":"Metodo getter proprietà mancante","missingSetter":"Metodo setter proprietà mancante","namedParamMissingInDest":"Il parametro della parola chiave \\"{name}\\" non è presente nella destinazione","namedParamMissingInSource":"Parametro della parola chiave \\"{name}\\" mancante nell’origine","namedParamTypeMismatch":"Non è possibile assegnare il parametro di parola chiave \\"{name}\\" di tipo \\"{sourceType}\\" al tipo \\"{destType}\\"","namedTupleNotAllowed":"Non è possibile usare NamedTuple per i controlli di istanze o classi","newMethodLocation":"Il metodo __new__ è definito nella classe \\"{type}\\"","newMethodSignature":"La firma del __new__ è \\"{type}\\"","newTypeClassNotAllowed":"Impossibile utilizzare la classe creata con NewType con controlli di classe e di istanza","noOverloadAssignable":"Nessuna funzione di overload corrisponde al tipo \\"{type}\\"","noneNotAllowed":"Non è possibile usare None per i controlli di istanze o classi","orPatternMissingName":"Nomi mancanti: {name}","overloadIndex":"L\'overload {index} è la corrispondenza più vicina","overloadNotAssignable":"Uno o più overload di \\"{name}\\" non sono assegnabili","overloadSignature":"La firma di overload è definita qui","overriddenMethod":"Metodo sottoposto a override","overriddenSymbol":"Simbolo sottoposto a override","overrideInvariantMismatch":"Il tipo di override \\"{overrideType}\\" non è uguale al tipo di base \\"{baseType}\\"","overrideIsInvariant":"La variabile è modificabile, quindi il relativo tipo è invariante","overrideNoOverloadMatches":"Nessuna firma di overload nell\'override è compatibile con il metodo di base","overrideNotClassMethod":"Il metodo di base è dichiarato come metodo di classe, ma l\'override non è","overrideNotInstanceMethod":"Il metodo di base è dichiarato come metodo di istanza, ma l’override non lo è","overrideNotStaticMethod":"Il metodo di base è dichiarato come metodo statico, ma l\'override non è","overrideOverloadNoMatch":"La sostituzione non gestisce tutti gli overload del metodo di base","overrideOverloadOrder":"Gli overload per il metodo di override devono essere nello stesso ordine del metodo di base","overrideParamKeywordNoDefault":"Parametro della parola chiave \\"{name}\\" non corrispondente: il parametro di base ha un valore di argomento predefinito, il parametro di override non è","overrideParamKeywordType":"Tipo del parametro della parola chiave \\"{name}\\" non corrispondente: il parametro di base è di tipo \\"{baseType}\\", il parametro di override è di tipo \\"{overrideType}\\"","overrideParamName":"Nome del parametro {index} non corrispondente: il parametro di base è denominato \\"{baseName}\\", il parametro di override è denominato \\"{overrideName}\\"","overrideParamNameExtra":"Parametro \\"{name}\\" mancante nella base","overrideParamNameMissing":"Parametro \\"{name}\\" mancante nell\'override","overrideParamNamePositionOnly":"Mancata corrispondenza del parametro {index}: il parametro di base \\"{baseName}\\" è un parametro di parola chiave, il parametro di override è di sola posizione","overrideParamNoDefault":"Parametro \\"{index}\\" non corrispondente: il parametro di base ha un valore di argomento predefinito, il parametro di override non è","overrideParamType":"Tipo di parametro {index} non corrispondente: il parametro di base è di tipo \\"{baseType}\\", il parametro di override è di tipo \\"{overrideType}\\"","overridePositionalParamCount":"Numero di parametri posizionali non corrispondente. Il metodo di base ne ha {baseCount}, ma l\'override ne ha {overrideCount}","overrideReturnType":"Tipo restituito non corrispondente: il metodo di base restituisce il tipo \\"{baseType}\\", l\'override restituisce il tipo \\"{overrideType}\\"","overrideType":"La classe di base definisce il tipo come \\"{type}\\"","paramAssignment":"Impossibile assegnare il parametro {index}: il tipo \\"{sourceType}\\" al tipo \\"{destType}\\"","paramSpecMissingInOverride":"Parametri ParamSpec mancanti nel metodo di override","paramType":"Tipo di parametro \\"{paramType}\\"","privateImportFromPyTypedSource":"Importa da \\"{module}\\"","propertyAccessFromProtocolClass":"Non è possibile accedere a una proprietà definita all\'interno di una classe di protocollo come variabile di classe","propertyMethodIncompatible":"Il metodo di proprietà \\"{name}\\" non è compatibile","propertyMethodMissing":"Metodo di proprietà \\"{name}\\" mancante nell\'override","propertyMissingDeleter":"La proprietà \\"{name}\\" non ha un deleter definito","propertyMissingSetter":"La proprietà \\"{name}\\" non ha un setter definito","protocolIncompatible":"\\"{sourceType}\\" non è compatibile con il protocollo \\"{destType}\\"","protocolMemberMissing":"\\"{name}\\" non è presente","protocolRequiresRuntimeCheckable":"La classe del protocollo deve essere @runtime_checkable in modo che sia possibile usarla con i controlli di istanza e classe","protocolSourceIsNotConcrete":"\\"{sourceType}\\" non è un tipo di classe concreto e non può essere assegnato al tipo \\"{destType}\\"","protocolUnsafeOverlap":"Gli attributi di “{name}” hanno gli stessi nomi del protocollo","pyrightCommentIgnoreTip":"Usare \\"# pyright: ignore[<diagnostic rules>] per eliminare la diagnostica per una singola riga","readOnlyAttribute":"L\'attributo \\"{name}\\" è di sola lettura","seeClassDeclaration":"Vedere la dichiarazione di classe","seeDeclaration":"Vedere la dichiarazione","seeFunctionDeclaration":"Vedere la dichiarazione di funzione","seeMethodDeclaration":"Vedere la dichiarazione del metodo","seeParameterDeclaration":"Vedere la dichiarazione del parametro","seeTypeAliasDeclaration":"Vedere la dichiarazione di alias di tipo","seeVariableDeclaration":"Vedere la dichiarazione di variabile","tupleAssignmentMismatch":"Il tipo \\"{type}\\" non è compatibile con la tupla di destinazione","tupleEntryTypeMismatch":"Il tipo della voce di tupla {entry} non è corretto","tupleSizeIndeterminateSrc":"Dimensioni tupla non corrispondenti; previsto {expected} ma ricevuto indeterminato","tupleSizeIndeterminateSrcDest":"Dimensioni della tupla non corrispondenti; previsto {expected} o più, ma ricevuto indeterminato","tupleSizeMismatch":"Dimensioni tupla non corrispondenti; previsto {expected} ma ricevuto {received}","tupleSizeMismatchIndeterminateDest":"Dimensioni della tupla non corrispondenti; previsto {expected} o più ma ricevuto {received}","typeAliasInstanceCheck":"Non è possibile usare l\'alias di tipo creato con l\'istruzione \\"type\\" con controlli di classe e istanza","typeAssignmentMismatch":"impossibile assegnare il tipo \\"{sourceType}\\" al tipo \\"{destType}\\"","typeBound":"Il tipo \\"{sourceType}\\" non è compatibile con il tipo associato \\"{destType}\\" per la variabile di tipo \\"{name}\\"","typeConstrainedTypeVar":"Il tipo \\"{type}\\" non è compatibile con la variabile di tipo vincolato \\"{name}\\"","typeIncompatible":"\\"{sourceType}\\" non è compatibile con \\"{destType}\\"","typeNotClass":"\\"{type}\\" non è una classe","typeNotStringLiteral":"\\"{type}\\" non è un valore letterale stringa","typeOfSymbol":"Il tipo di \\"{name}\\" è \\"{type}\\"","typeParamSpec":"Il tipo \\"{type}\\" non è compatibile con il \\"{name}\\" ParamSpec","typeUnsupported":"Il tipo \\"{type}\\" non è supportato","typeVarDefaultOutOfScope":"La variabile di tipo \\"{name}\\" non è nell\'ambito","typeVarIsContravariant":"Il parametro di tipo \\"{name}\\" è controvariante, ma \\"{sourceType}\\" non è un supertipo di \\"{destType}\\"","typeVarIsCovariant":"Il parametro di tipo \\"{name}\\" è covariante, ma \\"{sourceType}\\" non è un sottotipo di \\"{destType}\\"","typeVarIsInvariant":"Il parametro di tipo \\"{name}\\" è invariante, ma \\"{sourceType}\\" non è uguale a \\"{destType}\\"","typeVarNotAllowed":"TypeVar non consentito per i controlli di istanze o classi","typeVarTupleRequiresKnownLength":"Non è possibile associare TypeVarTuple a una tupla di lunghezza sconosciuta","typeVarUnnecessarySuggestion":"Usare invece {type}","typeVarUnsolvableRemedy":"Specificare un overload che specifica il tipo restituito quando l\'argomento non viene fornito","typeVarsMissing":"Variabili di tipo mancanti: {names}","typedDictBaseClass":"La classe \\"{type}\\" non è un TypedDict","typedDictClassNotAllowed":"Classe TypedDict non consentita per i controlli di istanze o classi","typedDictClosedExtraNotAllowed":"Non è possibile aggiungere l\'elemento \\"{name}\\"","typedDictClosedExtraTypeMismatch":"Non è possibile aggiungere l\'elemento \\"{name}\\" con tipo \\"{type}\\"","typedDictClosedFieldNotRequired":"Non è possibile aggiungere l\'elemento \\"{name}\\" perché deve essere NotRequired","typedDictExtraFieldNotAllowed":"\\"{name}\\" non è presente in \\"{type}\\"","typedDictExtraFieldTypeMismatch":"Il tipo di \\"{name}\\" non è compatibile con il tipo \\"__extra_items__\\" in \\"{type}\\"","typedDictFieldMissing":"\\"{name}\\" mancante nel \\"{type}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" non è di sola lettura in \\"{type}\\"","typedDictFieldNotRequired":"\\"{name}\\" non è obbligatorio in \\"{type}\\"","typedDictFieldRequired":"\\"{name}\\" è obbligatorio in \\"{type}\\"","typedDictFieldTypeMismatch":"Il tipo \\"{type}\\" non può essere assegnato all’elemento \\"{name}\\"","typedDictFieldUndefined":"\\"{name}\\" è un elemento non definito nel tipo \\"{type}\\"","typedDictFinalMismatch":"\\"{sourceType}\\" non è compatibile con \\"{destType}\\" a causa di una @final mancata corrispondenza","typedDictKeyAccess":"Usare [\\"{name}\\"] per fare riferimento all\'elemento in TypedDict","typedDictNotAllowed":"Non è possibile usare TypedDict per i controlli di istanze o classi","unhashableType":"Il tipo \\"{type}\\" non è hashable","uninitializedAbstractVariable":"La variabile di istanza \\"{name}\\" è definita nella classe di base astratta \\"{classType}\\" ma non è inizializzata","unreachableExcept":"\\"{exceptionType}\\" è una sottoclasse di \\"{parentType}\\"","useDictInstead":"Usare Dict[T1, T2] per indicare un tipo di dizionario","useListInstead":"Usare List[T] per indicare un tipo di elenco o Union[T1, T2] per indicare un tipo di unione","useTupleInstead":"Usare tuple[T1, ..., Tn] per indicare un tipo di tupla o Union[T1, T2] per indicare un tipo di unione","useTypeInstead":"In alternativa, usare Type[T]","varianceMismatchForClass":"La varianza dell\'argomento tipo \\"{typeVarName}\\" non è compatibile con la classe di base \\"{className}\\"","varianceMismatchForTypeAlias":"La varianza dell\'argomento tipo \\"{typeVarName}\\" non è compatibile con \\"{typeAliasParam}\\""}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.ja.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.ja.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"型スタブの作成","createTypeStubFor":"\\"{moduleName}\\" の型スタブを作成する","executingCommand":"コマンドの実行中","filesToAnalyzeCount":"分析する {count} 個のファイル","filesToAnalyzeOne":"分析する 1 つのファイル","findingReferences":"参照を検索しています","organizeImports":"インポートを整理","renameShadowedFile":"\\"{oldFile}\\" の名前を \\"{newFile}\\" に変更します"},"Completion":{"autoImportDetail":"自動インポート","indexValueDetail":"インデックス値"},"Diagnostic":{"abstractMethodInvocation":"メソッド \\"{method}\\" は抽象メソッドであり、実装されていないため、呼び出すことができません","annotatedParamCountMismatch":"パラメーター注釈数の不一致: {expected} が必要ですが、{received} を受信しました","annotatedTypeArgMissing":"\\"Annotationed\\" には 1 つの型引数と 1 つ以上の注釈が必要です","annotationFormatString":"型注釈では、書式指定文字列リテラル (f 文字列) を使用できません","annotationNotSupported":"このステートメントでは型注釈はサポートされていません","annotationSpansStrings":"型注釈を複数の文字列リテラルにまたがることはできません","annotationStringEscape":"型注釈にエスケープ文字を含めることはできません","argAssignment":"型 \\"{argType}\\" の引数を型 \\"{paramType}\\" のパラメーターに割り当てることはできません","argAssignmentFunction":"型 \\"{argType}\\" の引数を関数 \\"{functionName}\\" の型 \\"{paramType}\\" のパラメーターに割り当てることはできません","argAssignmentParam":"型 \\"{argType}\\" の引数を型 \\"{paramType}\\" のパラメーター \\"{paramName}\\" に割り当てることはできません","argAssignmentParamFunction":"型 \\"{argType}\\" の引数を、関数 \\"{functionName}\\" の型 \\"{paramType}\\" のパラメーター \\"{paramName}\\" に割り当てることはできません","argMissingForParam":"パラメーター {name} に引数がありません","argMissingForParams":"パラメーター {names} に引数がありません","argMorePositionalExpectedCount":"さらに {expected} 個の位置引数が必要です","argMorePositionalExpectedOne":"さらに 1 つの位置引数が必要です","argPositional":"必要な位置引数","argPositionalExpectedCount":"{expected} 個の位置引数が必要です","argPositionalExpectedOne":"1 個の位置引数が必要です","argTypePartiallyUnknown":"引数の型が部分的に不明です","argTypeUnknown":"引数の型が不明です","assertAlwaysTrue":"Assert 式は常に true に評価されます","assertTypeArgs":"\\"assert_type\\" には 2 つの位置引数が必要です","assertTypeTypeMismatch":"\\"assert_type\\" の不一致: \\"{expected}\\" が必要ですが、\\"{received}\\" を受信しました","assignmentExprComprehension":"代入式のターゲット \\"{name}\\" は、ターゲットの理解と同じ名前を使用できません","assignmentExprContext":"代入式は、モジュール、関数、またはラムダ内に存在する必要があります","assignmentExprInSubscript":"下付き文字内の代入式は、Python 3.10 以降でのみサポートされます","assignmentInProtocol":"Protocol クラス内のインスタンス変数またはクラス変数は、クラス本体内で明示的に宣言する必要があります","assignmentTargetExpr":"式を代入先にすることはできません","asyncNotInAsyncFunction":"非同期関数の外部では \\"async\\" の使用は許可されていません","awaitIllegal":"\\"await\\" を使用するには Python 3.5 以降が必要です","awaitNotAllowed":"型の注釈で \\"await\\" は使用できません","awaitNotInAsync":"\\"await\\" は非同期関数内でのみ許可されます","backticksIllegal":"バッククォートで囲まれた式は、Python 3.x ではサポートされていません。代わりに repr を使用してください","baseClassCircular":"クラス自体から派生することはできません","baseClassFinal":"基底クラス \\"{type}\\" は final とマークされており、サブクラス化できません","baseClassIncompatible":"{type} の基底クラスは相互に互換性がありません","baseClassInvalid":"クラスへの引数は基底クラスである必要があります","baseClassMethodTypeIncompatible":"\\"{classType}\\" の基底クラスは、互換性のない方法でメソッド \\"{name}\\" を定義します","baseClassUnknown":"基底クラスの型が不明で、派生クラスの型が不明です","baseClassVariableTypeIncompatible":"クラス \\"{classType}\\" の基底クラスは、互換性のない方法で変数 \\"{name}\\" を定義します","binaryOperationNotAllowed":"型の注釈で 2 項演算子は使用できません","bindTypeMismatch":"\\"{type}\\" がパラメーター \\"{paramName}\\" に割り当てできないため、メソッド \\"{methodName}\\" をバインドできませんでした","breakOutsideLoop":"\\"break\\" はループ内でのみ使用できます","callableExtraArgs":"\\"Callable\\" に必要な型引数は 2 つだけです","callableFirstArg":"パラメーターの型リストまたは \\"...\\" が必要です。","callableNotInstantiable":"型 \\"{type}\\" をインスタンス化できません","callableSecondArg":"\\"Callable\\" の 2 番目の型引数として戻り値の型が必要です","casePatternIsIrrefutable":"参照不可能なパターンは、最後の case ステートメントに対してのみ許可されます","classAlreadySpecialized":"型 \\"{type}\\" は既に特殊化されています","classDecoratorTypeUnknown":"型指定されていないクラス デコレーターはクラスの型を隠します。デコレーターを無視する","classDefinitionCycle":"\\"{name}\\" のクラス定義は、それ自体に依存します","classGetItemClsParam":"__class_getitem__ override は \\"cls\\" パラメーターを受け取る必要があります","classMethodClsParam":"クラス メソッドは \\"cls\\" パラメーターを受け取る必要があります","classNotRuntimeSubscriptable":"クラス \\"{name}\\" の添字はランタイム例外を生成します。型の注釈を引用符で囲む","classPatternBuiltInArgPositional":"クラス パターンは位置指定サブパターンのみを受け入れます","classPatternPositionalArgCount":"クラス \\"{type}\\" の位置指定パターンが多すぎます。{expected} が必要ですが、{received} を受信しました","classPatternTypeAlias":"\\"{type}\\" は特殊な型エイリアスであるため、クラス パターンでは使用できません","classPropertyDeprecated":"クラス プロパティは Python 3.11 では非推奨であり、Python 3.13 ではサポートされなくなります","classTypeParametersIllegal":"クラス型パラメーターの構文には Python 3.12 以降が必要です","classVarFirstArgMissing":"\\"ClassVar\\" の後に型引数が必要です","classVarNotAllowed":"\\"ClassVar\\" はこのコンテキストでは許可されていません","classVarOverridesInstanceVar":"クラス変数 \\"{name}\\" は、クラス \\"{className}\\" の同じ名前のインスタンス変数をオーバーライドします","classVarTooManyArgs":"\\"ClassVar\\" の後に必要な型引数は 1 つだけです","classVarWithTypeVar":"\\"ClassVar\\" 型に型変数を含めることはできません","clsSelfParamTypeMismatch":"パラメーター \\"{name}\\" の型は、そのクラス \\"{classType}\\" のスーパータイプである必要があります","codeTooComplexToAnalyze":"コードが複雑すぎるため、分析できません。サブルーチンにリファクタリングするか、条件付きコード パスを減らすことで複雑さを軽減してください","collectionAliasInstantiation":"型 \\"{type}\\" はインスタンス化できません。代わりに \\"{alias}\\" を使用してください","comparisonAlwaysFalse":"型 \\"{leftType}\\" と \\"{rightType}\\" に重複がないため、条件は常に False に評価されます","comparisonAlwaysTrue":"型 \\"{leftType}\\" と \\"{rightType}\\" に重複がないため、条件は常に True に評価されます","comprehensionInDict":"他の辞書エントリと共に理解することはできません","comprehensionInSet":"他のセット エントリと共に理解を使用することはできません","concatenateContext":"\\"Concatenate\\" はこのコンテキストで許可されていません","concatenateParamSpecMissing":"\\"Concatenate\\" の最後の型引数は ParamSpec または \\"...\\" である必要があります","concatenateTypeArgsMissing":"\\"連結\\" には少なくとも 2 つの型引数が必要です","conditionalOperandInvalid":"型 \\"{type}\\" の条件オペランドが無効です","constantRedefinition":"\\"{name}\\" は定数であり (大文字であるため)、再定義できません","constructorNoArgs":"\\"{type}\\" コンストラクターに引数が必要ありません","constructorParametersMismatch":"クラス \\"{classType}\\" の__new__と__init__のシグネチャの不一致","containmentAlwaysFalse":"型 \\"{leftType}\\" と \\"{rightType}\\" に重複がないため、式は常に False に評価されます","containmentAlwaysTrue":"型 \\"{leftType}\\" と \\"{rightType}\\" に重複がないため、式は常に True に評価されます","continueInFinally":"finally 句内では \\"continue\\" を使用できません","continueOutsideLoop":"\\"continue\\" はループ内でのみ使用できます","coroutineInConditionalExpression":"常に True に評価される条件式参照コルーチン","dataClassBaseClassFrozen":"固定されていないクラスは、固定されているクラスから継承できません","dataClassBaseClassNotFrozen":"固定されたクラスは、固定されていないクラスから継承できません","dataClassConverterFunction":"型 \\"{argType}\\" の引数は、型 \\"{fieldType}\\" のフィールド \\"{fieldName}\\" の有効なコンバーターではありません","dataClassConverterOverloads":"{funcName}\\" のオーバーロードは、型 \\"{fieldType}\\" のフィールド \\"{fieldName}\\" に対して有効なコンバーターではありません","dataClassFieldWithDefault":"既定値のないフィールドは、既定値を持つフィールドの後に表示できません","dataClassFieldWithPrivateName":"データクラス フィールドはプライベート名を使用できません","dataClassFieldWithoutAnnotation":"型注釈のないデータクラス フィールドが原因でランタイム例外が発生する","dataClassPostInitParamCount":"Dataclass __post_init__ パラメーター数が正しくありません。InitVar フィールドの数は {expected} です","dataClassPostInitType":"フィールド \\"{fieldName}\\" の Dataclass __post_init__ メソッド パラメーターの型が一致しません","dataClassSlotsOverwrite":"__slots__はクラスで既に定義されています","dataClassTransformExpectedBoolLiteral":"静的に True または False に評価される式が必要です","dataClassTransformFieldSpecifier":"クラスまたは関数のタプルが必要ですが、型 \\"{type}\\" を受け取りました","dataClassTransformPositionalParam":"\\"dataclass_transform\\" に対するすべての引数はキーワード引数である必要があります","dataClassTransformUnknownArgument":"引数 \\"{name}\\" はdataclass_transform でサポートされていません","dataProtocolInSubclassCheck":"データ プロトコル (メソッド以外の属性を含む) は、issubclass 呼び出しで使用できません","declaredReturnTypePartiallyUnknown":"宣言された戻り値の型 \\"{returnType}\\" は部分的に不明です","declaredReturnTypeUnknown":"宣言された戻り値の型が不明です","defaultValueContainsCall":"パラメーターの既定値の式内では、関数呼び出しと変更可能なオブジェクトは許可されません","defaultValueNotAllowed":"\\"*\\" または \\"**\\" のパラメーターに既定値を指定することはできません","delTargetExpr":"式を削除できません","deprecatedClass":"クラス \\"{name}\\" は非推奨です","deprecatedConstructor":"クラス \\"{name}\\" のコンストラクターは非推奨です","deprecatedDescriptorDeleter":"記述子 \\"{name}\\" の \\"__delete__\\" メソッドは非推奨です","deprecatedDescriptorGetter":"記述子 \\"{name}\\" の \\"__get__\\" メソッドは非推奨です","deprecatedDescriptorSetter":"記述子 \\"{name}\\" の \\"__set__\\" メソッドは非推奨です","deprecatedFunction":"関数 \\"{name}\\" は非推奨です","deprecatedMethod":"クラス \\"{className}\\" のメソッド \\"{name}\\" は非推奨です","deprecatedPropertyDeleter":"プロパティ \\"{name}\\" の削除子は非推奨です","deprecatedPropertyGetter":"プロパティ \\"{name}\\" のゲッターは非推奨です","deprecatedPropertySetter":"プロパティ \\"{name}\\" のセッターは非推奨です","deprecatedType":"この型は Python {version} では非推奨です。代わりに\\"{replacement}\\"を使用してください","dictExpandIllegalInComprehension":"辞書の展開は理解できません","dictInAnnotation":"辞書式は型注釈では使用できません","dictKeyValuePairs":"辞書エントリにはキー/値のペアが含まれている必要があります","dictUnpackIsNotMapping":"ディクショナリ アンパック演算子に必要なマッピング","dunderAllSymbolNotPresent":"\\"{name}\\" は __all__ で指定されていますが、モジュールには存在しません","duplicateArgsParam":"許可される \\"*\\" パラメーターは 1 つだけです","duplicateBaseClass":"重複する基底クラスは許可されていません","duplicateCapturePatternTarget":"Capture ターゲット \\"{name}\\" を同じパターン内に複数回出現させることはできません","duplicateCatchAll":"許可される catch-all except 句は 1 つだけです","duplicateEnumMember":"列挙型メンバー \\"{name}\\" は既に宣言されています","duplicateGenericAndProtocolBase":"許可される Generic[...] または Protocol[...] 基底クラスは 1 つだけです","duplicateImport":"\\"{importName}\\" が複数回インポートされています","duplicateKeywordOnly":"\\"*\\" 区切り記号を 1 つだけ使用できます","duplicateKwargsParam":"許可される \\"**\\" パラメーターは 1 つだけです","duplicateParam":"パラメーター \\"{name}\\" が重複しています","duplicatePositionOnly":"許可される \\"/\\" パラメーターは 1 つだけです","duplicateStarPattern":"パターン シーケンスで使用できる \\"*\\" パターンは 1 つだけです","duplicateStarStarPattern":"許可されている \\"**\\" エントリは 1 つだけです","duplicateUnpack":"リストで許可されているアンパック操作は 1 つだけです","ellipsisAfterUnpacked":"\\"...\\" はアンパックされた TypeVarTuple または tuple と共に使用することはできません","ellipsisContext":"\\"...\\" はこのコンテキストでは許可されていません","ellipsisSecondArg":"\\"...\\" は2 つの引数の 2 番目の引数としてのみ使用できます","enumClassOverride":"列挙型クラス \\"{name}\\" は最終的なクラスであり、サブクラス化できません","exceptionGroupIncompatible":"例外グループの構文 (\\"except*\\") には Python 3.11 以降が必要です","exceptionTypeIncorrect":"\\"{type}\\" は BaseException から派生していません","exceptionTypeNotClass":"\\"{type}\\" は有効な例外クラスではありません","exceptionTypeNotInstantiable":"例外の種類 \\"{type}\\" のコンストラクターには 1 つ以上の引数が必要です","expectedAfterDecorator":"デコレーターの後に必要な関数またはクラス宣言","expectedArrow":"\\"->\\" の後に戻り値の型注釈が続く必要があります","expectedAsAfterException":"例外の種類の後に \\"as\\" が必要です","expectedAssignRightHandExpr":"\\"=\\" の右側に式が必要です","expectedBinaryRightHandExpr":"演算子の右側に式が必要です","expectedBoolLiteral":"True または False が必要です","expectedCase":"\\"case\\" ステートメントが必要です","expectedClassName":"必要なクラス名","expectedCloseBrace":"\\"{\\" は閉じられていません","expectedCloseBracket":"\\"[\\" は閉じられていません","expectedCloseParen":"\\"(\\" が閉じられませんでした","expectedColon":"\\":\\" が必要です","expectedComplexNumberLiteral":"パターン マッチングに必要な複素数リテラル","expectedDecoratorExpr":"Python 3.9 より前のデコレーターでは、式フォームはサポートされていません","expectedDecoratorName":"デコレーター名が必要です","expectedDecoratorNewline":"デコレーターの末尾に新しい行が必要です","expectedDelExpr":"\\"del\\" の後に式が必要です","expectedElse":"\\"else\\" が必要です","expectedEquals":"\\"=\\" が必要です","expectedExceptionClass":"例外クラスまたはオブジェクトが無効です","expectedExceptionObj":"例外オブジェクト、例外クラス、または None が必要です","expectedExpr":"式が必要です","expectedFunctionAfterAsync":"\\"async\\" の後に必要な関数定義","expectedFunctionName":"\\"def\\" の後に関数名が必要です","expectedIdentifier":"必要な識別子","expectedImport":"\\"import\\" が必要です","expectedImportAlias":"\\"as\\" の後にシンボルが必要です","expectedImportSymbols":"インポート後に 1 つ以上のシンボル名が必要です","expectedIn":"\'in\' が必要です","expectedInExpr":"\\"in\\" の後に式が必要です","expectedIndentedBlock":"インデントされたブロックが必要です","expectedMemberName":"\\".\\" の後にメンバー名が必要です。","expectedModuleName":"必要なモジュール名","expectedNameAfterAs":"\\"as\\" の後にシンボル名が必要です","expectedNamedParameter":"キーワード パラメーターは \\"*\\" の後に続く必要があります","expectedNewline":"改行が必要です","expectedNewlineOrSemicolon":"ステートメントは改行またはセミコロンで区切る必要があります","expectedOpenParen":"\\"(\\" が必要です","expectedParamName":"必要なパラメーター名","expectedPatternExpr":"必要なパターン式","expectedPatternSubjectExpr":"必要なパターンの件名の式","expectedPatternValue":"\\"a.b\\" 形式のパターン値式が必要です","expectedReturnExpr":"\\"return\\" の後に式が必要です","expectedSliceIndex":"インデックスまたはスライス式が必要です","expectedTypeNotString":"必要な型ですが、文字列リテラルを受け取りました","expectedTypeParameterName":"必要な型パラメーター名","expectedYieldExpr":"yield ステートメントで必要な式","finalClassIsAbstract":"クラス \\"{type}\\" は final とマークされており、すべての抽象なシンボルを実装する必要があります","finalContext":"\\"Final\\" はこのコンテキストでは許可されていません","finalMethodOverride":"メソッド \\"{name}\\" は、クラス \\"{className}\\" で定義されている最終的なメソッドをオーバーライドできません","finalNonMethod":"関数 \\"{name}\\" はメソッドではないため、@final としてマークできません","finalReassigned":"\\"{name}\\" は Final として宣言されており、再割り当てできません","finalRedeclaration":"\\"{name}\\" は以前に Final として宣言されました","finalRedeclarationBySubclass":"親クラス \\"{className}\\" が Final として宣言しているため、\\"{name}\\" を再宣言できません","finalTooManyArgs":"\\"Final\\" の後に 1 つの型引数が必要です","finalUnassigned":"\\"{name}\\" は Final と宣言されていますが、値は割り当てされていません","formatStringBrace":"f-string リテラル内では、1 つの閉じかっこは使用できません。二重閉じかっこを使用してください","formatStringBytes":"書式指定文字列リテラル (f 文字列) をバイナリにすることはできません","formatStringDebuggingIllegal":"F-string デバッグ指定子 \\"=\\" には Python 3.8 以降が必要です","formatStringEscape":"Python 3.12 より前の f-string の式部分ではエスケープ シーケンス (バックスラッシュ) は使用できません","formatStringExpectedConversion":"f-string の \\"!\\" の後に変換指定子が必要です","formatStringIllegal":"書式文字列リテラル (f 文字列) には Python 3.6 以降が必要です","formatStringInPattern":"書式指定文字列はパターンでは使用できません","formatStringNestedFormatSpecifier":"書式指定子内で入れ子になった式が深すぎます","formatStringNestedQuote":"f-string 内で入れ子になった文字列は、Python 3.12 より前の f-string と同じ引用符文字を使用できません","formatStringUnicode":"書式指定文字列リテラル (f 文字列) を Unicode にすることはできません","formatStringUnterminated":"f-string の式が終了していません。\\"}\\" が必要です","functionDecoratorTypeUnknown":"型指定されていない関数デコレーターは、関数の型を隠します。デコレーターを無視しています","functionInConditionalExpression":"常に True に評価される条件式参照関数","functionTypeParametersIllegal":"関数型パラメーターの構文には Python 3.12 以降が必要です","futureImportLocationNotAllowed":"__future__ からのインポートは、ファイルの先頭にある必要があります","generatorAsyncReturnType":"非同期ジェネレーター関数の戻り値の型は、\\"AsyncGenerator[{yieldType}, Any]\\" と互換性がある必要があります","generatorNotParenthesized":"ジェネレーター式は、唯一の引数でない場合はかっこで囲む必要があります","generatorSyncReturnType":"ジェネレーター関数の戻り値の型は、\\"Generator[{yieldType}, Any, Any]\\" と互換性がある必要があります","genericBaseClassNotAllowed":"\\"Generic\\" 基底クラスを型パラメーター構文と共に使用することはできません","genericClassAssigned":"ジェネリック クラス型を割り当てることはできません","genericClassDeleted":"ジェネリック クラス型を削除できません","genericInstanceVariableAccess":"クラスを介したジェネリック インスタンス変数へのアクセスがあいまいです","genericNotAllowed":"\\"Generic\\" はこのコンテキストでは無効です","genericTypeAliasBoundTypeVar":"クラス内のジェネリック型エイリアスはバインドされた型変数 {names} を使用できません","genericTypeArgMissing":"\\"Generic\\" には少なくとも 1 つの型引数が必要です","genericTypeArgTypeVar":"\\"Generic\\" の型引数は型変数である必要があります","genericTypeArgUnique":"\\"Generic\\" の型引数は一意である必要があります","globalReassignment":"\\"{name}\\" はグローバル宣言の前に割り当てられます","globalRedefinition":"\\"{name}\\" は既にグローバルに宣言されています","implicitStringConcat":"暗黙的な文字列連結は許可されていません","importCycleDetected":"インポート チェーンで循環が検出されました","importDepthExceeded":"インポート チェーンの深さが {depth} を超えました","importResolveFailure":"インポート \\"{importName}\\" を解決できませんでした","importSourceResolveFailure":"インポート \\"{importName}\\" をソースから解決できませんでした","importSymbolUnknown":"\\"{name}\\" は不明なインポート シンボルです","incompatibleMethodOverride":"メソッド \\"{name}\\" は互換性のない方法でクラス \\"{className}\\" をオーバーライドします","inconsistentIndent":"元のサイズが前のインデントと一致しません","inconsistentTabs":"インデントでのタブとスペースの一貫性のない使用","initMustReturnNone":"\\"__init__\\" の戻り値の型は None でなければなりません","initSubclassCallFailed":"__init_subclass__ メソッドのキーワード引数が正しくありません","initSubclassClsParam":"__class_getitem__ override は \\"cls\\" パラメーターを受け取る必要があります","initVarNotAllowed":"\\"InitVar\\" はこのコンテキストでは許可されていません","instanceMethodSelfParam":"インスタンス メソッドは \\"self\\" パラメーターを受け取る必要があります","instanceVarOverridesClassVar":"インスタンス変数 \\"{name}\\" は、クラス \\"{className}\\" の同じ名前のクラス変数をオーバーライドします","instantiateAbstract":"抽象クラス \\"{type}\\" をインスタンス化できません","instantiateProtocol":"プロトコル クラス \\"{type}\\" をインスタンス化できません","internalBindError":"ファイル \\"{file}\\" のバインド中に内部エラーが発生しました: {message}","internalParseError":"ファイル \\"{file}\\" の解析中に内部エラーが発生しました: {message}","internalTypeCheckingError":"ファイル \\"{file}\\" の種類チェック中に内部エラーが発生しました: {message}","invalidIdentifierChar":"識別子の無効な文字","invalidStubStatement":"ステートメントは型スタブ ファイル内では意味がありません","invalidTokenChars":"トークン内の無効な文字 \\"{text}\\"","isInstanceInvalidType":"\\"isinstance\\" の 2 番目の引数は、クラスのクラスまたはタプルである必要があります","isSubclassInvalidType":"\\"issubclass\\" の 2 番目の引数は、クラスまたはクラスのタプルである必要があります","keyValueInSet":"キー/値のペアはセット内では使用できません","keywordArgInTypeArgument":"キーワード引数は型引数リストでは使用できません","keywordOnlyAfterArgs":"キーワードのみの引数の区切り記号は、\\"*\\" パラメーターの後には使用できません","keywordParameterMissing":"1 つ以上のキーワード パラメーターが \\"*\\" パラメーターの後に続く必要があります","keywordSubscriptIllegal":"添字内のキーワード引数はサポートされていません","lambdaReturnTypePartiallyUnknown":"ラムダの戻り値の型、\\"{returnType}\\" が部分的に不明です","lambdaReturnTypeUnknown":"ラムダの戻り値の型が不明です","listAssignmentMismatch":"型 \\"{type}\\" の式をターゲット リストに割り当てることはできません","listInAnnotation":"型注釈ではリスト式は使用できません","literalEmptyArgs":"\\"Literal\\" の後に 1 つ以上の型引数が必要です","literalNotAllowed":"\\"Literal\\" は、型引数なしでこのコンテキストでは使用できません","literalNotCallable":"リテラル型をインスタンス化できません","literalUnsupportedType":"\\"Literal\\" の型引数は None、リテラル値 (int、bool、str、または bytes)、または列挙型の値である必要があります","matchIncompatible":"Match ステートメントには Python 3.10 以降が必要です","matchIsNotExhaustive":"match ステートメント内のケースでは、すべての値が完全に処理されるわけではありません","maxParseDepthExceeded":"解析の最大深さを超えました。式を小さい部分式に分割する","memberAccess":"型 \\"{type}\\" のメンバー \\"{name}\\" にアクセスできません","memberDelete":"型 \\"{type}\\" のメンバー \\"{name}\\" を削除できません","memberSet":"型 \\"{type}\\" にメンバー \\"{name}\\" を割り当てることができません","metaclassConflict":"派生クラスのメタクラスは、そのすべての基底クラスのメタクラスのサブクラスである必要があります","metaclassDuplicate":"指定できるメタクラスは 1 つだけです","metaclassIsGeneric":"メタクラスをジェネリックにすることはできません","methodNotDefined":"\\"{name}\\" メソッドが定義されていません","methodNotDefinedOnType":"型 \\"{type}\\" に \\"{name}\\" メソッドが定義されていません","methodOrdering":"一貫性のあるメソッドの順序を作成できません","methodOverridden":"\\"{name}\\" は、クラス \\"{className}\\" の同じ名前のメソッドを互換性のない型 \\"{type}\\" でオーバーライドします","methodReturnsNonObject":"\\"{name}\\" メソッドはオブジェクトを返しません","missingSuperCall":"メソッド \\"{methodName}\\" は親クラスで同じ名前のメソッドを呼び出しません","moduleAsType":"モジュールを型として使用することはできません","moduleNotCallable":"モジュールは呼び出し可能ではありません","moduleUnknownMember":"\\"{memberName}\\" はモジュール \\"{moduleName}\\" の既知のメンバーではありません","namedExceptAfterCatchAll":"名前付き except 句は、catch-all except 句の後には使用できません","namedParamAfterParamSpecArgs":"ParamSpec args パラメーターの後にキーワード パラメーター \\"{name}\\" をシグネチャに含めることはできません","namedTupleEmptyName":"名前付きタプル内の名前を空にすることはできません","namedTupleEntryRedeclared":"親クラス \\"{className}\\" が名前付きタプルであるため、\\"{name}\\" をオーバーライドできません","namedTupleFirstArg":"最初の引数として名前付きタプル クラス名が必要です","namedTupleMultipleInheritance":"NamedTuple による複数の継承はサポートされていません","namedTupleNameKeyword":"フィールド名をキーワードにすることはできません","namedTupleNameType":"エントリ名と型を指定する 2 エントリタプルが必要です","namedTupleNameUnique":"名前付きタプル内の名前は一意である必要があります","namedTupleNoTypes":"\\"namedtuple\\" はタプル エントリに型を提供しません。代わりに \\"NamedTuple\\" を使用してください","namedTupleSecondArg":"2 番目の引数として名前付きタプル エントリ リストが必要です","newClsParam":"__new__ override は \\"cls\\" パラメーターを受け取る必要があります","newTypeAnyOrUnknown":"NewType の 2 番目の引数は、Any や Unknown ではなく、既知のクラスでなければなりません","newTypeBadName":"NewType の最初の引数は文字列リテラルである必要があります","newTypeLiteral":"NewType はリテラル型では使用できません","newTypeNameMismatch":"NewType は同じ名前の変数に割り当てる必要があります","newTypeNotAClass":"NewType の 2 番目の引数としてクラスが必要です","newTypeParamCount":"NewType には 2 つの位置引数が必要です","newTypeProtocolClass":"NewType は構造型 (プロトコルまたは TypedDict クラス) では使用できません","noOverload":"指定された引数に一致する \\"{name}\\" のオーバーロードがありません","noReturnContainsReturn":"戻り値の型が \\"NoReturn\\" として宣言されている関数に return ステートメントを含めることはできません","noReturnContainsYield":"戻り値の型 \\"NoReturn\\" を宣言した関数に yield ステートメントを含めることはできません","noReturnReturnsNone":"戻り値の型が \\"NoReturn\\" として宣言されている関数は \\"None\\" を返すことができません","nonDefaultAfterDefault":"既定以外の引数は既定の引数の後に続きます","nonLocalInModule":"モジュール レベルでは非ローカル宣言は許可されません","nonLocalNoBinding":"非ローカル \\"{name}\\" のバインドが見つかりません","nonLocalReassignment":"\\"{name}\\" は非ローカル宣言の前に割り当てられます","nonLocalRedefinition":"\\"{name}\\" は既に非ローカルとして宣言されています","noneNotCallable":"\\"None\\" 型のオブジェクトを呼び出すことはできません","noneNotIterable":"型 \\"None\\" のオブジェクトを反復可能な値として使用することはできません","noneNotSubscriptable":"\\"None\\" 型のオブジェクトは添字可能ではありません","noneNotUsableWith":"\\"None\\" 型のオブジェクトを \\"with\\" と共に使用することはできません","noneOperator":"演算子 \\"{operator}\\" は \\"None\\" ではサポートされていません","noneUnknownMember":"\\"{name}\\" は \\"None\\" の既知のメンバーではありません","notRequiredArgCount":"\\"NotRequired\\" の後に 1 つの型引数が必要です","notRequiredNotInTypedDict":"\\"NotRequired\\" はこのコンテキストでは許可されていません","objectNotCallable":"型 \\"{type}\\" のオブジェクトは呼び出し可能ではありません","obscuredClassDeclaration":"クラス宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","obscuredFunctionDeclaration":"関数宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","obscuredMethodDeclaration":"メソッド宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","obscuredParameterDeclaration":"パラメーター宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","obscuredTypeAliasDeclaration":"型エイリアス宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","obscuredVariableDeclaration":"宣言 \\"{name}\\" は、同じ名前の宣言によって隠されています","operatorLessOrGreaterDeprecated":"演算子 \\"<>\\" は Python 3 ではサポートされていません。代わりに \\"!=\\" を使用してください","optionalExtraArgs":"\\"Optional\\" の後に 1 つの型引数が必要です","orPatternIrrefutable":"参照不可能なパターンは、\\"or\\" パターンの最後のサブパターンとしてのみ許可されます","orPatternMissingName":"\\"or\\" パターン内のすべてのサブパターンは、同じ名前をターゲットにする必要があります","overlappingKeywordArgs":"入力された辞書はキーワード パラメーターと重複しています: {names}","overlappingOverload":"パラメーターがオーバーロード {obscuredBy} と重複しているため、\\"{name}\\" のオーバーロード {obscured} は使用されません","overloadAbstractMismatch":"オーバーロードされたメソッドはすべて抽象である必要があります。","overloadClassMethodInconsistent":"\\"{name}\\" のオーバーロードでは、@classmethod を不整合に使用します","overloadFinalInconsistencyImpl":"\\"{name}\\" のオーバーロードは @final としてマークされていますが、実装は @final としてマークされていません","overloadFinalInconsistencyNoImpl":"\\"{name}\\" のオーバーロード {index} は @final としてマークされていますが、オーバーロード 1 は @final としてマークされていません","overloadImplementationMismatch":"オーバーロードされた実装がオーバーロード {index} のシグネチャと一致しません","overloadReturnTypeMismatch":"\\"{name}\\" のオーバーロード {prevIndex} はオーバーロード {newIndex} と重複し、互換性のない型を返します","overloadStaticMethodInconsistent":"\\"{name}\\" のオーバーロードでは、@staticmethod を不整合に使用します","overloadWithoutImplementation":"\\"{name}\\" はオーバーロードとしてマークされていますが、実装は提供されていません","overriddenMethodNotFound":"メソッド \\"{name}\\" はオーバーライドとしてマークされていますが、同じ名前の基本メソッドが存在しません","overrideDecoratorMissing":"メソッド \\"{name}\\" はオーバーライドとしてマークされていませんが、クラス \\"{className}\\" のメソッドをオーバーライドしています","paramAfterKwargsParam":"パラメーターは \\"**\\" パラメーターの後に続けることはできません","paramAlreadyAssigned":"パラメーター \\"{name}\\" は既に割り当て済みです","paramAnnotationMissing":"パラメーター \\"{name}\\" に型注釈がありません","paramAssignmentMismatch":"型 \\"{sourceType}\\" の式を型 \\"{paramType}\\" のパラメーターに割り当てることはできません","paramNameMissing":"\\"{name}\\" という名前のパラメーターがありません","paramSpecArgsKwargsUsage":"ParamSpec の \\"args\\" メンバーと \\"kwargs\\" メンバーの両方が関数シグネチャ内に含まれている必要があります","paramSpecArgsMissing":"ParamSpec \\"{type}\\" の引数がありません","paramSpecArgsUsage":"ParamSpec の \\"args\\" メンバーは、*args パラメーターと共に使用する場合にのみ有効です","paramSpecAssignedName":"ParamSpec は 、\\"{name}\\" という名前の変数に割り当てる必要があります","paramSpecContext":"ParamSpec はこのコンテキストでは許可されていません","paramSpecDefaultNotTuple":"ParamSpec の既定値には、省略記号、タプル式、または ParamSpec が必要です","paramSpecFirstArg":"最初の引数として ParamSpec の名前が必要です","paramSpecKwargsUsage":"ParamSpec の \\"kwargs\\" メンバーは、**kwargs パラメーターと共に使用する場合にのみ有効です","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" はこのコンテキストでは意味がありません","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" は、戻り値の型内の呼び出し可能なスコープであり、関数本体では参照できません","paramSpecUnknownArg":"ParamSpec は複数の引数をサポートしていません","paramSpecUnknownMember":"\\"{name}\\" は ParamSpec の既知のメンバーではありません","paramSpecUnknownParam":"\\"{name}\\" は ParamSpec に対する不明なパラメーターです","paramTypeCovariant":"共変の型変数はパラメーター型では使用できません","paramTypePartiallyUnknown":"パラメーター \\"{paramName}\\" の型が部分的に不明です","paramTypeUnknown":"パラメーター \\"{paramName}\\" の型が不明です","parenthesizedContextManagerIllegal":"\\"with\\" ステートメント内のかっこには Python 3.9 以降が必要です","patternNeverMatches":"サブジェクトの種類 \\"{type}\\" のパターンは一致しません","positionArgAfterNamedArg":"キーワード引数の後に位置引数を指定することはできません","positionOnlyAfterArgs":"\\"*\\" パラメーターの後に位置のみのパラメーターの区切り文字を使用することはできません","positionOnlyAfterKeywordOnly":"\\"/\\" パラメーターは 、\\"*\\" パラメーターの前に指定する必要があります","positionOnlyAfterNon":"位置のみのパラメーターの後に位置のみのパラメーターを指定することはできません","positionOnlyFirstParam":"位置のみのパラメーターの区切り記号を最初のパラメーターとして使用することはできません","positionOnlyIncompatible":"位置のみのパラメーターの区切り文字には Python 3.8 以降が必要です","privateImportFromPyTypedModule":"\\"{name}\\" はモジュール \\"{module}\\" からエクスポートされていません","privateUsedOutsideOfClass":"\\"{name}\\" はプライベートであり、宣言されているクラスの外部で使用されます","privateUsedOutsideOfModule":"\\"{name}\\" はプライベートであり、それが宣言されているモジュールの外部で使用されています","propertyOverridden":"\\"{name}\\" は、クラス \\"{className}\\" の同じ名前のプロパティを誤ってオーバーライドします","propertyStaticMethod":"静的メソッドは、プロパティ getter、setter、または deleter では許可されていません","protectedUsedOutsideOfClass":"\\"{name}\\" は保護され、宣言されているクラスの外部で使用されます","protocolBaseClass":"プロトコル クラス \\"{classType}\\" は非プロトコル クラス \\"{baseType}\\" から派生できません","protocolBaseClassWithTypeArgs":"型パラメーター構文を使用する場合、Protocol クラスでは型引数を使用できません","protocolIllegal":"\\"Protocol\\" を使用するには Python 3.7 以降が必要です","protocolNotAllowed":"\\"Protocol\\" はこのコンテキストでは使用できません","protocolUnsafeOverlap":"クラスが安全でない方法で \\"{name}\\" と重複しており、実行時に一致する可能性があります","protocolVarianceContravariant":"ジェネリック プロトコル \\"{class}\\" で使用される型変数 \\"{variable}\\" は反変である必要があります","protocolVarianceCovariant":"ジェネリック プロトコル \\"{class}\\" で使用される型変数 \\"{variable}\\" は共変である必要があります","protocolVarianceInvariant":"ジェネリック プロトコル \\"{class}\\" で使用される型変数 \\"{variable}\\" は不変である必要があります","pyrightCommentInvalidDiagnosticBoolValue":"Pyright コメント ディレクティブの後には \\"=\\" と値 true または false を指定する必要があります","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright コメント ディレクティブの後に \\"=\\" を指定し、true、false、エラー、警告、情報、または none の値を指定する必要があります","pyrightCommentMissingDirective":"Pyright コメントの後にはディレクティブ (基本または厳格) または診断規則を指定する必要があります","pyrightCommentNotOnOwnLine":"ファイル レベルの設定を制御するために使用する Pyright コメントは、独自の行に表示する必要があります","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" は、azureight コメントの不明な診断規則です","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" は、pyright コメントに対して無効な値です。true、false、エラー、警告、情報、またはなしが必要です","pyrightCommentUnknownDirective":"\\"{directive}\\" は、pyright コメントの不明なディレクティブです。\\"strict\\" または \\"basic\\" が必要です","readOnlyArgCount":"\\"ReadOnly\\" の後に 1 つの型引数が必要です","readOnlyNotInTypedDict":"\\"ReadOnly\\" はこのコンテキストでは許可されていません","recursiveDefinition":"\\"{name}\\" の型は、それ自体を参照しているため、特定できませんでした","relativeImportNotAllowed":"相対インポートは、\\"import .a\\" フォームでは使用できません。代わりに \\"from . import a\\" を使用します。","requiredArgCount":"\\"Required\\" の後に 1 つの型引数が必要です","requiredNotInTypedDict":"このコンテキストでは\\"必須\\" は許可されていません","returnInAsyncGenerator":"値を持つ return ステートメントは、非同期ジェネレーターでは使用できません","returnMissing":"戻り値の型が \\"{returnType}\\" として宣言されている関数は、すべてのコード パスで値を返す必要があります","returnOutsideFunction":"\\"return\\" は関数内でのみ使用できます","returnTypeContravariant":"反変の型変数は戻り値の型では使用できません","returnTypeMismatch":"型 \\"{exprType}\\" の式を戻り値の型 \\"{returnType}\\" に割り当てることはできません","returnTypePartiallyUnknown":"戻り値の型 \\"{returnType}\\" は部分的に不明です","returnTypeUnknown":"戻り値の型が不明です","revealLocalsArgs":"\\"reveal_locals\\" 呼び出しに引数が必要ありません","revealLocalsNone":"このスコープにはローカルがありません","revealTypeArgs":"\\"reveal_type\\" 呼び出しに 1 つの位置引数が必要です","revealTypeExpectedTextArg":"関数 \\"reveal_type\\" の \\"expected_text\\" 引数は、str リテラル値である必要があります","revealTypeExpectedTextMismatch":"入力テキストの不一致;\\"{expected}\\" が必要ですが、\\"{received}\\" を受信しました","revealTypeExpectedTypeMismatch":"型が一致しません。\\"{expected}\\" が必要ですが、\\"{received}\\" を受信しました","selfTypeContext":"\\"Self\\" はこのコンテキストでは無効です","selfTypeMetaclass":"\\"Self\\" はメタクラス (\\"type\\" のサブクラス) 内では使用できません","selfTypeWithTypedSelfOrCls":"\\"Self\\" は、\\"Self\\" 以外の型注釈を持つ \'self\' または \'cls\' パラメーターを持つ関数では使用できません","setterGetterTypeMismatch":"プロパティ セッター値の型は、getter の戻り値の型に割り当てできません","singleOverload":"\\"{name}\\" はオーバーロードとしてマークされていますが、追加のオーバーロードがありません","slotsAttributeError":"__slots__で \\"{name}\\" が指定されていません","slotsClassVarConflict":"\\"{name}\\" が __slots__ で宣言されたインスタンス変数と競合しています","starPatternInAsPattern":"スター パターンを \\"as\\" ターゲットと共に使用することはできません","starPatternInOrPattern":"スター パターンを他のパターン内で OR 化することはできません","starStarWildcardNotAllowed":"** はワイルドカード \\"_\\" と共に使用できません","staticClsSelfParam":"静的メソッドに \\"self\\" または \\"cls\\" パラメーターを指定することはできません","stdlibModuleOverridden":"\\"{path}\\" は stdlib モジュール \\"{name}\\" をオーバーライドしています","stringNonAsciiBytes":"非 ASCII 文字はバイト文字列リテラルでは使用できません","stringNotSubscriptable":"型注釈では文字列式を添字にすることはできません。注釈全体を引用符で囲んでください","stringUnsupportedEscape":"文字列リテラルでサポートされていないエスケープ シーケンス","stringUnterminated":"文字列リテラルが未終了です","stubFileMissing":"\\"{importName}\\" のスタブ ファイルが見つかりません","stubUsesGetAttr":"スタブ ファイルの種類が不完全です。\\"__getattr__\\" はモジュールの型エラーを隠します","sublistParamsIncompatible":"Python 3.x ではサブリスト パラメーターはサポートされていません","superCallArgCount":"\\"super\\" 呼び出しには 2 つ以下の引数が必要です","superCallFirstArg":"\\"super\\" 呼び出しの最初の引数としてクラス型が必要ですが、\\"{type}\\" を受け取りました","superCallSecondArg":"\\"super\\" 呼び出しの 2 番目の引数は、\\"{type}\\" から派生したオブジェクトまたはクラスである必要があります","superCallZeroArgForm":"\\"super\\" 呼び出しの 0 引数形式は、メソッド内でのみ有効です","superCallZeroArgFormStaticMethod":"\\"super\\" 呼び出しの 0 引数形式は、静的メソッド内では有効ではありません","symbolIsPossiblyUnbound":"\\"{name}\\" はバインドされていない可能性があります","symbolIsUnbound":"\\"{name}\\" はバインドされていません","symbolIsUndefined":"\\"{name}\\" が定義されていません","symbolOverridden":"\\"{name}\\" はクラス \\"{className}\\" の同じ名前のシンボルをオーバーライドします","ternaryNotAllowed":"型の注釈で 3 項式 は使用できません","totalOrderingMissingMethod":"total_orderingを使用するには、クラスで \\"__lt__\\"、\\"__le__\\"、\\"__gt__\\"、または \\"__ge__\\" のいずれかを定義する必要があります","trailingCommaInFromImport":"末尾のコンマはかっこで囲まずには使用できません","tryWithoutExcept":"Try ステートメントには、少なくとも 1 つの except 句または finally 句が必要です","tupleAssignmentMismatch":"型 \\"{type}\\" の式をターゲット タプルに割り当てることはできません","tupleInAnnotation":"タプル式は型注釈では使用できません","tupleIndexOutOfRange":"インデックス {index} が型 {type} の範囲外です","typeAliasIllegalExpressionForm":"型エイリアス定義の式フォームが無効です","typeAliasIsRecursiveDirect":"型エイリアス \\"{name}\\" は、その定義でそれ自体を使用できません","typeAliasNotInModuleOrClass":"TypeAlias は、モジュールまたはクラススコープ内でのみ定義できます","typeAliasRedeclared":"\\"{name}\\" は TypeAlias として宣言されており、1 回だけ割り当てることができます","typeAliasStatementBadScope":"type ステートメントは、モジュールまたはクラススコープ内でのみ使用できます","typeAliasStatementIllegal":"型エイリアス ステートメントには Python 3.12 以降が必要です","typeAliasTypeBaseClass":"\\"type\\" ステートメントで定義された型エイリアスを基底クラスとして使用することはできません","typeAliasTypeMustBeAssigned":"TypeAliasType は、型エイリアスと同じ名前の変数に割り当てる必要があります","typeAliasTypeNameArg":"TypeAliasType の最初の引数は、型エイリアスの名前を表す文字列リテラルである必要があります","typeAliasTypeNameMismatch":"型エイリアスの名前は、それが割り当てられている変数の名前と一致する必要があります","typeAliasTypeParamInvalid":"型パラメーター リストは、TypeVar、TypeVarTuple、または ParamSpec のみを含むタプルである必要があります","typeAnnotationCall":"型式では呼び出し式を使用できません","typeAnnotationVariable":"型式では変数を使用できません","typeAnnotationWithCallable":"\\"type\\" の型引数はクラスである必要があります。呼び出し可能関数はサポートされていません","typeArgListExpected":"ParamSpec、省略記号、または型の一覧が必要です","typeArgListNotAllowed":"この型引数にはリスト式を使用できません","typeArgsExpectingNone":"クラス \\"{name}\\" に型引数が必要ありません","typeArgsMismatchOne":"1 つの型引数が必要ですが、{received} を受け取りました","typeArgsMissingForAlias":"ジェネリック型エイリアス \\"{name}\\" に必要な型引数","typeArgsMissingForClass":"ジェネリック クラス \\"{name}\\" に必要な型引数","typeArgsTooFew":"\\"{name}\\" に指定された型引数が少なすぎます。{expected} が必要ですが、{received} を受信しました","typeArgsTooMany":"\\"{name}\\" に指定された型引数が多すぎます。{expected} が必要ですが、{received} を受信しました","typeAssignmentMismatch":"型 \\"{sourceType}\\" の式を宣言された型 \\"{destType}\\" に割り当てることはできません","typeAssignmentMismatchWildcard":"宣言された型 \\"{destType}\\" に割り当てできないシンボル \\"{name}\\" のインポートに型 \\"{sourceType}\\" があります","typeCallNotAllowed":"type() 呼び出しは型注釈で使用しないでください","typeCheckOnly":"\\"{name}\\" は@type_check_onlyとしてマークされており、型注釈でのみ使用できます","typeCommentDeprecated":"型コメントの使用は非推奨です。代わりに型注釈を使用してください","typeExpectedClass":"型式が必要ですが、\\"{type}\\" を受け取りました","typeGuardArgCount":"\\"TypeGuard\\" または \\"TypeIs\\" の後に 1 つの型引数が必要です","typeGuardParamCount":"ユーザー定義型ガード関数とメソッドには、少なくとも 1 つの入力パラメーターが必要です","typeIsReturnType":"TypeIs の戻り値の型 (\\"{returnType}\\") と値パラメーターの型 (\\"{type}\\") が一致しません","typeNotAwaitable":"\\"{type}\\" は待機できません","typeNotIntantiable":"\\"{type}\\" をインスタンス化できません","typeNotIterable":"\\"{type}\\" は反復できません","typeNotSpecializable":"型 \\"{type}\\" を特殊化できませんでした","typeNotSubscriptable":"型 \\"{type}\\" のオブジェクトは添字可能ではありません","typeNotSupportBinaryOperator":"演算子 \\"{operator}\\" は型 \\"{leftType}\\" と \\"{rightType}\\" ではサポートされていません","typeNotSupportBinaryOperatorBidirectional":"型 \\"{leftType}\\" と \\"{rightType}\\" に対して演算子 \\"{operator}\\" はサポートされていません。予期された型が \\"{expectedType}\\" の場合","typeNotSupportUnaryOperator":"演算子 \\"{operator}\\" は型 \\"{type}\\" ではサポートされていません","typeNotSupportUnaryOperatorBidirectional":"型 \\"{type}\\" が \\"{expectedType}\\" の場合、演算子 \\"{operator}\\" はサポートされていません","typeNotUsableWith":"型 \\"{type}\\" のオブジェクトは 、{method} を実装していないため、\\"with\\" と共に使用できません","typeParameterBoundNotAllowed":"バインドまたは制約を可変個引数型パラメーターまたは ParamSpec と共に使用することはできません","typeParameterConstraintTuple":"型パラメーター制約は、2 つ以上の型のタプルである必要があります","typeParameterExistingTypeParameter":"型パラメーター \\"{name}\\" は既に使用されています","typeParameterNotDeclared":"型パラメーター \\"{name}\\" は、\\"{container}\\" の型パラメーターリストに含まれていません","typeParametersMissing":"少なくとも 1 つの型パラメーターを指定する必要があります","typePartiallyUnknown":"\\"{name}\\" の種類が部分的に不明です","typeUnknown":"\\"{name}\\" の種類が不明です","typeVarAssignedName":"TypeVar は 、\\"{name}\\" という名前の変数に割り当てる必要があります","typeVarAssignmentMismatch":"型 \\"{type}\\" を型変数 \\"{name}\\" に割り当てることはできません","typeVarBoundAndConstrained":"TypeVar をバインドと制約の両方にすることはできません","typeVarBoundGeneric":"TypeVar バインド型をジェネリックにすることはできません","typeVarConstraintGeneric":"TypeVar 制約型をジェネリックにすることはできません","typeVarDefaultBoundMismatch":"TypeVar の既定の型はバインドされた型のサブタイプである必要があります","typeVarDefaultConstraintMismatch":"TypeVar の既定の型は、制約付き型のいずれかである必要があります","typeVarDefaultIllegal":"型変数の既定の型には Python 3.13 以降が必要です","typeVarDefaultInvalidTypeVar":"型パラメーター \\"{name}\\" には、スコープ外の 1 つ以上の型変数を参照する既定の型があります","typeVarFirstArg":"最初の引数として TypeVar の名前が必要です","typeVarNoMember":"TypeVar \\"{type}\\" にはメンバー \\"{name}\\" がありません","typeVarNotSubscriptable":"TypeVar \\"{type}\\" は添字可能ではありません","typeVarNotUsedByOuterScope":"型変数 \\"{name}\\" は、このコンテキストでは意味がありません","typeVarPossiblyUnsolvable":"呼び出し元がパラメーター \\"{param}\\" に引数を指定しない場合、型変数 \\"{name}\\" は解決されない可能性があります","typeVarScopedToReturnType":"型変数 \\"{name}\\" のスコープは戻り値の型内の呼び出し可能な変数であり、関数本体では参照できません","typeVarSingleConstraint":"TypeVar には少なくとも 2 つの制約付き型が必要です","typeVarTupleConstraints":"TypeVarTuple に値制約を持たせることはできません","typeVarTupleContext":"TypeVarTuple はこのコンテキストでは許可されていません","typeVarTupleDefaultNotUnpacked":"TypeVarTuple の既定の型は、アンパックされたタプルまたは TypeVarTuple である必要があります","typeVarTupleMustBeUnpacked":"TypeVarTuple 値にはアンパック演算子が必要です","typeVarTupleUnknownParam":"\\"{name}\\" は TypeVarTuple に対する不明なパラメーターです","typeVarUnknownParam":"\\"{name}\\" は TypeVar に対する不明なパラメーターです","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" は外部スコープで既に使用されています","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" はジェネリック関数シグネチャに 1 回だけ出現します","typeVarVariance":"TypeVar を共変と反変の両方にすることはできません","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" には既定値があり、TypeVarTuple \\"{variadicName}\\" の後に続けることはできません","typeVarWithoutDefault":"\\"{name}\\" は既定の型がないため、型パラメーター リストの \\"{other}\\" の後に表示できません","typeVarsNotInGenericOrProtocol":"Generic[] または Protocol[] には、すべての型変数を含める必要があります","typedDictAccess":"TypedDict の項目にアクセスできませんでした","typedDictAssignedName":"TypedDict は \\"{name}\\" という名前の変数に割り当てる必要があります","typedDictBadVar":"TypedDict クラスには型注釈のみを含めることができます","typedDictBaseClass":"TypedDict クラスのすべての基底クラスも TypedDict クラスである必要があります","typedDictBoolParam":"\\"{name}\\" パラメーターの値は True または False である必要があります","typedDictClosedExtras":"基底クラス \\"{name}\\" は終了した TypedDict です。余分な項目は型 \\"{type}\\" である必要があります","typedDictClosedNoExtras":"基底クラス \\"{name}\\" は終了した TypedDict です。追加のアイテムは許可されていません","typedDictDelete":"TypedDict の項目を削除できませんでした","typedDictEmptyName":"TypedDict 内の名前を空にすることはできません","typedDictEntryName":"辞書エントリ名に文字列リテラルが必要です","typedDictEntryUnique":"ディクショナリ内の名前は一意である必要があります","typedDictExtraArgs":"追加の TypedDict 引数はサポートされていません","typedDictFieldNotRequiredRedefinition":"TypedDict アイテム \\"{name}\\" を NotRequired として再定義することはできません","typedDictFieldReadOnlyRedefinition":"TypedDict アイテム \\"{name}\\" を ReadOnly として再定義することはできません","typedDictFieldRequiredRedefinition":"TypedDict アイテム \\"{name}\\" を Required として再定義することはできません","typedDictFirstArg":"最初の引数として TypedDict クラス名が必要です","typedDictInitsubclassParameter":"TypedDict は __init_subclass__パラメーター \\"{name}\\" をサポートしていません","typedDictNotAllowed":"\\"TypedDict\\" はこのコンテキストでは使用できません","typedDictSecondArgDict":"2 番目のパラメーターとして dict パラメーターまたはキーワード パラメーターが必要です","typedDictSecondArgDictEntry":"単純な辞書エントリが必要です","typedDictSet":"TypedDict で項目を割り当てることができませんでした","unaccessedClass":"クラス \\"{name}\\" にアクセスできません","unaccessedFunction":"関数 \\"{name}\\" にアクセスできません","unaccessedImport":"インポート \\"{name}\\" にアクセスできません","unaccessedSymbol":"\\"{name}\\" にアクセスできません","unaccessedVariable":"変数 \\"{name}\\" にアクセスできません","unannotatedFunctionSkipped":"関数 \\"{name}\\" の分析は、表示されないためスキップされます","unaryOperationNotAllowed":"型の注釈で単項演算子は使用できません","unexpectedAsyncToken":"\\"def\\"、\\"with\\"、または \\"for\\" が \\"async\\" の後に続く必要があります","unexpectedExprToken":"式の最後に予期しないトークンが含まれています","unexpectedIndent":"予期しないインデント","unexpectedUnindent":"インデント解除は予期されていません","unhashableDictKey":"辞書キーはハッシュ可能である必要があります","unhashableSetEntry":"設定エントリはハッシュ可能である必要があります","uninitializedAbstractVariables":"抽象基底クラスで定義された変数は、最終クラス \\"{classType}\\" で初期化されません","uninitializedInstanceVariable":"インスタンス変数 \\"{name}\\" は、クラス本体または__init__ メソッドで初期化されていません","unionForwardReferenceNotAllowed":"共用体構文を文字列オペランドと共に使用することはできません。式全体を引用符で囲んでください","unionSyntaxIllegal":"共用体の代替構文には Python 3.10 以降が必要です","unionTypeArgCount":"共用体には 2 つ以上の型引数が必要です","unionUnpackedTuple":"アンパックされたタプルを union に含めることはできません","unionUnpackedTypeVarTuple":"アンパックされた TypeVarTuple を union に含めることはできません","unnecessaryCast":"不要な \\"キャスト\\" 呼び出し。型は既に \\"{type}\\" です","unnecessaryIsInstanceAlways":"不要な isinstance 呼び出し。\\"{testType}\\" は常に \\"{classType}\\" のインスタンスです","unnecessaryIsSubclassAlways":"不要な issubclass 呼び出し。\\"{testType}\\" は常に \\"{classType}\\" のサブクラスです","unnecessaryPyrightIgnore":"不要な \\"#ight: ignore\\" コメント","unnecessaryPyrightIgnoreRule":"不要な \\"# pyright: ignore\\" ルール: \\"{name}\\"","unnecessaryTypeIgnore":"不要な \\"# type: ignore\\" コメント","unpackArgCount":"\\"Unpack\\" の後に 1 つの型引数が必要です","unpackExpectedTypeVarTuple":"Unpack の型引数として TypeVarTuple または tuple が必要です","unpackExpectedTypedDict":"Unpack に必要な TypedDict 型引数","unpackIllegalInComprehension":"アンパック操作は理解できません","unpackInAnnotation":"型注釈ではアンパック演算子は使用できません","unpackInDict":"アンパック操作はディクショナリで許可されていません","unpackInSet":"アンパック演算子はセット内では使用できません","unpackNotAllowed":"アンパックはこのコンテキストでは許可されていません","unpackOperatorNotAllowed":"このコンテキストではアンパック操作は許可されていません","unpackTuplesIllegal":"Python 3.8 より前のタプルではアンパック操作は許可されていません","unpackedArgInTypeArgument":"アンパックされた引数は、型引数リストでは使用できません","unpackedArgWithVariadicParam":"アンパックされた引数は TypeVarTuple パラメーターには使用できません","unpackedDictArgumentNotMapping":"** の後の引数式は、\\"str\\" キー型のマッピングである必要があります","unpackedDictSubscriptIllegal":"下付き文字の辞書アンパック演算子は使用できません","unpackedSubscriptIllegal":"下付き文字の Unpack 演算子には Python 3.11 以降が必要です","unpackedTypeVarTupleExpected":"アンパックされた TypeVarTuple が必要です。Unpack[{name1}] または *{name2} を使用してください","unpackedTypedDictArgument":"アンパックされた TypedDict 引数をパラメーターと一致させることはできません","unreachableCode":"コードに到達できません","unreachableExcept":"例外が既に処理されているため、Except 句に到達できません","unsupportedDunderAllOperation":"\\"__all__\\" に対する操作はサポートされていないため、エクスポートされたシンボル リストが正しくない可能性があります","unusedCallResult":"呼び出し式の結果は \\"{type}\\" 型であり、使用されません。これが意図的な場合は変数 \\"_\\" に代入する","unusedCoroutine":"非同期関数呼び出しの結果は使用されません。\\"await\\" を使用するか、結果を変数に代入してください","unusedExpression":"式の値が使用されていません","varAnnotationIllegal":"変数の型注釈には Python 3.6 以降が必要です。以前のバージョンとの互換性のために型コメントを使用する","variableFinalOverride":"変数 \\"{name}\\" は Final とマークされ、クラス \\"{className}\\" の同じ名前の Final 以外の変数をオーバーライドします","variadicTypeArgsTooMany":"型引数リストには、アンパックされた TypeVarTuple または tuple を最大 1 つ含めることができます","variadicTypeParamTooManyAlias":"型エイリアスには TypeVarTuple 型パラメーターを最大 1 つ含めることができますが、複数の ({names}) を受け取りました","variadicTypeParamTooManyClass":"ジェネリック クラスには最大 1 つの TypeVarTuple 型パラメーターを指定できますが、複数の ({names}) を受け取りました","walrusIllegal":"演算子 \\":=\\" には Python 3.8 以降が必要です","walrusNotAllowed":"演算子 \\":=\\" は、かっこを囲まないこのコンテキストでは使用できません","wildcardInFunction":"ワイルドカードのインポートは、クラスまたは関数内では許可されていません","wildcardLibraryImport":"ライブラリからのワイルドカードインポートは許可されていません","wildcardPatternTypePartiallyUnknown":"ワイルドカード パターンによってキャプチャされた型は部分的に不明です","wildcardPatternTypeUnknown":"ワイルドカード パターンによってキャプチャされた型が不明です","yieldFromIllegal":"\\"yield from\\" を使用するには Python 3.3 以降が必要です","yieldFromOutsideAsync":"非同期関数では \\"yield from\\" は使用できません","yieldOutsideFunction":"関数またはラムダの外部では \\"yield\\" は許可されません","yieldWithinListCompr":"\\"yield\\" はリスト理解内では使用できません","zeroCaseStatementsFound":"Match ステートメントには、少なくとも 1 つの case ステートメントを含める必要があります","zeroLengthTupleNotAllowed":"このコンテキストでは長さ 0 のタプルは使用できません"},"DiagnosticAddendum":{"annotatedNotAllowed":"\\"注釈付き\\" 特殊フォームは、インスタンスおよびクラスのチェックでは使用できません","argParam":"引数はパラメーター \\"{paramName}\\" に対応します","argParamFunction":"引数は関数 \\"{functionName}\\" のパラメーター \\"{paramName}\\" に対応します","argsParamMissing":"パラメーター \\"*{paramName}\\" に対応するパラメーターがありません","argsPositionOnly":"位置のみのパラメーターの不一致。{expected} が必要ですが、{received} を受信しました","argumentType":"引数の型は \\"{type}\\" です","argumentTypes":"引数の型: ({types})","assignToNone":"型を \\"None\\" 型に割り当てることはできません","asyncHelp":"\\"async with\\" を意味しましたか?","baseClassIncompatible":"基底クラス \\"{baseClass}\\" は型 \\"{type}\\" と互換性がありません","baseClassIncompatibleSubclass":"基底クラス \\"{baseClass}\\" は、型 \\"{type}\\" と互換性のない \\"{subclass}\\" から派生しています","baseClassOverriddenType":"基底クラス \\"{baseClass}\\" は、オーバーライドされる型 \\"{type}\\" を提供します","baseClassOverridesType":"基底クラス \\"{baseClass}\\" は型 \\"{type}\\" でオーバーライドします","bytesTypePromotions":"disableBytesTypePromotions を false に設定して、\\"bytearray\\" と \\"memoryview\\" の型昇格動作を有効にします","conditionalRequiresBool":"型 \\"{operandType}\\" のメソッド __bool__は、\\"bool\\" ではなく型 \\"{boolReturnType}\\" を返します","dataClassFieldLocation":"フィールド宣言","dataClassFrozen":"\\"{name}\\" は固定されています","dataProtocolUnsupported":"\\"{name}\\" はデータ プロトコルです","descriptorAccessBindingFailed":"記述子クラス \\"{className}\\" のメソッド \\"{name}\\" をバインドできませんでした","descriptorAccessCallFailed":"記述子クラス \\"{className}\\" のメソッド \\"{name}\\" を呼び出せませんでした","finalMethod":"最終的なメソッド","functionParamDefaultMissing":"パラメーター \\"{name}\\" に既定の引数がありません","functionParamName":"パラメーター名の不一致: \\"{destName}\\" と \\"{srcName}\\"","functionParamPositionOnly":"位置のみのパラメーターの不一致; パラメーター \\"{name}\\" は位置のみではありません","functionReturnTypeMismatch":"関数の戻り値の型 \\"{sourceType}\\" は型 \\"{destType}\\" と互換性がありません","functionTooFewParams":"関数が受け入れる位置指定パラメーターが少なすぎます。{expected} が必要ですが、{received} を受信しました","functionTooManyParams":"関数が受け入れる位置指定パラメーターが多すぎます。{expected} が必要ですが、{received} を受信しました","genericClassNotAllowed":"インスタンスまたはクラスのチェックでは、型引数を含むジェネリック型は使用できません","incompatibleDeleter":"プロパティ削除子メソッドに互換性がありません","incompatibleGetter":"プロパティ getter メソッドに互換性がありません","incompatibleSetter":"プロパティ セッター メソッドに互換性がありません","initMethodLocation":"__init__ メソッドはクラス \\"{type}\\" で定義されています","initMethodSignature":"__init__の署名は \\"{type}\\" です","initSubclassLocation":"__init_subclass__ メソッドはクラス \\"{name}\\" で定義されています","invariantSuggestionDict":"\\"dict\\" から値の型の共変である \\"Mapping\\" への切り替えを検討してください","invariantSuggestionList":"\\"list\\" から共変である \\"Sequence\\" への切り替えを検討してください","invariantSuggestionSet":"\\"set\\" から共変である \\"Container\\" への切り替えを検討してください","keyNotRequired":"\\"{name}\\" は \\"{type}\\" の必須キーではないため、アクセスすると実行時例外が発生する可能性があります","keyReadOnly":"\\"{name}\\" は \\"{type}\\" の読み取り専用キーです","keyRequiredDeleted":"\\"{name}\\" は必須キーであり、削除できません","keyUndefined":"\\"{name}\\" は \\"{type}\\" で定義されたキーではありません","kwargsParamMissing":"パラメーター \\"**{paramName}\\" に対応するパラメーターがありません","listAssignmentMismatch":"型 \\"{type}\\" はターゲット リストと互換性がありません","literalAssignmentMismatch":"\\"{sourceType}\\" を型 \\"{destType}\\" に割り当てることはできません","matchIsNotExhaustiveHint":"完全な処理が意図されていない場合は、\\"case _: pass\\" を追加します","matchIsNotExhaustiveType":"ハンドルされない型: \\"{type}\\"","memberAssignment":"型 \\"{type}\\" の式をクラス \\"{classType}\\" のメンバー \\"{name}\\" に割り当てることはできません","memberIsAbstract":"\\"{type}.{name}\\" は実装されていません","memberIsAbstractMore":"その他 {count} 件...","memberIsClassVarInProtocol":"\\"{name}\\" はプロトコルで ClassVar として定義されています","memberIsFinalInProtocol":"\\"{name}\\" はプロトコルで Final とマークされています","memberIsInitVar":"メンバー \\"{name}\\" は init 専用フィールドです","memberIsInvariant":"\\"{name}\\" は変更可能であるため、不変です","memberIsNotClassVarInClass":"プロトコルと互換性を持たせるには、\\"{name}\\" を ClassVar として定義する必要があります","memberIsNotClassVarInProtocol":"\\"{name}\\" はプロトコルで ClassVar として定義されていません","memberIsNotFinalInProtocol":"\\"{name}\\" はプロトコルで Final としてマークされていません","memberIsWritableInProtocol":"\\"{name}\\" はプロトコルで書き込み可能です","memberSetClassVar":"メンバー \\"{name}\\" は ClassVar であるため、クラス インスタンスを介して割り当てることはできません","memberTypeMismatch":"\\"{name}\\" は互換性のない型です","memberUnknown":"メンバー \\"{name}\\" が不明です","metaclassConflict":"メタクラス \\"{metaclass1}\\" が \\"{metaclass2}\\" と競合しています","missingDeleter":"プロパティ削除メソッドがありません","missingGetter":"プロパティ getter メソッドがありません","missingSetter":"プロパティ セッター メソッドがありません","namedParamMissingInDest":"キーワード パラメーター \\"{name}\\" が変換先に見つかりません","namedParamMissingInSource":"キーワード パラメーター \\"{name}\\" がソースに見つかりません","namedParamTypeMismatch":"型 \\"{sourceType}\\" のキーワード パラメーター \\"{name}\\" を型 \\"{destType}\\" に割り当てることはできません","namedTupleNotAllowed":"NamedTuple はインスタンスまたはクラスのチェックには使用できません","newMethodLocation":"__new__ メソッドはクラス \\"{type}\\" で定義されています","newMethodSignature":"__new__の署名は \\"{type}\\" です","newTypeClassNotAllowed":"NewType で作成されたクラスは、インスタンスおよびクラスのチェックでは使用できません","noOverloadAssignable":"型 \\"{type}\\" に一致するオーバーロードされた関数はありません","noneNotAllowed":"インスタンスまたはクラスのチェックには何も使用できません","orPatternMissingName":"名前がありません: {name}","overloadIndex":"オーバーロード {index} が最も近い一致です","overloadNotAssignable":"\\"{name}\\" の 1 つ以上のオーバーロードが割り当て可能ではありません","overloadSignature":"オーバーロードシグネチャはここで定義されています","overriddenMethod":"オーバーライドされたメソッド","overriddenSymbol":"オーバーライドされたシンボル","overrideInvariantMismatch":"オーバーライドの型 \\"{overrideType}\\" が基本データ型 \\"{baseType}\\" と同じではありません","overrideIsInvariant":"変数は変更可能であるため、その型は不変です","overrideNoOverloadMatches":"オーバーライドのオーバーロード シグネチャが基本メソッドと互換性がありません","overrideNotClassMethod":"基本メソッドは classmethod として宣言されていますが、オーバーライドはされていません","overrideNotInstanceMethod":"基本メソッドはインスタンス メソッドとして宣言されていますが、オーバーライドは宣言されていません","overrideNotStaticMethod":"基本メソッドは staticmethod として宣言されていますが、オーバーライドは宣言されていません","overrideOverloadNoMatch":"オーバーライドは基本メソッドのすべてのオーバーロードを処理しません","overrideOverloadOrder":"オーバーライド メソッドのオーバーロードは、基本メソッドと同じ順序にする必要があります","overrideParamKeywordNoDefault":"キーワード パラメーター \\"{name}\\" の不一致: 基本パラメーターに既定の引数値があり、オーバーライド パラメーターにはありません","overrideParamKeywordType":"キーワード パラメーター \\"{name}\\" の型が一致しません: 基本パラメーターは型 \\"{baseType}\\"、オーバーライド パラメーターは型 \\"{overrideType}\\" です","overrideParamName":"パラメーター {index} 名が一致しません: ベース パラメーターの名前は \\"{baseName}\\"、オーバーライド パラメーターは \\"{overrideName}\\" です","overrideParamNameExtra":"パラメーター \\"{name}\\" が ベース に見つかりません","overrideParamNameMissing":"パラメーター \\"{name}\\" がオーバーライドに見つかりません","overrideParamNamePositionOnly":"パラメーター {index} の不一致: ベース パラメーター \\"{baseName}\\" はキーワード パラメーターで、オーバーライド パラメーターは位置のみです","overrideParamNoDefault":"パラメーター {index} の不一致: 基本パラメーターに既定の引数値があり、オーバーライド パラメーターが指定されていません","overrideParamType":"パラメーター {index} の型が一致しません: 基本パラメーターは型 \\"{baseType}\\"、オーバーライド パラメーターは型 \\"{overrideType}\\" です","overridePositionalParamCount":"位置指定パラメーター数が一致しません。基本メソッドには {baseCount} がありますが、オーバーライドには {overrideCount} があります","overrideReturnType":"戻り値の型の不一致: 基本メソッドは型 \\"{baseType}\\" を返し、オーバーライドは型 \\"{overrideType}\\" を返します","overrideType":"基底クラスは型を \\"{type}\\" として定義します","paramAssignment":"パラメーター {index}: 型 \\"{sourceType}\\" を型 \\"{destType}\\" に割り当てることはできません","paramSpecMissingInOverride":"ParamSpec パラメーターが override メソッドに見つかりません","paramType":"パラメーターの型は \\"{paramType}\\" です","privateImportFromPyTypedSource":"代わりに \\"{module}\\" からインポートする","propertyAccessFromProtocolClass":"プロトコル クラス内で定義されたプロパティにクラス変数としてアクセスできない","propertyMethodIncompatible":"プロパティ メソッド \\"{name}\\" は互換性がありません","propertyMethodMissing":"プロパティ メソッド \\"{name}\\" がオーバーライドに見つかりません","propertyMissingDeleter":"プロパティ \\"{name}\\" に定義済みの削除子がありません","propertyMissingSetter":"プロパティ \\"{name}\\" に定義済みのセッターがありません","protocolIncompatible":"\\"{sourceType}\\" はプロトコル \\"{destType}\\" と互換性がありません","protocolMemberMissing":"\\"{name}\\" が存在しません","protocolRequiresRuntimeCheckable":"インスタンスとクラスのチェックで使用するには、プロトコル クラスは @runtime_checkable である必要があります","protocolSourceIsNotConcrete":"\\"{sourceType}\\" は具象クラス型ではないため、型 \\"{destType}\\" に割り当てることはできません","protocolUnsafeOverlap":"\\"{name}\\" の属性の名前がプロトコルの名前と同じです","pyrightCommentIgnoreTip":"\\"#ight: ignore[<diagnostic rules>] を使用して 1 行の診断を抑制する","readOnlyAttribute":"属性 \\"{name}\\" は読み取り専用です","seeClassDeclaration":"クラス宣言を参照してください","seeDeclaration":"宣言を参照してください","seeFunctionDeclaration":"関数の宣言を参照してください","seeMethodDeclaration":"メソッド宣言を参照してください","seeParameterDeclaration":"パラメーター宣言を参照してください","seeTypeAliasDeclaration":"型のエイリアス宣言を参照してください","seeVariableDeclaration":"変数宣言を参照してください","tupleAssignmentMismatch":"型 \\"{type}\\" はターゲット タプルと互換性がありません","tupleEntryTypeMismatch":"タプル エントリ {entry} の型が正しくありません","tupleSizeIndeterminateSrc":"タプル サイズが一致しません。{expected} が必要ですが、受け取りは不確定です","tupleSizeIndeterminateSrcDest":"タプル サイズが一致しません。{expected} 以上が必要ですが、受け取りは不確定です","tupleSizeMismatch":"タプルのサイズが一致しません。{expected} が必要ですが、{received} を受信しました","tupleSizeMismatchIndeterminateDest":"タプルのサイズが一致しません。{expected} 以上が必要ですが、{received} を受信しました","typeAliasInstanceCheck":"\\"type\\" ステートメントで作成された型エイリアスは、インスタンスとクラスのチェックでは使用できません","typeAssignmentMismatch":"型 \\"{sourceType}\\" を型 \\"{destType}\\" に割り当てることはできません","typeBound":"型 \\"{sourceType}\\" は、型変数 \\"{name}\\" のバインドされた型 \\"{destType}\\" と互換性がありません","typeConstrainedTypeVar":"型 \\"{type}\\" は制約付き型変数 \\"{name}\\" と互換性がありません","typeIncompatible":"\\"{sourceType}\\" は \\"{destType}\\" と互換性がありません","typeNotClass":"\\"{type}\\" はクラスではありません","typeNotStringLiteral":"\\"{type}\\" は文字列リテラルではありません","typeOfSymbol":"\\"{name}\\" の型は \\"{type}\\" です","typeParamSpec":"型 \\"{type}\\" は ParamSpec \\"{name}\\" と互換性がありません","typeUnsupported":"型 \\"{type}\\" はサポートされていません","typeVarDefaultOutOfScope":"型変数 \\"{name}\\" はスコープ内にありません","typeVarIsContravariant":"型パラメーター \\"{name}\\" は反変ですが、\\"{sourceType}\\" は \\"{destType}\\" のスーパータイプではありません","typeVarIsCovariant":"型パラメーター \\"{name}\\" は共変ですが、\\"{sourceType}\\" は \\"{destType}\\" のサブタイプではありません","typeVarIsInvariant":"型パラメーター \\"{name}\\" は不変ですが、\\"{sourceType}\\" は \\"{destType}\\" と同じではありません","typeVarNotAllowed":"TypeVar は、インスタンスまたはクラスのチェックには使用できません","typeVarTupleRequiresKnownLength":"TypeVarTuple を不明な長さのタプルにバインドすることはできません","typeVarUnnecessarySuggestion":"代わりに {type} を使用してください","typeVarUnsolvableRemedy":"引数が指定されていない場合に戻り値の型を指定するオーバーロードを指定します","typeVarsMissing":"型変数がありません: {names}","typedDictBaseClass":"クラス \\"{type}\\" は TypedDict ではありません","typedDictClassNotAllowed":"TypedDict クラスはインスタンスまたはクラスのチェックには使用できません","typedDictClosedExtraNotAllowed":"アイテム \\"{name}\\" を追加できません","typedDictClosedExtraTypeMismatch":"型 \\"{type}\\" のアイテム \\"{name}\\" を追加できません","typedDictClosedFieldNotRequired":"アイテム \\"{name}\\" を追加できません。これは NotRequired である必要があるためです。","typedDictExtraFieldNotAllowed":"\\"{name}\\" は \\"{type}\\" に存在しません","typedDictExtraFieldTypeMismatch":"\\"{name}\\" の型は、\\"{type}\\" の \\"__extra_items__\\" 型と互換性がありません","typedDictFieldMissing":"\\"{name}\\" が \\"{type}\\" に見つかりません","typedDictFieldNotReadOnly":"\\"{name}\\" は \\"{type}\\" では読み取り専用ではありません","typedDictFieldNotRequired":"\\"{name}\\" は \\"{type}\\" には必要ありません","typedDictFieldRequired":"\\"{name}\\" は \\"{type}\\" に必要です","typedDictFieldTypeMismatch":"型 \\"{type}\\" は、アイテム \\"{name}\\" に割り当てできません","typedDictFieldUndefined":"\\"{name}\\" は型 \\"{type}\\" の未定義のアイテムです","typedDictFinalMismatch":"@final が一致しないため、\\"{sourceType}\\" は \\"{destType}\\" と互換性がありません","typedDictKeyAccess":"[\\"{name}\\"] を使用して TypedDict の項目を参照する","typedDictNotAllowed":"TypedDict はインスタンスまたはクラスのチェックには使用できません","unhashableType":"型 \\"{type}\\" はハッシュ可能ではありません","uninitializedAbstractVariable":"インスタンス変数 \\"{name}\\" は抽象基本クラス \\"{classType}\\" で定義されていますが、初期化されていません","unreachableExcept":"\\"{exceptionType}\\" は \\"{parentType}\\" のサブクラスです","useDictInstead":"辞書の種類を示すには、Dict[T1, T2] を使用します","useListInstead":"List[T] を使用してリストの種類を指定するか、Union[T1, T2] を使用して共用体の型を示す","useTupleInstead":"tuple[T1, ..., Tn] を使用してタプル型を示すか、Union[T1, T2] を使用して共用体型を示します","useTypeInstead":"代わりに Type[T] を使用する","varianceMismatchForClass":"型引数 \\"{typeVarName}\\" の分散は、基底クラス \\"{className}\\" と互換性がありません","varianceMismatchForTypeAlias":"型引数 \\"{typeVarName}\\" の分散は \\"{typeAliasParam}\\" と互換性がありません"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.ko.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.ko.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"형식 스텁 만들기","createTypeStubFor":"\\"{moduleName}\\"에 대한 형식 스텁 만들기","executingCommand":"명령 실행","filesToAnalyzeCount":"분석할 파일 {count}개","filesToAnalyzeOne":"분석할 파일 1개","findingReferences":"참조 찾기","organizeImports":"가져오기 구성","renameShadowedFile":"‘{oldFile}’에서 ‘{newFile}’(으)로 이름 바꾸기"},"Completion":{"autoImportDetail":"자동 가져오기","indexValueDetail":"인덱스 값"},"Diagnostic":{"abstractMethodInvocation":"메서드 \\"{method}\\"은(는) 추상적이고 구현되지 않았으므로 호출할 수 없습니다.","annotatedParamCountMismatch":"매개 변수 주석 개수가 일치하지 않습니다. {expected}이)(가) 필요하지만 {received}을(를) 받았습니다.","annotatedTypeArgMissing":"\\"Annotated\\"에 대해 하나의 형식 인수와 하나 이상의 주석이 필요합니다.","annotationFormatString":"형식 주석은 형식 문자열 리터럴(f-문자열)을 사용할 수 없습니다.","annotationNotSupported":"이 문에는 형식 주석이 지원되지 않습니다.","annotationSpansStrings":"형식 주석은 여러 문자열 리터럴에 걸쳐 있을 수 없습니다.","annotationStringEscape":"형식 주석에는 이스케이프 문자를 사용할 수 없습니다.","argAssignment":"\\"{argType}\\" 형식의 인수를 \\"{paramType}\\" 형식의 매개 변수에 할당할 수 없습니다.","argAssignmentFunction":"\\"{argType}\\" 형식의 인수를 \\"{functionName}\\" 함수의 \\"{paramType}\\" 형식의 매개 변수에 할당할 수 없습니다.","argAssignmentParam":"\\"{argType}\\" 형식의 인수를 \\"{paramType}\\" 형식의 \\"{paramName}\\" 매개 변수에 할당할 수 없습니다.","argAssignmentParamFunction":"\\"{argType}\\" 형식의 인수를 \\"{functionName}\\" 함수에서 \\"{paramType}\\" 형식의 \\"{paramName}\\" 매개 변수에 할당할 수 없습니다.","argMissingForParam":"매개 변수 {name}에 대한 인수가 없습니다.","argMissingForParams":"매개 변수 {names}에 대한 인수가 없습니다.","argMorePositionalExpectedCount":"{expected}개 이상의 위치 인수가 필요합니다.","argMorePositionalExpectedOne":"1개의 위치 인수가 더 필요합니다.","argPositional":"위치 인수가 필요합니다.","argPositionalExpectedCount":"{expected} 위치 인수가 필요합니다.","argPositionalExpectedOne":"1개의 위치 인수가 필요합니다.","argTypePartiallyUnknown":"인수 형식을 부분적으로 알 수 없습니다.","argTypeUnknown":"인수 형식을 알 수 없습니다.","assertAlwaysTrue":"어설션 식은 항상 true로 평가됩니다.","assertTypeArgs":"\\"assert_type\\"에는 두 개의 위치 인수가 필요합니다.","assertTypeTypeMismatch":"\\"assert_type\\" 불일치: \\"{expected}\\"이(가) 필요하지만 \\"{received}\\"을(를) 받았습니다.","assignmentExprComprehension":"‘{name}’ 할당 식 대상은 대상에 대한 이해력과 같은 이름을 사용할 수 없습니다.","assignmentExprContext":"할당 식은 모듈, 함수 또는 람다 내에 있어야 합니다.","assignmentExprInSubscript":"아래 첨자 내의 할당 식은 Python 3.10 이상에서만 지원됩니다.","assignmentInProtocol":"Protocol 클래스 내의 인스턴스 또는 클래스 변수는 클래스 본문 내에서 명시적으로 선언해야 합니다.","assignmentTargetExpr":"식은 할당 대상이 될 수 없습니다.","asyncNotInAsyncFunction":"비동기 함수 외부에서는 ‘async’가 허용되지 않습니다.","awaitIllegal":"\\"await\\"를 사용하려면 Python 3.5 이상이 필요합니다.","awaitNotAllowed":"형식 주석은 \\"await\\"를 사용할 수 없습니다.","awaitNotInAsync":"비동기 함수 내에서만 \\"await\\"를 사용할 수 있습니다.","backticksIllegal":"백틱으로 묶인 식은 Python 3.x에서 지원되지 않습니다. 대신 repr 사용","baseClassCircular":"클래스는 스스로에서 파생될 수 없습니다.","baseClassFinal":"기본 클래스 \\"{type}\\"이(가) final로 표시되어 서브클래스할 수 없습니다.","baseClassIncompatible":"{type}의 기본 클래스는 상호 호환되지 않습니다.","baseClassInvalid":"클래스에 대한 인수는 기본 클래스여야 합니다.","baseClassMethodTypeIncompatible":"\\"{classType}\\" 클래스의 기본 클래스가 호환되지 않는 방식으로 \\"{name}\\" 메서드를 정의합니다.","baseClassUnknown":"기본 클래스 형식을 알 수 없으므로 파생 클래스의 형식이 모호합니다.","baseClassVariableTypeIncompatible":"\\"{classType}\\" 클래스의 기본 클래스가 \\"{name}\\" 변수를 호환되지 않는 방식으로 정의합니다.","binaryOperationNotAllowed":"형식 주석에는 이항 연산자를 사용할 수 없습니다.","bindTypeMismatch":"‘{type}’을(를) 매개 변수 ‘{paramName}’에 할당할 수 없으므로 ‘{methodName}’ 메서드를 바인딩할 수 없습니다.","breakOutsideLoop":"‘break’는 루프 내에서만 사용할 수 있습니다.","callableExtraArgs":"\\"Callable\\"에 두 개의 형식 인수만 필요합니다.","callableFirstArg":"매개 변수 형식 목록 또는 \\"...\\"가 필요합니다.","callableNotInstantiable":"\\"{type}\\" 형식을 인스턴스화할 수 없습니다.","callableSecondArg":"반환 형식이 \\"Callable\\"에 대한 두 번째 형식 인수로 필요합니다.","casePatternIsIrrefutable":"되돌릴 수 없는 패턴은 마지막 case 문에만 사용할 수 있습니다.","classAlreadySpecialized":"\\"{type}\\" 형식이 이미 특수화되어 있습니다.","classDecoratorTypeUnknown":"형식화되지 않은 클래스 데코레이터는 클래스 형식을 모호하게 합니다. 데코레이터를 무시합니다.","classDefinitionCycle":"‘{name}’에 대한 클래스 정의가 스스로에 종속됩니다.","classGetItemClsParam":"__class_getitem__ 재정의는 \\"cls\\" 매개 변수를 사용해야 합니다.","classMethodClsParam":"클래스 메서드는 ‘cls’ 매개 변수를 사용해야 합니다.","classNotRuntimeSubscriptable":"클래스 \\"{name}\\"에 대한 첨자는 런타임 예외를 생성합니다. 따옴표로 형식 주석 묶기","classPatternBuiltInArgPositional":"클래스 패턴은 위치 하위 패턴만 허용합니다.","classPatternPositionalArgCount":"클래스 \\"{type}\\"에 대한 위치 패턴이 너무 많습니다. {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","classPatternTypeAlias":"‘{type}’은(는) 특수 형식 별칭이므로 클래스 패턴에서 사용할 수 없습니다.","classPropertyDeprecated":"클래스 속성은 Python 3.11에서 더 이상 사용되지 않으며 Python 3.13에서 지원되지 않습니다.","classTypeParametersIllegal":"클래스 형식 매개 변수 구문에는 Python 3.12 이상이 필요합니다.","classVarFirstArgMissing":"‘ClassVar’ 뒤에 형식 인수가 필요합니다.","classVarNotAllowed":"이 컨텍스트에서는 \\"ClassVar\\"를 사용할 수 없습니다.","classVarOverridesInstanceVar":"클래스 변수 \\"{name}\\"이(가) \\"{className}\\" 클래스에서 같은 이름의 인스턴스 변수를 재정의합니다.","classVarTooManyArgs":"‘ClassVar’ 뒤에는 형식 인수가 하나만 필요합니다.","classVarWithTypeVar":"‘ClassVar’ 형식에는 형식 변수를 포함할 수 없습니다.","clsSelfParamTypeMismatch":"‘{name}’ 매개 변수의 형식은 해당 ‘{classType}’ 클래스의 상위 형식이어야 합니다.","codeTooComplexToAnalyze":"코드가 너무 복잡하여 분석할 수 없습니다. 하위 경로로 리팩터링하거나 조건부 코드 경로를 줄여 복잡성 감소","collectionAliasInstantiation":"‘{type}’ 형식을 인스턴스화할 수 없습니다. 대신 ‘{alias}’을(를) 사용하세요.","comparisonAlwaysFalse":"\\"{leftType}\\" 및 \\"{rightType}\\" 형식이 겹치지 않으므로 조건은 항상 False로 평가됩니다.","comparisonAlwaysTrue":"\\"{leftType}\\" 및 \\"{rightType}\\" 형식이 겹치지 않으므로 조건은 항상 True로 평가됩니다.","comprehensionInDict":"이해력은 다른 사전 항목과 함께 사용할 수 없습니다.","comprehensionInSet":"이해력은 다른 집합 항목과 함께 사용할 수 없습니다.","concatenateContext":"이 컨텍스트에서는 \\"연결\\"을 사용할 수 없습니다.","concatenateParamSpecMissing":"\\"Concatenate\\"의 마지막 형식 인수는 ParamSpec 또는 \\"...\\"이어야 합니다.","concatenateTypeArgsMissing":"‘연결’에는 적어도 두 개의 형식 인수가 필요합니다.","conditionalOperandInvalid":"’{type}’ 형식의 조건부 피연산자입니다.","constantRedefinition":"‘{name}’은(는) 대문자이므로 상수이고 다시 정의할 수 없습니다.","constructorNoArgs":"\\"{type}\\" 생성자에 인수가 필요하지 않습니다.","constructorParametersMismatch":"‘{classType}’ 클래스에서 __new__ 서명과 __init__가 불일치합니다.","containmentAlwaysFalse":"‘{leftType}’ 및 ‘{rightType}’ 형식이 겹치지 않으므로 식은 항상 False로 평가됩니다.","containmentAlwaysTrue":"‘{leftType}’ 및 ‘{rightType}’ 형식이 겹치지 않으므로 식은 항상 True로 평가됩니다.","continueInFinally":"finally 절 내에서는 \\"continue\\"를 사용할 수 없습니다.","continueOutsideLoop":"\\"continue\\"는 루프 내에서만 사용할 수 있습니다.","coroutineInConditionalExpression":"조건식은 항상 True로 평가되는 코루틴을 참조합니다.","dataClassBaseClassFrozen":"고정되지 않은 클래스는 고정된 클래스에서 상속할 수 없습니다.","dataClassBaseClassNotFrozen":"고정 클래스는 고정되지 않은 클래스에서 상속할 수 없습니다.","dataClassConverterFunction":"\\"{argType}\\" 형식의 인수는 \\"{fieldType}\\" 형식의 \\"{fieldName}\\" 필드에 유효한 변환기가 아닙니다.","dataClassConverterOverloads":"\\"{funcName}\\"의 오버로드는 \\"{fieldType}\\" 형식의 \\"{fieldName}\\" 필드에 유효한 변환기가 아닙니다.","dataClassFieldWithDefault":"기본값이 없는 필드는 기본값이 있는 필드 뒤에 나타날 수 없습니다.","dataClassFieldWithPrivateName":"데이터 클래스 필드는 프라이빗 이름을 사용할 수 없습니다.","dataClassFieldWithoutAnnotation":"형식 주석이 없는 데이터 클래스 필드를 사용하면 런타임 예외가 발생합니다.","dataClassPostInitParamCount":"데이터 클래스 __post_init__의 잘못된 매개 변수 수입니다. InitVar 필드 수가 {expected}개입니다.","dataClassPostInitType":"데이터 클래스 __post_init__ 메서드 매개 변수 형식이 필드 \\"{fieldName}\\"에 대해 일치하지 않습니다.","dataClassSlotsOverwrite":"__slots__ 클래스에 이미 정의되어 있습니다.","dataClassTransformExpectedBoolLiteral":"정적으로 True 또는 False로 계산되는 식이 필요합니다.","dataClassTransformFieldSpecifier":"클래스 또는 함수의 튜플이 필요하지만 ‘{type}’ 형식을 받았습니다.","dataClassTransformPositionalParam":"\\"dataclass_transform\\"에 대한 모든 인수는 키워드 인수여야 합니다.","dataClassTransformUnknownArgument":"dataclass_transform은 \\"{name}\\" 인수를 지원하지 않습니다.","dataProtocolInSubclassCheck":"데이터 프로토콜(비 메서드 특성 포함)은 issubclass 호출에서 허용되지 않습니다.","declaredReturnTypePartiallyUnknown":"선언된 반환 형식 \\"{returnType}\\"을(를) 부분적으로 알 수 없습니다.","declaredReturnTypeUnknown":"선언된 반환 형식을 알 수 없습니다.","defaultValueContainsCall":"매개 변수 기본값 식 내에서는 함수 호출 및 변경 가능한 개체를 사용할 수 없습니다.","defaultValueNotAllowed":"\\"*\\" 또는 \\"**\\"가 있는 매개 변수는 기본값을 가질 수 없습니다.","delTargetExpr":"식을 삭제할 수 없습니다.","deprecatedClass":"‘{name}’ 클래스는 사용되지 않습니다.","deprecatedConstructor":"클래스 \\"{name}\\"의 생성자는 더 이상 사용되지 않습니다.","deprecatedDescriptorDeleter":"\\"{name}\\" 설명자에 대한 \\"____delete____\\" 메서드는 사용되지 않습니다.","deprecatedDescriptorGetter":"\\"{name}\\" 설명자에 대한 \\"__get__\\" 메서드는 사용되지 않습니다.","deprecatedDescriptorSetter":"\\"{name}\\" 설명자에 대한 \\"__set__\\" 메서드는 사용되지 않습니다.","deprecatedFunction":"\\"{name}\\" 함수는 더 이상 사용되지 않습니다.","deprecatedMethod":"\\"{className}\\" 클래스의 \\"{name}\\" 메서드는 더 이상 사용되지 않습니다.","deprecatedPropertyDeleter":"\\"{name}\\" 속성에 대한 deleter는 사용되지 않습니다.","deprecatedPropertyGetter":"\\"{name}\\" 속성에 대한 getter는 사용되지 않습니다.","deprecatedPropertySetter":"\\"{name}\\" 속성에 대한 setter는 사용되지 않습니다.","deprecatedType":"이 형식은 Python {version}부터 사용되지 않습니다. 대신 \\"{replacement}\\"을(를) 사용하세요.","dictExpandIllegalInComprehension":"사전 확장은 이해에 사용할 수 없습니다.","dictInAnnotation":"형식 주석에는 사전 식을 사용할 수 없습니다.","dictKeyValuePairs":"사전 항목은 키/값 쌍을 포함해야 합니다.","dictUnpackIsNotMapping":"사전 압축 풀기 연산자에 대한 매핑이 필요합니다.","dunderAllSymbolNotPresent":"\\"{name}\\"이(가) __all__에 지정되었지만 모듈에 없습니다.","duplicateArgsParam":"\\"*\\" 매개 변수 하나만 허용됨","duplicateBaseClass":"중복 기본 클래스는 허용되지 않습니다.","duplicateCapturePatternTarget":"‘{name}’ 캡처 대상이 동일한 패턴 내에 두 번 이상 나타날 수 없습니다.","duplicateCatchAll":"절을 제외한 하나의 catch-all만 허용됨","duplicateEnumMember":"열거형 멤버 \\"{name}\\"이(가) 이미 선언되었습니다.","duplicateGenericAndProtocolBase":"하나의 Generic[...] 또는 Protocol[...] 기본 클래스만 허용됩니다.","duplicateImport":"\\"{importName}\\"을(를) 두 번 이상 가져왔습니다.","duplicateKeywordOnly":"\\"*\\" 구분 기호는 하나만 사용할 수 있습니다.","duplicateKwargsParam":"\\"**\\" 매개 변수 하나만 허용됨","duplicateParam":"매개 변수 \\"{name}\\"이(가) 중복되었습니다.","duplicatePositionOnly":"‘/’ 매개 변수 하나민 허용됩니다.","duplicateStarPattern":"패턴 시퀀스에는 ‘*’ 패턴을 하나만 사용할 수 있습니다.","duplicateStarStarPattern":"‘**’ 항목 하나만 허용됩니다.","duplicateUnpack":"목록에서는 한 개의 압축 풀기 작업만 허용됩니다.","ellipsisAfterUnpacked":"\\"...\\" 압축을 풀고 있는 TypeVarTuple 또는 튜플과 함께 사용할 수 없습니다.","ellipsisContext":"\\"...\\"는 이 컨텍스트에서는 허용되지 않습니다.","ellipsisSecondArg":"\\"...\\"는 두 인수 중 두 번째 인수로만 허용됩니다.","enumClassOverride":"열거형 클래스 \\"{name}\\"은(는) 최종 클래스이며 서브클래스할 수 없습니다.","exceptionGroupIncompatible":"예외 그룹 구문(\\"except*\\")에는 Python 3.11 이상이 필요합니다.","exceptionTypeIncorrect":"‘{type}’은 BaseException에서 파생되지 않습니다.","exceptionTypeNotClass":"\\"{type}\\"은(는) 올바른 예외 클래스가 아닙니다.","exceptionTypeNotInstantiable":"예외 형식 \\"{type}\\"에 대한 생성자에는 하나 이상의 인수가 필요합니다.","expectedAfterDecorator":"데코레이터 다음에 함수 또는 클래스 선언이 필요합니다.","expectedArrow":"\\"->\\" 다음에 반환 형식 주석이 와야 합니다.","expectedAsAfterException":"예외 형식 뒤에 ‘as’가 필요합니다.","expectedAssignRightHandExpr":"\\"=\\" 오른쪽에 식이 필요합니다.","expectedBinaryRightHandExpr":"연산자 오른쪽에 식이 필요합니다.","expectedBoolLiteral":"True 또는 False가 필요합니다.","expectedCase":"\\"case\\" 문이 필요합니다.","expectedClassName":"클래스 이름이 필요합니다.","expectedCloseBrace":"\\"{\\"가 닫혀 있지 않습니다.","expectedCloseBracket":"\\"[{0}\\"이(가) 닫혀 있지 않습니다.","expectedCloseParen":"\\"(\\"가 닫혀 있지 않음","expectedColon":"\':\'가 필요합니다.","expectedComplexNumberLiteral":"패턴 일치에 복소수 리터럴이 필요합니다.","expectedDecoratorExpr":"Python 3.9 이전의 데코레이터에는 식 형식이 지원되지 않습니다.","expectedDecoratorName":"데코레이터 이름이 필요합니다.","expectedDecoratorNewline":"데코레이터 끝에 새 줄이 필요합니다.","expectedDelExpr":"\\"del\\" 뒤에 식이 필요합니다.","expectedElse":"\\"else\\"가 필요합니다.","expectedEquals":"\\"=\\"가 필요합니다.","expectedExceptionClass":"잘못된 예외 클래스 또는 개체","expectedExceptionObj":"필요한 예외 개체, 예외 클래스 또는 없음","expectedExpr":"식이 필요합니다.","expectedFunctionAfterAsync":"‘async’ 다음에 함수 정의가 필요합니다.","expectedFunctionName":"\\"def\\" 뒤에 함수 이름이 필요합니다.","expectedIdentifier":"식별자가 필요합니다.","expectedImport":"\\"import\\"가 필요합니다.","expectedImportAlias":"\\"as\\" 뒤에 기호가 필요합니다.","expectedImportSymbols":"가져온 후 하나 이상의 기호 이름이 필요합니다.","expectedIn":"\\"in\\"이 필요합니다.","expectedInExpr":"\\"in\\" 뒤에 식이 필요합니다.","expectedIndentedBlock":"들여쓰기 블록이 필요합니다.","expectedMemberName":"\\".\\" 뒤에 멤버 이름이 필요합니다.","expectedModuleName":"필요한 모듈 이름","expectedNameAfterAs":"‘as’ 뒤에는 기호 이름이 와야 합니다.","expectedNamedParameter":"키워드 매개 변수는 \\"*\\"를 따라야 합니다.","expectedNewline":"줄 바꿈이 필요합니다.","expectedNewlineOrSemicolon":"문은 줄 바꿈 또는 세미콜론으로 구분해야 합니다.","expectedOpenParen":"’(‘가 필요합니다.","expectedParamName":"매개 변수 이름이 필요합니다.","expectedPatternExpr":"패턴 식이 필요합니다.","expectedPatternSubjectExpr":"패턴 제목 식이 필요합니다.","expectedPatternValue":"\\"a.b\\" 형식의 패턴 값 식이 필요합니다.","expectedReturnExpr":"\\"return\\" 뒤에 식이 필요합니다.","expectedSliceIndex":"인덱스 또는 조각 식이 필요합니다.","expectedTypeNotString":"형식이 필요하지만 문자열 리터럴을 받았습니다.","expectedTypeParameterName":"형식 매개 변수 이름이 필요합니다.","expectedYieldExpr":"yield 문에 식이 필요합니다.","finalClassIsAbstract":"\\"{type}\\" 클래스가 Final로 표시되어 있으며 모든 추상 기호를 구현해야 합니다.","finalContext":"\\"Final\\"은 이 컨텍스트에서 허용되지 않습니다.","finalMethodOverride":"\\"{name}\\" 메서드는 \\"{className}\\" 클래스에 정의된 최종 메서드를 재정의할 수 없습니다.","finalNonMethod":"함수 \\"{name}\\"은(는) 메서드가 아니므로 @final로 표시할 수 없습니다.","finalReassigned":"‘{name}’이 Final로 선언되었으므로 다시 할당할 수 없습니다.","finalRedeclaration":"\\"{name}\\"이(가) 이전에 Final로 선언되었습니다.","finalRedeclarationBySubclass":"부모 클래스 \\"{className}\\"이(가) Final로 선언하므로 \\"{name}\\"을(를) 다시 선언할 수 없습니다.","finalTooManyArgs":"\\"Final\\" 뒤에 단일 형식 인수가 필요합니다.","finalUnassigned":"\\"{name}\\"이(가) Final로 선언되었지만 값이 할당되지 않았습니다.","formatStringBrace":"f-string 리터럴 내에서는 단일 닫는 중괄호를 사용할 수 없습니다. 이중 닫는 중괄호를 사용하세요.","formatStringBytes":"형식 문자열 리터럴(f-strings)은 이진일 수 없습니다.","formatStringDebuggingIllegal":"F-string 디버깅 지정자인 ‘=’는 Python 3.8 이상이 필요합니다.","formatStringEscape":"Python 3.12 이전의 f-string의 식 부분에 이스케이프 시퀀스(백슬래시)를 사용할 수 없습니다.","formatStringExpectedConversion":"f-string에서 \\"!\\" 뒤에 변환 지정자가 필요합니다.","formatStringIllegal":"형식 문자열 리터럴(f-strings)은 Python 3.6 이상이 필요합니다.","formatStringInPattern":"패턴에서 형식 문자열을 사용할 수 없습니다.","formatStringNestedFormatSpecifier":"형식 문자열 지정자 내에 너무 깊게 중첩된 식","formatStringNestedQuote":"f-string 내에 중첩된 문자열은 Python 3.12 이전의 f-string과 같은 따옴표를 사용할 수 없습니다.","formatStringUnicode":"형식 문자열 리터럴(f-문자열)은 유니코드일 수 없습니다.","formatStringUnterminated":"f-string에 종결되지 않은 식이 있습니다. ‘}‘가 필요합니다.","functionDecoratorTypeUnknown":"형식화되지 않은 함수 데코레이터는 함수 형식을 모호하게 합니다. 데코레이터 무시","functionInConditionalExpression":"조건식은 항상 True로 평가되는 함수를 참조합니다.","functionTypeParametersIllegal":"함수 형식 매개 변수 구문에는 Python 3.12 이상이 필요합니다.","futureImportLocationNotAllowed":"__future__ 가져오기는 파일의 시작 부분에 있어야 합니다.","generatorAsyncReturnType":"비동기 생성기 함수의 반환 형식은 \\"AsyncGenerator[{yieldType}, Any]\\"와 호환되어야 합니다.","generatorNotParenthesized":"생성기 식은 단독 인수가 아닌 경우 괄호로 지정해야 합니다.","generatorSyncReturnType":"생성기 함수의 반환 형식은 \\"Generator[{yieldType}, Any, Any]\\"와 호환되어야 합니다.","genericBaseClassNotAllowed":"‘제네릭’ 기본 클래스는 형식 매개 변수 구문과 함께 사용할 수 없습니다.","genericClassAssigned":"제네릭 클래스 형식을 할당할 수 없습니다.","genericClassDeleted":"제네릭 클래스 형식을 삭제할 수 없습니다.","genericInstanceVariableAccess":"클래스를 통한 제네릭 인스턴스 변수에 대한 액세스가 모호합니다.","genericNotAllowed":"이 컨텍스트에서 \\"Generic\\"이 잘못되었습니다.","genericTypeAliasBoundTypeVar":"클래스 내의 제네릭 형식 별칭은 바인딩된 형식 변수 {names}을(를) 사용할 수 없습니다.","genericTypeArgMissing":"\\"Generic\\"에는 하나 이상의 형식 인수가 필요합니다.","genericTypeArgTypeVar":"\\"Generic\\"의 형식 인수는 형식 변수여야 합니다.","genericTypeArgUnique":"\\"Generic\\"의 형식 인수는 고유해야 합니다.","globalReassignment":"전역 선언 전에 \\"{name}\\"이(가) 할당되었습니다.","globalRedefinition":"\\"{name}\\"이(가) 이미 전역으로 선언되었습니다.","implicitStringConcat":"암시적 문자열 연결이 허용되지 않습니다.","importCycleDetected":"가져오기 체인에서 순환이 검색되었습니다.","importDepthExceeded":"가져오기 체인 깊이가 {depth}을(를) 초과했습니다.","importResolveFailure":"가져오기 \\"{importName}\\"을(를) 확인할 수 없습니다.","importSourceResolveFailure":"원본에서 가져오기 \\"{importName}\\"을(를) 확인할 수 없습니다.","importSymbolUnknown":"\\"{name}\\"은(는) 알 수 없는 가져오기 기호입니다.","incompatibleMethodOverride":"\\"{name}\\" 메서드가 호환되지 않는 방식으로 \\"{className}\\" 클래스를 재정의합니다.","inconsistentIndent":"들여쓰기하지 않은 양이 이전 들여쓰기와 일치하지 않습니다.","inconsistentTabs":"들여쓰기에서 탭 및 공백의 일관성 없는 사용","initMustReturnNone":"\\"__init__\\"의 반환 형식은 None이어야 합니다.","initSubclassCallFailed":"__init_subclass__ 메서드의 키워드 인수가 잘못됨","initSubclassClsParam":"__init_subclass__ 재정의는 \\"cls\\" 매개 변수를 사용해야 합니다.","initVarNotAllowed":"이 컨텍스트에서는 \\"InitVar\\"가 허용되지 않습니다.","instanceMethodSelfParam":"인스턴스 메서드는 \\"self\\" 매개 변수를 사용해야 합니다.","instanceVarOverridesClassVar":"‘{name}’ 인스턴스 변수가 ‘{className}’ 클래스에서 같은 이름의 클래스 변수를 재정의합니다.","instantiateAbstract":"\'{type}\' 추상 클래스를 인스턴스화할 수 없습니다.","instantiateProtocol":"‘{type}’ 프로토콜 클래스를 인스턴스화할 수 없습니다.","internalBindError":"파일 \\"{file}\\"을(를) 바인딩하는 동안 내부 오류가 발생했습니다. {message}","internalParseError":"파일 \\"{file}\\"을(를) 구문 분석하는 동안 내부 오류가 발생했습니다. {message}","internalTypeCheckingError":"파일 \\"{file}\\"의 형식을 확인하는 동안 내부 오류가 발생했습니다. {message}","invalidIdentifierChar":"식별자에 잘못된 문자가 있습니다.","invalidStubStatement":"형식 스텁 파일 내에서는 문이 의미가 없습니다.","invalidTokenChars":"토큰에 잘못된 문자 ‘{text}’이(가) 있습니다.","isInstanceInvalidType":"‘issubclass’에 대한 두 번째 인수는 클래스 또는 클래스의 튜플이어야 합니다.","isSubclassInvalidType":"\\"issubclass\\"에 대한 두 번째 인수는 클래스 또는 클래스의 튜플이어야 합니다.","keyValueInSet":"집합 내에서 키/값 쌍을 사용할 수 없습니다.","keywordArgInTypeArgument":"키워드 인수는 형식 인수 목록에서 사용할 수 없습니다.","keywordOnlyAfterArgs":"키워드 전용 인수 구분 기호는 \\"*\\" 매개 변수 뒤에 사용할 수 없습니다.","keywordParameterMissing":"하나 이상의 키워드 매개 변수는 ’*‘ 매개 변수 뒤에 와야 합니다.","keywordSubscriptIllegal":"아래 첨자 내의 키워드 인수는 지원되지 않습니다.","lambdaReturnTypePartiallyUnknown":"람다의 반환 형식 \\"{returnType}\\"을(를) 부분적으로 알 수 없습니다.","lambdaReturnTypeUnknown":"람다의 반환 형식을 알 수 없습니다.","listAssignmentMismatch":"형식이 \\"{type}\\"인 식을 대상 목록에 할당할 수 없습니다.","listInAnnotation":"형식 주석에는 목록 식을 사용할 수 없습니다.","literalEmptyArgs":"‘Literal’ 뒤에 하나 이상의 형식 인수가 필요합니다.","literalNotAllowed":"형식 인수가 없으면 이 컨텍스트에서 \\"Literal\\"을 사용할 수 없습니다.","literalNotCallable":"리터럴 형식은 인스턴스화할 수 없습니다.","literalUnsupportedType":"\\"Literal\\"의 형식 인수는 None, 리터럴 값(int, bool, str 또는 bytes) 또는 열거형 값이어야 합니다.","matchIncompatible":"Match 문에는 Python 3.10 이상이 필요합니다.","matchIsNotExhaustive":"match 문 내의 사례는 모든 값을 완전히 처리하지 않습니다.","maxParseDepthExceeded":"최대 구문 분석 깊이를 초과했습니다. 식을 더 작은 하위 식으로 나누기","memberAccess":"\\"{type}\\" 형식의 멤버 \\"{name}\\"에 액세스할 수 없습니다.","memberDelete":"\\"{type}\\" 형식의 멤버 \\"{name}\\"을(를) 삭제할 수 없습니다.","memberSet":"‘{type}’ 형식의 ‘{name}’ 멤버에 액세스할 수 없습니다.","metaclassConflict":"파생 클래스의 메타클래스는 모든 기본 클래스의 메타클래스의 서브클래스여야 합니다.","metaclassDuplicate":"메타클래스를 하나만 제공할 수 있습니다.","metaclassIsGeneric":"메타클래스는 제네릭일 수 없습니다.","methodNotDefined":"\\"{name}\\" 메서드가 정의되지 않았습니다.","methodNotDefinedOnType":"\\"{name}\\" 메서드가 \\"{type}\\" 형식에 정의되지 않았습니다.","methodOrdering":"일관된 메서드 순서를 만들 수 없습니다.","methodOverridden":"‘{name}’은(는) ‘{className}’ 클래스에서 같은 이름의 메서드를 호환되지 않는 ‘{type}’ 형식으로 재정의합니다.","methodReturnsNonObject":"\\"{name}\\" 메서드가 개체를 반환하지 않습니다.","missingSuperCall":"\\"{methodName}\\" 메서드가 부모 클래스에서 같은 이름의 메서드를 호출하지 않습니다.","moduleAsType":"모듈은 형식으로 사용할 수 없습니다.","moduleNotCallable":"모듈을 호출할 수 없습니다.","moduleUnknownMember":"‘{memberName}’은(는) ‘{moduleName}’ 모듈의 알려진 멤버가 아닙니다.","namedExceptAfterCatchAll":"명명된 except 절은 catch-all except 절 뒤에 나타날 수 없습니다.","namedParamAfterParamSpecArgs":"ParamSpec args 매개 변수 뒤에 키워드 매개 변수 \\"{name}\\"을(를) 시그니처에 표시할 수 없습니다.","namedTupleEmptyName":"명명된 튜플 내의 이름은 비워 둘 수 없습니다.","namedTupleEntryRedeclared":"부모 클래스 \\"{className}\\"이(가) 명명된 튜플이므로 \\"{name}\\"을(를) 재정의할 수 없습니다.","namedTupleFirstArg":"명명된 튜플 클래스 이름이 첫 번째 인수로 필요합니다.","namedTupleMultipleInheritance":"NamedTuple을 사용한 여러 상속은 지원되지 않습니다.","namedTupleNameKeyword":"필드 이름은 키워드일 수 없습니다.","namedTupleNameType":"항목 이름 및 형식을 지정하는 2개 항목 튜플이 필요합니다.","namedTupleNameUnique":"명명된 튜플 내의 이름은 고유해야 합니다.","namedTupleNoTypes":"\\"namedtuple\\"은 튜플 항목에 대한 형식을 제공하지 않습니다. 대신 \\"NamedTuple\\" 사용","namedTupleSecondArg":"두 번째 인수로 명명된 튜플 항목 목록이 필요합니다.","newClsParam":"__new__ 재정의는 \\"cls\\" 매개 변수를 사용해야 합니다.","newTypeAnyOrUnknown":"NewType에 대한 두 번째 인수는 Any 또는 Unknown이 아닌 알려진 클래스여야 합니다.","newTypeBadName":"NewType의 첫 번째 인수는 문자열 리터럴이어야 합니다.","newTypeLiteral":"NewType은 리터럴 형식과 함께 사용할 수 없습니다.","newTypeNameMismatch":"NewType은 이름이 같은 변수에 할당되어야 합니다.","newTypeNotAClass":"NewType에 대한 두 번째 인수로 클래스가 필요합니다.","newTypeParamCount":"NewType에는 두 개의 위치 인수가 필요합니다.","newTypeProtocolClass":"NewType은 구조적 유형(프로토콜 또는 TypedDict 클래스)과 함께 사용할 수 없습니다.","noOverload":"제공된 인수와 일치하는 \\"{name}\\"에 대한 오버로드가 없습니다.","noReturnContainsReturn":"선언된 반환 형식이 \\"NoReturn\\"인 함수는 return 문을 포함할 수 없습니다.","noReturnContainsYield":"선언된 반환 형식이 \\"NoReturn\\"인 함수는 yield 문을 포함할 수 없습니다.","noReturnReturnsNone":"선언된 반환 형식이 \\"NoReturn\\"인 함수는 \\"None\\"을 반환할 수 없습니다.","nonDefaultAfterDefault":"기본값이 아닌 인수가 기본 인수를 따릅니다.","nonLocalInModule":"모듈 수준에서는 비로컬 선언을 사용할 수 없습니다.","nonLocalNoBinding":"비로컬 \\"{name}\\"에 대한 바인딩을 찾을 수 없습니다.","nonLocalReassignment":"비로컬 선언 전에 \\"{name}\\"이(가) 할당되었습니다.","nonLocalRedefinition":"\\"{name}\\"이(가) 이미 비로컬로 선언되었습니다.","noneNotCallable":"‘None’ 유형의 개체를 호출할 수 없습니다.","noneNotIterable":"\\"None\\" 형식의 개체는 반복 가능한 값으로 사용할 수 없습니다.","noneNotSubscriptable":"’None’ 유형의 개체는 아래 첨자를 사용할 수 없습니다.","noneNotUsableWith":"\\"None\\" 형식의 개체는 \\"with\\"와 함께 사용할 수 없습니다.","noneOperator":"\\"None\\"에 대해 연산자 \\"{operator}\\"이(가) 지원되지 않습니다.","noneUnknownMember":"\\"{name}\\"은(는) \\"None\\"의 알려진 멤버가 아닙니다.","notRequiredArgCount":"\\"NotRequired\\" 뒤에 단일 형식 인수가 필요합니다.","notRequiredNotInTypedDict":"이 컨텍스트에서는 \\"NotRequired\\"를 사용할 수 없습니다.","objectNotCallable":"\\"{type}\\" 형식의 개체를 호출할 수 없습니다.","obscuredClassDeclaration":"클래스 선언 \\"{name}\\"이(가) 같은 이름의 선언으로 가려져 있습니다.","obscuredFunctionDeclaration":"함수 선언 \\"{name}\\"이(가) 동일한 이름의 선언으로 가려집니다.","obscuredMethodDeclaration":"메서드 선언 \\"{name}\\"이(가) 동일한 이름의 선언으로 가려집니다.","obscuredParameterDeclaration":"매개 변수 선언 \\"{name}\\"이(가) 동일한 이름의 선언으로 가려집니다.","obscuredTypeAliasDeclaration":"형식 별칭 선언 \\"{name}\\"이(가) 동일한 이름의 선언으로 가려집니다.","obscuredVariableDeclaration":"\\"{name}\\" 선언이 같은 이름의 선언으로 가려집니다.","operatorLessOrGreaterDeprecated":"\\"<>\\" 연산자는 Python 3에서 지원되지 않습니다. 대신 \\"!=\\"를 사용하세요.","optionalExtraArgs":"‘선택 사항’ 뒤에 1개의 형식 인수가 필요합니다.","orPatternIrrefutable":"되돌릴 수 없는 패턴은 ‘or’ 패턴의 마지막 하위 페이지로만 허용됩니다.","orPatternMissingName":"\\"or\\" 패턴 내의 모든 하위 패턴은 동일한 이름을 대상으로 해야 합니다.","overlappingKeywordArgs":"형식화된 사전이 키워드 매개 변수 {names}과(와) 겹칩니다.","overlappingOverload":"매개 변수가 오버로드 {obscuredBy}과(와) 겹치므로 \\"{name}\\"에 대한 오버로드 {obscured}이(가) 사용되지 않습니다.","overloadAbstractMismatch":"오버로드된 메서드는 모두 추상이거나 모두 추상이 아니어야 합니다.","overloadClassMethodInconsistent":"\\"{name}\\"의 오버로드가 @classmethod를 일관되지 않게 사용합니다.","overloadFinalInconsistencyImpl":"\\"{name}\\"에 대한 오버로드가 @final로 표시되었지만 구현은 아닙니다.","overloadFinalInconsistencyNoImpl":"\\"{name}\\"에 대한 오버로드 {index}는 @final로 표시되지만 오버로드 1은 표시되지 않습니다.","overloadImplementationMismatch":"오버로드된 구현이 오버로드 {index}의 시그니처와 일치하지 않습니다.","overloadReturnTypeMismatch":"\\"{name}\\"에 대한 {prevIndex} 오버로드가 오버로드 {newIndex}과(와) 겹치고 호환되지 않는 형식을 반환합니다.","overloadStaticMethodInconsistent":"\\"{name}\\"의 오버로드가 @staticmethod를 일관되지 않게 사용합니다.","overloadWithoutImplementation":"‘{name}’이(가) 오버로드로 표시되어 있지만 구현이 제공되지 않았습니다.","overriddenMethodNotFound":"‘{name}’ 메서드가 재정의로 표시되어 있지만 이름이 같은 기본 메서드가 없습니다.","overrideDecoratorMissing":"‘{name}’ 메서드가 재정의로 표시되지 않았지만 ‘{className}’ 클래스에서 메서드를 재정의하고 있습니다.","paramAfterKwargsParam":"매개 변수는 ‘**’ 매개 변수 다음에 와야 합니다.","paramAlreadyAssigned":"매개 변수 \\"{name}\\"이(가) 이미 할당되었습니다.","paramAnnotationMissing":"‘{name}’ 매개 변수에 대한 형식 주석이 없습니다.","paramAssignmentMismatch":"‘{sourceType}’ 형식의 식을 ‘{paramType}’ 형식의 매개 변수에 할당할 수 없습니다.","paramNameMissing":"이름이 \\"{name}\\"인 매개 변수가 없습니다.","paramSpecArgsKwargsUsage":"ParamSpec의 \\"args\\" 및 \\"kwargs\\" 멤버는 모두 함수 서명 내에 나타나야 합니다.","paramSpecArgsMissing":"ParamSpec \\"{type}\\"에 대한 인수가 없습니다.","paramSpecArgsUsage":"ParamSpec의 ‘args’ 멤버는 *args 매개 변수와 함께 사용할 경우에만 유효합니다.","paramSpecAssignedName":"ParamSpec을 \\"{name}\\"이라는 변수에 할당해야 합니다.","paramSpecContext":"ParamSpec은 이 컨텍스트에서 허용되지 않습니다.","paramSpecDefaultNotTuple":"ParamSpec의 기본값에는 줄임표, 튜플 식 또는 ParamSpec이 필요합니다.","paramSpecFirstArg":"첫 번째 인수로 ParamSpec의 이름이 필요합니다.","paramSpecKwargsUsage":"ParamSpec의 \\"kwargs\\" 멤버는 **kwargs 매개 변수와 함께 사용할 때만 유효합니다.","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\"은(는) 이 컨텍스트에서 의미가 없습니다.","paramSpecScopedToReturnType":"ParamSpec ‘{name}’은 반환 형식 내에서 호출 가능으로 범위가 지정되며 함수 본문에서 참조할 수 없습니다.","paramSpecUnknownArg":"ParamSpec은 한 개 이상의 인수를 지원하지 않습니다.","paramSpecUnknownMember":"\\"{name}\\"은(는) ParamSpec의 알려진 멤버가 아닙니다.","paramSpecUnknownParam":"‘{name}’은(는) ParamSpec에 대한 알 수 없는 매개 변수입니다.","paramTypeCovariant":"공변(Covariant) 형식 변수는 매개 변수 형식에 사용할 수 없습니다.","paramTypePartiallyUnknown":"매개 변수 \\"{paramName}\\"의 형식을 부분적으로 알 수 없습니다.","paramTypeUnknown":"매개 변수 \\"{paramName}\\"의 형식을 알 수 없습니다.","parenthesizedContextManagerIllegal":"‘with’ 문 내의 괄호는 Python 3.9 이상이 필요합니다.","patternNeverMatches":"제목 형식 \\"{type}\\"에 대해 패턴이 일치하지 않습니다.","positionArgAfterNamedArg":"위치 인수는 키워드 인수 뒤에 나타날 수 없습니다.","positionOnlyAfterArgs":"위치 전용 매개 변수 구분 기호는 \\"*\\" 매개 변수 뒤에 사용할 수 없습니다.","positionOnlyAfterKeywordOnly":"\\"/\\" 매개 변수는 \\"*\\" 매개 변수 앞에 나타나야 합니다.","positionOnlyAfterNon":"위치 전용이 아닌 매개 변수 다음에는 위치 전용 매개 변수를 사용할 수 없습니다.","positionOnlyFirstParam":"위치 전용 매개 변수 구분 기호는 첫 번째 매개 변수로 허용되지 않습니다.","positionOnlyIncompatible":"위치 전용 매개 변수 구분 기호에는 Python 3.8 이상이 필요합니다.","privateImportFromPyTypedModule":"\\"{name}\\"은(는) \\"{module}\\" 모듈에서 내보내지지 않습니다.","privateUsedOutsideOfClass":"\\"{name}\\"은(는) 프라이빗이며 선언된 클래스 외부에서 사용됩니다.","privateUsedOutsideOfModule":"\\"{name}\\"은(는) 프라이빗이며 선언된 모듈 외부에서 사용됩니다.","propertyOverridden":"‘{name}’은(는) ‘{className}’ 클래스에서 같은 이름의 속성을 잘못 재정의합니다.","propertyStaticMethod":"속성 getter, setter 또는 deleter에는 정적 메서드를 사용할 수 없습니다.","protectedUsedOutsideOfClass":"‘{name}’은(는) 선언된 클래스 외부에서 보호되고 사용됩니다.","protocolBaseClass":"‘{classType}’ 프로토콜 클래스는 ‘{baseType}’ 비프로토콜 클래스에서 파생될 수 없습니다.","protocolBaseClassWithTypeArgs":"형식 매개 변수 구문을 사용할 때는 Protocol 클래스에 형식 인수가 허용되지 않습니다.","protocolIllegal":"\\"프로토콜\\"을 사용하려면 Python 3.7 이상이 필요합니다.","protocolNotAllowed":"이 컨텍스트에서는 \\"Protocol\\"을 사용할 수 없습니다.","protocolUnsafeOverlap":"클래스가 \\"{name}\\"과(와) 안전하지 않게 겹치며 런타임에 일치 항목을 생성할 수 있습니다.","protocolVarianceContravariant":"‘{class}‘ 제네릭 프로토콜에서 사용되는 ’{variable}‘ 형식 변수는 반공변이어야 합니다.","protocolVarianceCovariant":"‘{class}‘ 제네릭 프로토콜에서 사용되는 ’{variable}‘ 형식 변수는 공변이어야 합니다","protocolVarianceInvariant":"‘{class}‘ 제네릭 프로토콜에서 사용되는 ’{variable}‘ 형식 변수는 고정 변수여야 합니다.","pyrightCommentInvalidDiagnosticBoolValue":"Pyright 주석 지시문 뒤에는 \\"=\\"와 true 또는 false 값이 와야 합니다.","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright 주석 지시문 뒤에는 \\"=\\"와 true, false, error, warning, information 또는 none 값이 와야 합니다.","pyrightCommentMissingDirective":"Pyright 주석 뒤에는 지시문(기본 또는 엄격) 또는 진단 규칙이 있어야 합니다.","pyrightCommentNotOnOwnLine":"파일 수준 설정을 제어하는 데 사용되는Pyright 주석은 고유의 줄에 표시되어야 합니다.","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\"은(는) pyright 주석에 대한 알 수 없는 진단 규칙입니다.","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\"이(가) pyright 주석에 대해 잘못된 값입니다. true, false, error, warning, information 또는 none이 필요합니다.","pyrightCommentUnknownDirective":"\\"{directive}\\"은(는) pyright 주석에 대한 알 수 없는 지시문입니다. \\"strict\\" 또는 \\"basic\\"이 필요합니다.","readOnlyArgCount":"‘ReadOnly‘ 뒤에는 단일 형식 인수가 필요합니다.","readOnlyNotInTypedDict":"이 컨텍스트에서는 \\"ReadOnly\\"를 사용할 수 없습니다.","recursiveDefinition":"‘{name}’ 형식이 스스로를 참조하므로 확인할 수 없습니다.","relativeImportNotAllowed":"상대 가져오기는 \\"import .a\\" 양식과 함께 사용할 수 없습니다. 대신 \\"from . import a\\"을(를) 사용합니다.","requiredArgCount":"‘Required’ 뒤에 단일 형식 인수가 필요합니다.","requiredNotInTypedDict":"이 컨텍스트에서는 \\"Required\\"를 사용할 수 없습니다.","returnInAsyncGenerator":"값이 있는 Return 문은 비동기 생성기에서 사용할 수 없습니다.","returnMissing":"선언된 반환 형식이 \\"{returnType}\\"인 함수는 모든 코드 경로에서 값을 반환해야 합니다.","returnOutsideFunction":"‘return’은 함수 내에서만 사용할 수 있습니다.","returnTypeContravariant":"반공변 유형 변수는 반환 형식에 사용할 수 없습니다.","returnTypeMismatch":"\\"{exprType}\\" 형식의 식을 반환 형식 \\"{returnType}\\"에 할당할 수 없습니다.","returnTypePartiallyUnknown":"반환 형식 \\"{returnType}\\"을(를) 부분적으로 알 수 없습니다.","returnTypeUnknown":"반환 유형을 알 수 없습니다.","revealLocalsArgs":"‘reveal_locals’ 호출은 인수가 필요하지 않습니다.","revealLocalsNone":"이 범위에 로컬이 없습니다.","revealTypeArgs":"\\"reveal_type\\" 호출에는 단일 위치 인수가 필요합니다.","revealTypeExpectedTextArg":"‘reveal_type’ 함수의 ‘expected_text’ 인수는 str 리터럴 값이어야 합니다.","revealTypeExpectedTextMismatch":"텍스트 형식이 일치하지 않습니다. \\"{expected}\\"이(가) 필요하지만 \\"{received}\\"을(를) 받았습니다.","revealTypeExpectedTypeMismatch":"텍스트 형식이 일치하지 않습니다. ‘{expected}’이(가) 필요하지만 ‘{received}’을(를) 받았습니다.","selfTypeContext":"이 컨텍스트에서는 \\"Self\\"가 잘못되었습니다.","selfTypeMetaclass":"메타클래스(\\"type\\"의 서브클래스) 내에서 \\"Self\\"를 사용할 수 없습니다.","selfTypeWithTypedSelfOrCls":"\\"Self\\"는 \\"Self\\" 이외의 형식 주석이 있는 \'self\' 또는 \'cls\' 매개 변수가 있는 함수에서 사용할 수 없습니다.","setterGetterTypeMismatch":"속성 setter 값 형식을 getter 반환 형식에 할당할 수 없습니다.","singleOverload":"\\"{name}\\"이(가) 오버로드로 표시되었지만 추가 오버로드가 없습니다.","slotsAttributeError":"__slots__에서 ‘{name}’이(가) 지정되지 않았습니다.","slotsClassVarConflict":"‘{name}‘이(가) __slots__에 선언된 instance 변수와 충돌합니다.","starPatternInAsPattern":"별 무늬는 \\"as\\" 대상과 함께 사용할 수 없습니다.","starPatternInOrPattern":"별 무늬는 다른 패턴 내에서 ORed할 수 없습니다.","starStarWildcardNotAllowed":"**는 와일드카드 \\"_\\"와 함께 사용할 수 없습니다.","staticClsSelfParam":"정적 메서드는 \\"self\\" 또는 \\"cls\\" 매개 변수를 사용하면 안 됩니다.","stdlibModuleOverridden":"‘{path}’이(가) ‘{name}’ stdlib 모듈을 재정의하고 있습니다.","stringNonAsciiBytes":"ASCII가 아닌 문자는 바이트 문자열 리터럴에 허용되지 않습니다.","stringNotSubscriptable":"형식 주석에는 문자열 식을 첨자할 수 없습니다. 전체 주석을 따옴표로 묶습니다.","stringUnsupportedEscape":"문자열 리터럴에 지원되지 않는 이스케이프 시퀀스가 있습니다.","stringUnterminated":"문자열 리터럴이 종료되지 않았습니다.","stubFileMissing":"\\"{importName}\\"에 대한 스텁 파일을 찾을 수 없습니다.","stubUsesGetAttr":"형식 스텁 파일이 불완전합니다. \\"__getattr__\\"는 모듈에 대한 형식 오류를 모호하게 합니다.","sublistParamsIncompatible":"하위 목록 매개 변수는 Python 3.x에서 지원되지 않습니다.","superCallArgCount":"‘super’ 호출에는 인수가 2개 이하여야 합니다.","superCallFirstArg":"\\"super\\" 호출에 대한 첫 번째 인수로 클래스 형식이 필요하지만 \\"{type}\\"을(를) 받았습니다.","superCallSecondArg":"\\"super\\" 호출에 대한 두 번째 인수는 \\"{type}\\"에서 파생된 개체 또는 클래스여야 합니다.","superCallZeroArgForm":"\\"super\\" 호출의 인수가 0인 형식은 메서드 내에서만 유효합니다.","superCallZeroArgFormStaticMethod":"\\"super\\" 호출의 인수가 0인 형식은 정적 메서드 내에서 유효하지 않습니다.","symbolIsPossiblyUnbound":"\\"{name}\\"은(는) 바인딩되지 않은 것일 수 있습니다.","symbolIsUnbound":"\\"{name}\\"의 바인딩이 해제되었습니다.","symbolIsUndefined":"\\"{name}\\"이(가) 정의되지 않았습니다.","symbolOverridden":"\\"{name}\\"이(가) 클래스 \\"{className}\\"에서 동일한 이름의 기호를 재정의합니다.","ternaryNotAllowed":"형식 주석에는 3항 식이 허용되지 않습니다.","totalOrderingMissingMethod":"클래스는 total_ordering을 사용하려면 \\"__lt__\\", \\"__le__\\", \\"__gt__\\" 또는 \\"__ge__\\" 중 하나를 정의해야 합니다.","trailingCommaInFromImport":"주변 괄호 없이는 후행 쉼표를 사용할 수 없습니다.","tryWithoutExcept":"try 문에는 except 또는 finally 절이 하나 이상 있어야 합니다.","tupleAssignmentMismatch":"형식이 ‘{type}’인 식을 대상 목록에 할당할 수 없습니다.","tupleInAnnotation":"형식 주석에는 튜플 식을 사용할 수 없습니다.","tupleIndexOutOfRange":"{index} 인덱스가 {type} 형식의 범위를 벗어났습니다.","typeAliasIllegalExpressionForm":"형식 별칭 정의에 대한 식 양식이 잘못되었습니다.","typeAliasIsRecursiveDirect":"형식 별칭 ‘{name}’의 정의에서 스스로를 사용할 수 없습니다.","typeAliasNotInModuleOrClass":"TypeAlias는 모듈 또는 클래스 범위 내에서만 정의할 수 있습니다.","typeAliasRedeclared":"\\"{name}\\"은(는) TypeAlias로 선언되며 한 번만 할당할 수 있습니다.","typeAliasStatementBadScope":"type 문은 모듈 또는 클래스 범위 내에서만 사용할 수 있습니다.","typeAliasStatementIllegal":"형식 별칭 문에는 Python 3.12 이상이 필요합니다.","typeAliasTypeBaseClass":"\\"type\\" 문에 정의된 형식 별칭은 기본 클래스로 사용할 수 없습니다.","typeAliasTypeMustBeAssigned":"TypeAliasType은 형식 별칭과 이름이 같은 변수에 할당해야 합니다.","typeAliasTypeNameArg":"TypeAliasType의 첫 번째 인수는 형식 별칭의 이름을 나타내는 문자열 리터럴이어야 합니다.","typeAliasTypeNameMismatch":"형식 별칭의 이름은 할당된 변수의 이름과 일치해야 합니다.","typeAliasTypeParamInvalid":"형식 매개 변수 목록은 TypeVar, TypeVarTuple 또는 ParamSpec만 포함하는 튜플이어야 합니다.","typeAnnotationCall":"형식 식에는 호출 식을 사용할 수 없습니다.","typeAnnotationVariable":"형식 식에는 변수를 사용할 수 없습니다.","typeAnnotationWithCallable":"\\"type\\"에 대한 형식 인수는 클래스여야 합니다. 콜러블은 지원되지 않습니다.","typeArgListExpected":"ParamSpec, 줄임표 또는 형식 목록이 필요합니다.","typeArgListNotAllowed":"이 형식 인수에는 목록 식을 사용할 수 없습니다.","typeArgsExpectingNone":"클래스 \\"{name}\\"에 형식 인수가 필요하지 않습니다.","typeArgsMismatchOne":"하나의 형식 인수가 필요하지만 {received}을(를) 받았습니다.","typeArgsMissingForAlias":"제네릭 형식 별칭 \\"{name}\\"에 대한 형식 인수가 필요합니다.","typeArgsMissingForClass":"‘{name}’ 제네릭 클래스에 대한 형식 인수가 필요합니다.","typeArgsTooFew":"\\"{name}\\"에 대해 제공된 형식 인수가 너무 적습니다. {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","typeArgsTooMany":"‘{name}’에 대한 형식 인수가 너무 많습니다. {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","typeAssignmentMismatch":"\\"{sourceType}\\" 형식의 식을 선언된 형식 \\"{destType}\\"에 할당할 수 없습니다.","typeAssignmentMismatchWildcard":"가져오기 기호 \\"{name}\\"에 선언된 형식 \\"{destType}\\"에 할당할 수 없는 \\"{sourceType}\\" 형식이 있습니다.","typeCallNotAllowed":"type() 호출은 형식 주석에 사용하면 안 됩니다.","typeCheckOnly":"\\"{name}\\"이(가) @type_check_only로 표시되어 있으므로 형식 주석에서만 사용할 수 있습니다.","typeCommentDeprecated":"형식 주석의 사용은 더 이상 사용되지 않습니다. 대신 형식 주석 사용","typeExpectedClass":"형식 식이 필요하지만 \\"{type}\\"을(를) 받았습니다.","typeGuardArgCount":"\\"TypeGuard\\" 또는 \\"TypeIs\\" 뒤에 단일 형식 인수가 필요합니다.","typeGuardParamCount":"사용자 정의 type guard 함수 및 메서드에는 하나 이상의 입력 매개 변수가 있어야 합니다.","typeIsReturnType":"TypeIs의 반환 형식(\\"{returnType}\\")이 값 매개 변수 형식(\\"{type}\\")과 일치하지 않습니다.","typeNotAwaitable":"‘{type}’은(는) 대기할 수 없습니다.","typeNotIntantiable":"\\"{type}\\"을(를) 인스턴스화할 수 없습니다.","typeNotIterable":"\\"{type}\\" 반복할 수 없습니다.","typeNotSpecializable":"‘{type}’ 형식을 특수화할 수 없습니다.","typeNotSubscriptable":"\\"{type}\\" 형식의 개체를 첨자할 수 없습니다.","typeNotSupportBinaryOperator":"‘{operator}’ 연산자는 ‘{leftType}’ 및 ‘{rightType}’ 형식에 대해 지원되지 않습니다.","typeNotSupportBinaryOperatorBidirectional":"예상 형식이 ‘{expectedType}’인 경우 ‘{leftType}’ 및 ‘{rightType}’ 형식에 대해 ‘{operator}’ 연산자가 지원되지 않습니다.","typeNotSupportUnaryOperator":"‘{type}’‘에 대해 ’{operator}‘ 연산자가 지원되지 않습니다.","typeNotSupportUnaryOperatorBidirectional":"예상 형식이 \\"{expectedType}\\" 경우 형식 \\"{type}\\"에 대해 연산자 \\"{operator}\\"이(가) 지원되지 않습니다.","typeNotUsableWith":"\\"{type}\\" 형식의 개체는 {method}을(를) 구현하지 않으므로 \\"with\\"와 함께 사용할 수 없습니다.","typeParameterBoundNotAllowed":"바운드 또는 제약 조건은 가변 인자 형식 매개 변수 또는 ParamSpec와 함께 사용할 수 없습니다.","typeParameterConstraintTuple":"형식 매개 변수 제약 조건은 두 개 이상의 형식 튜플이어야 합니다.","typeParameterExistingTypeParameter":"형식 매개 변수 \\"{name}\\"이(가) 이미 사용 중입니다.","typeParameterNotDeclared":"형식 매개 변수 \\"{name}\\"이(가) \\"{container}\\"의 형식 매개 변수 목록에 포함되어 있지 않습니다.","typeParametersMissing":"하나 이상의 형식 매개 변수를 지정해야 합니다.","typePartiallyUnknown":"\\"{name}\\"의 형식을 부분적으로 알 수 없습니다.","typeUnknown":"\\"{name}\\" 유형을 알 수 없습니다.","typeVarAssignedName":"TypeVar을 \\"{name}\\"이라는 변수에 할당해야 합니다.","typeVarAssignmentMismatch":"‘{type}’ 형식을 ‘{name}’ 형식 변수에 할당할 수 없습니다.","typeVarBoundAndConstrained":"TypeVar는 바인딩되고 제한될 수 없습니다.","typeVarBoundGeneric":"TypeVar 바인딩 형식은 제네릭일 수 없습니다.","typeVarConstraintGeneric":"TypeVar 제약 조건 형식은 제네릭일 수 없습니다.","typeVarDefaultBoundMismatch":"TypeVar 기본 형식은 바인딩된 형식의 하위 형식이어야 합니다.","typeVarDefaultConstraintMismatch":"TypeVar 기본 형식은 제약이 있는 형식 중 하나여야 합니다.","typeVarDefaultIllegal":"형식 변수 기본 형식은 Python 3.13 이상이 필요합니다.","typeVarDefaultInvalidTypeVar":"형식 매개 변수 \\"{name}\\"에 범위를 벗어난 하나 이상의 형식 변수를 참조하는 기본 형식이 있습니다.","typeVarFirstArg":"TypeVar의 이름이 첫 번째 인수로 필요합니다.","typeVarNoMember":"TypeVar \\"{type}\\"에 멤버 \\"{name}\\"이(가) 없습니다.","typeVarNotSubscriptable":"TypeVar \\"{type}\\"을(를) 첨자할 수 없습니다.","typeVarNotUsedByOuterScope":"형식 변수 \\"{name}\\"은(는) 이 컨텍스트에서 의미가 없습니다.","typeVarPossiblyUnsolvable":"호출자가 ‘{param}’ 매개 변수에 대한 인수를 제공하지 않으면 ‘{name}’ 형식 변수가 확인되지 않을 수 있습니다.","typeVarScopedToReturnType":"‘{name}’ 형식 변수는 반환 형식 내에서 호출 가능으로 범위가 지정되며 함수 본문에서 참조할 수 없습니다.","typeVarSingleConstraint":"TypeVar에는 두 개 이상의 제한된 형식이 있어야 합니다.","typeVarTupleConstraints":"TypeVarTuple에는 값 제약 조건이 있을 수 없습니다.","typeVarTupleContext":"TypeVarTuple은 이 컨텍스트에서 허용되지 않습니다.","typeVarTupleDefaultNotUnpacked":"TypeVarTuple 기본 형식은 압축을 푼 튜플 또는 TypeVarTuple이어야 합니다.","typeVarTupleMustBeUnpacked":"TypeVarTuple 값에는 압축 풀기 연산자가 필요합니다.","typeVarTupleUnknownParam":"\\"{name}\\"은(는) TypeVarTuple에 대한 알 수 없는 매개 변수입니다.","typeVarUnknownParam":"‘{name}’은(는) TypeVar에 대한 알 수 없는 매개 변수입니다.","typeVarUsedByOuterScope":"TypeVar ‘{name}’은(는) 외부 범위에서 이미 사용 중입니다.","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\"이(가) 제네릭 함수 시그니처에 한 번만 나타납니다.","typeVarVariance":"TypeVar는 공변이면서 반공변일 수 없습니다.","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\"에 기본값이 있으며 TypeVarTuple \\"{variadicName}\\"을(를) 따를 수 없습니다.","typeVarWithoutDefault":"‘{name}’은 기본 형식이 없으므로 형식 매개 변수 목록에서 ‘{other}’ 뒤에 나타날 수 없습니다.","typeVarsNotInGenericOrProtocol":"Generic[] 또는 Protocol[]에는 모든 형식 변수가 포함되어야 합니다.","typedDictAccess":"TypedDict의 항목에 액세스할 수 없습니다.","typedDictAssignedName":"TypedDict를 \\"{name}\\"이라는 변수에 할당해야 합니다.","typedDictBadVar":"TypedDict 클래스는 형식 주석만 포함할 수 있습니다.","typedDictBaseClass":"TypedDict 클래스의 모든 기본 클래스도 TypedDict 클래스여야 합니다.","typedDictBoolParam":"\\"{name}\\" 매개 변수에 True 또는 False 값이 있어야 합니다.","typedDictClosedExtras":"기본 클래스 \\"{name}\\"은(는) 닫힌 TypedDict입니다. 추가 항목은 \\"{type}\\" 형식이어야 합니다.","typedDictClosedNoExtras":"기본 클래스 \\"{name}\\"은(는) 닫힌 TypedDict입니다. 추가 항목은 허용되지 않습니다.","typedDictDelete":"TypedDict에서 항목을 삭제할 수 없습니다.","typedDictEmptyName":"TypedDict 내의 이름은 비워 둘 수 없습니다.","typedDictEntryName":"사전 항목 이름에 필요한 문자열 리터럴","typedDictEntryUnique":"사전 내의 이름은 고유해야 합니다.","typedDictExtraArgs":"추가 TypedDict 인수가 지원되지 않음","typedDictFieldNotRequiredRedefinition":"TypedDict 항목 \\"{name}\\"은(는) NotRequired로 재정의될 수 없습니다.","typedDictFieldReadOnlyRedefinition":"TypedDict 항목 \\"{name}\\"은(는) ReadOnly로 재정의될 수 없습니다.","typedDictFieldRequiredRedefinition":"TypedDict 항목 \\"{name}\\"은(는) 필수 항목으로 재정의될 수 없습니다.","typedDictFirstArg":"TypedDict 클래스 이름이 첫 번째 인수로 필요합니다.","typedDictInitsubclassParameter":"TypedDict는 __init_subclass__ 매개 변수 \\"{name}\\"을(를) 지원하지 않습니다.","typedDictNotAllowed":"이 컨텍스트에서는 \\"TypedDict\\"를 사용할 수 없습니다.","typedDictSecondArgDict":"두 번째 매개 변수로 사전 또는 키워드 매개 변수가 필요합니다.","typedDictSecondArgDictEntry":"단순 사전 항목이 필요합니다.","typedDictSet":"TypedDict에서 항목을 할당할 수 없습니다.","unaccessedClass":"‘{name}’ 클래스에 액세스할 수 없습니다.","unaccessedFunction":"함수 \\"{name}\\"에 액세스할 수 없습니다.","unaccessedImport":"가져오기 \\"{name}\\"에 액세스할 수 없습니다.","unaccessedSymbol":"\\"{name}\\"에 액세스할 수 없습니다.","unaccessedVariable":"변수 \\"{name}\\"에 액세스할 수 없습니다.","unannotatedFunctionSkipped":"주석이 없으므로 ‘{name}’ 함수 분석을 건너뜁니다.","unaryOperationNotAllowed":"형식 주석에는 단항 연산자를 사용할 수 없습니다.","unexpectedAsyncToken":"\\"async\\"를 따르려면 \\"def\\", \\"with\\" 또는 \\"for\\"가 필요합니다.","unexpectedExprToken":"식 끝에 예기치 않은 토큰이 있습니다.","unexpectedIndent":"예기치 않은 들여쓰기","unexpectedUnindent":"들여쓰기가 필요 없음","unhashableDictKey":"사전 키는 해시 가능해야 합니다.","unhashableSetEntry":"집합 항목은 해시가 가능해야 합니다.","uninitializedAbstractVariables":"추상 기본 클래스에 정의된 변수가 최종 클래스 \\"{classType}\\"에서 초기화되지 않았습니다.","uninitializedInstanceVariable":"인스턴스 변수 \\"{name}\\"이(가) 클래스 본문 또는 __init__ 메서드에서 초기화되지 않았습니다.","unionForwardReferenceNotAllowed":"공용 구조체 구문은 문자열 피연산자에서 사용할 수 없습니다. 전체 식 주위에 따옴표 사용","unionSyntaxIllegal":"공용 구조체에 대한 대체 구문에는 Python 3.10 이상이 필요합니다.","unionTypeArgCount":"공용 구조체에는 둘 이상의 형식 인수가 필요합니다.","unionUnpackedTuple":"Union은 압축을 푼 튜플을 포함할 수 없습니다.","unionUnpackedTypeVarTuple":"Union은 압축을 푼 TypeVarTuple을 포함할 수 없습니다.","unnecessaryCast":"불필요한 ‘캐스트’ 호출입니다. 형식이 이미 ‘{type}’입니다.","unnecessaryIsInstanceAlways":"불필요한 isinstance 호출입니다. \\"{testType}\\"은(는) 항상 \\"{classType}\\"의 인스턴스입니다.","unnecessaryIsSubclassAlways":"불필요한 issubclass 호출입니다. ’{testType}‘은(는) 항상 ’{classType}‘의 하위 클래스입니다.","unnecessaryPyrightIgnore":"불필요한 ‘# pyright: 무시’ 주석입니다.","unnecessaryPyrightIgnoreRule":"불필요한 \\"#ight: ignore\\" 규칙: \\"{name}\\"","unnecessaryTypeIgnore":"불필요한 ‘# 형식: 무시’ 주석입니다.","unpackArgCount":"‘Final’ 뒤에는 단일 형식 인수가 필요합니다.","unpackExpectedTypeVarTuple":"Unpack에 대한 형식 인수로 TypeVarTuple 또는 튜플이 필요합니다.","unpackExpectedTypedDict":"압축 풀기를 위해서는 TypedDict 형식 인수가 필요합니다.","unpackIllegalInComprehension":"압축 풀기 작업은 이해에서 사용할 수 없습니다.","unpackInAnnotation":"형식 주석에는 압축 풀기 연산자를 사용할 수 없습니다.","unpackInDict":"사전에서 압축 풀기 작업이 허용되지 않음","unpackInSet":"집합 내에서는 압축 풀기 연산자를 사용할 수 없습니다.","unpackNotAllowed":"이 컨텍스트에서는 압축 풀기가 허용되지 않습니다.","unpackOperatorNotAllowed":"이 컨텍스트에서는 압축 풀기 작업이 허용되지 않습니다.","unpackTuplesIllegal":"Python 3.8 이전의 튜플에서는 압축 풀기 작업이 허용되지 않습니다.","unpackedArgInTypeArgument":"압축되지 않은 인수는 형식 인수 목록에 사용할 수 없습니다.","unpackedArgWithVariadicParam":"압축을 푼 인수는 TypeVarTuple 매개 변수에 사용할 수 없습니다.","unpackedDictArgumentNotMapping":"** 뒤의 인수 식은 \\"str\\" 키 형식의 매핑이어야 합니다.","unpackedDictSubscriptIllegal":"아래 첨자에서 사전 압축 풀기 연산자는 사용할 수 없습니다.","unpackedSubscriptIllegal":"아래 첨자의 압축 풀기 연산자에는 Python 3.11 이상이 필요합니다.","unpackedTypeVarTupleExpected":"압축 해제된 TypeVarTuple이 필요합니다. 압축 풀기[{name1}] 또는 *{name2} 사용","unpackedTypedDictArgument":"압축되지 않은 TypedDict 인수를 매개 변수와 일치시킬 수 없습니다.","unreachableCode":"코드에 접근할 수 없습니다.","unreachableExcept":"예외가 이미 처리되었으므로 Except 절에 연결할 수 없습니다.","unsupportedDunderAllOperation":"\\"__all__\\"에 대한 작업이 지원되지 않으므로 내보낸 기호 목록이 잘못되었을 수 있습니다.","unusedCallResult":"호출 식의 결과가 ‘{type}’ 형식이므로 사용되지 않습니다. 의도적인 경우 변수 ‘_’에 할당하세요.","unusedCoroutine":"비동기 함수 호출의 결과가 사용되지 않습니다. \\"await\\"를 사용하거나 변수에 결과 할당","unusedExpression":"식 값은 사용되지 않습니다.","varAnnotationIllegal":"변수에 대한 형식 주석에는 Python 3.6 이상이 필요합니다. 이전 버전과의 호환성을 위해 형식 주석 사용","variableFinalOverride":"변수 \\"{name}\\"이(가) Final로 표시되고 \\"{className}\\" 클래스에서 이름이 같은 비-Final 변수를 재정의합니다.","variadicTypeArgsTooMany":"형식 인수 목록에는 압축을 풀고 있는 TypeVarTuple 또는 튜플이 하나만 있을 수 있습니다.","variadicTypeParamTooManyAlias":"형식 별칭에는 TypeVarTuple 형식 매개 변수가 최대 하나만 있을 수 있지만 여러 ({names})가 수신되었습니다.","variadicTypeParamTooManyClass":"제네릭 클래스에는 TypeVarTuple 형식 매개 변수가 하나만 있을 수 있지만 여러 ({names})을(를) 받았습니다.","walrusIllegal":"연산자 \\":=\\"에는 Python 3.8 이상이 필요합니다.","walrusNotAllowed":"주변 괄호 없이는 이 컨텍스트에서 \\":=\\" 연산자를 사용할 수 없습니다.","wildcardInFunction":"클래스 또는 함수 내에서 와일드카드 가져오기가 허용되지 않음","wildcardLibraryImport":"라이브러리에서 와일드카드를 가져오는 것은 허용되지 않습니다.","wildcardPatternTypePartiallyUnknown":"와일드카드 패턴으로 캡처된 형식을 부분적으로 알 수 없습니다.","wildcardPatternTypeUnknown":"와일드카드 패턴으로 캡처된 형식을 부분적으로 알 수 없습니다.","yieldFromIllegal":"\\"yield from\\"을 사용하려면 Python 3.3 이상이 필요합니다.","yieldFromOutsideAsync":"비동기 함수에서는 \\"yield from\\"을 사용할 수 없습니다.","yieldOutsideFunction":"함수 또는 람다 외부에서는 ‘yield’를 사용할 수 없습니다.","yieldWithinListCompr":"목록 이해 내에서는 \\"yield\\"를 사용할 수 없습니다.","zeroCaseStatementsFound":"Match 문에는 Case 문이 하나 이상 포함되어야 합니다.","zeroLengthTupleNotAllowed":"길이가 0인 튜플은 이 컨텍스트에서 허용되지 않습니다."},"DiagnosticAddendum":{"annotatedNotAllowed":"\\"주석이 추가된\\" 특수 양식은 인스턴스 및 클래스 검사와 함께 사용할 수 없습니다.","argParam":"인수가 \\"{paramName}\\" 매개 변수에 해당합니다.","argParamFunction":"인수가 \\"{functionName}\\" 함수의 \\"{paramName}\\" 매개 변수에 해당합니다.","argsParamMissing":"‘*{paramName}’ 매개 변수에 해당하는 매개 변수가 없습니다.","argsPositionOnly":"위치 전용 매개 변수가 일치하지 않습니다. {expected}이)(가) 필요하지만 {received}을(를) 받았습니다.","argumentType":"인수 형식이 \\"{type}\\"입니다.","argumentTypes":"인수 형식: ({types})","assignToNone":"\\"None\\" 형식에는 형식을 할당할 수 없습니다.","asyncHelp":"‘async with’를 사용하시겠습니까?","baseClassIncompatible":"기본 클래스 \\"{baseClass}\\"은(는) \\"{type}\\" 유형과 호환되지 않습니다.","baseClassIncompatibleSubclass":"기본 클래스 \\"{baseClass}\\"은(는) \\"{type}\\" 유형과 호환되지 않는 \\"{subclass}\\"에서 파생됩니다.","baseClassOverriddenType":"기본 클래스 \\"{baseClass}\\"이(가) 재정의된 \\"{type}\\" 형식을 제공합니다.","baseClassOverridesType":"‘{baseClass}’ 기본 클래스가 ‘{type}’ 형식을 재정의합니다.","bytesTypePromotions":"disableBytesTypePromotions를 false로 설정하여 \\"bytearray\\" 및 \\"memoryview\\"에 대한 형식 승격 동작을 사용하도록 설정합니다.","conditionalRequiresBool":"\\"{operandType}\\" 형식에 대한 메서드 __bool__에서 \\"bool\\" 대신 \\"{boolReturnType}\\" 형식을 반환합니다.","dataClassFieldLocation":"필드 선언","dataClassFrozen":"\\"{name}\\"이(가) 고정되어 있습니다.","dataProtocolUnsupported":"\\"{name}\\"은(는) 데이터 프로토콜입니다.","descriptorAccessBindingFailed":"설명자 클래스 \\"{className}\\"에 대한 메서드 \\"{name}\\"을(를) 바인딩하지 못했습니다.","descriptorAccessCallFailed":"설명자 클래스 \\"{className}\\"에 대한 메서드 \\"{name}\\"을(를) 호출하지 못했습니다.","finalMethod":"최종 메서드","functionParamDefaultMissing":"‘{name}’ 매개 변수에 기본 인수가 없습니다.","functionParamName":"매개 변수 이름 불일치: \\"{destName}\\" 및 \\"{srcName}\\"","functionParamPositionOnly":"위치 전용 매개 변수가 일치하지 않습니다. 매개 변수 \\"{name}\\"은(는) 위치 전용이 아닙니다.","functionReturnTypeMismatch":"‘{sourceType}’ 함수 반환 형식은 ‘{destType}’ 형식과 호환되지 않습니다.","functionTooFewParams":"함수가 너무 적은 위치 매개 변수를 허용합니다. {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","functionTooManyParams":"함수가 너무 많은 위치 매개 변수를 허용합니다. {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","genericClassNotAllowed":"인스턴스 또는 클래스 검사에 형식 인수가 허용되지 않는 제네릭 형식","incompatibleDeleter":"속성 삭제자 메서드가 호환되지 않습니다.","incompatibleGetter":"속성 getter 메서드가 호환되지 않습니다.","incompatibleSetter":"속성 setter 메서드가 호환되지 않습니다.","initMethodLocation":"__init__ 메서드가 \\"{type}\\" 클래스에 정의되어 있습니다.","initMethodSignature":"__init__의 서명은 \\"{type}\\"입니다.","initSubclassLocation":"__init_subclass__ 메서드는 \\"{name}\\" 클래스에 정의되어 있음","invariantSuggestionDict":"값 형식에서 공변(covariant)인 \\"dict\\"에서 \\"Mapping\\"(매핑)으로 전환하는 것이 좋습니다.","invariantSuggestionList":"공변(covariant)인 \\"list\\"에서 \\"Sequence\\"로 전환하는 것이 좋습니다.","invariantSuggestionSet":"공변(covariant)인 \\"set\\"에서 \\"Container\\"로 전환하는 것이 좋습니다.","keyNotRequired":"‘{name}’은(는) ‘{type}’에서 필수 키가 아니므로 액세스로 인해 런타임 예외가 발생할 수 있습니다.","keyReadOnly":"\\"{name}\\"은(는) \\"{type}\\"의 읽기 전용 키입니다.","keyRequiredDeleted":"\\"{name}\\"은(는) 필수 키이므로 삭제할 수 없습니다.","keyUndefined":"\\"{name}\\"이 \\"{type}\\"에 정의된 키가 아닙니다.","kwargsParamMissing":"‘**{paramName}’ 매개 변수에 해당하는 매개 변수가 없습니다.","listAssignmentMismatch":"\\"{type}\\" 형식이 대상 목록과 호환되지 않습니다.","literalAssignmentMismatch":"\\"{sourceType}\\"을(를) \\"{destType}\\" 형식에 할당할 수 없습니다.","matchIsNotExhaustiveHint":"전체 처리가 의도되지 않은 경우 \\"case _: pass\\"를 추가합니다.","matchIsNotExhaustiveType":"처리되지 않은 형식: \\"{type}\\"","memberAssignment":"‘{type}’ 형식의 식을 ‘{classType}’ 클래스의 ‘{name}’ 멤버에 할당할 수 없습니다.","memberIsAbstract":"\\"{type}.{name}\\"이(가) 구현되지 않았습니다.","memberIsAbstractMore":"{count}개 더...","memberIsClassVarInProtocol":"\\"{name}\\"은(는) 프로토콜에서 ClassVar로 정의됩니다.","memberIsFinalInProtocol":"\\"{name}\\"이(가) 프로토콜에서 Final로 표시됨","memberIsInitVar":"멤버 \\"{name}\\"은(는) 초기화 전용 필드입니다.","memberIsInvariant":"\\"{name}\\"은(는) 변경 가능하므로 고정되지 않습니다.","memberIsNotClassVarInClass":"\\"{name}\\"은(는) 프로토콜과 호환되려면 ClassVar로 정의해야 합니다.","memberIsNotClassVarInProtocol":"\\"{name}\\"이(가) 프로토콜에서 ClassVar로 정의되지 않았습니다.","memberIsNotFinalInProtocol":"‘{name}’이(가) 프로토콜에서 최종으로 표시되지 않았습니다.","memberIsWritableInProtocol":"\\"{name}\\"은(는) 프로토콜에서 쓸 수 있습니다.","memberSetClassVar":"‘{name}’ 멤버는 ClassVar이므로 클래스 인스턴스를 통해 할당할 수 없습니다.","memberTypeMismatch":"\\"{name}\\"은(는) 호환되지 않는 형식입니다.","memberUnknown":"멤버 \\"{name}\\"을(를) 알 수 없습니다.","metaclassConflict":"메타클래스 \\"{metaclass1}\\"이(가) \\"{metaclass2}\\"과(와) 충돌합니다.","missingDeleter":"속성 삭제자 메서드가 없습니다.","missingGetter":"속성 getter 메서드가 없습니다.","missingSetter":"속성 setter 메서드가 없습니다.","namedParamMissingInDest":"키워드 매개 변수 ‘{name}’이(가) 대상에 없습니다.","namedParamMissingInSource":"키워드 매개 변수 ‘{name}’이(가) 소스에 없습니다.","namedParamTypeMismatch":"\\"{sourceType}\\" 형식의 키워드 매개 변수 \\"{name}\\"을(를) \\"{destType}\\" 형식에 할당할 수 없습니다.","namedTupleNotAllowed":"인스턴스 또는 클래스 검사에는 NamedTuple을 사용할 수 없습니다.","newMethodLocation":"__new__ 메서드가 \\"{type}\\" 클래스에 정의되어 있습니다.","newMethodSignature":"__new__ 의 서명은 \\"{type}\\"입니다.","newTypeClassNotAllowed":"NewType으로 만든 클래스는 인스턴스 및 클래스 검사에 사용할 수 없습니다.","noOverloadAssignable":"\\"{type}\\" 형식과 일치하는 오버로드된 함수가 없습니다.","noneNotAllowed":"인스턴스 또는 클래스 검사에는 None을 사용할 수 없음","orPatternMissingName":"누락된 이름: {name}","overloadIndex":"오버로드 {index}이(가) 가장 가까운 일치 항목입니다.","overloadNotAssignable":"\\"{name}\\"의 오버로드를 하나 이상 할당할 수 없습니다.","overloadSignature":"오버로드 서명은 여기에 정의되어 있습니다.","overriddenMethod":"재정의된 메서드","overriddenSymbol":"재정의된 기호","overrideInvariantMismatch":"\\"{overrideType}\\" 재정의 형식이 \\"{baseType}\\" 기본 형식과 같지 않습니다.","overrideIsInvariant":"변수를 변경할 수 있으므로 해당 형식은 고정됩니다.","overrideNoOverloadMatches":"재정의의 오버로드 서명이 기본 메서드와 호환되지 않습니다.","overrideNotClassMethod":"기본 메서드가 classmethod로 선언되었지만 재정의는 그렇지 않은 경우","overrideNotInstanceMethod":"기본 메서드가 instance 메서드로 선언되었지만 재정의가","overrideNotStaticMethod":"기본 메서드가 staticmethod로 선언되었지만 재정의는 그렇지 않습니다.","overrideOverloadNoMatch":"재정의는 기본 메서드의 모든 오버로드를 처리하지 않습니다.","overrideOverloadOrder":"재정의 메서드에 대한 오버로드는 기본 메서드와 동일한 순서여야 합니다.","overrideParamKeywordNoDefault":"‘{name}’ 키워드 매개 변수가 불일치합니다. 기본 매개 변수에 기본 인수 값이 있습니다. 재정의 매개 변수에는 없습니다.","overrideParamKeywordType":"‘{name}’ 키워드 매개 변수 형식이 일치하지 않습니다. 기본 매개 변수는 형식이 ‘{baseType}’, 재정의 매개 변수는 형식이 ‘{overrideType}’입니다.","overrideParamName":"{index} 매개 변수 이름이 일치하지 않습니다. 기본 매개 변수는 이름이 ‘{baseName}’입니다. 재정의 매개 변수는 이름이 ‘{overrideName}’입니다.","overrideParamNameExtra":"기본에 매개 변수 \\"{name}\\"이(가) 없습니다.","overrideParamNameMissing":"재정의에 ‘{name}’ 매개 변수가 없습니다.","overrideParamNamePositionOnly":"매개 변수 {index} 불일치: 기본 매개 변수 \\"{baseName}\\"은(는) 키워드 매개 변수이며 재정의 매개 변수는 위치 전용임","overrideParamNoDefault":"{index} 매개 변수가 불일치합니다. 기본 매개 변수에 기본 인수 값이 있습니다. 재정의 매개 변수에는 없습니다.","overrideParamType":"‘{index}’ 매개 변수 형식이 일치하지 않습니다. 기본 매개 변수는 형식이 ‘{baseType}’, 재정의 매개 변수는 형식이 ‘{overrideType}’입니다.","overridePositionalParamCount":"위치 매개 변수 개수가 일치하지 않습니다. 기본 메서드에 {baseCount}개가 있지만 재정의에는 {overrideCount}개가 있습니다.","overrideReturnType":"반환 형식 불일치: 기본 메서드는 \\"{baseType}\\" 형식을 반환하고 재정의는 \\"{overrideType}\\" 형식을 반환합니다.","overrideType":"기본 클래스는 형식을 \\"{type}\\"으로 정의합니다.","paramAssignment":"매개 변수 {index}: \\"{sourceType}\\" 형식을 \\"{destType}\\" 형식에 할당할 수 없습니다.","paramSpecMissingInOverride":"재정의 메서드에 ParamSpec 매개 변수가 없습니다.","paramType":"매개 변수 형식은 \\"{paramType}\\"입니다.","privateImportFromPyTypedSource":"대신 \\"{module}\\"에서 가져오기","propertyAccessFromProtocolClass":"프로토콜 클래스 내에 정의된 속성은 클래스 변수로 액세스할 수 없습니다.","propertyMethodIncompatible":"속성 메서드 \\"{name}\\"이(가) 호환되지 않습니다.","propertyMethodMissing":"재정의에 ‘{name}’ 속성 메서드가 없습니다.","propertyMissingDeleter":"\\"{name}\\" 속성에 정의된 삭제자가 없습니다.","propertyMissingSetter":"\\"{name}\\" 속성에 정의된 setter가 없습니다.","protocolIncompatible":"‘{sourceType}’은(는) ‘{destType}’ 프로토콜과 호환되지 않습니다.","protocolMemberMissing":"\\"{name}\\"이(가) 없습니다.","protocolRequiresRuntimeCheckable":"인스턴스 및 클래스 검사와 함께 사용하려면 프로토콜 클래스를 @runtime_checkable 합니다.","protocolSourceIsNotConcrete":"‘{sourceType}’은(는) 구체적인 클래스 형식이 아니므로 ‘{destType}’ 형식에 할당할 수 없습니다.","protocolUnsafeOverlap":"\\"{name}\\"의 특성은 프로토콜과 이름이 같습니다.","pyrightCommentIgnoreTip":"\\"# pyright: ignore[<diagnostic rules>]을(를) 사용하여 한 줄에 대한 진단을 억제합니다.","readOnlyAttribute":"특성 \\"{name}\\"은(는) 읽기 전용입니다.","seeClassDeclaration":"클래스 선언 참조","seeDeclaration":"선언 참조","seeFunctionDeclaration":"함수 선언 참조","seeMethodDeclaration":"메서드 선언 참조","seeParameterDeclaration":"매개 변수 선언 보기","seeTypeAliasDeclaration":"형식 별칭 선언 참조","seeVariableDeclaration":"변수 선언 보기","tupleAssignmentMismatch":"‘{type}’ 형식이 대상 튜플과 호환되지 않습니다.","tupleEntryTypeMismatch":"튜플 항목 {entry}이(가) 잘못된 형식입니다.","tupleSizeIndeterminateSrc":"튜플 크기 불일치: {expected}이(가) 필요하지만 미정을 받았습니다.","tupleSizeIndeterminateSrcDest":"튜플 크기 불일치: {expected} 이상이 필요하지만 미정을 받았습니다.","tupleSizeMismatch":"튜플 크기 불일치: {expected}이(가) 필요하지만 {received}을(를) 받았습니다.","tupleSizeMismatchIndeterminateDest":"튜플 크기 불일치: {expected} 이상이 필요하지만 {received}을(를) 받았습니다.","typeAliasInstanceCheck":"\\"type\\" 문을 사용해 만든 형식 별칭은 인스턴스 및 클래스 검사에 사용할 수 없습니다.","typeAssignmentMismatch":"\\"{sourceType}\\" 형식은 \\"{destType}\\" 형식에 할당할 수 없습니다.","typeBound":"형식 변수 \\"{name}\\"에 대해 형식 \\"{sourceType}\\"이(가) 바인딩된 형식 \\"{destType}\\"과(와) 호환되지 않습니다.","typeConstrainedTypeVar":"\\"{type}\\" 형식이 제한된 형식 변수 \\"{name}\\"과(와) 호환되지 않습니다.","typeIncompatible":"\\"{sourceType}\\"이(가) \\"{destType}\\"과(와) 호환되지 않습니다.","typeNotClass":"\\"{type}\\"이 클래스가 아닙니다.","typeNotStringLiteral":"‘{type}’은(는) 문자열 리터럴이 아닙니다.","typeOfSymbol":"‘{name}’의 유형이 ‘{type}’입니다.","typeParamSpec":"\\"{type}\\" 형식이 ParamSpec \\"{name}\\"과(와) 호환되지 않습니다.","typeUnsupported":"\\"{type}\\" 형식은 지원되지 않습니다.","typeVarDefaultOutOfScope":"형식 변수 \\"{name}\\"이(가) 범위에 없습니다.","typeVarIsContravariant":"\\"{name}\\" 형식 매개 변수는 반공변형식 매개 변수)이지만 \\"{sourceType}\\"은(는) \\"{destType}\\"의 상위 형식이 아닙니다.","typeVarIsCovariant":"\\"{name}\\" 형식 매개 변수는 공변(covariant)이지만 \\"{sourceType}\\"은(는) \\"{destType}\\"의 하위 형식이 아닙니다.","typeVarIsInvariant":"\\"{name}\\" 형식 매개 변수는 고정이지만 \\"{sourceType}\\"은(는) \\"{destType}\\"와 같지 않습니다.","typeVarNotAllowed":"인스턴스 또는 클래스 검사에 TypeVar가 허용되지 않음","typeVarTupleRequiresKnownLength":"TypeVarTuple을 알 수 없는 길이의 튜플에 바인딩할 수 없습니다.","typeVarUnnecessarySuggestion":"대신 {type}을(를) 사용하세요.","typeVarUnsolvableRemedy":"인수가 제공되지 않을 때 반환 형식을 지정하는 오버로드를 제공합니다.","typeVarsMissing":"누락된 형식 변수: {names}","typedDictBaseClass":"\\"{type}\\" 클래스는 TypedDict가 아닙니다.","typedDictClassNotAllowed":"인스턴스 또는 클래스 검사에 TypedDict 클래스를 사용할 수 없습니다.","typedDictClosedExtraNotAllowed":"항목 \\"{name}\\"을(를) 추가할 수 없음","typedDictClosedExtraTypeMismatch":"형식이 \\"{type}\\"인 항목 \\"{name}\\"을(를) 추가할 수 없음","typedDictClosedFieldNotRequired":"\\"{name}\\" 항목은 NotRequired여야 하므로 추가할 수 없습니다.","typedDictExtraFieldNotAllowed":"\\"{name}\\"이(가) \\"{type}\\"에 없음","typedDictExtraFieldTypeMismatch":"\\"{name}\\" 형식은 \\"{type}\\"의 \\"__extra_items__\\" 형식과 호환되지 않습니다.","typedDictFieldMissing":"\\"{name}\\"이(가) \\"{type}\\"에 없습니다.","typedDictFieldNotReadOnly":"\\"{name}\\"은(는) \\"{type}\\"에서 읽기 전용이 아닙니다.","typedDictFieldNotRequired":"\\"{name}\\"은(는) \\"{type}\\"에 필요하지 않습니다.","typedDictFieldRequired":"\\"{type}\\"에 \\"{name}\\"이(가) 필요합니다.","typedDictFieldTypeMismatch":"\\"{type}\\" 형식은 \\"{name}\\" 항목에 할당할 수 없습니다.","typedDictFieldUndefined":"\\"{name}\\"은(는) \\"{type}\\" 형식의 정의되지 않은 항목입니다.","typedDictFinalMismatch":"@final 불일치로 인해 \\"{sourceType}\\"이(가) \\"{destType}\\"과(와) 호환되지 않습니다.","typedDictKeyAccess":"TypedDict에서 항목을 참조하려면 [\\"{name}\\"]을(를) 사용하세요.","typedDictNotAllowed":"TypedDict는 인스턴스 또는 클래스 검사에 사용할 수 없습니다.","unhashableType":"‘{type}’ 형식을 해시할 수 없습니다.","uninitializedAbstractVariable":"인스턴스 변수 \\"{name}\\"이(가) 추상 기본 클래스 \\"{classType}\\"에 정의되어 있지만 초기화되지 않았습니다.","unreachableExcept":"\\"{exceptionType}\\"은(는) \\"{parentType}\\"의 서브클래스입니다.","useDictInstead":"사전 형식을 나타내려면 Dict[T1, T2]를 사용하세요.","useListInstead":"List[T]를 사용하여 목록 형식을 나타내거나 Union[T1, T2]를 사용하여 공용 구조체 형식을 나타내세요.","useTupleInstead":"튜플[T1, ..., Tn]을 사용하여 튜플 형식을 나타내거나 Union[T1, T2]을 사용하여 공용 구조체 형식을 나타냅니다.","useTypeInstead":"대신 Type[T] 사용","varianceMismatchForClass":"‘{typeVarName}’ 형식 인수의 차이는 ‘{className}’ 기본 클래스와 호환되지 않습니다.","varianceMismatchForTypeAlias":"‘{typeVarName}’ 형식 인수의 차이는 ‘{typeAliasParam}’와(과) 호환되지 않습니다."}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.pl.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.pl.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Utwórz typ zastępczy","createTypeStubFor":"Utwórz typ zastępczy dla „{moduleName}”","executingCommand":"Wykonywanie polecenia","filesToAnalyzeCount":"Pliki do przeanalizowania: {count}","filesToAnalyzeOne":"1 plik do analizy","findingReferences":"Znajdowanie odwołań","organizeImports":"Organizuj dyrektywy Import","renameShadowedFile":"Zmień nazwę „{oldFile}” na „{newFile}”"},"Completion":{"autoImportDetail":"Automatyczne importowanie","indexValueDetail":"Wartość indeksu"},"Diagnostic":{"abstractMethodInvocation":"Nie można wywołać metody „{method}”, ponieważ jest abstrakcyjna i niezaimplementowana","annotatedParamCountMismatch":"Niezgodność liczby adnotacji parametru; oczekiwano {expected}, a uzyskano {received}","annotatedTypeArgMissing":"Oczekiwano jednego argumentu typu i co najmniej jednej adnotacji dla wartości „Annotated”","annotationFormatString":"Adnotacje typu nie mogą używać literałów ciągów formatu (f-strings)","annotationNotSupported":"Adnotacja typu nie jest obsługiwana dla tej instrukcji","annotationSpansStrings":"Adnotacje typu nie mogą obejmować wielu literałów ciągów","annotationStringEscape":"Adnotacje typu nie mogą zawierać znaków ucieczki","argAssignment":"Argumentu typu „{argType}” nie można przypisać do parametru typu „{paramType}”","argAssignmentFunction":"Argumentu typu „{argType}” nie można przypisać do parametru typu „{paramType}” w funkcji „{functionName}”","argAssignmentParam":"Argumentu typu „{argType}” nie można przypisać do parametru „{paramName}” typu „{paramType}”","argAssignmentParamFunction":"Argumentu typu „{argType}” nie można przypisać do parametru „{paramName}” typu „{paramType}” w funkcji „{functionName}”","argMissingForParam":"Brak argumentu dla parametru {name}","argMissingForParams":"Brak argumentów dla parametrów {names}","argMorePositionalExpectedCount":"Oczekiwano większej liczby argumentów pozycyjnych: {expected}","argMorePositionalExpectedOne":"Oczekiwano jeszcze 1 argumentu pozycyjnego","argPositional":"Oczekiwano argumentu pozycyjnego","argPositionalExpectedCount":"Oczekiwano liczby argumentów pozycyjnych: {expected}","argPositionalExpectedOne":"Oczekiwano 1 argumentu pozycyjnego","argTypePartiallyUnknown":"Typ argumentu jest częściowo nieznany","argTypeUnknown":"Typ argumentu jest nieznany","assertAlwaysTrue":"Wyrażenie Assert zawsze ma wartość Prawda","assertTypeArgs":"Typ „assert_type” oczekuje dwóch argumentów pozycyjnych","assertTypeTypeMismatch":"Niezgodność „assert_type”; oczekiwano „{expected}”, ale otrzymano „{received}”","assignmentExprComprehension":"Element docelowy wyrażenia przypisania „{name}” nie może używać tej samej nazwy co zrozumienie dla elementu docelowego","assignmentExprContext":"Wyrażenie przypisania musi należeć do modułu, funkcji lub wyrażenia lambda","assignmentExprInSubscript":"Wyrażenia przypisania w indeksie dolnym są obsługiwane tylko w języku Python w wersji 3.10 i nowszej","assignmentInProtocol":"Zmienne wystąpienia lub klasy w klasie protokołu muszą być jawnie zadeklarowane w treści klasy","assignmentTargetExpr":"Wyrażenie nie może być elementem docelowym przypisania","asyncNotInAsyncFunction":"Użycie wartość „async” jest niedozwolone poza funkcją asynchroniczną","awaitIllegal":"Użycie „oczekiwania” wymaga języka Python w wersji 3.5 lub nowszej","awaitNotAllowed":"Adnotacje typu nie mogą używać elementu „await”","awaitNotInAsync":"Wartość „await” jest dozwolona tylko w ramach funkcji asynchronicznej","backticksIllegal":"Wyrażenia otoczone znakami wstecznymi nie są obsługiwane w języku Python w wersji 3.x; zamiast tego użyj wyrażenia repr","baseClassCircular":"Klasa nie może pochodzić od samej siebie","baseClassFinal":"Klasa bazowa „{type}” jest oznaczona jako końcowa i nie można jej podzielić na podklasy","baseClassIncompatible":"Klasy bazowe typu {type} są wzajemnie niezgodne","baseClassInvalid":"Argument klasy musi być klasą bazową","baseClassMethodTypeIncompatible":"Klasy bazowe dla klasy „{classType}” definiują metodę „{name}” w niezgodny sposób","baseClassUnknown":"Typ klasy bazowej jest nieznany, zasłaniając typ klasy pochodnej","baseClassVariableTypeIncompatible":"Klasy bazowe dla klasy „{classType}” definiują zmienną „{name}” w niezgodny sposób","binaryOperationNotAllowed":"Operator binarny nie jest dozwolony w adnotacji typu","bindTypeMismatch":"Nie można powiązać metody „{methodName}”, ponieważ nie można przypisać typu „{type}” do parametru „{paramName}”","breakOutsideLoop":"Wartość „break” może być używana tylko w pętli","callableExtraArgs":"Oczekiwano tylko dwóch argumentów typu „Callable”","callableFirstArg":"Oczekiwano listy typów parametrów lub znaków „...”","callableNotInstantiable":"Nie można utworzyć wystąpienia typu „{type}”","callableSecondArg":"Oczekiwano zwracanego typu jako drugiego argumentu typu dla elementu „Callable”","casePatternIsIrrefutable":"Niepodważalny wzorzec jest dozwolony tylko dla ostatniej instrukcji dotyczącej wielkości liter","classAlreadySpecialized":"Typ „{type}” jest już wyspecjalizowany","classDecoratorTypeUnknown":"Dekorator klasy bez typu przesłania typ klasy; ignorowanie dekoratora","classDefinitionCycle":"Definicja klasy dla „{name}” zależy od niej samej","classGetItemClsParam":"Przesłonięcie __class_getitem__ powinno przyjmować parametr „cls”.","classMethodClsParam":"Metody klasy powinny przyjmować parametr „cls”","classNotRuntimeSubscriptable":"Indeks dolny dla klasy „{name}” wygeneruje wyjątek czasu uruchamiania; umieść adnotację typu w cudzysłowie","classPatternBuiltInArgPositional":"Wzorzec klasy akceptuje tylko podwzorzec pozycyjny","classPatternPositionalArgCount":"Zbyt wiele wzorców pozycyjnych dla klasy „{type}”; oczekiwano {expected}, ale otrzymano {received}","classPatternTypeAlias":"„{type}” nie może być używany we wzorcu klasy, ponieważ jest to alias typu specjalnego","classPropertyDeprecated":"Właściwości klasy są przestarzałe w języku Python 3.11 i nie będą obsługiwane w języku Python 3.13","classTypeParametersIllegal":"Składnia parametru typu klasy wymaga języka Python w wersji 3.12 lub nowszej","classVarFirstArgMissing":"Oczekiwano argumentu typu po wartości „ClassVar”","classVarNotAllowed":"Element „ClassVar” jest niedozwolony w tym kontekście","classVarOverridesInstanceVar":"Zmienna klasy „{name}” przesłania zmienną wystąpienia o tej samej nazwie w klasie „{className}”","classVarTooManyArgs":"Oczekiwano tylko jednego argumentu typu po wartości „ClassVar”","classVarWithTypeVar":"Typ „ClassVar” nie może zawierać zmiennych typu","clsSelfParamTypeMismatch":"Typ parametru „{name}” musi być nadtypem jego klasy „{classType}”","codeTooComplexToAnalyze":"Kod jest zbyt złożony, aby go analizować; zmniejsz złożoność przez refaktoryzację w podprocedury lub poprzez zmniejszenie ścieżek kodu warunkowego","collectionAliasInstantiation":"Nie można utworzyć wystąpienia typu „{type}”. Zamiast niego użyj „{alias}”","comparisonAlwaysFalse":"Warunek zawsze będzie miał wartość Fałsz, ponieważ typy „{leftType}” i „{rightType}” nie nakładają się","comparisonAlwaysTrue":"Warunek zawsze będzie miał wartość Prawda, ponieważ typy „{leftType}” i „{rightType}” nie nakładają się","comprehensionInDict":"Zrozumienia nie można używać z innymi wpisami słownika","comprehensionInSet":"Nie można używać rozumienia z innymi wpisami zestawu","concatenateContext":"„Łączenie” jest niedozwolone w tym kontekście","concatenateParamSpecMissing":"Ostatni argument typu dla elementu „Concatenate” musi mieć wartość ParamSpec lub „...”","concatenateTypeArgsMissing":"Element „Concatenate” wymaga co najmniej dwóch argumentów typu","conditionalOperandInvalid":"Nieprawidłowy warunkowy argument operacji typu „{type}”","constantRedefinition":"Nazwa „{name}” jest stałą (ponieważ jest pisana wielkimi literami) i nie można jej ponownie zdefiniować","constructorNoArgs":"Oczekiwano braku argumentów do konstruktora „{type}”.","constructorParametersMismatch":"Niezgodność między sygnaturą „__new__” i „__init__” w klasie „{classType}”","containmentAlwaysFalse":"Warunek zawsze będzie miał wartość „Fałsz”, ponieważ typy „{leftType}” i „{rightType}” nie nakładają się na siebie","containmentAlwaysTrue":"Warunek zawsze będzie miał wartość „True”, ponieważ typy „{leftType}” i „{rightType}” nie nakładają się na siebie","continueInFinally":"Wartość „continue” nie może być używana w klauzuli finally","continueOutsideLoop":"Wartość „continue” może być używana tylko w pętli","coroutineInConditionalExpression":"Wyrażenie warunkowe odwołuje się do koprocedury, która zawsze wyznacza wartość True","dataClassBaseClassFrozen":"Klasa niezablokowana nie może dziedziczyć po klasie zablokowanej","dataClassBaseClassNotFrozen":"Zamrożona klasa nie może dziedziczyć po klasie niezamrożonej","dataClassConverterFunction":"Argument typu „{argType}” nie jest prawidłowym konwerterem pola „{fieldName}” typu „{fieldType}”","dataClassConverterOverloads":"Żadne przeciążenia „{funcName}” nie są prawidłowymi konwerterami dla pola „{fieldName}” typu „{fieldType}”","dataClassFieldWithDefault":"Pola bez wartości domyślnych nie mogą występować po polach z wartościami domyślnymi","dataClassFieldWithPrivateName":"Pole klasy danych nie może używać nazwy prywatnej","dataClassFieldWithoutAnnotation":"Pole klasy danych bez adnotacji typu spowoduje wyjątek środowiska uruchomieniowego","dataClassPostInitParamCount":"Klasa danych __post_init__ ma niepoprawną liczbę parametrów; oczekiwana liczba pól InitVar to: {expected}","dataClassPostInitType":"Klasa danych __post_init__ ma niezgodność typu parametru metody dla pola „{fieldName}”","dataClassSlotsOverwrite":"Element __slots__ jest już zdefiniowany w klasie","dataClassTransformExpectedBoolLiteral":"Oczekiwano wyrażenia, które statycznie daje w wyniku wartość True lub False","dataClassTransformFieldSpecifier":"Oczekiwano krotki klas lub funkcji, a uzyskano typ „{type}”","dataClassTransformPositionalParam":"Wszystkie argumenty elementu „dataclass_transform” muszą być argumentami słów kluczowych","dataClassTransformUnknownArgument":"Argument „{name}” nie jest obsługiwany przez dataclass_transform","dataProtocolInSubclassCheck":"Protokoły danych (które zawierają atrybuty niebędące atrybutami metody) są niedozwolone w wywołaniach klasy issubclass","declaredReturnTypePartiallyUnknown":"Zadeklarowany zwracany typ „{returnType}” jest częściowo nieznany","declaredReturnTypeUnknown":"Deklarowany zwracany typ jest nieznany","defaultValueContainsCall":"Wywołania funkcji i modyfikowalne obiekty są niedozwolone w wyrażeniu wartości domyślnej parametru","defaultValueNotAllowed":"Parametr o wartości „*” lub „**” nie może mieć wartości domyślnej","delTargetExpr":"Nie można usunąć wyrażenia","deprecatedClass":"Klasa „{name}” jest przestarzała","deprecatedConstructor":"Konstruktor klasy „{name}” jest przestarzały","deprecatedDescriptorDeleter":"Metoda „__set__” dla deskryptora „{name}” jest przestarzała","deprecatedDescriptorGetter":"Metoda „__set__” dla deskryptora „{name}” jest przestarzała","deprecatedDescriptorSetter":"Metoda „__set__” dla deskryptora „{name}” jest przestarzała","deprecatedFunction":"Ta funkcja „{name}” jest przestarzała","deprecatedMethod":"Metoda „{name}” w klasie „{className}” jest przestarzała","deprecatedPropertyDeleter":"Metoda usuwająca dla właściwości „{name}” jest przestarzała","deprecatedPropertyGetter":"Metoda pobierająca dla właściwości „{name}” jest przestarzała","deprecatedPropertySetter":"Metoda pobierająca dla właściwości „{name}” jest przestarzała","deprecatedType":"Ten typ jest przestarzały dla języka Python w wersji {version}; zamiast tego użyj „{replacement}”.","dictExpandIllegalInComprehension":"Rozszerzanie słownika jest niedozwolone w rozumieniu","dictInAnnotation":"Wyrażenie słownikowe jest niedozwolone w adnotacji typu","dictKeyValuePairs":"Wpisy słownika muszą zawierać pary klucz/wartość","dictUnpackIsNotMapping":"Oczekiwano mapowania dla operatora rozpakowywania słownika","dunderAllSymbolNotPresent":"Nazwa „{name}” jest określona w wartości __all__, ale nie występuje w module","duplicateArgsParam":"Dozwolony tylko jeden parametr „*”","duplicateBaseClass":"Zduplikowana klasa bazowa jest niedozwolona","duplicateCapturePatternTarget":"Element docelowy przechwytywania „{name}” nie może występować więcej niż raz w obrębie tego samego wzorca","duplicateCatchAll":"Dozwolona jest tylko jedna klauzula typu catch-all z wyjątkiem klauzuli","duplicateEnumMember":"Składowa wyliczenia „{name}” jest już zadeklarowana","duplicateGenericAndProtocolBase":"Dozwolona jest tylko jedna klasa bazowa Generic[...] lub Protocol[...].","duplicateImport":"Nazwa „{importName}” została zaimportowana więcej niż raz","duplicateKeywordOnly":"Dozwolony tylko jeden separator „*”.","duplicateKwargsParam":"Dozwolony tylko jeden parametr „**”.","duplicateParam":"Duplikuj parametr „{name}”","duplicatePositionOnly":"Dozwolony tylko jeden parametr „/”","duplicateStarPattern":"W sekwencji wzorca dozwolony jest tylko jeden wzorzec „*”","duplicateStarStarPattern":"Dozwolony jest tylko jeden wpis „**”","duplicateUnpack":"Na liście dozwolona jest tylko jedna operacja rozpakowywania","ellipsisAfterUnpacked":"Nie można używać „...” z rozpakowanym typeVarTuple lub krotką","ellipsisContext":"Wartość „...” jest niedozwolona w tym kontekście","ellipsisSecondArg":"Wartość „...” jest dozwolona tylko jako drugi z dwóch argumentów","enumClassOverride":"Klasa wyliczenia „{name}” jest ostateczna i nie można jej podzielić na podklasy","exceptionGroupIncompatible":"Składnia grupy wyjątków („except*”) wymaga języka Python w wersji 3.11 lub nowszej","exceptionTypeIncorrect":"Typ „{type}” nie pochodzi od parametru BaseException","exceptionTypeNotClass":"Typ „{type}” nie jest prawidłową klasą wyjątku","exceptionTypeNotInstantiable":"Konstruktor typu wyjątku „{type}” wymaga co najmniej jednego argumentu","expectedAfterDecorator":"Oczekiwano deklaracji funkcji lub klasy po dekoratorze","expectedArrow":"Oczekiwano wartości „->”, po której następuje adnotacja zwracanego typu","expectedAsAfterException":"Oczekiwano „jako” po typie wyjątku","expectedAssignRightHandExpr":"Oczekiwano wyrażenia po prawej stronie znaku „=”","expectedBinaryRightHandExpr":"Oczekiwano wyrażenia po prawej stronie operatora","expectedBoolLiteral":"Oczekiwano wartości True lub False","expectedCase":"Oczekiwano instrukcji „case”","expectedClassName":"Oczekiwano nazwy klasy","expectedCloseBrace":"Brak zamknięcia dla: „{”","expectedCloseBracket":"Brak zamknięcia dla: „[”","expectedCloseParen":"Brak zamknięcia dla: „(”","expectedColon":"Oczekiwano „:”","expectedComplexNumberLiteral":"Oczekiwano literału liczby zespolonej na potrzeby dopasowywania wzorca","expectedDecoratorExpr":"Formularz wyrażenia nie jest obsługiwany przez dekorator w wersji wcześniejszej niż Python 3.9","expectedDecoratorName":"Oczekiwano nazwy dekoratora","expectedDecoratorNewline":"Oczekiwano nowego wiersza na końcu dekoratora","expectedDelExpr":"Oczekiwano wyrażenia po „del”","expectedElse":"Oczekiwano elementu „innego”","expectedEquals":"Oczekiwano „=”","expectedExceptionClass":"Nieprawidłowa klasa lub obiekt wyjątku","expectedExceptionObj":"Oczekiwano obiektu wyjątku, klasy wyjątku lub wartości Brak","expectedExpr":"Oczekiwano wyrażenia","expectedFunctionAfterAsync":"Oczekiwano definicji funkcji po wartości „async”","expectedFunctionName":"Oczekiwano nazwy funkcji po wyrażeniu „def”","expectedIdentifier":"Oczekiwany identyfikator","expectedImport":"Oczekiwano wartości „import”","expectedImportAlias":"Oczekiwano symbolu po parametrze „as”","expectedImportSymbols":"Oczekiwano jednej lub więcej nazw symboli po zaimportowaniu","expectedIn":"Oczekiwano parametru „in”","expectedInExpr":"Oczekiwano wyrażenia po „in”","expectedIndentedBlock":"Oczekiwano wciętego bloku","expectedMemberName":"Oczekiwano nazwy składowej po znaku „.”","expectedModuleName":"Oczekiwana nazwa modułu","expectedNameAfterAs":"Oczekiwano nazwy symbolu po „jako”","expectedNamedParameter":"Parametr słowa kluczowego musi następować po znaku „*”","expectedNewline":"Oczekiwano nowego wiersza","expectedNewlineOrSemicolon":"Instrukcje muszą być oddzielone znakami nowych wierszy lub średnikami","expectedOpenParen":"Oczekiwano „(”","expectedParamName":"Oczekiwano nazwy parametru","expectedPatternExpr":"Oczekiwano wyrażenia wzorca","expectedPatternSubjectExpr":"Oczekiwano wyrażenia tematu wzorca","expectedPatternValue":"Oczekiwano wyrażenia wartości wzorca w postaci „a.b”","expectedReturnExpr":"Oczekiwano wyrażenia po „return”.","expectedSliceIndex":"Oczekiwano wyrażenia indeksu lub wycinka","expectedTypeNotString":"Oczekiwano typu, ale otrzymano literał ciągu","expectedTypeParameterName":"Oczekiwano nazwy parametru typu","expectedYieldExpr":"Oczekiwano wyrażenia w instrukcji wstrzymywania","finalClassIsAbstract":"Klasa „{type}” jest oznaczona jako ostateczna i musi implementować wszystkie symbole abstrakcyjne","finalContext":"Wartość „Final” jest niedozwolona w tym kontekście","finalMethodOverride":"Metoda „{name}” nie może przesłonić metody końcowej zdefiniowanej w klasie „{className}”","finalNonMethod":"Nie można oznaczyć funkcji „{name}” jako @final, ponieważ nie jest to metoda","finalReassigned":"Element „{name}” jest zadeklarowany jako wersja ostateczna i nie można go ponownie przypisać","finalRedeclaration":"Nazwa „{name}” została wcześniej zadeklarowana jako końcowa","finalRedeclarationBySubclass":"Nie można ponownie zadeklarować nazwy „{name}”, ponieważ klasa nadrzędna „{className}” deklaruje ją jako końcową","finalTooManyArgs":"Oczekiwano jednego argumentu typu po wartości „Final”","finalUnassigned":"Nazwa „{name}” jest zadeklarowana jako końcowa, ale wartość nie jest przypisana","formatStringBrace":"Pojedynczy zamykający nawias klamrowy jest niedozwolony w literale ciągu f; użyj podwójnego zamykającego nawiasu klamrowego","formatStringBytes":"Literały ciągów formatu (ciągi f) nie mogą być binarne","formatStringDebuggingIllegal":"Specyfikator debugowania ciągu f „=” wymaga wersji języka Python 3.8 lub nowszej","formatStringEscape":"Sekwencja ucieczki (ukośnik odwrotny) jest niedozwolona w części wyrażenia ciągu f w wersji języka wcześniejszej niż Python 3.12","formatStringExpectedConversion":"Oczekiwano specyfikatora konwersji po znaku „!” w ciągu f-string","formatStringIllegal":"Literały ciągów formatu (ciągi f) wymagają wersji języka Python 3.6 lub nowszej","formatStringInPattern":"Ciąg formatu jest niedozwolony we wzorcu","formatStringNestedFormatSpecifier":"Wyrażenia zagnieżdżone zbyt głęboko w specyfikatorze ciągu formatu","formatStringNestedQuote":"Ciągi zagnieżdżone w ciągu f nie mogą używać tego samego znaku cudzysłowu co ciąg f w wersji języka wcześniejszej niż Python 3.12","formatStringUnicode":"Literały ciągu formatu (f-strings) nie mogą być formatu unicode","formatStringUnterminated":"Niezakończone wyrażenie w ciągu f; oczekiwano znaku „}”","functionDecoratorTypeUnknown":"Nietypowany dekorator funkcji zasłania typ funkcji; ignorując dekoratora","functionInConditionalExpression":"Wyrażenie warunkowe odwołuje się do funkcji, której wynikiem zawsze jest wartość Prawda","functionTypeParametersIllegal":"Składnia parametru typu klasy wymaga wersji języka Python 3.12 lub nowszej","futureImportLocationNotAllowed":"Importy z __future__ muszą znajdować się na początku pliku","generatorAsyncReturnType":"Zwracany typ funkcji generatora asynchronicznego musi być zgodny z elementem „AsyncGenerator[{yieldType}, Any]”","generatorNotParenthesized":"Wyrażenia generatora muszą być ujęte w nawiasy, jeśli nie są jedynym argumentem","generatorSyncReturnType":"Zwracany typ funkcji generatora musi być zgodny z elementem „Generator[{yieldType}, Any, Any]”","genericBaseClassNotAllowed":"Nie można użyć klasy bazowej „Generic” ze składnią parametru typu","genericClassAssigned":"Nie można przypisać ogólnego typu klasy","genericClassDeleted":"Nie można usunąć ogólnego typu klasy","genericInstanceVariableAccess":"Dostęp do ogólnej zmiennej wystąpienia za pośrednictwem klasy jest niejednoznaczny","genericNotAllowed":"Element „ogólny” jest nieprawidłowy w tym kontekście","genericTypeAliasBoundTypeVar":"Alias typu ogólnego w klasie nie może używać zmiennych typu powiązanego {names}","genericTypeArgMissing":"Wartość „Generic” wymaga co najmniej jednego argumentu typu","genericTypeArgTypeVar":"Argument typu dla wartości „Generic” musi być zmienną typu","genericTypeArgUnique":"Argumenty typu dla elementu „Generic” muszą być unikatowe","globalReassignment":"Nazwa „{name}” jest przypisywana przed deklaracją globalną","globalRedefinition":"Nazwa „{name}” została już zadeklarowana jako globalna","implicitStringConcat":"Niejawne łączenie ciągów jest niedozwolone","importCycleDetected":"Wykryto cykl w łańcuchu importu","importDepthExceeded":"Głębokość łańcucha importu przekroczyła {depth}","importResolveFailure":"Nie można rozpoznać importu „{importName}”.","importSourceResolveFailure":"Nie można rozpoznać importu „{importName}” ze źródła","importSymbolUnknown":"Nazwa „{name}” jest nieznanym symbolem importu","incompatibleMethodOverride":"Metoda „{name}” przesłania klasę „{className}” w niezgodny sposób","inconsistentIndent":"Wartość zmniejszenia wcięcia jest niezgodna z poprzednim wcięciem","inconsistentTabs":"Niespójne użycie tabulatorów i spacji we wcięciach","initMustReturnNone":"Zwracany typ „__init__” musi mieć wartość Brak","initSubclassCallFailed":"Nieprawidłowe argumenty słów kluczowych dla metody __init_subclass__","initSubclassClsParam":"Przesłonięcie __init_subclass__ powinno przyjmować parametr „cls”.","initVarNotAllowed":"Element „InitVar” jest niedozwolony w tym kontekście","instanceMethodSelfParam":"Metody wystąpienia powinny przyjmować parametr „self”","instanceVarOverridesClassVar":"Zmienna wystąpienia „{name}” zastępuje zmienną klasy o tej samej nazwie w klasie „{className}”","instantiateAbstract":"Nie można utworzyć wystąpienia klasy abstrakcyjnej „{type}”","instantiateProtocol":"Nie można utworzyć wystąpienia klasy protokołu typu „{type}”","internalBindError":"Wystąpił błąd wewnętrzny podczas wiązania pliku „{file}”: {message}","internalParseError":"Wystąpił błąd wewnętrzny podczas analizowania pliku „{file}”: {message}","internalTypeCheckingError":"Wystąpił błąd wewnętrzny podczas sprawdzania typu pliku „{file}”: {message}","invalidIdentifierChar":"Nieprawidłowy znak w identyfikatorze","invalidStubStatement":"Instrukcja nie ma znaczenia w pliku zastępczym typu","invalidTokenChars":"Nieprawidłowy znak „{text}” w tokenie","isInstanceInvalidType":"Drugi argument instrukcji „isinstance” musi być klasą lub krotką klas","isSubclassInvalidType":"Drugi argument „issubclass” musi być klasą lub krotką klas","keyValueInSet":"Pary klucz/wartość nie są dozwolone w zestawie","keywordArgInTypeArgument":"Argumentów słów kluczowych nie można używać na listach argumentów typu","keywordOnlyAfterArgs":"Separator argumentów tylko ze słowami kluczowymi jest niedozwolony po parametrze „*”","keywordParameterMissing":"Co najmniej jeden parametr słowa kluczowego musi występować po parametrze „*”","keywordSubscriptIllegal":"Argumenty słów kluczowych w indeksach podrzędnych nie są obsługiwane","lambdaReturnTypePartiallyUnknown":"Zwracany typ wyrażenia lambda „{returnType}” jest częściowo nieznany","lambdaReturnTypeUnknown":"Zwracany typ wyrażenia lambda jest nieznany","listAssignmentMismatch":"Wyrażenia typu „{type}” nie można przypisać do listy docelowej","listInAnnotation":"Wyrażenie listy jest niedozwolone w adnotacji typu","literalEmptyArgs":"Oczekiwano co najmniej jednego argumentu typu po wartości „Literal”","literalNotAllowed":"„Literał” nie może być używany w tym kontekście bez argumentu typu","literalNotCallable":"Nie można utworzyć wystąpienia typu literału","literalUnsupportedType":"Argumenty typu dla elementu „Literal” muszą mieć wartość Brak, wartość literału (int, bool, str lub bytes) lub wartość wyliczenia","matchIncompatible":"Instrukcje dopasowania wymagają języka Python w wersji 3.10 lub nowszej","matchIsNotExhaustive":"Przypadki w instrukcji dopasowania nie obsługują wyczerpująco wszystkich wartości","maxParseDepthExceeded":"Przekroczono maksymalną głębokość analizy; podziel wyrażenie na mniejsze wyrażenia podrzędne","memberAccess":"Nie można uzyskać dostępu do składowej „{name}” dla typu „{type}”","memberDelete":"Nie można usunąć składowej „{name}” dla typu „{type}”","memberSet":"Nie można uzyskać przypisać składowej „{name}” dla typu „{type}”","metaclassConflict":"Metaklasa klasy pochodnej musi być podklasą metaklas wszystkich jej klas bazowych","metaclassDuplicate":"Można podać tylko jedną metaklasę","metaclassIsGeneric":"Metaklasa nie może być ogólna","methodNotDefined":"Nie zdefiniowano metody „{name}”.","methodNotDefinedOnType":"Metoda „{name}” nie została zdefiniowana dla typu „{type}”","methodOrdering":"Nie można utworzyć spójnej kolejności metod","methodOverridden":"„{name}” przesłania metodę o tej samej nazwie w klasie „{className}” o niezgodnym typie „{type}”","methodReturnsNonObject":"Metoda „{name}” nie zwraca obiektu","missingSuperCall":"Metoda „{methodName}” nie wywołuje metody o tej samej nazwie w klasie nadrzędnej","moduleAsType":"Nie można użyć modułu jako typu","moduleNotCallable":"Moduł nie jest wywoływalny","moduleUnknownMember":"„{memberName}” nie jest znaną składową modułu „{moduleName}”","namedExceptAfterCatchAll":"Nazwana klauzula „except” nie może występować po klauzuli „catch-all except”","namedParamAfterParamSpecArgs":"Parametr słowa kluczowego \\"{name}\\" nie może występować w sygnaturze po parametrze argumentów ParamSpec","namedTupleEmptyName":"Nazwy w nazwanej krotce nie mogą być puste","namedTupleEntryRedeclared":"Nie można nadpisać „{name}”, ponieważ klasa nadrzędna „{className}” jest nazwaną krotką.","namedTupleFirstArg":"Oczekiwano nazwanej nazwy klasy krotki jako pierwszego argumentu","namedTupleMultipleInheritance":"Wielokrotne dziedziczenie z kotki NamedTuple nie jest obsługiwane","namedTupleNameKeyword":"Nazwy pól nie mogą być słowem kluczowym","namedTupleNameType":"Oczekiwano krotki z dwoma wpisami określającej nazwę i typ wpisu","namedTupleNameUnique":"Nazwy w nazwanej krotce muszą być unikatowe","namedTupleNoTypes":"Krotka „namedtuple” nie zapewnia typów wpisów krotki; zamiast tego użyj „NamedTuple”.","namedTupleSecondArg":"Oczekiwano nazwanej listy wpisów krotki jako drugiego argumentu","newClsParam":"Przesłonięcie __new__ powinno przyjmować parametr „cls”.","newTypeAnyOrUnknown":"Drugi argument elementu NewType musi być znaną klasą, a nie dowolną lub nieznaną","newTypeBadName":"Pierwszy argument elementu NewType musi być literałem ciągu","newTypeLiteral":"Typ NewType nie może być używany z typem Literał","newTypeNameMismatch":"Element NewType musi być przypisany do zmiennej o tej samej nazwie","newTypeNotAClass":"Oczekiwano klasy jako drugiego argumentu dla elementu NewType","newTypeParamCount":"Typ NewType wymaga dwóch argumentów pozycyjnych","newTypeProtocolClass":"Elementu NewType nie można używać z typem strukturalnym (protokołem lub klasą TypedDict)","noOverload":"Żadne przeciążenia dla nazwy „{name}” nie pasują do podanych argumentów","noReturnContainsReturn":"Funkcja z zadeklarowanym zwracanym typem „NoReturn” nie może zawierać instrukcji Return","noReturnContainsYield":"Funkcja z zadeklarowanym zwracanym typem „NoReturn” nie może zawierać instrukcji Yield","noReturnReturnsNone":"Funkcja z zadeklarowanym typem zwracanym „NoReturn” nie może zwracać wartości „None”","nonDefaultAfterDefault":"Argument inny niż domyślny następuje po argumencie domyślnym","nonLocalInModule":"Deklaracja nielokalna nie jest dozwolona na poziomie modułu","nonLocalNoBinding":"Nie znaleziono powiązania dla nielokalnej nazwy „{name}”.","nonLocalReassignment":"Nazwa „{name}” jest przypisywana przed deklaracją nielokalną","nonLocalRedefinition":"Nazwa „{name}” została już zadeklarowana jako nielokalna","noneNotCallable":"Nie można wywołać obiektu typu „None”","noneNotIterable":"Obiekt typu „Brak” nie może być używany jako wartość iterowalna","noneNotSubscriptable":"Obiekt typu „None” nie może być użyty w indeksie dolnym","noneNotUsableWith":"Obiekt typu „Brak” nie może być używany z parametrem „with”","noneOperator":"Operator „{operator}” nie jest obsługiwany dla wartości „Brak”","noneUnknownMember":"Nazwa „{name}” nie jest znaną składową elementu „None”","notRequiredArgCount":"Oczekiwano jednego argumentu typu po wartości „NotRequired”","notRequiredNotInTypedDict":"Element „NotRequired” jest niedozwolony w tym kontekście","objectNotCallable":"Obiekt typu „{type}” nie jest wywoływalny","obscuredClassDeclaration":"Deklaracja klasy „{name}” jest zasłonięta przez deklarację o tej samej nazwie","obscuredFunctionDeclaration":"Deklaracja funkcji „{name}” jest zasłonięta przez deklarację o tej samej nazwie","obscuredMethodDeclaration":"Deklaracja metody „{name}” jest zasłonięta przez deklarację o tej samej nazwie","obscuredParameterDeclaration":"Deklaracja parametru „{name}” jest zasłonięta przez deklarację o tej samej nazwie","obscuredTypeAliasDeclaration":"Deklaracja aliasu typu „{name}” jest zasłonięta przez deklarację o tej samej nazwie","obscuredVariableDeclaration":"Deklaracja „{name}” jest zasłonięta przez deklarację o tej samej nazwie","operatorLessOrGreaterDeprecated":"Operator „<>” nie jest obsługiwany w języku Python w wersji 3; zamiast tego użyj „!=”.","optionalExtraArgs":"Oczekiwano jednego argumentu typu po parametrze „Optional”","orPatternIrrefutable":"Niepodważalny wzorzec jest dozwolony tylko jako ostatni podwzorzec we wzorcu „or”","orPatternMissingName":"Wszystkie wzorce podrzędne we wzorcu „or” muszą dotyczyć tych samych nazw","overlappingKeywordArgs":"Wpisany słownik nakłada się na parametr słowa kluczowego: {names}","overlappingOverload":"Przeciążenie {obscured} dla nazwy „{name}” nigdy nie zostanie użyte, ponieważ jego parametry nakładają się na przeciążenie {obscuredBy}","overloadAbstractMismatch":"Przeciążone metody muszą być abstrakcyjne lub nieabstrakcyjne","overloadClassMethodInconsistent":"Przeciążenia dla nazwy „{name}” używają metody @classmethod niekonsekwentnie","overloadFinalInconsistencyImpl":"Przeciążenie elementu „{name}” jest oznaczone @final, ale implementacja nie jest","overloadFinalInconsistencyNoImpl":"Przeciążenie {index} dla elementu „{name}” jest oznaczone @final, ale przeciążenie 1 nie jest","overloadImplementationMismatch":"Przeciążone wdrożenie jest niespójne z sygnaturą przeciążenia {index}","overloadReturnTypeMismatch":"Przeciążenie {prevIndex} dla nazwy „{name}” nakłada się na przeciążenie {newIndex} i zwraca niezgodny typ","overloadStaticMethodInconsistent":"Przeciążenia dla nazwy „{name}” używają metody @staticmethod niekonsekwentnie","overloadWithoutImplementation":"Element „{name}” jest oznaczony jako przeciążony, ale nie podano implementacji","overriddenMethodNotFound":"Metoda „{name}” jest oznaczona jako zastąpienie, ale nie istnieje metoda bazowa o tej samej nazwie","overrideDecoratorMissing":"Metoda „{name}” nie jest oznaczona jako zastąpienie, ale zastępuje metodę w klasie „{className}”","paramAfterKwargsParam":"Parametr nie może następować po parametrze „**”","paramAlreadyAssigned":"Parametr „{name}” jest już przypisany","paramAnnotationMissing":"Brak adnotacji typu dla parametru „{name}”","paramAssignmentMismatch":"Wyrażenia typu „{sourceType}” nie można przypisać do parametru typu „{paramType}”","paramNameMissing":"Brak parametru o nazwie „{name}”","paramSpecArgsKwargsUsage":"Składowe „args” i „kwargs” specyfikacji ParamSpec muszą znajdować się w sygnaturze funkcji","paramSpecArgsMissing":"Brak argumentów dla parametru ParamSpec „{type}”.","paramSpecArgsUsage":"Składowa „args” parametru ParamSpec jest ważna tylko wtedy, gdy jest używana z parametrem *args","paramSpecAssignedName":"Parametr ParamSpec musi być przypisany do zmiennej o nazwie „{name}”","paramSpecContext":"Wartość ParamSpec jest niedozwolona w tym kontekście","paramSpecDefaultNotTuple":"Oczekiwano wielokropka, wyrażenia krotki lub parametru ParamSpec dla domyślnej wartości ParamSpec","paramSpecFirstArg":"Oczekiwano nazwy parametru ParamSpec jako pierwszego argumentu","paramSpecKwargsUsage":"Składowa „kwargs” parametru ParamSpec jest ważna tylko wtedy, gdy jest używana z parametrem **kwargs","paramSpecNotUsedByOuterScope":"Element ParamSpec „{name}” nie ma znaczenia w tym kontekście","paramSpecScopedToReturnType":"Parametr ParamSpec „{name}” jest objęty zakresem możliwości wywołania w ramach zwracanego typu i nie można odwoływać się do niego w treści funkcji","paramSpecUnknownArg":"Parametr ParamSpec nie obsługuje więcej niż jednego argumentu","paramSpecUnknownMember":"Nazwa „{name}” nie jest znaną składową parametru ParamSpec","paramSpecUnknownParam":"„{name}” jest nieznanym parametrem dla parametru ParamSpec","paramTypeCovariant":"Zmienna typu kowariantnego nie może być używana w typie parametru","paramTypePartiallyUnknown":"Typ parametru „{paramName}” jest częściowo nieznany","paramTypeUnknown":"Typ parametru „{paramName}” jest nieznany","parenthesizedContextManagerIllegal":"Nawiasy w instrukcji „with” wymagają wersji języka Python 3.9 lub nowszej","patternNeverMatches":"Wzorzec nigdy nie zostanie dopasowany do typu podmiotu „{type}”","positionArgAfterNamedArg":"Argument pozycyjny nie może występować po argumentach słów kluczowych","positionOnlyAfterArgs":"Separator parametru tylko do pozycjonowania jest niedozwolony po parametrze „*”","positionOnlyAfterKeywordOnly":"Parametr „/” musi występować przed parametrem „*”.","positionOnlyAfterNon":"Parametr tylko do pozycjonowania jest niedozwolony po parametrze, który nie jest tylko do pozycjonowania","positionOnlyFirstParam":"Separator parametrów tylko do pozycjonowania nie jest dozwolony jako pierwszy parametr","positionOnlyIncompatible":"Separator parametrów tylko do pozycjonowania wymaga języka Python 3.8 lub nowszego","privateImportFromPyTypedModule":"Nazwa „{name}” nie jest eksportowana z modułu „{module}”","privateUsedOutsideOfClass":"Nazwa „{name}” jest prywatna i używana poza klasą, w której została zadeklarowana","privateUsedOutsideOfModule":"Nazwa „{name}” jest prywatna i używana poza modułem, w którym została zadeklarowana","propertyOverridden":"„{name}” nieprawidłowo zastępuje właściwość o tej samej nazwie w klasie „{className}”","propertyStaticMethod":"Metody statyczne nie są dozwolone w przypadku metod pobierających, ustawiających lub usuwających właściwości","protectedUsedOutsideOfClass":"Nazwa „{name}” jest chroniona i używana poza klasą, w której została zadeklarowana","protocolBaseClass":"Klasa protokołu typu „{classType}” nie może pochodzić od klasy niebędącej klasą protokołu typu „{baseType}”","protocolBaseClassWithTypeArgs":"Argumenty typu są niedozwolone w przypadku klasy protokołu, gdy jest używana składnia parametru typu","protocolIllegal":"Użycie elementu „Protocol” wymaga języka Python w wersji 3.7 lub nowszej","protocolNotAllowed":"„Protokół” nie może być używany w tym kontekście","protocolUnsafeOverlap":"Klasa nakłada się niebezpiecznie na element „{name}” i może utworzyć dopasowanie w czasie wykonywania","protocolVarianceContravariant":"Zmienna typu „{variable}” używana w klasie protokołu ogólnego „{class}” powinna być kontrawariantna","protocolVarianceCovariant":"Zmienna typu „{variable}” używana w klasie protokołu ogólnego „{class}” powinna być kowariantna","protocolVarianceInvariant":"Zmienna typu „{variable}” używana w klasie protokołu ogólnego „{class}” powinna być niezmienna","pyrightCommentInvalidDiagnosticBoolValue":"Po dyrektywie komentarza Pyright musi następować znak „=” oraz wartość Prawda lub Fałsz","pyrightCommentInvalidDiagnosticSeverityValue":"Po dyrektywie komentarza Pyright musi następować znak „=” oraz wartość Prawda, Fałsz, Błąd, Ostrzeżenie, Informacja lub Brak","pyrightCommentMissingDirective":"Komentarz Pyright musi poprzedzać dyrektywę (bazową lub ścisłą) lub regułę diagnostyczną","pyrightCommentNotOnOwnLine":"Komentarze Pyright używane do kontrolowania ustawień na poziomie plików muszą pojawiać się w oddzielnych wierszach","pyrightCommentUnknownDiagnosticRule":"Reguła „{rule}” jest nieznaną regułą diagnostyczną dla komentarza Pyright","pyrightCommentUnknownDiagnosticSeverityValue":"Wartość „{value}” jest nieprawidłowa dla komentarza Pyright; oczekiwano wartości: Prawda, Fałsz, Błąd, Ostrzeżenie, Informacja lub Brak","pyrightCommentUnknownDirective":"Wartość „{directive}” jest nieznaną dyrektywą dla komentarza Pyright; oczekiwano wartości „strict” lub „basic”","readOnlyArgCount":"Oczekiwano jednego argumentu typu po wartości „ReadOnly”","readOnlyNotInTypedDict":"Element „ReadOnly” jest niedozwolony w tym kontekście","recursiveDefinition":"Nie można określić typu „{name}”, ponieważ odwołuje się on do samego siebie","relativeImportNotAllowed":"Importy względne nie mogą być używane z formularzem „import .a”; zamiast tego użyj „from . import a”.","requiredArgCount":"Oczekiwano jednego argumentu typu po wartości „Required”","requiredNotInTypedDict":"Element „Required” jest niedozwolony w tym kontekście","returnInAsyncGenerator":"Instrukcja „return” z wartością jest niedozwolona w generatorze asynchronicznym","returnMissing":"Funkcja z zadeklarowanym typem zwracanym „{returnType}” musi zwracać wartość we wszystkich ścieżkach kodu","returnOutsideFunction":"Instrukcja „return” może być używana tylko w ramach funkcji","returnTypeContravariant":"Kontrawariantna zmienna typu nie może być używana w zwracanym typie","returnTypeMismatch":"Wyrażenia typu „{exprType}” nie można przypisać do zwracanego typu „{returnType}”","returnTypePartiallyUnknown":"Zwracany typ „{returnType}” jest częściowo nieznany","returnTypeUnknown":"Zwracany typ jest nieznany","revealLocalsArgs":"Oczekiwano braku argumentów dla wywołania „reveal_locals”","revealLocalsNone":"Brak elementów lokalnych w tym zakresie","revealTypeArgs":"Oczekiwano pojedynczego argumentu pozycyjnego dla wywołania „reveal_type”","revealTypeExpectedTextArg":"Argument „expected_text” dla funkcji „reveal_type” musi być wartością literału str","revealTypeExpectedTextMismatch":"Wpisz niezgodność tekstu; oczekiwano „{expected}”, ale otrzymano „{received}”","revealTypeExpectedTypeMismatch":"Niezgodność typu; oczekiwano wartości „{expected}”, a uzyskano „{received}”","selfTypeContext":"Wartość „Self” jest nieprawidłowa w tym kontekście","selfTypeMetaclass":"Nie można użyć elementu „Self” w ramach metaklasy (podklasy elementu „type”)","selfTypeWithTypedSelfOrCls":"Nie można użyć wartości „Self” w funkcji z parametrem „self” lub „cls”, która ma adnotację typu inną niż „Self”","setterGetterTypeMismatch":"Typu wartości metody ustawiającej właściwość nie można przypisać do zwracanego typu metody pobierającej","singleOverload":"Nazwa „{name}” jest oznaczona jako przeciążona, ale brakuje dodatkowych przeciążeń","slotsAttributeError":"Nie określono atrybutu „{name}” w elemencie __slots__","slotsClassVarConflict":"„{name}” powoduje konflikt ze zmienną wystąpienia zadeklarowaną w elemencie „__slots__”","starPatternInAsPattern":"Wzór gwiazdy nie może być użyty z miejscem docelowym parametru „as”.","starPatternInOrPattern":"Wzór gwiazdy nie może mieć wartości ORed w ramach innych wzorów","starStarWildcardNotAllowed":"Symbolu ** nie można używać z symbolem wieloznacznym „_”","staticClsSelfParam":"Metody statyczne nie powinny przyjmować parametru „self” ani „cls”.","stdlibModuleOverridden":"Ścieżka „{path}” zastępuje moduł stdlib „{name}”","stringNonAsciiBytes":"Znak inny niż ASCII jest niedozwolony w literale ciągu bajtów","stringNotSubscriptable":"Wyrażenie ciągu nie może być indeksowane w adnotacji typu; ujmij całą adnotację w cudzysłów","stringUnsupportedEscape":"Nieobsługiwana sekwencja ucieczki w literale ciągu","stringUnterminated":"Literał ciągu jest niezakończony","stubFileMissing":"Nie znaleziono pliku zastępczego dla „{importName}”","stubUsesGetAttr":"Typ pliku zastępczego jest niekompletny; element „__getattr__” przesłania błędy typu dla modułu","sublistParamsIncompatible":"Parametry podlisty nie są obsługiwane w wersji języka Python 3.x","superCallArgCount":"Oczekiwano nie więcej niż dwóch argumentów wywołania „super”","superCallFirstArg":"Oczekiwano typu klasy jako pierwszego argumentu wywołania „super”, ale otrzymano „{type}”","superCallSecondArg":"Drugi argument wywołania „super” musi być obiektem lub klasą wywodzącą się z typu „{type}”","superCallZeroArgForm":"Forma bez argumentów wywołania „super” jest prawidłowa tylko w ramach metody","superCallZeroArgFormStaticMethod":"Forma z zerowym argumentem wywołania „super” jest nieprawidłowa w metodzie statycznej","symbolIsPossiblyUnbound":"Nazwa „{name}” jest prawdopodobnie niepowiązana","symbolIsUnbound":"Nazwa „{name}” jest niepowiązana","symbolIsUndefined":"Nazwa „{name}” nie jest zdefiniowana","symbolOverridden":"Nazwa „{name}” przesłania symbol o tej samej nazwie w klasie „{className}”","ternaryNotAllowed":"Wyrażenie słownikowe jest niedozwolone w adnotacji typu","totalOrderingMissingMethod":"Klasa musi definiować jedną z następujących wartości: „__lt__”, „__le__”, „__gt__” lub „__ge__”, aby użyć parametru total_ordering","trailingCommaInFromImport":"Końcowy przecinek nie jest dozwolony bez otaczających nawiasów","tryWithoutExcept":"Instrukcja „Try” musi mieć co najmniej jedną klauzulę „except” lub „finally”","tupleAssignmentMismatch":"Wyrażenia typu „{type}” nie można przypisać do docelowej krotki","tupleInAnnotation":"Wyrażenie krotki jest niedozwolone w adnotacji typu","tupleIndexOutOfRange":"Indeks {index} jest poza zakresem dla typu {type}","typeAliasIllegalExpressionForm":"Nieprawidłowy formularz wyrażenia dla definicji aliasu typu","typeAliasIsRecursiveDirect":"Alias typu „{name}” nie może używać samego siebie w swojej definicji","typeAliasNotInModuleOrClass":"Typ TypeAlias można zdefiniować tylko w zakresie modułu lub klasy","typeAliasRedeclared":"Nazwa „{name}” jest zadeklarowana jako TypeAlias i może być przypisana tylko raz","typeAliasStatementBadScope":"Deklaracja typu może być użyta tylko w zakresie modułu lub klasy","typeAliasStatementIllegal":"Instrukcja typu alias wymaga języka Python w wersji 3.12 lub nowszej","typeAliasTypeBaseClass":"Alias typu zdefiniowany w instrukcji „{type}” nie może być użyty jako klasa bazowa","typeAliasTypeMustBeAssigned":"Typ TypeAliasType musi być przypisany do zmiennej o takiej samej nazwie jak alias typu","typeAliasTypeNameArg":"Pierwszy argument dla typu typeAliasType musi być literałem ciągu reprezentującym nazwę aliasu typu","typeAliasTypeNameMismatch":"Nazwa aliasu typu musi być zgodna z nazwą zmiennej, do której jest przypisana","typeAliasTypeParamInvalid":"Lista parametrów typu musi być krotką zawierającą tylko parametry TypeVar, TypeVarTuple lub ParamSpec","typeAnnotationCall":"Wyrażenie wywołania jest niedozwolone w wyrażeniu typu","typeAnnotationVariable":"Zmienna niedozwolona w wyrażeniu typu","typeAnnotationWithCallable":"Argument typu „type” musi być klasą; elementy wywoływane nie są obsługiwane","typeArgListExpected":"Oczekiwano parametru ParamSpec, wielokropka lub listy typów","typeArgListNotAllowed":"Wyrażenie listy jest niedozwolone dla tego argumentu typu","typeArgsExpectingNone":"Oczekiwano braku argumentów typu dla klasy „{name}”","typeArgsMismatchOne":"Oczekiwano jednego argumentu typu, ale otrzymano {received}","typeArgsMissingForAlias":"Oczekiwano argumentów typu dla aliasu typu ogólnego „{name}”","typeArgsMissingForClass":"Oczekiwano argumentów typu dla ogólnej klasy „{name}”","typeArgsTooFew":"Podano zbyt mało argumentów typu dla „{name}”; oczekiwano wartości {expected}, ale otrzymano {received}","typeArgsTooMany":"Podano zbyt wiele argumentów typu dla nazwy „{name}”; oczekiwano {expected}, a uzyskano {received}","typeAssignmentMismatch":"Wyrażenie typu „{sourceType}” nie może być przypisane do zadeklarowanego typu „{destType}”","typeAssignmentMismatchWildcard":"Symbol importu „{name}” ma typ „{sourceType}”, którego nie można przypisać do zadeklarowanego typu „{destType}”","typeCallNotAllowed":"Wywołanie type() nie powinno być używane w adnotacji typu","typeCheckOnly":"Nazwa „{name}” jest oznaczona jako @type_check_only i może być używana tylko w adnotacjach typu","typeCommentDeprecated":"Używanie komentarzy typu jest przestarzałe; zamiast tego użyj adnotacji typu","typeExpectedClass":"Oczekiwano wyrażenia typu, ale otrzymano „{type}”","typeGuardArgCount":"Oczekiwano pojedynczego argumentu typu po parametrze „TypeGuard” lub „TypeIs”","typeGuardParamCount":"Funkcje i metody zabezpieczające typu zdefiniowane przez użytkownika muszą mieć co najmniej jeden parametr wejściowy","typeIsReturnType":"Zwracany typ TypeIs („{returnType}”) jest niezgodny z typem parametru wartości („{type}”)","typeNotAwaitable":"Nie można oczekiwać typu „{type}”","typeNotIntantiable":"Nie można utworzyć wystąpienia „{type}”","typeNotIterable":"Typ „{type}” nie jest iterowalny","typeNotSpecializable":"Nie można specjalizować typu „{type}”","typeNotSubscriptable":"Obiekt typu „{type}” nie może być użyty w indeksie dolnym","typeNotSupportBinaryOperator":"Operator „{operator}” nieobsługiwany dla typów „{leftType}” i „{rightType}”","typeNotSupportBinaryOperatorBidirectional":"Operator „{operator}” nie jest obsługiwany dla typów „{leftType}” i „{rightType}”, gdy oczekiwanym typem jest „{expectedType}”","typeNotSupportUnaryOperator":"Operator „{operator}” nie jest obsługiwany dla typu „{type}”","typeNotSupportUnaryOperatorBidirectional":"Operator „{operator}” nie jest obsługiwany dla typu „{type}”, gdy oczekiwanym typem jest „{expectedType}”","typeNotUsableWith":"Obiekt typu „{type}” nie może być używany z parametrem „with”, ponieważ nie wdraża metody {method}","typeParameterBoundNotAllowed":"Powiązanie lub ograniczenie nie może być używane z parametrem typu ze zmienną liczbą argumentów lub parametrem ParamSpec","typeParameterConstraintTuple":"Ograniczenie parametru typu musi być krotką dwóch lub więcej typów","typeParameterExistingTypeParameter":"Parametr typu „{name}” jest już używany","typeParameterNotDeclared":"Parametr typu „{name}” nie znajduje się na liście parametrów typu dla „{container}”","typeParametersMissing":"Należy określić co najmniej jeden parametr typu","typePartiallyUnknown":"Typ „{name}” jest częściowo nieznany","typeUnknown":"Typ „{name}” jest nieznany","typeVarAssignedName":"Typ TypeVar musi być przypisany do zmiennej o nazwie „{name}”","typeVarAssignmentMismatch":"Nie można przypisać typu „{type}” do zmiennej typu „{name}”","typeVarBoundAndConstrained":"Typ TypeVar nie może być jednocześnie powiązany i ograniczony","typeVarBoundGeneric":"Typ powiązany TypeVar nie może być ogólny","typeVarConstraintGeneric":"Typ ograniczenia TypeVar nie może być ogólny","typeVarDefaultBoundMismatch":"Domyślny typ TypeVar musi być podtypem powiązanego typu","typeVarDefaultConstraintMismatch":"Typ domyślny TypeVar musi być jednym z typów z ograniczeniami","typeVarDefaultIllegal":"Typy domyślne zmiennych typów wymagają wersji języka Python 3.13 lub nowszej","typeVarDefaultInvalidTypeVar":"Parametr typu „{name}” ma typ domyślny, który odnosi się do co najmniej jednej zmiennej typu, która jest poza zakresem","typeVarFirstArg":"Oczekiwano nazwy TypeVar jako pierwszego argumentu","typeVarNoMember":"Typ TypeVar „{type}” nie ma składowej „{name}”","typeVarNotSubscriptable":"Typ TypeVar „{type}” nie może być subskrybowany","typeVarNotUsedByOuterScope":"Zmienna typu „{name}” nie ma w tym kontekście żadnego znaczenia","typeVarPossiblyUnsolvable":"Zmienna typu „{name}” może zostać nierozwiązana, jeśli obiekt wywołujący nie poda argumentu dla parametru „{param}”","typeVarScopedToReturnType":"Zmienna typu „{name}” jest objęta zakresem możliwości wywołania w typie zwracanym i nie można odwoływać się do niej w treści funkcji","typeVarSingleConstraint":"Typ TypeVar musi mieć co najmniej dwa typy ograniczone","typeVarTupleConstraints":"Element TypeVarTuple nie może mieć ograniczeń wartości","typeVarTupleContext":"Wartość TypeVarTuple jest niedozwolona w tym kontekście","typeVarTupleDefaultNotUnpacked":"Typ domyślny TypeVarTuple musi być nierozpakowaną krotką lub parametrem TypeVarTuple","typeVarTupleMustBeUnpacked":"Operator rozpakowywania jest wymagany dla wartości parametru TypeVarTuple","typeVarTupleUnknownParam":"Nazwa „{name}” jest nieznanym parametrem typu TypeVarTuple","typeVarUnknownParam":"„{name}” jest nieznanym parametrem dla argumentu TypeVar","typeVarUsedByOuterScope":"Argument TypeVar „{name}” jest już używany przez zakres zewnętrzny","typeVarUsedOnlyOnce":"Typ TypeVar „{name}” pojawia się tylko raz w sygnaturze funkcji ogólnej","typeVarVariance":"Zmienna typu TypeVar nie może być jednocześnie kowariantna i kontrawariantna","typeVarWithDefaultFollowsVariadic":"Wartość TypeVar „{typeVarName}” ma wartość domyślną i nie może następować po wartości TypeVarTuple „{variadicName}”.","typeVarWithoutDefault":"Element „{name}” nie może występować po elemencie „{other}” na liście parametrów typu, ponieważ nie ma typu domyślnego","typeVarsNotInGenericOrProtocol":"Elementy Generic[] lub Protocol[] muszą zawierać wszystkie zmienne typu","typedDictAccess":"Nie można uzyskać dostępu do elementu w TypedDict","typedDictAssignedName":"Element TypedDict musi być przypisany do zmiennej o nazwie „{name}”","typedDictBadVar":"Klasy TypedDict mogą zawierać tylko adnotacje typu","typedDictBaseClass":"Wszystkie klasy bazowe dla klas TypedDict muszą być również klasami TypedDict","typedDictBoolParam":"Oczekiwano, że parametr „{name}” będzie miał wartość Prawda lub Fałsz","typedDictClosedExtras":"Klasa bazowa „{name}” jest zamkniętym elementem TypedDict; dodatkowe elementy muszą być typu „{type}”","typedDictClosedNoExtras":"Klasa bazowa „{name}” jest zamkniętym elementem TypedDict; dodatkowe elementy są niedozwolone","typedDictDelete":"Nie można usunąć elementu w typie TypedDict","typedDictEmptyName":"Nazwy w elemencie TypedDict nie mogą być puste","typedDictEntryName":"Oczekiwano literału ciągu dla nazwy wpisu słownika","typedDictEntryUnique":"Nazwy w słowniku muszą być unikatowe","typedDictExtraArgs":"Dodatkowe argumenty TypedDict nie są obsługiwane","typedDictFieldNotRequiredRedefinition":"Element TypedDict „{name}” nie może zostać przedefiniowany jako Niewymagany","typedDictFieldReadOnlyRedefinition":"Element TypedDict „{name}” nie może być przedefiniowany jako Tylko do odczytu.","typedDictFieldRequiredRedefinition":"Element TypedDict „{name}” nie może zostać przedefiniowany jako Wymagany","typedDictFirstArg":"Oczekiwano nazwy klasy TypedDict jako pierwszego argumentu","typedDictInitsubclassParameter":"Element TypedDict nie obsługuje parametru __init_subclass__ „{name}”","typedDictNotAllowed":"Nie można użyć elementu „TypedDict” w tym kontekście","typedDictSecondArgDict":"Oczekiwano parametru dict lub słowa kluczowego jako drugiego parametru","typedDictSecondArgDictEntry":"Oczekiwano prostego wpisu słownika","typedDictSet":"Nie można przypisać elementu w TypedDict","unaccessedClass":"Nie uzyskano dostępu do klasy „{name}”","unaccessedFunction":"Brak dostępu do funkcji „{name}”.","unaccessedImport":"Import „{name}” nie jest dostępny","unaccessedSymbol":"Brak dostępu do „{name}”.","unaccessedVariable":"Brak dostępu do zmiennej „{name}”.","unannotatedFunctionSkipped":"Analiza funkcji „{name}” została pominięta, ponieważ nie ma adnotacji","unaryOperationNotAllowed":"Operator jednoargumentowy nie jest dozwolony w adnotacji typu","unexpectedAsyncToken":"Oczekiwano wartości „def”, „with” lub „for” po „async”","unexpectedExprToken":"Nieoczekiwany token na końcu wyrażenia","unexpectedIndent":"Nieoczekiwane wcięcie","unexpectedUnindent":"Nieoczekiwany brak wcięcia","unhashableDictKey":"Klucz słownika musi być wartością skrótu","unhashableSetEntry":"Ustawiany wpis musi być wartością skrótu","uninitializedAbstractVariables":"Zmienne zdefiniowane w abstrakcyjnej klasie bazowej nie są inicjowane w klasie końcowej „{classType}”","uninitializedInstanceVariable":"Zmienna wystąpienia „{name}” nie została zainicjowana w treści klasy ani w metodzie __init__","unionForwardReferenceNotAllowed":"Składnia unii nie może być używana z operandem ciągu; użyj cudzysłowów wokół całego wyrażenia","unionSyntaxIllegal":"Alternatywna składnia unii wymaga języka Python w wersji 3.10 lub nowszej","unionTypeArgCount":"Unia wymaga co najmniej dwóch argumentów typu","unionUnpackedTuple":"Związek nie może zawierać rozpakowanej krotki","unionUnpackedTypeVarTuple":"Unia nie może zawierać rozpakowanego elementu TypeVarTuple","unnecessaryCast":"Niepotrzebne wywołanie „cast”; typ jest już „{type}”","unnecessaryIsInstanceAlways":"Niepotrzebne wywołanie wystąpienia; „{testType}” jest zawsze wystąpieniem „{classType}”","unnecessaryIsSubclassAlways":"Niepotrzebne wywołanie „issubclass”; „{testType}” jest zawsze podklasą klasy „{classType}”","unnecessaryPyrightIgnore":"Niepotrzebny komentarz „# pyright: ignore”","unnecessaryPyrightIgnoreRule":"Niepotrzebna reguła „# pyright: ignore”: „{name}”","unnecessaryTypeIgnore":"Niepotrzebny komentarz „# type: ignore”","unpackArgCount":"Oczekiwano jednego argumentu typu po wartości „Unpack”","unpackExpectedTypeVarTuple":"Oczekiwano typu TypeVarTuple lub krotki jako argumentu typu dla rozpakowywania","unpackExpectedTypedDict":"Oczekiwano argumentu typu TypedDict dla rozpakowywania","unpackIllegalInComprehension":"Operacja rozpakowywania nie jest dozwolona w rozumieniu","unpackInAnnotation":"Operator rozpakowywania nie jest dozwolony w adnotacji typu","unpackInDict":"Operacja rozpakowywania nie jest dozwolona w słownikach","unpackInSet":"Rozpakowywanie operatora jest niedozwolone w zestawie","unpackNotAllowed":"Rozpakowywanie jest niedozwolone w tym kontekście","unpackOperatorNotAllowed":"Operacja rozpakowywania jest niedozwolona w tym kontekście","unpackTuplesIllegal":"Operacja rozpakowywania nie jest dozwolona w krotkach przed językiem Python w wersji 3.8","unpackedArgInTypeArgument":"Rozpakowanych argumentów nie można używać na listach argumentów typu","unpackedArgWithVariadicParam":"Nie można użyć nierozpakowanego argumentu dla parametru TypeVarTuple","unpackedDictArgumentNotMapping":"Wyrażenie argumentu po znakach ** musi być mapowaniem z typem klucza „str”","unpackedDictSubscriptIllegal":"Operator rozpakowywania słownika w indeksie dolnym jest niedozwolony","unpackedSubscriptIllegal":"Operator rozpakowywania w indeksie dolnym wymaga języka Python w wersji 3.11 lub nowszej","unpackedTypeVarTupleExpected":"Oczekiwano nierozpakowanego typu TypeVarTuple; użyj Unpack[{name1}] lub *{name2}","unpackedTypedDictArgument":"Nie można dopasować nierozpakowanego argumentu TypedDict do parametrów","unreachableCode":"Kod jest nieosiągalny","unreachableExcept":"Klauzula wyjątku jest nieosiągalna, ponieważ wyjątek jest już obsługiwany","unsupportedDunderAllOperation":"Operacja na elemencie „__all__” nie jest obsługiwana, więc wyeksportowana lista symboli może być nieprawidłowa","unusedCallResult":"Wynik wyrażenia wywołania jest typu „{type}” i nie jest używany; przypisz do zmiennej „_”, jeśli jest to zamierzone","unusedCoroutine":"Wynik wywołania funkcji asynchronicznej nie jest używany; użyj wartości „await” lub przypisz wynik do zmiennej","unusedExpression":"Wartość wyrażenia jest nieużywana","varAnnotationIllegal":"Adnotacje typu dla zmiennych wymagają języka Python w wersji 3.6 lub nowszej; użyj komentarza typu, aby uzyskać zgodność z poprzednimi wersjami","variableFinalOverride":"Zmienna „{name}” jest oznaczona jako końcowa i zastępuje zmienną inną niż końcowa o tej samej nazwie w klasie „{className}”","variadicTypeArgsTooMany":"Lista argumentów typu może zawierać co najwyżej jeden nierozpakowany typ TypeVarTuple lub krotkę","variadicTypeParamTooManyAlias":"Alias typu może mieć co najwyżej jeden parametr typu TypeVarTuple, ale otrzymał wiele ({names})","variadicTypeParamTooManyClass":"Klasa ogólna może mieć co najwyżej jeden parametr typu TypeVarTuple, ale otrzymał wiele ({names})","walrusIllegal":"Operator „:=” wymaga języka Python w wersji 3.8 lub nowszej","walrusNotAllowed":"Operator „:=” jest niedozwolony w tym kontekście bez otaczających nawiasów","wildcardInFunction":"Importowanie symboli wieloznacznych jest niedozwolone w obrębie klasy lub funkcji","wildcardLibraryImport":"Importowanie symboli wieloznacznych z biblioteki jest niedozwolone","wildcardPatternTypePartiallyUnknown":"Typ przechwycony przez wzorzec symboli wieloznacznych jest częściowo nieznany","wildcardPatternTypeUnknown":"Typ przechwycony przez wzorzec symboli wieloznacznych jest nieznany","yieldFromIllegal":"Użycie wartości „yield from” wymaga języka Python w wersji 3.3 lub nowszej","yieldFromOutsideAsync":"Instrukcja „yield from” jest niedozwolona w funkcji asynchronicznej","yieldOutsideFunction":"Instrukcja „yield” jest niedozwolona poza funkcją lub wyrażeniem lambda","yieldWithinListCompr":"Instrukcja „yield” nie jest dozwolona w rozumieniu listy","zeroCaseStatementsFound":"Instrukcja dopasowania musi zawierać co najmniej jedną instrukcję dotyczącą wielkości liter","zeroLengthTupleNotAllowed":"Krotka o zerowej długości jest niedozwolona w tym kontekście"},"DiagnosticAddendum":{"annotatedNotAllowed":"Formularza specjalnego „Adnotacja” nie można używać z kontrolami wystąpień i klas","argParam":"Argument odpowiada parametrowi „{paramName}”","argParamFunction":"Argument odpowiada parametrowi „{paramName}” w funkcji „{functionName}”","argsParamMissing":"Parametr „*{paramName}” nie ma odpowiadającego mu parametru","argsPositionOnly":"Niezgodność parametrów tylko dla pozycji; oczekiwano wartości „{expected}”, a uzyskano „{received}”","argumentType":"Typ argumentu to „{type}”","argumentTypes":"Typy argumentów: ({types})","assignToNone":"Nie można przypisać typu do typu „Brak”","asyncHelp":"Czy chodziło o wartość „async with”?","baseClassIncompatible":"Klasa bazowa „{baseClass}” jest niezgodna z typem „{type}”","baseClassIncompatibleSubclass":"Klasa bazowa „{baseClass}” pochodzi od klasy podrzędnej „{subclass}”, która jest niezgodna z typem „{type}”","baseClassOverriddenType":"Klasa bazowa „{baseClass}” udostępnia typ „{type}”, który jest przesłonięty","baseClassOverridesType":"Zastąpienie klasy bazowej „{baseClass}” typem „{type}”","bytesTypePromotions":"Ustaw właściwość disableBytesTypePromotions na wartość false, aby włączyć zachowanie promocji typu dla elementów „bytearray” i „memoryview”","conditionalRequiresBool":"Metoda __bool__ dla typu „{operandType}” zwraca typ \\"{boolReturnType}\\" zamiast „bool”","dataClassFieldLocation":"Deklaracja pola","dataClassFrozen":"Nazwa „{name}” jest zamrożona","dataProtocolUnsupported":"Element „{name}” to protokół danych","descriptorAccessBindingFailed":"Nie można powiązać metody „{name}” dla klasy deskryptora „{className}”","descriptorAccessCallFailed":"Nie można wywołać metody „{name}” dla klasy deskryptora „{className}”","finalMethod":"Metoda końcowa","functionParamDefaultMissing":"Brak domyślnego argumentu dla parametru „{name}”","functionParamName":"Niezgodność nazw parametrów: „{destName}” a „{srcName}”","functionParamPositionOnly":"Niezgodność parametrów tylko do położenia; parametr „{name}” nie jest tylko pozycją","functionReturnTypeMismatch":"Typ zwracanego typu funkcji „{sourceType}” jest niezgodny z typem „{destType}”","functionTooFewParams":"Funkcja akceptuje zbyt mało parametrów pozycyjnych; oczekiwano {expected}, ale otrzymano {received}","functionTooManyParams":"Funkcja akceptuje zbyt wiele parametrów pozycyjnych; oczekiwano {expected}, ale otrzymano {received}","genericClassNotAllowed":"Typ ogólny z argumentami typu jest niedozwolony dla sprawdzania wystąpienia lub klasy","incompatibleDeleter":"Metoda usuwająca właściwości jest niezgodna","incompatibleGetter":"Metoda pobierająca właściwości jest niezgodna","incompatibleSetter":"Metoda ustawiająca właściwości jest niezgodna","initMethodLocation":"Metoda __init__ jest zdefiniowana w klasie „{type}”","initMethodSignature":"Sygnatura __init__ to typ „{type}”","initSubclassLocation":"Metoda __init_subclass__ jest zdefiniowana w klasie „{name}”","invariantSuggestionDict":"Rozważ przełączenie z wartości „dict” na „Mapping”, która jest kowariantna w typie wartości","invariantSuggestionList":"Rozważ zmianę wartości „list” na „Sequence”, która jest kowariantna","invariantSuggestionSet":"Rozważ przełączenie z wartości „set” na „Container”, która jest kowariantna","keyNotRequired":"„{name}” nie jest wymaganym kluczem w typie „{type}”, więc dostęp może spowodować wyjątek środowiska uruchomieniowego","keyReadOnly":"Nazwa „{name}” jest kluczem tylko do odczytu w typie „{type}”","keyRequiredDeleted":"Nazwa „{name}” jest wymaganym kluczem i nie można go usunąć","keyUndefined":"Nazwa „{name}” nie jest zdefiniowanym kluczem w typie „{type}”","kwargsParamMissing":"Parametr „**{paramName}” nie ma odpowiadającego mu parametru","listAssignmentMismatch":"Typ „{type}” jest niezgodny z listą docelową","literalAssignmentMismatch":"Nie można przypisać typu „{sourceType}” do typu „{destType}”","matchIsNotExhaustiveHint":"Jeśli kompleksowa obsługa nie jest zamierzona, dodaj „case _: pass”","matchIsNotExhaustiveType":"Nieobsługiwany typ: „{type}”","memberAssignment":"Wyrażenia typu „{type}” nie można przypisać do składowej „{name}” klasy „{classType}”","memberIsAbstract":"„{type}.{name}” nie zostało zaimplementowane","memberIsAbstractMore":"i jeszcze {count}...","memberIsClassVarInProtocol":"Element „{name}” jest zdefiniowany jako element ClassVar w protokole","memberIsFinalInProtocol":"Nazwa „{name}” jest oznaczona jako końcowa w protokole","memberIsInitVar":"Składowa „{name}” jest polem tylko do operacji init","memberIsInvariant":"Nazwa „{name}” jest niezmienna, ponieważ jest modyfikowalna","memberIsNotClassVarInClass":"Element „{name}” musi być zdefiniowany jako ClassVar, aby był zgodny z protokołem","memberIsNotClassVarInProtocol":"Element „{name}” nie jest zdefiniowany jako ClassVar w protokole","memberIsNotFinalInProtocol":"Element „{name}” nie jest oznaczony jako wersja ostateczna w protokole","memberIsWritableInProtocol":"Nazwa „{name}” jest zapisywalna w protokole","memberSetClassVar":"Nie można przypisać składowej „{name}” przez wystąpienie klasy, ponieważ jest to element ClassVar","memberTypeMismatch":"Nazwa „{name}” jest niezgodnym typem","memberUnknown":"Składowa „{name}” jest nieznana","metaclassConflict":"Metaklasa „{metaclass1}” powoduje konflikt z „{metaclass2}”","missingDeleter":"Brak metody usuwania właściwości","missingGetter":"Brak metody pobierającej właściwości","missingSetter":"Brak metody zestawu właściwości","namedParamMissingInDest":"W lokalizacji docelowej brakuje parametru słowa kluczowego „{name}”.","namedParamMissingInSource":"W źródle brakuje parametru słowa kluczowego „{name}”.","namedParamTypeMismatch":"Parametru słowa kluczowego „{name}” typu „{sourceType}” nie można przypisać do typu „{destType}”","namedTupleNotAllowed":"Funkcja NamedTuple nie może być używana do sprawdzania wystąpień lub klas","newMethodLocation":"Metoda __new__ jest zdefiniowana w klasie „{type}”","newMethodSignature":"Sygnatura __new__ to typ „{type}”","newTypeClassNotAllowed":"Klasy utworzonej za pomocą elementu NewType nie można używać z sprawdzaniem wystąpień i klas","noOverloadAssignable":"Żadna przeciążona funkcja nie pasuje do typu „{type}”","noneNotAllowed":"Żadne nie może być używane do sprawdzania wystąpienia ani klasy","orPatternMissingName":"Brak nazw: {name}","overloadIndex":"Przeciążenie {index} jest najbardziej zbliżonym dopasowaniem","overloadNotAssignable":"Nie można przypisać jednego lub więcej przeciążeń „{name}”.","overloadSignature":"Sygnatura przeciążenia jest zdefiniowana tutaj","overriddenMethod":"Przesłonięta metoda","overriddenSymbol":"Przesłonięty symbol","overrideInvariantMismatch":"Typ zastąpienia „{overrideType}” nie jest taki sam jak typ podstawowy „{baseType}”","overrideIsInvariant":"Zmienna podlega przeobrażeniom, dlatego jej typ jest niezmienny","overrideNoOverloadMatches":"Żadna sygnatura przeciążenia w przesłonięciu nie jest zgodna z metodą bazową","overrideNotClassMethod":"Metoda bazowa jest zadeklarowana jako metoda classmethod, ale przesłonięcie nie","overrideNotInstanceMethod":"Metoda bazowa jest zadeklarowana jako metoda wystąpienia, ale zastąpienie nie jest","overrideNotStaticMethod":"Metoda bazowa jest zadeklarowana jako metoda statyczna, ale przesłonięcie nie","overrideOverloadNoMatch":"Zastąpienie nie obsługuje wszystkich przeciążeń metody podstawowej","overrideOverloadOrder":"Przeciążenia dla metody przesłaniania muszą być w takiej samej kolejności, co metoda bazowa","overrideParamKeywordNoDefault":"Niezgodność parametru słowa kluczowego „{name}”: parametr bazowy ma domyślną wartość argumentu, parametr zastąpienia nie ma jej","overrideParamKeywordType":"Niezgodność typu parametru słowa kluczowego „{name}”: parametr bazowy jest typu „{baseType}”, a parametr zastąpienia jest typu „{overrideType}”","overrideParamName":"Niezgodność nazwy parametru {index}: parametr podstawowy nosi nazwę „{baseName}”, a parametr zastąpienia — „{overrideName}”","overrideParamNameExtra":"W bazie brakuje parametru „{name}”.","overrideParamNameMissing":"Brak parametru „{name}” w zastąpieniu","overrideParamNamePositionOnly":"Niezgodność parametru {index}: parametr podstawowy „{baseName}” jest parametrem słowa kluczowego, parametr przesłonięcia jest tylko w pozycji","overrideParamNoDefault":"Niezgodność parametru {index}: parametr bazowy ma domyślną wartość argumentu, a parametr zastąpienia nie ma jej","overrideParamType":"Niezgodność typów parametru {index}: parametr bazowy jest typu „{baseType}”, parametr zastąpienia jest typu „{overrideType}”","overridePositionalParamCount":"Niezgodność liczby parametrów pozycyjnych; metoda podstawowa ma {baseCount}, a zastąpienie {overrideCount}","overrideReturnType":"Niezgodność zwracanego typu: metoda podstawowa zwraca typ „{baseType}”, przesłonięcie zwraca typ „{overrideType}”","overrideType":"Klasa bazowa definiuje typ jako „{type}”","paramAssignment":"Parametr {index}: typu „{sourceType}” nie można przypisać do typu „{destType}”","paramSpecMissingInOverride":"Brak parametrów ParamSpec w metodzie zastąpienia","paramType":"Typ parametru to „{paramType}”","privateImportFromPyTypedSource":"Zamiast tego importuj z modułu „{module}”.","propertyAccessFromProtocolClass":"Nie można uzyskać dostępu do właściwości zdefiniowanej w klasie protokołu jako zmiennej klasy","propertyMethodIncompatible":"Metoda właściwości „{name}” jest niezgodna","propertyMethodMissing":"Brak metody właściwości „{name}” w zastąpieniu","propertyMissingDeleter":"Właściwość „{name}” nie ma zdefiniowanego elementu usuwającego","propertyMissingSetter":"Właściwość „{name}” nie ma zdefiniowanej metody ustawiającej","protocolIncompatible":"Protokół „{sourceType}” jest niezgodny z protokołem „{destType}”","protocolMemberMissing":"Brak nazwy „{name}”.","protocolRequiresRuntimeCheckable":"Klasa protokołu musi być @runtime_checkable, aby mogła być używana ze sprawdzaniem wystąpienia i klasy","protocolSourceIsNotConcrete":"„{sourceType}” nie jest typem specyficznej klasy i nie można go przypisać do typu „{destType}”","protocolUnsafeOverlap":"Atrybuty „{name}” mają takie same nazwy jak protokół","pyrightCommentIgnoreTip":"Użyj polecenia „# pyright: ignore[<diagnostic rules>], aby pominąć diagnostykę przez jeden wiersz","readOnlyAttribute":"Atrybut „{name}” jest tylko do odczytu","seeClassDeclaration":"Zobacz deklarację klasy","seeDeclaration":"Zobacz deklarację","seeFunctionDeclaration":"Zobacz deklarację funkcji","seeMethodDeclaration":"Zobacz deklarację metody","seeParameterDeclaration":"Zobacz deklarację parametru","seeTypeAliasDeclaration":"Zobacz deklarację aliasu typu","seeVariableDeclaration":"Zobacz deklarację zmiennej","tupleAssignmentMismatch":"Typ „{type}” jest niezgodny z docelową krotką","tupleEntryTypeMismatch":"Wpis krotki {entry} jest nieprawidłowego typu","tupleSizeIndeterminateSrc":"Niezgodność rozmiaru krotki; oczekiwano {expected}, ale otrzymano nieokreślony","tupleSizeIndeterminateSrcDest":"Niezgodność rozmiaru krotki; oczekiwano {expected}, a otrzymano rozmiar nieokreślony","tupleSizeMismatch":"Niezgodność rozmiaru krotki; oczekiwano {expected}, ale otrzymano {received}","tupleSizeMismatchIndeterminateDest":"Niezgodność rozmiaru krotki; oczekiwano {expected}, a otrzymano {received}","typeAliasInstanceCheck":"Alias typu utworzony za pomocą instrukcji „{type}” nie może być użyty do sprawdzania wystąpień i klas","typeAssignmentMismatch":"Nie można przypisać typu „{sourceType}” do typu „{destType}”","typeBound":"Typ „{sourceType}” jest niezgodny z typem powiązanym „{destType}” dla zmiennej typu „{name}”","typeConstrainedTypeVar":"Typ „{type}” jest niezgodny ze zmienną typu ograniczonego „{name}”","typeIncompatible":"Typ „{sourceType}” jest niezgodny z „{destType}”","typeNotClass":"Typ „{type}” nie jest klasą","typeNotStringLiteral":"„{type}” nie jest literałem ciągu","typeOfSymbol":"Typ nazwy „{name}” jest to „{type}”","typeParamSpec":"Typ „{type}” jest niezgodny ze specyfikacją ParamSpec „{name}”","typeUnsupported":"Typ „{type}” nie jest obsługiwany","typeVarDefaultOutOfScope":"Zmienna typu „{name}” nie wchodzi w zakres","typeVarIsContravariant":"Parametr typu „{name}” jest kontrawariantny, ale „{sourceType}” nie jest nadtypem „{destType}”","typeVarIsCovariant":"Parametr typu „{name}” jest kowariantny, ale „{sourceType}” nie jest podtypem „{destType}”","typeVarIsInvariant":"Parametr typu „{name}” jest niezmienny, ale „{sourceType}” nie jest taki sam jak „{destType}”","typeVarNotAllowed":"Typ TypeVar nie jest dozwolony dla sprawdzania wystąpienia lub klasy","typeVarTupleRequiresKnownLength":"Nie można powiązać parametru TypeVarTuple z krotką o nieznanej długości","typeVarUnnecessarySuggestion":"Zamiast tego użyj elementu {type}","typeVarUnsolvableRemedy":"Podaj przeciążenie, które określa zwracany typ, gdy nie podano argumentu","typeVarsMissing":"Brak zmiennych typu: {names}","typedDictBaseClass":"Klasa „{type}” nie jest typem TypedDict","typedDictClassNotAllowed":"Klasa TypedDict nie jest dozwolona na potrzeby sprawdzania wystąpienia lub klasy","typedDictClosedExtraNotAllowed":"Nie można dodać elementu \\"{name}\\"","typedDictClosedExtraTypeMismatch":"Nie można dodać elementu \\"{name}\\" z typem „{type}”","typedDictClosedFieldNotRequired":"Nie można dodać elementu \\"{name}\\", ponieważ musi on mieć wartość NotRequired","typedDictExtraFieldNotAllowed":"Element „{name}” nie jest obecny w typie „{type}”","typedDictExtraFieldTypeMismatch":"Typ „{name}” jest niezgodny z typem „__extra_items__” w typie „{type}”","typedDictFieldMissing":"Brak nazwy „{name}” w „{type}”","typedDictFieldNotReadOnly":"Nazwa „{name}” nie jest tylko do odczytu w „{type}”","typedDictFieldNotRequired":"Nazwa „{name}” nie jest wymagana w typie „{type}”","typedDictFieldRequired":"Nazwa „{name}” jest wymagana w typie „{type}”","typedDictFieldTypeMismatch":"Nie można przypisać typu „{type}” do elementu „{name}”","typedDictFieldUndefined":"Nazwa „{name}” jest niezdefiniowanym elementem w typie „{type}”","typedDictFinalMismatch":"Typ „{sourceType}” jest niezgodny z typem „{destType}” z powodu niezgodności @final","typedDictKeyAccess":"Użyj elementu [\\"{name}\\"], aby odwołać się do elementu w TypedDict","typedDictNotAllowed":"Funkcja TypedDict nie może być używana do sprawdzania wystąpień lub klas","unhashableType":"Typ „{type}” nie jest wartością skrótu","uninitializedAbstractVariable":"zmienna wystąpienia „{name}” jest zdefiniowana w abstrakcyjnej klasie bazowej „{classType}” ale nie została zainicjowana","unreachableExcept":"Typ „{exceptionType}” jest podklasą typu „{parentType}”","useDictInstead":"Użyj funkcji Dict[T1, T2], aby wskazać typ słownika","useListInstead":"Użyj funkcji List[T], aby wskazać typ listy, lub Union[T1, T2], aby wskazać typ unii","useTupleInstead":"Użyj Tuple[T1, ..., Tn], aby wskazać typ krotki lub Union[T1, T2], aby wskazać typ unii","useTypeInstead":"Zamiast tego użyj typu Type[T].","varianceMismatchForClass":"Wariancja argumentu typu „{typeVarName}” jest niezgodna z klasą bazową „{className}”","varianceMismatchForTypeAlias":"Wariancja argumentu typu „{typeVarName}” jest niezgodna z parametrem „{typeAliasParam}”"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.pt-br.json":
/*!*******************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.pt-br.json ***!
  \*******************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Criar Stub de Tipo","createTypeStubFor":"Criar stub de tipo para \\"{moduleName}\\"","executingCommand":"Executando comando","filesToAnalyzeCount":"{count} arquivos a serem analisados","filesToAnalyzeOne":"1 arquivo a ser analisado","findingReferences":"Localizando referências","organizeImports":"Organizar as importações","renameShadowedFile":"Renomear \\"{oldFile}\\" para \\"{newFile}\\""},"Completion":{"autoImportDetail":"Importação automática","indexValueDetail":"Valor do índice"},"Diagnostic":{"abstractMethodInvocation":"O método \\"{method}\\" não pode ser chamado porque é abstrato e não está implementado","annotatedParamCountMismatch":"Incompatibilidade de contagem de anotações de parâmetro: esperado {expected}, mas recebido {received}","annotatedTypeArgMissing":"Esperava-se um argumento de tipo e uma ou mais anotações para \\"Annotated\\"","annotationFormatString":"As anotações de tipo não podem usar literais de cadeia de caracteres de formato (cadeias de caracteres f)","annotationNotSupported":"Anotação de tipo sem suporte para esta instrução","annotationSpansStrings":"Anotações de tipo não podem abranger vários literais de cadeia de caracteres","annotationStringEscape":"Anotações de tipo não podem conter caracteres de escape","argAssignment":"O argumento do tipo \\"{argType}\\" não pode ser atribuído ao parâmetro do tipo \\"{paramType}\\"","argAssignmentFunction":"O argumento do tipo \\"{argType}\\" não pode ser atribuído ao parâmetro do tipo \\"{paramType}\\" na função \\"{functionName}\\"","argAssignmentParam":"O argumento do tipo \\"{argType}\\" não pode ser atribuído ao parâmetro \\"{paramName}\\" do tipo \\"{paramType}\\"","argAssignmentParamFunction":"O argumento do tipo \\"{argType}\\" não pode ser atribuído ao parâmetro \\"{paramName}\\" do tipo \\"{paramType}\\" na função \\"{functionName}\\"","argMissingForParam":"Argumento ausente para o parâmetro {name}","argMissingForParams":"Argumentos ausentes para os parâmetros {names}","argMorePositionalExpectedCount":"Esperavam-se mais {expected} argumentos posicionais","argMorePositionalExpectedOne":"Espera-se mais um argumento posicional","argPositional":"Argumento posicional esperado","argPositionalExpectedCount":"{expected} argumentos posicionais esperados","argPositionalExpectedOne":"Argumento posicional esperado 1","argTypePartiallyUnknown":"O tipo de argumento é parcialmente desconhecido","argTypeUnknown":"O tipo de argumento é desconhecido","assertAlwaysTrue":"A expressão assert sempre é avaliada como true","assertTypeArgs":"\\"assert_type\\" espera dois argumentos posicionais","assertTypeTypeMismatch":"Incompatibilidade \\"assert_type\\": esperava-se \\"{expected}\\", mas recebeu \\"{received}\\"","assignmentExprComprehension":"O destino da expressão de atribuição \\"{name}\\" não pode usar o mesmo nome da compreensão para o destino","assignmentExprContext":"A expressão de atribuição deve estar dentro de módulo, função ou lambda","assignmentExprInSubscript":"Expressões de atribuição em um subscrito são compatíveis apenas no Python 3.10 e mais recente","assignmentInProtocol":"As variáveis de instância ou classe dentro de uma classe Protocol devem ser declaradas explicitamente dentro do corpo da classe","assignmentTargetExpr":"A expressão não pode ser o destino de atribuição","asyncNotInAsyncFunction":"Uso de \\"async\\" não permitido fora da função assíncrona","awaitIllegal":"O uso de \\"await\\" requer o Python 3.5 ou mais recente","awaitNotAllowed":"Anotações de tipo não podem usar \\"await\\"","awaitNotInAsync":"\\"await\\" permitido somente dentro da função assíncrona","backticksIllegal":"Não há suporte para expressões delimitadas por backticks no Python 3.x. Use repr em vez disso","baseClassCircular":"A classe não pode derivar de si mesma","baseClassFinal":"A classe base \\"{type}\\" está marcada como final e não pode ser subclasse","baseClassIncompatible":"Classes base de {type} são mutuamente incompatíveis","baseClassInvalid":"O argumento para a classe deve ser uma classe base","baseClassMethodTypeIncompatible":"Classes base para a classe \\"{classType}\\" definem o método \\"{name}\\" de maneira incompatível","baseClassUnknown":"O tipo de classe base é desconhecido, ocultando o tipo de classe derivada","baseClassVariableTypeIncompatible":"Classes base para a classe \\"{classType}\\" definem a variável \\"{name}\\" de maneira incompatível","binaryOperationNotAllowed":"Operador binário não permitido na anotação de tipo","bindTypeMismatch":"Não foi possível associar o método \\"{methodName}\\" porque \\"{type}\\" não é atribuível ao parâmetro \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" só pode ser usado dentro de um loop","callableExtraArgs":"Esperava-se apenas dois argumentos de tipo para \\"Callable\\"","callableFirstArg":"Lista de tipos de parâmetro esperado ou \\"...\\"","callableNotInstantiable":"Não é possível criar uma instância do tipo \\"{type}\\"","callableSecondArg":"Tipo de retorno esperado como segundo argumento de tipo para \\"Callable\\"","casePatternIsIrrefutable":"O padrão irrefutável é permitido somente para a última instrução case","classAlreadySpecialized":"O tipo \\"{type}\\" já é especializado","classDecoratorTypeUnknown":"Um decorador de classe sem tipo obscurece o tipo de classe. Ignorando o decorador","classDefinitionCycle":"A definição de classe para \\"{name}\\" depende de si mesma","classGetItemClsParam":"A substituição__class_getitem__ deve usar um parâmetro \\"cls\\"","classMethodClsParam":"Os métodos de classe devem usar um parâmetro \\"cls\\"","classNotRuntimeSubscriptable":"O subscrito para a classe \\"{name}\\" gerará uma exceção de runtime. Coloque a anotação de tipo entre aspas","classPatternBuiltInArgPositional":"O padrão de classe aceita apenas sub-padrão posicional","classPatternPositionalArgCount":"Muitos padrões posicionais para a classe \\"{type}\\"; esperado {expected} mas recebido {received}","classPatternTypeAlias":"\\"{type}\\" não pode ser usado em um padrão de classe porque é um alias de tipo especializado","classPropertyDeprecated":"As propriedades de classe foram preteridas no Python 3.11 e não terão suporte no Python 3.13","classTypeParametersIllegal":"A sintaxe do parâmetro de tipo de classe requer o Python 3.12 ou mais recente","classVarFirstArgMissing":"Um argumento de tipo era esperado após \\"ClassVar\\"","classVarNotAllowed":"\\"ClassVar\\" não é permitido neste contexto","classVarOverridesInstanceVar":"A variável de classe \\"{name}\\" substitui a variável de instância do mesmo nome na classe \\"{className}\\"","classVarTooManyArgs":"Espera-se apenas um argumento de tipo após \\"ClassVar\\"","classVarWithTypeVar":"O tipo \\"ClassVar\\" não pode incluir variáveis de tipo","clsSelfParamTypeMismatch":"O tipo de parâmetro \\"{name}\\" deve ser um supertipo de sua classe \\"{classType}\\"","codeTooComplexToAnalyze":"O código é muito complexo para ser analisado. Reduza a complexidade refatorando em sub-rotinas ou reduzindo caminhos de código condicionais","collectionAliasInstantiation":"O tipo \\"{type}\\" não pode ser instanciado, use \\"{alias}\\" em vez disso","comparisonAlwaysFalse":"A condição sempre será avaliada como False, pois os tipos \\"{leftType}\\" e \\"{rightType}\\" não têm sobreposição","comparisonAlwaysTrue":"A condição sempre será avaliada como True, pois os tipos \\"{leftType}\\" e \\"{rightType}\\" não têm sobreposição","comprehensionInDict":"A compreensão não pode ser usada com outras entradas de dicionário","comprehensionInSet":"A compreensão não pode ser usada com outras entradas definidas","concatenateContext":"\\"Concatenate\\" não é permitido nesse contexto","concatenateParamSpecMissing":"O último tipo de argumento para \\"Concatenate\\" deve ser um ParamSpec ou \\"...\\"","concatenateTypeArgsMissing":"\\"Concatenate\\" requer pelo menos dois argumentos de tipo","conditionalOperandInvalid":"Operando condicional inválido do tipo \\"{type}\\"","constantRedefinition":"\\"{name}\\" é constante (porque está em maiúsculas) e não pode ser redefinido","constructorNoArgs":"Nenhum argumento esperado para o construtor \\"{type}\\"","constructorParametersMismatch":"Incompatibilidade entre a assinatura de __new__ e __init__ na classe \\"{classType}\\"","containmentAlwaysFalse":"A expressão sempre será avaliada como False, pois os tipos \\"{leftType}\\" e \\"{rightType}\\" não têm sobreposição","containmentAlwaysTrue":"A expressão sempre será avaliada como True, pois os tipos \\"{leftType}\\" e \\"{rightType}\\" não têm sobreposição","continueInFinally":"\\"continue\\" não pode ser usado em uma cláusula finally","continueOutsideLoop":"\\"continue\\" só pode ser usado dentro de um loop","coroutineInConditionalExpression":"A expressão condicional faz referência à corrotina, que sempre é avaliada como True","dataClassBaseClassFrozen":"Uma classe não congelada não pode herdar de uma classe congelada","dataClassBaseClassNotFrozen":"Uma classe congelada não pode herdar de uma classe que não está congelada","dataClassConverterFunction":"O argumento do tipo \\"{argType}\\" não é um conversor válido para o campo \\"{fieldName}\\" do tipo \\"{fieldType}\\"","dataClassConverterOverloads":"Nenhuma sobrecarga de \\"{funcName}\\" são conversores válidos para o campo \\"{fieldName}\\" do tipo \\"{fieldType}\\"","dataClassFieldWithDefault":"Campos sem valores padrão não podem aparecer após campos com valores padrão","dataClassFieldWithPrivateName":"O campo Dataclass não pode usar o nome privado","dataClassFieldWithoutAnnotation":"O campo Dataclass sem anotação de tipo causará uma exceção de runtime","dataClassPostInitParamCount":"Contagem de parâmetros de dataclasse __post_init__ incorreta. O número de campos InitVar é {expected}","dataClassPostInitType":"Incompatibilidade de tipo de parâmetro de método de dataclasse __post_init__ para o campo \\"{fieldName}\\"","dataClassSlotsOverwrite":"__slots__ já está definido na classe","dataClassTransformExpectedBoolLiteral":"Expressão esperada que é avaliada estaticamente como True ou False","dataClassTransformFieldSpecifier":"Esperava-se tupla de classes ou funções, mas recebeu o tipo \\"{type}\\"","dataClassTransformPositionalParam":"Todos os argumentos para \\"dataclass_transform\\" devem ser argumentos de palavra-chave","dataClassTransformUnknownArgument":"O argumento \\"{name}\\" dataclass_transform não é compatível","dataProtocolInSubclassCheck":"Protocolos de dados (que incluem atributos que não são de método) não são permitidos em chamadas issubclass","declaredReturnTypePartiallyUnknown":"O tipo de retorno declarado, \\"{returnType}\\", é parcialmente desconhecido","declaredReturnTypeUnknown":"O tipo de retorno declarado é desconhecido","defaultValueContainsCall":"Chamadas de função e objetos mutáveis não permitidos na expressão de valor padrão do parâmetro","defaultValueNotAllowed":"O parâmetro com \\"*\\" ou \\"**\\" não pode ter valor padrão","delTargetExpr":"A expressão não pode ser excluída","deprecatedClass":"A classe \\"{name}\\" foi preterida","deprecatedConstructor":"O construtor da classe \\"{name}\\" foi preterido","deprecatedDescriptorDeleter":"O método \\"__delete__\\" para o descritor \\"{name}\\" está preterido","deprecatedDescriptorGetter":"O método \\"__get__\\" para o descritor \\"{name}\\" está preterido","deprecatedDescriptorSetter":"O método \\"__set__\\" para o descritor \\"{name}\\" está preterido","deprecatedFunction":"A função \\"{name}\\" está obsoleta","deprecatedMethod":"O método \\"{name}\\" na classe \\"{className}\\" está obsoleto","deprecatedPropertyDeleter":"O excluídor da propriedade \\"{name}\\" foi preterido","deprecatedPropertyGetter":"O getter da propriedade \\"{name}\\" foi preterido","deprecatedPropertySetter":"O setter da propriedade \\"{name}\\" está preterido","deprecatedType":"Este tipo foi preterido no Python {version}. Use \\"{replacement}\\" em vez disso","dictExpandIllegalInComprehension":"Expansão de dicionário não permitida na compreensão","dictInAnnotation":"Expressão de dicionário não permitida na anotação de tipo","dictKeyValuePairs":"Entradas de dicionário devem conter pares chave/valor","dictUnpackIsNotMapping":"Mapeamento esperado para o operador de desempacotamento de dicionário","dunderAllSymbolNotPresent":"\\"{name}\\" está especificado no __all__ mas não está presente no módulo","duplicateArgsParam":"Somente um parâmetro \\"*\\" permitido","duplicateBaseClass":"Classe base duplicada não permitida","duplicateCapturePatternTarget":"O destino de captura \\"{name}\\" não pode aparecer mais de uma vez dentro do mesmo padrão","duplicateCatchAll":"Somente uma cláusula de exceção catch-all é permitida","duplicateEnumMember":"O membro de enumeração \\"{name}\\" já está declarado","duplicateGenericAndProtocolBase":"Somente uma classe base Generic[...] ou Protocol[...] é permitida","duplicateImport":"\\"{importName}\\" foi importado mais de uma vez","duplicateKeywordOnly":"Somente um separador \\"*\\" permitido","duplicateKwargsParam":"Somente um parâmetro \\"**\\" é permitido","duplicateParam":"Nome de parâmetro \\"{name}\\" duplicado","duplicatePositionOnly":"Somente um parâmetro \\"/\\" permitido","duplicateStarPattern":"Somente um padrão \\"*\\" permitido em uma sequência de padrões","duplicateStarStarPattern":"Somente uma entrada \\"**\\" é permitida","duplicateUnpack":"Somente uma operação unpack é permitida na lista","ellipsisAfterUnpacked":"\\"...\\" não pode ser usado com um TypeVarTuple ou tupla descompactado","ellipsisContext":"\\"...\\" não é permitido neste contexto","ellipsisSecondArg":"\\"...\\" é permitido apenas como o segundo de dois argumentos","enumClassOverride":"A classe Enum \\"{name}\\" é final e não pode ser subclasse","exceptionGroupIncompatible":"A sintaxe do grupo de exceção (\\"exceto*\\") requer o Python 3.11 ou mais recente","exceptionTypeIncorrect":"\\"{type}\\" não deriva de BaseException","exceptionTypeNotClass":"\\"{type}\\" não é uma classe de exceção válida","exceptionTypeNotInstantiable":"O construtor para o tipo de exceção \\"{type}\\" requer um ou mais argumentos","expectedAfterDecorator":"Função ou declaração de classe esperada após o decorador","expectedArrow":"Esperava-se \\"->\\" seguido pela anotação de tipo de retorno","expectedAsAfterException":"Espera-se \\"as\\" após o tipo de exceção","expectedAssignRightHandExpr":"Expressão esperada à direita de \\"=\\"","expectedBinaryRightHandExpr":"Expressão esperada à direita do operador","expectedBoolLiteral":"Espera-se True ou False","expectedCase":"Instrução \\"case\\" esperada","expectedClassName":"Nome de classe esperado","expectedCloseBrace":"\\"{\\" não foi fechado","expectedCloseBracket":"\\"[\\" não foi fechado","expectedCloseParen":"\\"(\\" não foi fechado","expectedColon":"Esperava-se \\":\\"","expectedComplexNumberLiteral":"Literal de número complexo esperado para correspondência de padrões","expectedDecoratorExpr":"Formulário de expressão sem suporte para decorador antes do Python 3.9","expectedDecoratorName":"Nome do decorador esperado","expectedDecoratorNewline":"Nova linha esperada no final do decorador","expectedDelExpr":"Expressão esperada após \\"del\\"","expectedElse":"Esperava-se #else","expectedEquals":"Esperava-se \\"=\\"","expectedExceptionClass":"Classe ou objeto de exceção inválido","expectedExceptionObj":"Objeto de exceção esperado: classe de exceção ou None","expectedExpr":"Expressão esperada","expectedFunctionAfterAsync":"Definição de função esperada após \\"assíncrona\\"","expectedFunctionName":"Nome da função esperado após \\"def\\"","expectedIdentifier":"Identificador esperado","expectedImport":"\\"importação\\" esperada","expectedImportAlias":"Símbolo esperado após \\"as\\"","expectedImportSymbols":"Esperado um ou mais nomes de símbolo após a importação","expectedIn":"Esperava-se \\"in\\"","expectedInExpr":"Expressão esperada após \\"in\\"","expectedIndentedBlock":"Bloco recuado esperado","expectedMemberName":"Nome de membro esperado após \\".\\"","expectedModuleName":"Nome do módulo esperado","expectedNameAfterAs":"Nome de símbolo esperado após \\"as\\"","expectedNamedParameter":"O parâmetro de palavra-chave deve seguir \\"*\\"","expectedNewline":"Nova linha esperada","expectedNewlineOrSemicolon":"As instruções devem ser separadas por novas linhas ou ponto e vírgula","expectedOpenParen":"Esperava-se \\"(\\"","expectedParamName":"Nome do parâmetro esperado","expectedPatternExpr":"Expressão padrão esperada","expectedPatternSubjectExpr":"Expressão de assunto padrão esperada","expectedPatternValue":"Expressão de valor padrão esperada da forma \\"a.b\\"","expectedReturnExpr":"Expressão esperada após \\"return\\" ","expectedSliceIndex":"Expressão de índice ou fatia esperada","expectedTypeNotString":"Tipo esperado, mas recebeu um literal de cadeia de caracteres","expectedTypeParameterName":"Nome do parâmetro de tipo esperado","expectedYieldExpr":"Expressão esperada na instrução yield","finalClassIsAbstract":"A classe \\"{type}\\" está marcada como final e deve implementar todos os símbolos abstratos","finalContext":"\\"Final\\" não é permitido neste contexto","finalMethodOverride":"O método \\"{name}\\" não pode substituir o método final definido na classe \\"{className}\\"","finalNonMethod":"A função \\"{name}\\" não pode ser marcada como @final porque não é um método","finalReassigned":"\\"{name}\\" está declarado como Final e não pode ser reatribuído","finalRedeclaration":"\\"{name}\\" foi declarado anteriormente como Final","finalRedeclarationBySubclass":"\\"{name}\\" não pode ser redeclarado porque a classe pai \\"{className}\\" a declara como Final","finalTooManyArgs":"Argumento de tipo único esperado após \\"Final\\"","finalUnassigned":"\\"{name}\\" está declarado como Final, mas o valor não foi atribuído","formatStringBrace":"Chave de fechamento única não permitida no literal de cadeia de caracteres f. Usar chave de fechamento dupla","formatStringBytes":"Literais de cadeia de caracteres de formato (cadeia de caracteres f) não podem ser binárias","formatStringDebuggingIllegal":"O especificador de depuração de cadeia de caracteres f \\"=\\" requer o Python 3.8 ou mais recente","formatStringEscape":"Sequência de escape (barra invertida) não permitida na parte de expressão da cadeia de caracteres f em versões anteriores ao Python 3.12","formatStringExpectedConversion":"Esperava-se um especificador de conversão após \\"!\\" na cadeia de caracteres f","formatStringIllegal":"Literais de cadeia de caracteres de formato (cadeias de caracteres f) exigem Python 3.6 ou mais recente","formatStringInPattern":"Cadeia de caracteres de formato não permitida no padrão","formatStringNestedFormatSpecifier":"Expressões aninhadas muito profundamente dentro do especificador de cadeia de caracteres de formato","formatStringNestedQuote":"Cadeias de caracteres aninhadas em uma cadeia de caracteres f não podem usar o mesmo caractere de aspas que a cadeia de caracteres f antes do Python 3.12","formatStringUnicode":"As literais de cadeia de caracteres de formato (f-strings) não podem ser unicode","formatStringUnterminated":"Expressão não finalizada na cadeia de caracteres f. \\"}\\" era esperado","functionDecoratorTypeUnknown":"Um decorador de função sem tipo obscurece o tipo de função. Ignorando o decorador","functionInConditionalExpression":"Função de referências de expressão condicional que sempre é avaliada como True","functionTypeParametersIllegal":"A sintaxe do parâmetro de tipo de função requer o Python 3.12 ou mais recente","futureImportLocationNotAllowed":"As importações __future__ devem estar no início do arquivo","generatorAsyncReturnType":"O tipo de retorno da função geradora assíncrona deve ser compatível com \\"AsyncGenerator[{yieldType}, Any]\\"","generatorNotParenthesized":"As expressões de gerador devem estar entre parênteses se não forem argumentos exclusivos","generatorSyncReturnType":"O tipo de retorno da função de gerador deve ser compatível com \\"Generator[{yieldType}, Any, Any]\\"","genericBaseClassNotAllowed":"A classe base \\"Generic\\" não pode ser usada com sintaxe de parâmetro de tipo","genericClassAssigned":"O tipo de classe genérica não pode ser atribuído","genericClassDeleted":"O tipo de classe genérica não pode ser excluído","genericInstanceVariableAccess":"O acesso à variável de instância genérica por meio da classe é ambíguo","genericNotAllowed":"__arglist não é válido neste contexto","genericTypeAliasBoundTypeVar":"O alias de tipo genérico dentro da classe não pode usar variáveis de tipo associado {names}","genericTypeArgMissing":"\\"Generic\\" requer pelo menos um argumento de tipo","genericTypeArgTypeVar":"O argumento de tipo para \\"Generic\\" deve ser uma variável de tipo","genericTypeArgUnique":"Os argumentos de tipo para \\"Genérico\\" devem ser exclusivos","globalReassignment":"\\"{name}\\" é atribuído antes da declaração global","globalRedefinition":"\\"{name}\\" já foi declarado global","implicitStringConcat":"Concatenação de cadeia de caracteres implícita não permitida","importCycleDetected":"Ciclo detectado na cadeia de importação","importDepthExceeded":"A profundidade da cadeia de importação excedeu {depth}","importResolveFailure":"Não foi possível resolver a importação \\"{importName}\\"","importSourceResolveFailure":"Não foi possível resolver a importação \\"{importName}\\" da origem","importSymbolUnknown":"\\"{name}\\" é um símbolo de importação desconhecido","incompatibleMethodOverride":"O método \\"{name}\\" substitui a classe \\"{className}\\" de maneira incompatível","inconsistentIndent":"O valor de recuo não corresponde ao recuo anterior","inconsistentTabs":"Uso inconsistente de guias e espaços no recuo","initMustReturnNone":"O tipo de retorno de \\"__init__\\" deve ser None","initSubclassCallFailed":"Argumentos de palavra-chave incorretos para o método __init_subclass__","initSubclassClsParam":"A substituição __init_subclass__ deve usar um parâmetro \\"cls\\"","initVarNotAllowed":"\\"InitVar\\" não é permitido neste contexto","instanceMethodSelfParam":"Os métodos de instância devem usar um parâmetro \\"self\\"","instanceVarOverridesClassVar":"A variável de instância \\"{name}\\" substitui a variável de classe de mesmo nome na classe \\"{className}\\"","instantiateAbstract":"Não é possível instanciar a classe abstrata \\"{type}\\"","instantiateProtocol":"Não é possível instanciar a classe de protocolo \\"{type}\\"","internalBindError":"Erro interno ao associar o arquivo de associação \\"{file}\\": {message}","internalParseError":"Ocorreu um erro interno ao analisar o arquivo \\"{file}\\": {message}","internalTypeCheckingError":"Erro interno ao digitar o arquivo de verificação \\"{file}\\": {message}","invalidIdentifierChar":"Caractere inválido no identificador","invalidStubStatement":"A instrução não faz sentido dentro de um arquivo stub de tipo","invalidTokenChars":"Caractere inválido \\"{text}\\" no token","isInstanceInvalidType":"O segundo argumento para \\"instance\\" deve ser uma classe ou tupla de classes","isSubclassInvalidType":"O segundo argumento para \\"issubclass\\" deve ser uma classe ou tupla de classes","keyValueInSet":"Pares chave/valor não são permitidos em um conjunto","keywordArgInTypeArgument":"Argumentos de palavra-chave não podem ser usados em listas de argumentos de tipo","keywordOnlyAfterArgs":"Separador de argumento somente palavra-chave não permitido após o parâmetro \\"*\\"","keywordParameterMissing":"Um ou mais parâmetros de palavra-chave devem seguir o parâmetro \\"*\\"","keywordSubscriptIllegal":"Não há suporte para argumentos de palavra-chave em subscritos","lambdaReturnTypePartiallyUnknown":"O tipo de retorno de lambda, \\"{returnType}\\", é parcialmente desconhecido","lambdaReturnTypeUnknown":"O tipo de retorno de lambda é desconhecido","listAssignmentMismatch":"A expressão com o tipo \\"{type}\\" não pode ser atribuída à lista de destino","listInAnnotation":"Expressão de lista não permitida na anotação de tipo","literalEmptyArgs":"Um ou mais argumentos de tipo esperados após \\"Literal\\"","literalNotAllowed":"\\"Literal\\" não pode ser usado nesse contexto sem um argumento de tipo","literalNotCallable":"O tipo literal não pode ser instanciado","literalUnsupportedType":"Os argumentos de tipo para \\"Literal\\" devem ser None, um valor literal (int, bool, str ou bytes) ou um valor de enumeração","matchIncompatible":"As instruções de correspondência exigem Python 3.10 ou mais recente","matchIsNotExhaustive":"Os casos dentro da instrução match não lidam exaustivamente com todos os valores","maxParseDepthExceeded":"Profundidade máxima de análise excedida. Divida a expressão em subexpressões menores","memberAccess":"Não é possível acessar o membro \\"{name}\\" para o tipo \\"{type}\\"","memberDelete":"Não é possível excluir o membro \\"{name}\\" para o tipo \\"{type}\\"","memberSet":"Não é possível atribuir o membro \\"{name}\\" para o tipo \\"{type}\\"","metaclassConflict":"A metaclasse de uma classe derivada deve ser uma subclasse das metaclasses de todas as suas classes base","metaclassDuplicate":"Apenas uma metaclasse pode ser fornecida","metaclassIsGeneric":"A metaclasse não pode ser genérica","methodNotDefined":"Método \\"{name}\\" não definido","methodNotDefinedOnType":"Método \\"{name}\\" não definido no tipo \\"{type}\\"","methodOrdering":"Não é possível criar ordenação de método consistente","methodOverridden":"\\"{name}\\" substitui o método de mesmo nome na classe \\"{className}\\" pelo tipo incompatível \\"{type}\\"","methodReturnsNonObject":"O método \\"{name}\\" não retorna um objeto","missingSuperCall":"O método \\"{methodName}\\" não chama o método do mesmo nome na classe pai","moduleAsType":"O módulo não pode ser usado como um tipo.","moduleNotCallable":"O módulo não pode ser chamado","moduleUnknownMember":"\\"{memberName}\\" não é um membro conhecido do módulo \\"{moduleName}\\"","namedExceptAfterCatchAll":"Uma cláusula except nomeada não pode aparecer após a cláusula catch-all except","namedParamAfterParamSpecArgs":"O parâmetro de palavra-chave \\"{name}\\" não pode aparecer na assinatura após o parâmetro args ParamSpec","namedTupleEmptyName":"Nomes dentro de uma tupla nomeada não podem ficar vazios","namedTupleEntryRedeclared":"Não é possível substituir \\"{name}\\" porque a classe pai \\"{className}\\" é uma tupla nomeada","namedTupleFirstArg":"Nome de classe de tupla nomeado esperado como primeiro argumento","namedTupleMultipleInheritance":"Não há suporte para herança múltipla com NamedTuple","namedTupleNameKeyword":"Os nomes dos campos não podem ser uma palavra-chave","namedTupleNameType":"Tupla de duas entradas esperada especificando o nome e o tipo de entrada","namedTupleNameUnique":"Os nomes dentro de uma tupla nomeada devem ser exclusivos","namedTupleNoTypes":"\\"namedtuple\\" não fornece tipos para entradas de tupla. Em vez disso, use \\"NamedTuple\\"","namedTupleSecondArg":"Lista de entrada de tupla nomeada esperada como segundo argumento","newClsParam":"A substituição __new__ deve usar um parâmetro \\"cls\\"","newTypeAnyOrUnknown":"O segundo argumento para NewType deve ser uma classe conhecida, não Qualquer ou Desconhecido","newTypeBadName":"O primeiro argumento para NewType deve ser um literal de cadeia de caracteres","newTypeLiteral":"NewType não pode ser usado com o tipo Literal","newTypeNameMismatch":"NewType deve ser atribuído a uma variável com o mesmo nome","newTypeNotAClass":"Classe esperada como segundo argumento para NewType","newTypeParamCount":"NewType requer dois argumentos posicionais","newTypeProtocolClass":"NewType não pode ser usado com tipo estrutural (um protocolo ou classe TypedDict)","noOverload":"Nenhuma sobrecarga para \\"{name}\\" corresponde aos argumentos fornecidos","noReturnContainsReturn":"A função com o tipo de retorno declarado \\"NoReturn\\" não pode incluir uma instrução return","noReturnContainsYield":"A função com o tipo de retorno declarado \\"NoReturn\\" não pode incluir uma instrução yield","noReturnReturnsNone":"Função com tipo de retorno declarado \\"NoReturn\\" não pode retornar \\"None\\"","nonDefaultAfterDefault":"O argumento não padrão segue o argumento padrão","nonLocalInModule":"Declaração não local não permitida no nível do módulo","nonLocalNoBinding":"Nenhuma associação para \\"{name}\\" não local encontrada","nonLocalReassignment":"\\"{name}\\" é atribuído antes da declaração não local","nonLocalRedefinition":"\\"{name}\\" já foi declarado não local","noneNotCallable":"O objeto do tipo \\"None\\" não pode ser chamado","noneNotIterable":"O objeto do tipo \\"None\\" não pode ser usado como valor iterável","noneNotSubscriptable":"O objeto do tipo \\"None\\" não é subscrito","noneNotUsableWith":"O objeto do tipo \\"None\\" não pode ser usado com \\"with\\"","noneOperator":"Operador \\"{operator}\\" incompatível com \\"None\\"","noneUnknownMember":"\\"{name}\\" não é um membro conhecido de \\"None\\"","notRequiredArgCount":"Argumento de tipo único esperado após \\"NotRequired\\"","notRequiredNotInTypedDict":"\\"NotRequired\\" não é permitido neste contexto","objectNotCallable":"O objeto do tipo \\"{type}\\" não pode ser chamado","obscuredClassDeclaration":"A declaração de classe \\"{name}\\" está obscurecida por uma declaração de mesmo nome","obscuredFunctionDeclaration":"A declaração de função \\"{name}\\" é obscurecida por uma declaração de mesmo nome","obscuredMethodDeclaration":"A declaração de método \\"{name}\\" é obscurecida por uma declaração de mesmo nome","obscuredParameterDeclaration":"A declaração de parâmetro \\"{name}\\" é obscurecida por uma declaração de mesmo nome","obscuredTypeAliasDeclaration":"A declaração de alias de tipo \\"{name}\\" é obscurecida por uma declaração de mesmo nome","obscuredVariableDeclaration":"A declaração \\"{name}\\" é obscurecida por uma declaração de mesmo nome","operatorLessOrGreaterDeprecated":"O operador \\"<>\\" não é compatível no Python 3. Use \\"!=\\" em vez disso","optionalExtraArgs":"Espera-se um argumento de tipo após \\"Opcional\\"","orPatternIrrefutable":"Padrão irrefutável permitido somente como o último subpadrão em um padrão \\"or\\"","orPatternMissingName":"Todos os subpadrões dentro de um padrão \\"ou\\" devem ter como destino os mesmos nomes","overlappingKeywordArgs":"O dicionário digitado se sobrepõe ao parâmetro de palavra-chave: {names}","overlappingOverload":"A sobrecarga {obscured} para \\"{name}\\" nunca será usada porque seus parâmetros se sobrepõem à sobrecarga {obscuredBy}","overloadAbstractMismatch":"Os métodos sobrecarregados devem ser abstratos ou não","overloadClassMethodInconsistent":"Sobrecargas para \\"{name}\\" usam @classmethod inconsistentemente","overloadFinalInconsistencyImpl":"A sobrecarga para \\"{name}\\" está marcada como @final mas a implementação não está","overloadFinalInconsistencyNoImpl":"A sobrecarga {index} para \\"{name}\\" está marcada como @final mas a sobrecarga 1 não está","overloadImplementationMismatch":"A implementação sobrecarregada não é consistente com a assinatura da sobrecarga {index}","overloadReturnTypeMismatch":"A sobrecarga {prevIndex} para \\"{name}\\" sobrepõe a sobrecarga {newIndex} e retorna um tipo incompatível","overloadStaticMethodInconsistent":"Sobrecargas para \\"{name}\\" usam @staticmethod inconsistentemente","overloadWithoutImplementation":"\\"{name}\\" está marcado como sobrecarga, mas nenhuma implementação foi fornecida","overriddenMethodNotFound":"O método \\"{name}\\" está marcado como substituição, mas nenhum método base de mesmo nome está presente","overrideDecoratorMissing":"O método \\"{name}\\" não está marcado como substituição, mas está substituindo um método na classe \\"{className}\\"","paramAfterKwargsParam":"O parâmetro não pode seguir o parâmetro \\"**\\"","paramAlreadyAssigned":"O parâmetro \\"{name}\\" já está atribuído","paramAnnotationMissing":"A anotação de tipo está ausente para o parâmetro \\"{name}\\"","paramAssignmentMismatch":"A expressão do tipo \\"{sourceType}\\" não pode ser atribuída ao parâmetro do tipo \\"{paramType}\\"","paramNameMissing":"Nenhum parâmetro chamado \\"{name}\\"","paramSpecArgsKwargsUsage":"Os membros \\"args\\" e \\"kwargs\\" de ParamSpec devem aparecer dentro de uma assinatura de função","paramSpecArgsMissing":"Argumentos para ParamSpec \\"{type}\\" estão ausentes","paramSpecArgsUsage":"O membro \\"args\\" de ParamSpec é válido somente quando usado com o parâmetro *args","paramSpecAssignedName":"ParamSpec deve ser atribuído a uma variável chamada \\"{name}\\"","paramSpecContext":"ParamSpec não é permitido neste contexto","paramSpecDefaultNotTuple":"Reticências esperadas, uma expressão de tupla ou ParamSpec para o valor padrão de ParamSpec","paramSpecFirstArg":"Nome esperado de ParamSpec como primeiro argumento","paramSpecKwargsUsage":"O membro \\"kwargs\\" de ParamSpec é válido somente quando usado com o parâmetro **kwargs","paramSpecNotUsedByOuterScope":"O ParamSpec \\"{name}\\" não tem significado neste contexto","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" tem como escopo um chamador dentro do tipo de retorno e não pode ser referenciado no corpo da função","paramSpecUnknownArg":"ParamSpec não é compatível com mais de um argumento","paramSpecUnknownMember":"\\"{name}\\" não é um membro conhecido de ParamSpec","paramSpecUnknownParam":"\\"{name}\\" é um parâmetro desconhecido para ParamSpec","paramTypeCovariant":"Variável de tipo covariante não pode ser usada no tipo de parâmetro","paramTypePartiallyUnknown":"O tipo de parâmetro \\"{paramName}\\" é parcialmente desconhecido","paramTypeUnknown":"O tipo de parâmetro \\"{paramName}\\" é desconhecido","parenthesizedContextManagerIllegal":"Parênteses dentro da instrução \\"with\\" exigem Python 3.9 ou mais recente","patternNeverMatches":"O padrão nunca será correspondido para o tipo de assunto \\"{type}\\"","positionArgAfterNamedArg":"O argumento posicional não pode aparecer após argumentos de palavra-chave","positionOnlyAfterArgs":"Separador de parâmetro somente de posição não permitido após o parâmetro \\"*\\"","positionOnlyAfterKeywordOnly":"O parâmetro \\"/\\" deve aparecer antes do parâmetro \\"*\\"","positionOnlyAfterNon":"Parâmetro somente de posição não permitido após o parâmetro que não é somente posição","positionOnlyFirstParam":"Separador de parâmetro somente de posição não permitido como primeiro parâmetro","positionOnlyIncompatible":"O separador de parâmetro somente de posição requer o Python 3.8 ou mais recente","privateImportFromPyTypedModule":"\\"{name}\\" não é exportado do módulo \\"{module}\\"","privateUsedOutsideOfClass":"\\"{name}\\" é privado e usado fora da classe na qual é declarado","privateUsedOutsideOfModule":"\\"{name}\\" é privado e usado fora do módulo no qual ele é declarado","propertyOverridden":"\\"{name}\\" substitui incorretamente a propriedade de mesmo nome na classe \\"{className}\\"","propertyStaticMethod":"Métodos estáticos não permitidos para as propriedades getter, setter ou deleter","protectedUsedOutsideOfClass":"\\"{name}\\" está protegido e usado fora da classe na qual está declarado","protocolBaseClass":"A classe de protocolo \\"{classType}\\" não pode derivar da classe \\"{baseType}\\" que não é de protocolo","protocolBaseClassWithTypeArgs":"Argumentos de tipo não são permitidos com a classe Protocol ao usar a sintaxe de parâmetro de tipo","protocolIllegal":"O uso de \\"Protocol\\" requer o Python 3.7 ou mais recente","protocolNotAllowed":"\\"Protocol\\" não pode ser usado nesse contexto","protocolUnsafeOverlap":"A classe se sobrepõe a \\"{name}\\" de forma não segura e pode produzir uma correspondência em runtime","protocolVarianceContravariant":"A variável de tipo \\"{variable}\\" usada no protocolo genérico \\"{class}\\" deve ser contravariante","protocolVarianceCovariant":"A variável de tipo \\"{variable}\\" usada no protocolo genérico \\"{class}\\" deve ser covariante","protocolVarianceInvariant":"A variável de tipo \\"{variable}\\" usada no protocolo genérico \\"{class}\\" deve ser invariável","pyrightCommentInvalidDiagnosticBoolValue":"A diretiva de comentário Pyright deve ser seguida por \\"=\\" e um valor true ou false","pyrightCommentInvalidDiagnosticSeverityValue":"A diretiva de comentário Pyright deve ser seguida por \\"=\\" e um valor de true, false, error, warning, information ou none","pyrightCommentMissingDirective":"O comentário pyright deve ser seguido por uma diretiva (básica ou estrita) ou uma regra de diagnóstico","pyrightCommentNotOnOwnLine":"Comentários pyright usados para controlar as configurações de nível de arquivo devem aparecer em sua própria linha","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" é uma regra de diagnóstico desconhecida para o comentário pyright","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" é um valor inválido para o comentário pyright. True, false, error, warning, information ou none esperados.","pyrightCommentUnknownDirective":"\\"{directive}\\" é uma diretiva desconhecida para o comentário pyright. Esperava-se \\"estrito\\" ou \\"básico\\"","readOnlyArgCount":"Argumento de tipo único esperado após \\"ReadOnly\\"","readOnlyNotInTypedDict":"\\"ReadOnly\\" não é permitido neste contexto","recursiveDefinition":"Não foi possível determinar o tipo de \\"{name}\\" porque ele refere-se a si mesmo","relativeImportNotAllowed":"Importações relativas não podem ser usadas com o formulário \\"import. a\\". Use \\"from . import a\\" em vez disso","requiredArgCount":"Argumento de tipo único esperado após \\"Obrigatório\\"","requiredNotInTypedDict":"\\"Obrigatório\\" não é permitido neste contexto","returnInAsyncGenerator":"A instrução return com valor não é permitida no gerador assíncrono","returnMissing":"Função com tipo de retorno declarado \\"{returnType}\\" deve retornar valor em todos os caminhos de código","returnOutsideFunction":"\\"return\\" só pode ser usado dentro de uma função","returnTypeContravariant":"A variável de tipo contravariante não pode ser usada no tipo de retorno","returnTypeMismatch":"A expressão do tipo \\"{exprType}\\" não pode ser atribuída ao tipo de retorno \\"{returnType}\\"","returnTypePartiallyUnknown":"O tipo de retorno, \\"{returnType}\\", é parcialmente desconhecido","returnTypeUnknown":"O tipo de retorno é desconhecido","revealLocalsArgs":"Nenhum argumento esperado para a chamada \\"reveal_locals\\"","revealLocalsNone":"Nenhum local neste escopo","revealTypeArgs":"Esperava-se um único argumento posicional para a chamada \\"reveal_type\\"","revealTypeExpectedTextArg":"O argumento \\"expected_text\\" para a função \\"reveal_type\\" deve ser um valor literal str","revealTypeExpectedTextMismatch":"Tipo de incompatibilidade de texto. O esperado era \\"{expected}\\", mas recebeu \\"{received}\\"","revealTypeExpectedTypeMismatch":"Incompatibilidade de tipo. Esperava-se \\"{expected}\\", mas recebeu \\"{received}\\"","selfTypeContext":"\\"Self\\" não é válido neste contexto.","selfTypeMetaclass":"\\"Self\\" não pode ser usado em uma metaclasse (uma subclasse de \\"type\\")","selfTypeWithTypedSelfOrCls":"\\"Self\\" não pode ser usado em uma função com um parâmetro `self` ou `cls que tenha uma anotação de tipo diferente de \\"Self\\"","setterGetterTypeMismatch":"O tipo de valor do setter da propriedade não é atribuível ao tipo de retorno getter","singleOverload":"\\"{name}\\" está marcado como sobrecarga, mas sobrecargas adicionais estão ausentes","slotsAttributeError":"\\"{name}\\" não está especificado em __slots__","slotsClassVarConflict":"\\"{name}\\" está em conflito com a variável de instância declarada __slots__","starPatternInAsPattern":"O padrão de estrela não pode ser usado com o destino \\"as\\"","starPatternInOrPattern":"O padrão de estrela não pode ser ORed em outros padrões","starStarWildcardNotAllowed":"** não pode ser usado com curinga \\"_\\"","staticClsSelfParam":"Os métodos estáticos não devem usar um parâmetro \\"self\\" ou \\"cls\\"","stdlibModuleOverridden":"\\"{path}\\" está substituindo o módulo stdlib \\"{name}\\"","stringNonAsciiBytes":"Caractere não ASCII não permitido em literal de cadeia de caracteres de bytes","stringNotSubscriptable":"A expressão de cadeia de caracteres não pode ser subscrito na anotação de tipo. Coloque a anotação inteira entre aspas","stringUnsupportedEscape":"Sequência de escape sem suporte no literal de cadeia de caracteres","stringUnterminated":"Literal de cadeia de caracteres não finalizado","stubFileMissing":"Arquivo stub não encontrado para \\"{importName}\\"","stubUsesGetAttr":"O arquivo stub de tipo está incompleto. \\"__getattr__\\" obscurece erros de tipo para o módulo","sublistParamsIncompatible":"parâmetros de sublista não são suportados no Python 3.x","superCallArgCount":"Não mais que dois argumentos eram esperados para a chamada \\"super\\"","superCallFirstArg":"Tipo de classe esperado como o primeiro argumento para a chamada \\"super\\", mas recebeu \\"{type}\\"","superCallSecondArg":"O segundo argumento para a chamada \\"super\\" deve ser objeto ou classe que deriva de \\"{type}\\"","superCallZeroArgForm":"A forma de chamada \\"super\\" com argumento zero é válida apenas dentro de um método","superCallZeroArgFormStaticMethod":"A forma de chamada \\"super\\" com argumento zero é válida apenas dentro de um método","symbolIsPossiblyUnbound":"\\"{name}\\" possivelmente não está associado","symbolIsUnbound":"\\"{name}\\" não está associado","symbolIsUndefined":"\\"{name}\\" não está definido","symbolOverridden":"\\"{name}\\" substitui o símbolo de mesmo nome na classe \\"{className}\\"","ternaryNotAllowed":"Expressão de ternário não permitida na anotação de tipo","totalOrderingMissingMethod":"A classe deve definir um dos \\"__lt__\\", \\"__le__\\", \\"__gt__\\" ou \\"__ge__\\" para usar total_ordering","trailingCommaInFromImport":"A vírgula à direita não é permitida sem parênteses ao redor","tryWithoutExcept":"A instrução Try deve ter pelo menos uma cláusula except ou finally","tupleAssignmentMismatch":"A expressão com o tipo \\"{type}\\" não pode ser atribuída à tupla de destino","tupleInAnnotation":"Expressão de tupla não permitida na anotação de tipo","tupleIndexOutOfRange":"O índice {index} está fora do intervalo para o tipo {type}","typeAliasIllegalExpressionForm":"Formulário de expressão inválido para definição de alias de tipo","typeAliasIsRecursiveDirect":"O alias de tipo \\"{name}\\" não pode usar a si mesmo em sua definição","typeAliasNotInModuleOrClass":"Um TypeAlias só pode ser definido dentro de um módulo ou escopo de classe","typeAliasRedeclared":"\\"{name}\\" é declarado como um TypeAlias e só pode ser atribuído uma vez","typeAliasStatementBadScope":"Uma instrução type só pode ser usada dentro de um módulo ou escopo de classe","typeAliasStatementIllegal":"A instrução de alias de tipo requer o Python 3.12 ou mais recente","typeAliasTypeBaseClass":"Um alias de tipo definido em uma instrução \\"type\\" não pode ser usado como uma classe base","typeAliasTypeMustBeAssigned":"TypeAliasType deve ser atribuído a uma variável com o mesmo nome que o alias de tipo","typeAliasTypeNameArg":"O primeiro argumento para TypeAliasType deve ser um literal de cadeia de caracteres que representa o nome do alias de tipo","typeAliasTypeNameMismatch":"O nome do alias de tipo deve corresponder ao nome da variável à qual ela está atribuída","typeAliasTypeParamInvalid":"A lista de parâmetros de tipo deve ser uma tupla contendo apenas TypeVar, TypeVarTuple ou ParamSpec","typeAnnotationCall":"Expressão de chamada não permitida na expressão de tipo","typeAnnotationVariable":"Variável não permitida na expressão de tipo","typeAnnotationWithCallable":"O argumento de tipo para \\"type\\" deve ser uma classe; não há suporte para callables","typeArgListExpected":"ParamSpec, reticências ou lista de tipos esperados","typeArgListNotAllowed":"Expressão de lista não permitida para este argumento de tipo","typeArgsExpectingNone":"Nenhum argumento de tipo era esperado para a classe \\"{name}\\"","typeArgsMismatchOne":"Esperava-se um argumento de tipo, mas recebeu {received}","typeArgsMissingForAlias":"Argumentos de tipo esperados para o alias de tipo genérico \\"{name}\\"","typeArgsMissingForClass":"Argumentos de tipo esperados para a classe genérica \\"{name}\\"","typeArgsTooFew":"Poucos argumentos de tipo fornecidos para \\"{name}\\". Esperava-se {expected}, mas recebeu {received}","typeArgsTooMany":"Muitos argumentos de tipo fornecidos para \\"{name}\\". Esperava-se {expected}, mas recebeu {received}","typeAssignmentMismatch":"A expressão do tipo \\"{sourceType}\\" não pode ser atribuída ao tipo declarado \\"{destType}\\"","typeAssignmentMismatchWildcard":"O símbolo de importação \\"{name}\\" tem o tipo \\"{sourceType}\\", que não pode ser atribuído ao tipo declarado \\"{destType}\\"","typeCallNotAllowed":"A chamada type() não deve ser usada na anotação de tipo","typeCheckOnly":"\\"{name}\\" está marcado como @type_check_only e pode ser usado apenas em anotações de tipo","typeCommentDeprecated":"O uso de comentários de tipo foi preterido. Use anotação de tipo em vez disso","typeExpectedClass":"Expressão de tipo esperada, mas recebeu \\"{type}\\"","typeGuardArgCount":"Argumento de tipo único esperado após \\"TypeGuard\\" ou \\"TypeIs\\"","typeGuardParamCount":"Funções e métodos de proteção de tipo definidos pelo usuário devem ter pelo menos um parâmetro de entrada","typeIsReturnType":"O tipo de retorno de TypeIs (\\"{returnType}\\") não é consistente com o tipo de parâmetro de valor (\\"{type}\\")","typeNotAwaitable":"\\"{type}\\" não é previsível","typeNotIntantiable":"\\"{type}\\" não pode ser instanciado","typeNotIterable":"\\"{type}\\" não é iterável","typeNotSpecializable":"Não foi possível especializar o tipo \\"{type}\\"","typeNotSubscriptable":"O objeto do tipo \\"{type}\\" não é subscrito","typeNotSupportBinaryOperator":"Operador \\"{operator}\\" sem suporte para os tipos \\"{leftType}\\" e \\"{rightType}\\"","typeNotSupportBinaryOperatorBidirectional":"O operador \\"{operator}\\" não tem suporte para os tipos \\"{leftType}\\" e \\"{rightType}\\" quando o tipo esperado é \\"{expectedType}\\"","typeNotSupportUnaryOperator":"Operador \\"{operator}\\" sem suporte para o tipo \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"O operador \\"{operator}\\" não tem suporte para o tipo \\"{type}\\" quando o tipo esperado é \\"{expectedType}\\"","typeNotUsableWith":"O objeto do tipo \\"{type}\\" não pode ser usado com \\"with\\" porque não implementa {method}","typeParameterBoundNotAllowed":"Associação ou restrição não pode ser usada com um parâmetro de tipo variadic ou ParamSpec","typeParameterConstraintTuple":"A restrição de parâmetro de tipo deve ser uma tupla de dois ou mais tipos","typeParameterExistingTypeParameter":"O parâmetro de tipo \\"{name}\\" já está em uso","typeParameterNotDeclared":"O parâmetro de tipo \\"{name}\\" não está incluído na lista de parâmetros de tipo para \\"{container}\\"","typeParametersMissing":"Pelo menos um parâmetro de tipo deve ser especificado","typePartiallyUnknown":"O tipo de \\"{name}\\" é parcialmente desconhecido","typeUnknown":"O tipo de \\"{name}\\" é desconhecido","typeVarAssignedName":"TypeVar deve ser atribuído a uma variável chamada \\"{name}\\"","typeVarAssignmentMismatch":"O tipo \\"{type}\\" não pode ser atribuído à variável de tipo \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar não pode ser associado e restrito","typeVarBoundGeneric":"O tipo associado TypeVar não pode ser genérico","typeVarConstraintGeneric":"O tipo de restrição TypeVar não pode ser genérico","typeVarDefaultBoundMismatch":"O tipo padrão TypeVar deve ser um subtipo do tipo associado","typeVarDefaultConstraintMismatch":"O tipo padrão TypeVar deve ser um dos tipos restritos","typeVarDefaultIllegal":"Tipos padrão de variável de tipo exigem Python 3.13 ou mais recente","typeVarDefaultInvalidTypeVar":"O parâmetro de tipo \\"{name}\\" tem um tipo padrão que se refere a uma ou mais variáveis de tipo que estão fora do escopo","typeVarFirstArg":"Nome esperado de TypeVar como primeiro argumento","typeVarNoMember":"TypeVar \\"{type}\\" não tem membro \\"{name}\\"","typeVarNotSubscriptable":"Não é possível subscrever TypeVar \\"{type}\\"","typeVarNotUsedByOuterScope":"A variável de tipo \\"{name}\\" não tem significado neste contexto","typeVarPossiblyUnsolvable":"A variável de tipo \\"{name}\\" pode ficar sem resolução se o chamador não fornecer nenhum argumento para o parâmetro \\"{param}\\"","typeVarScopedToReturnType":"A variável de tipo \\"{name}\\" tem como escopo um chamador dentro do tipo de retorno e não pode ser referenciada no corpo da função","typeVarSingleConstraint":"TypeVar deve ter pelo menos dois tipos restritos","typeVarTupleConstraints":"TypeVarTuple não pode ter restrições de valor","typeVarTupleContext":"TypeVarTuple não é permitido neste contexto","typeVarTupleDefaultNotUnpacked":"O tipo padrão TypeVarTuple deve ser uma tupla desempacotamento ou TypeVarTuple","typeVarTupleMustBeUnpacked":"O operador Unpack é necessário para o valor TypeVarTuple","typeVarTupleUnknownParam":"\\"{name}\\" é um parâmetro desconhecido para TypeVarTuple","typeVarUnknownParam":"\\"{name}\\" é um parâmetro desconhecido para TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" já está em uso por um escopo externo","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" aparece apenas uma vez na assinatura de função genérica","typeVarVariance":"TypeVar não pode ser covariante e contravariante","typeVarWithDefaultFollowsVariadic":"O TypeVar \\"{typeVarName}\\" tem um valor padrão e não pode seguir TypeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" não pode aparecer após \\"{other}\\" na lista de parâmetros de tipo porque não tem nenhum tipo padrão","typeVarsNotInGenericOrProtocol":"Generic[] ou Protocol[] deve incluir todas as variáveis de tipo","typedDictAccess":"Não foi possível acessar o item em TypedDict","typedDictAssignedName":"TypedDict deve ser atribuído a uma variável chamada \\"{name}\\"","typedDictBadVar":"As classes TypedDict podem conter apenas anotações de tipo","typedDictBaseClass":"Todas as classes base para classes TypedDict também devem ser classes TypedDict","typedDictBoolParam":"Esperava-se que o parâmetro \\"{name}\\" tivesse um valor True ou False","typedDictClosedExtras":"A classe base \\"{name}\\" é um TypedDict fechado; itens extras devem ser do tipo \\"{type}\\"","typedDictClosedNoExtras":"A classe base \\"{name}\\" é um TypedDict fechado; itens extras não são permitidos","typedDictDelete":"Não foi possível excluir o item em TypedDict","typedDictEmptyName":"Os nomes dentro de um TypedDict não podem estar vazios","typedDictEntryName":"Literal de cadeia de caracteres esperado para o nome da entrada do dicionário","typedDictEntryUnique":"Os nomes dentro de um dicionário devem ser exclusivos","typedDictExtraArgs":"Argumentos TypedDict extras são incompatíveis","typedDictFieldNotRequiredRedefinition":"O item TypedDict \\"{name}\\" não pode ser redefinido como NotRequired","typedDictFieldReadOnlyRedefinition":"O item TypedDict \\"{name}\\" não pode ser redefinido como ReadOnly","typedDictFieldRequiredRedefinition":"O item TypedDict \\"{name}\\" não pode ser redefinido como Obrigatório","typedDictFirstArg":"Nome da classe TypedDict esperado como primeiro argumento","typedDictInitsubclassParameter":"TypedDict não dá suporte ao parâmetro __init_subclass__ \\"{name}\\"","typedDictNotAllowed":"\\"TypedDict\\" não pode ser usado neste contexto","typedDictSecondArgDict":"Parâmetro dict ou de palavra-chave esperado como segundo parâmetro","typedDictSecondArgDictEntry":"Entrada de dicionário simples esperada","typedDictSet":"Não foi possível atribuir o item em TypedDict","unaccessedClass":"A classe \\"{name}\\" não foi acessada","unaccessedFunction":"A função \\"{name}\\" não foi acessada","unaccessedImport":"A importação \\"{name}\\" não foi acessada","unaccessedSymbol":"\\"{name}\\" não foi acessado","unaccessedVariable":"A variável \\"{name}\\" não foi acessada","unannotatedFunctionSkipped":"A análise da função \\"{name}\\" foi ignorada porque não foi anotada","unaryOperationNotAllowed":"Operador unário não permitido na anotação de tipo","unexpectedAsyncToken":"Esperado \\"def\\", \\"with\\" ou \\"for\\" para acompanhar \\"async\\"","unexpectedExprToken":"Token inesperado no final da expressão","unexpectedIndent":"Recuo inesperado","unexpectedUnindent":"Recuo não esperado","unhashableDictKey":"A chave do dicionário deve ser hash","unhashableSetEntry":"A entrada set deve ser permitir hash","uninitializedAbstractVariables":"As variáveis definidas na classe base abstrata não são inicializadas na classe final \\"{classType}\\"","uninitializedInstanceVariable":"A variável de instância \\"{name}\\" não foi inicializada no corpo da classe ou no método __init__","unionForwardReferenceNotAllowed":"A sintaxe de união não pode ser usada com operando de cadeia de caracteres. Use aspas em toda a expressão","unionSyntaxIllegal":"A sintaxe alternativa para uniões requer o Python 3.10 ou mais recente","unionTypeArgCount":"A união requer dois ou mais argumentos de tipo","unionUnpackedTuple":"A união não pode incluir uma tupla desempacotada","unionUnpackedTypeVarTuple":"A união não pode incluir um TypeVarTuple desempacotado","unnecessaryCast":"Chamada \\"cast\\" desnecessária. O tipo já é \\"{type}\\"","unnecessaryIsInstanceAlways":"Chamada de iinstância desnecessária. \\"{testType}\\" é sempre uma instância de \\"{classType}\\"","unnecessaryIsSubclassAlways":"Chamada issubclass desnecessária. \\"{testType}\\" é sempre uma subclasse de \\"{classType}\\"","unnecessaryPyrightIgnore":"Comentário desnecessário \\"# pyright: ignore\\"","unnecessaryPyrightIgnoreRule":"Regra desnecessária \\"# pyright: ignore\\": \\"{name}\\"","unnecessaryTypeIgnore":"Comentário \\"# type: ignore\\" desnecessário","unpackArgCount":"Argumento de tipo único esperado após \\"Unpack\\"","unpackExpectedTypeVarTuple":"TypeVarTuple ou tupla esperado como argumento de tipo para Unpack","unpackExpectedTypedDict":"Argumento de tipo TypedDict esperado para Desempacotar","unpackIllegalInComprehension":"Operação de desempacotamento não permitida na compreensão","unpackInAnnotation":"Operador Desempacotar não permitido na anotação de tipo","unpackInDict":"Operação de desempacotamento não permitida em dicionários","unpackInSet":"Operador unpack não permitido em um conjunto","unpackNotAllowed":"Descompactar não é permitido neste contexto","unpackOperatorNotAllowed":"A operação de descompactação não é permitida neste contexto","unpackTuplesIllegal":"Operação de desempacotamento não permitida em tuplas anteriores ao Python 3.8","unpackedArgInTypeArgument":"Argumentos desempacotamento não podem ser usados em listas de argumentos de tipo","unpackedArgWithVariadicParam":"O argumento desempacotado não pode ser usado para o parâmetro TypeVarTuple","unpackedDictArgumentNotMapping":"A expressão de argumento após ** deve ser um mapeamento com um tipo de chave \\"str\\"","unpackedDictSubscriptIllegal":"O operador de desempacotamento de dicionário no subscrito não é permitido","unpackedSubscriptIllegal":"O operador Unpack no subscrito requer o Python 3.11 ou mais recente","unpackedTypeVarTupleExpected":"Esperava-se TypeVarTuple desempacotada. Use Unpack[{name1}] ou *{name2}","unpackedTypedDictArgument":"Não é possível corresponder o argumento TypedDict desempacotado aos parâmetros","unreachableCode":"O código está inacessível.","unreachableExcept":"A cláusula Except está inacessível porque a exceção já foi tratada","unsupportedDunderAllOperation":"A operação em \\"__all__\\" não é compatível, portanto, a lista de símbolos exportada pode estar incorreta","unusedCallResult":"O resultado da expressão de chamada é do tipo \\"{type}\\" e não é usado. Atribua à variável \\"_\\" se isso for intencional","unusedCoroutine":"O resultado da chamada de função assíncrona não foi usado. Use \\"await\\" ou atribua o resultado à variável","unusedExpression":"O valor da expressão não é usado","varAnnotationIllegal":"As anotações de tipo para variáveis exigem Python 3.6 ou mais recente. Use comentário de tipo para compatibilidade com versões anteriores","variableFinalOverride":"A variável \\"{name}\\" está marcada como Final e substitui a variável não final de mesmo nome na classe \\"{className}\\"","variadicTypeArgsTooMany":"A lista de argumentos de tipo pode ter no máximo um TypeVarTuple ou tupla descompactado","variadicTypeParamTooManyAlias":"O alias de tipo pode ter no máximo um parâmetro de tipo TypeVarTuple, mas recebeu vários ({names})","variadicTypeParamTooManyClass":"A classe genérica pode ter no máximo um parâmetro de tipo TypeVarTuple, mas recebeu vários ({names})","walrusIllegal":"O operador \\":=\\" requer o Python 3.8 ou mais recente","walrusNotAllowed":"Operador \\":=\\" não é permitido neste contexto sem parênteses","wildcardInFunction":"Importação de curinga não permitida em uma classe ou função","wildcardLibraryImport":"Importação de curinga de uma biblioteca não permitida","wildcardPatternTypePartiallyUnknown":"O tipo capturado pelo padrão curinga é parcialmente desconhecido","wildcardPatternTypeUnknown":"O tipo capturado pelo padrão curinga é desconhecido","yieldFromIllegal":"O uso de \\"yield from\\" requer o Python 3.3 ou mais recente","yieldFromOutsideAsync":"\\"yield from\\" não é permitido em uma função assíncrona","yieldOutsideFunction":"\\"yield\\" não permitido fora de uma função ou lambda","yieldWithinListCompr":"\\"yield\\" não é permitido dentro de uma compreensão de lista","zeroCaseStatementsFound":"A instrução Match deve incluir pelo menos uma instrução case","zeroLengthTupleNotAllowed":"Tupla de comprimento zero não é permitida neste contexto"},"DiagnosticAddendum":{"annotatedNotAllowed":"O formulário especial \\"Anotado\\" não pode ser usado com verificações de instância e classe","argParam":"O argumento corresponde ao parâmetro \\"{paramName}\\"","argParamFunction":"O argumento corresponde ao parâmetro \\"{paramName}\\" na função \\"{functionName}\\"","argsParamMissing":"O parâmetro \\"*{paramName}\\" não tem nenhum parâmetro correspondente","argsPositionOnly":"Incompatibilidade de parâmetro somente de posição; esperava-se {expected}, mas recebeu {received}","argumentType":"O tipo de argumento é \\"{type}\\"","argumentTypes":"Tipos de argumento: ({types})","assignToNone":"O tipo não pode ser atribuído ao tipo \\"None\\"","asyncHelp":"Você quis dizer \\"async with\\"?","baseClassIncompatible":"A classe base \\"{baseClass}\\" é incompatível com o tipo \\"{type}\\"","baseClassIncompatibleSubclass":"A classe base \\"{baseClass}\\" deriva de \\"{subclass}\\" que é incompatível com o tipo \\"{type}\\"","baseClassOverriddenType":"A classe base \\"{baseClass}\\" fornece o tipo \\"{type}\\", que é substituído","baseClassOverridesType":"A classe base \\"{baseClass}\\" substitui pelo tipo \\"{type}\\"","bytesTypePromotions":"Defina disableBytesTypePromotions como false para habilitar o comportamento de promoção de tipo para \\"bytearray\\" e \\"memoryview\\"","conditionalRequiresBool":"O método __bool__ para o tipo \\"{operandType}\\" retorna o tipo \\"{boolReturnType}\\" em vez de \\"bool\\"","dataClassFieldLocation":"Declaração de campo","dataClassFrozen":"\\"{name}\\" está congelado","dataProtocolUnsupported":"\\"{name}\\" é um protocolo de dados","descriptorAccessBindingFailed":"Falha ao associar o método \\"{name}\\" para a classe de descritor \\"{className}\\"","descriptorAccessCallFailed":"Falha ao chamar o método \\"{name}\\" para a classe de descritor \\"{className}\\"","finalMethod":"Método final","functionParamDefaultMissing":"O parâmetro \\"{name}\\" não tem um argumento padrão","functionParamName":"Incompatibilidade de nome de parâmetro: \\"{destName}\\" versus \\"{srcName}\\"","functionParamPositionOnly":"Incompatibilidade de parâmetro somente posição; o parâmetro \\"{name}\\" não é somente posição","functionReturnTypeMismatch":"O tipo de retorno de função \\"{sourceType}\\" é incompatível com o tipo \\"{destType}\\"","functionTooFewParams":"A função aceita poucos parâmetros posicionais. Esperava-se {expected}, mas recebeu {received}","functionTooManyParams":"A função aceita muitos parâmetros posicionais. Esperava-se {expected}, mas recebeu {received}","genericClassNotAllowed":"Tipo genérico com argumentos de tipo não permitidos para verificações de instância ou de classe","incompatibleDeleter":"O método de exclusão de propriedade é incompatível","incompatibleGetter":"O método getter de propriedade é incompatível","incompatibleSetter":"O método setter de propriedade é incompatível","initMethodLocation":"O método __init__ é definido na classe \\"{type}\\"","initMethodSignature":"A assinatura de __init__ é \\"{type}\\"","initSubclassLocation":"O método __init_subclass__ é definido na classe \\"{name}\\"","invariantSuggestionDict":"Considere alternar de \\"dict\\" para \\"Mapping\\", que é covariante no tipo de valor","invariantSuggestionList":"Considere alternar de \\"list\\" para \\"Sequence\\", que é covariante","invariantSuggestionSet":"Considere alternar de \\"set\\" para \\"Container\\", que é covariante","keyNotRequired":"\\"{name}\\" não é uma chave necessária em \\"{type}\\", portanto, o acesso pode resultar em exceção de runtime","keyReadOnly":"\\"{name}\\" é uma chave somente leitura em \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" é uma chave obrigatória e não pode ser excluída","keyUndefined":"\\"{name}\\" não é uma chave definida em \\"{type}\\"","kwargsParamMissing":"O parâmetro \\"**{paramName}\\" não tem nenhum parâmetro correspondente","listAssignmentMismatch":"O tipo \\"{type}\\" é incompatível com a lista de destino","literalAssignmentMismatch":"\\"{sourceType}\\" não pode ser atribuído ao tipo \\"{destType}\\"","matchIsNotExhaustiveHint":"Se não pretende usar a manipulação exaustiva, adicione \\"case _: pass\\"","matchIsNotExhaustiveType":"Tipo sem tratamento: \\"{type}\\"","memberAssignment":"A expressão do tipo \\"{type}\\" não pode ser atribuída ao membro \\"{name}\\" da classe \\"{classType}\\"","memberIsAbstract":"\\"{type}.{name}\\" não está implementado","memberIsAbstractMore":"e mais {count}...","memberIsClassVarInProtocol":"\\"{name}\\" é definido como um ClassVar no protocolo","memberIsFinalInProtocol":"\\"{name}\\" está marcado como Final no protocolo","memberIsInitVar":"O membro \\"{name}\\" é um campo somente inicialização","memberIsInvariant":"\\"{name}\\" é invariável porque é mutável","memberIsNotClassVarInClass":"\\"{name}\\" deve ser definido como um ClassVar para ser compatível com o protocolo","memberIsNotClassVarInProtocol":"\\"{name}\\" não está definido como um ClassVar no protocolo","memberIsNotFinalInProtocol":"\\"{name}\\" não está marcado como Final no protocolo","memberIsWritableInProtocol":"\\"{name}\\" é gravável no protocolo","memberSetClassVar":"O membro \\"{name}\\" não pode ser atribuído por meio de uma instância de classe porque é um ClassVar","memberTypeMismatch":"\\"{name}\\" é um tipo incompatível","memberUnknown":"O membro \\"{name}\\" é desconhecido","metaclassConflict":"A metaclasse \\"{metaclass1}\\" entra em conflito com \\"{metaclass2}\\"","missingDeleter":"O método de exclusão de propriedade está ausente","missingGetter":"O método getter da propriedade está ausente","missingSetter":"O método setter da propriedade está ausente","namedParamMissingInDest":"O parâmetro de palavra-chave \\"{name}\\" está ausente no destino","namedParamMissingInSource":"O parâmetro de palavra-chave \\"{name}\\" está ausente na origem","namedParamTypeMismatch":"O parâmetro de palavra-chave \\"{name}\\" do tipo \\"{sourceType}\\" não pode ser atribuído ao tipo \\"{destType}\\"","namedTupleNotAllowed":"NamedTuple não pode ser usado para verificações de instância ou de classe","newMethodLocation":"O método __new__ é definido na classe \\"{type}\\"","newMethodSignature":"A assinatura de__new__ é \\"{type}\\"","newTypeClassNotAllowed":"A classe criada com NewType não pode ser usada com verificações de instância e classe","noOverloadAssignable":"Nenhuma função sobrecarregada corresponde ao tipo \\"{type}\\"","noneNotAllowed":"Nenhum não pode ser usado para verificações de instância ou de classe","orPatternMissingName":"Nomes ausentes: {name}","overloadIndex":"Sobrecarga {index} é a correspondência mais próxima","overloadNotAssignable":"Uma ou mais sobrecargas de \\"{name}\\" não podem ser atribuídas","overloadSignature":"A assinatura de sobrecarga é definida aqui","overriddenMethod":"Método substituído","overriddenSymbol":"Símbolo substituído","overrideInvariantMismatch":"O tipo da substituição \\"{overrideType}\\" não é o mesmo do tipo básico \\"{baseType}\\"","overrideIsInvariant":"A variável é mutável, então seu tipo é invariável","overrideNoOverloadMatches":"Nenhuma assinatura de sobrecarga na substituição é compatível com o método base","overrideNotClassMethod":"O método base é declarado como um classmethod, mas a substituição não é","overrideNotInstanceMethod":"O método base é declarado como um método de instância, mas a substituição não é","overrideNotStaticMethod":"O método base é declarado como staticmethod, mas a substituição não é","overrideOverloadNoMatch":"Override não lida com todas as sobrecargas do método base","overrideOverloadOrder":"As sobrecargas para o método de substituição devem estar na mesma ordem que o método base","overrideParamKeywordNoDefault":"Incompatibilidade de parâmetro de palavra-chave \\"{name}\\": o parâmetro base tem valor de argumento padrão, o parâmetro de substituição não","overrideParamKeywordType":"Incompatibilidade de tipo de parâmetro de palavra-chave \\"{name}\\": o parâmetro base é do tipo \\"{baseType}\\", o parâmetro de substituição é do tipo \\"{overrideType}\\"","overrideParamName":"Incompatibilidade de nome de parâmetro {index}: o parâmetro base é denominado \\"{baseName}\\", o parâmetro de substituição é denomidado \\"{overrideName}\\"","overrideParamNameExtra":"O parâmetro \\"{name}\\" está ausente na base","overrideParamNameMissing":"O parâmetro \\"{name}\\" está ausente na substituição","overrideParamNamePositionOnly":"Incompatibilidade de parâmetro {index}: o parâmetro base \\"{baseName}\\" é o parâmetro de palavra-chave, o parâmetro de substituição é somente posição","overrideParamNoDefault":"Parâmetro {index} incompatível: o parâmetro base tem valor de argumento padrão, o parâmetro de substituição não","overrideParamType":"Incompatibilidade de tipo de parâmetro {index}: o parâmetro base é do tipo \\"{baseType}\\", o parâmetro de substituição é do tipo \\"{overrideType}\\"","overridePositionalParamCount":"Incompatibilidade de contagem de parâmetros posicionais. O método base tem {baseCount}, mas a substituição tem {overrideCount}","overrideReturnType":"Incompatibilidade de tipo de retorno: o método base retorna o tipo \\"{baseType}\\", a substituição retorna o tipo \\"{overrideType}\\"","overrideType":"A classe base define o tipo como \\"{type}\\"","paramAssignment":"Parâmetro {index}: o tipo \\"{sourceType}\\" não pode ser atribuído ao tipo \\"{destType}\\"","paramSpecMissingInOverride":"Os parâmetros ParamSpec estão ausentes no método de substituição","paramType":"O tipo de parâmetro é \\"{paramType}\\"","privateImportFromPyTypedSource":"Em vez disso, importe de \\"{module}\\"","propertyAccessFromProtocolClass":"Uma propriedade definida dentro de uma classe de protocolo não pode ser acessada como uma variável de classe","propertyMethodIncompatible":"O método de propriedade \\"{name}\\" é incompatível","propertyMethodMissing":"O método de propriedade \\"{name}\\" está ausente na substituição","propertyMissingDeleter":"A propriedade \\"{name}\\" não tem nenhum excluidor definido","propertyMissingSetter":"A propriedade \\"{name}\\" não tem um setter definido","protocolIncompatible":"\\"{sourceType}\\" é incompatível com o protocolo \\"{destType}\\"","protocolMemberMissing":"\\"{name}\\" não está presente","protocolRequiresRuntimeCheckable":"A classe do protocolo deve ser @runtime_checkable para ser usada com verificações de instância e de classe","protocolSourceIsNotConcrete":"\\"{sourceType}\\" não é um tipo de classe concreta e não pode ser atribuído ao tipo \\"{destType}\\"","protocolUnsafeOverlap":"Os atributos de \\"{name}\\" têm os mesmos nomes que o protocolo","pyrightCommentIgnoreTip":"Use \\"# pyright: ignore[<diagnostic rules>] para suprimir o diagnóstico de uma única linha","readOnlyAttribute":"O atributo \\"{name}\\" é somente leitura","seeClassDeclaration":"Consulte a declaração de classe","seeDeclaration":"Consulte a declaração","seeFunctionDeclaration":"Ver declaração de função","seeMethodDeclaration":"Consulte a declaração de método","seeParameterDeclaration":"Consulte a declaração de parâmetro","seeTypeAliasDeclaration":"Ver declaração de alias de tipo","seeVariableDeclaration":"Consulte a declaração de variável","tupleAssignmentMismatch":"O tipo \\"{type}\\" é incompatível com a tupla de destino","tupleEntryTypeMismatch":"A entrada de tupla {entry} é do tipo incorreto","tupleSizeIndeterminateSrc":"Incompatibilidade de tamanho de tupla; esperado {expected} mas recebido indeterminado","tupleSizeIndeterminateSrcDest":"Incompatibilidade de tamanho de tupla; {expected} ou mais esperado, mas indeterminado recebido","tupleSizeMismatch":"Incompatibilidade de tamanho de tupla; esperado {expected} mas recebido {received}","tupleSizeMismatchIndeterminateDest":"Incompatibilidade de tamanho de tupla; {expected} ou mais esperado, mas {received} recebido","typeAliasInstanceCheck":"O alias de tipo criado com a instrução \\"type\\" não pode ser usado com verificações de instância e de classe","typeAssignmentMismatch":"O tipo \\"{sourceType}\\" não pode ser atribuído ao tipo \\"{destType}\\"","typeBound":"O tipo \\"{sourceType}\\" é incompatível com o tipo associado \\"{destType}\\" para a variável de tipo \\"{name}\\"","typeConstrainedTypeVar":"O tipo \\"{type}\\" é incompatível com a variável de tipo restrita \\"{name}\\"","typeIncompatible":"\\"{sourceType}\\" é incompatível com \\"{destType}\\"","typeNotClass":"\\"{type}\\" não é uma classe.","typeNotStringLiteral":"\\"{type}\\" não é um literal de cadeia de caracteres","typeOfSymbol":"O tipo de \\"{name}\\" é \\"{type}\\"","typeParamSpec":"O tipo \\"{type}\\" é incompatível com ParamSpec \\"{name}\\"","typeUnsupported":"O tipo \\"{type}\\" é incompatível","typeVarDefaultOutOfScope":"A variável de tipo \\"{name}\\" não está no escopo","typeVarIsContravariant":"O parâmetro de tipo \\"{name}\\" é contravariante, mas \\"{sourceType}\\" não é um supertipo de \\"{destType}\\"","typeVarIsCovariant":"O parâmetro de tipo \\"{name}\\" é covariante, mas \\"{sourceType}\\" não é um subtipo de \\"{destType}\\"","typeVarIsInvariant":"O parâmetro de tipo \\"{name}\\" é invariável, mas \\"{sourceType}\\" não é o mesmo que \\"{destType}\\"","typeVarNotAllowed":"TypeVar não permitido para verificações de instância ou de classe","typeVarTupleRequiresKnownLength":"TypeVarTuple não pode ser associado a uma tupla de comprimento desconhecido","typeVarUnnecessarySuggestion":"Use {type} em vez disso","typeVarUnsolvableRemedy":"Forneça uma sobrecarga que especifica o tipo de retorno quando o argumento não é fornecido","typeVarsMissing":"Variáveis de tipo ausentes: {names}","typedDictBaseClass":"A classe \\"{type}\\" não é um TypedDict","typedDictClassNotAllowed":"A classe TypedDict não é permitida para verificações de instância ou classe","typedDictClosedExtraNotAllowed":"Não é possível adicionar o item \\"{name}\\"","typedDictClosedExtraTypeMismatch":"Não é possível adicionar o item \\"{name}\\" com o tipo \\"{type}\\"","typedDictClosedFieldNotRequired":"Não é possível adicionar o item \\"{name}\\" porque ele deve ser NotRequired","typedDictExtraFieldNotAllowed":"\\"{name}\\" não está presente em \\"{type}\\"","typedDictExtraFieldTypeMismatch":"O tipo de \\"{name}\\" é incompatível com o tipo de \\"__extra_items__\\" em \\"{type}\\"","typedDictFieldMissing":"\\"{name}\\" está ausente de \\"{type}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" não é somente leitura em \\"{type}\\"","typedDictFieldNotRequired":"\\"{name}\\" não é obrigatório em \\"{type}\\"","typedDictFieldRequired":"\\"{name}\\" é necessário em \\"{type}\\"","typedDictFieldTypeMismatch":"O tipo \\"{type}\\" não é atribuível ao item \\"{name}\\"","typedDictFieldUndefined":"\\"{name}\\" é um item indefinido no tipo \\"{type}\\"","typedDictFinalMismatch":"\\"{sourceType}\\" é incompatível com \\"{destType}\\" devido a uma @final incompatível","typedDictKeyAccess":"Usar [\\"{name}\\"] para fazer referência ao item em TypedDict","typedDictNotAllowed":"TypedDict não pode ser usado para verificações de instância ou de classe","unhashableType":"O tipo \\"{type}\\" não é pode fazer hash","uninitializedAbstractVariable":"A variável de instância \\"{name}\\" está definida na classe base abstrata \\"{classType}\\", mas não foi inicializada","unreachableExcept":"\\"{exceptionType}\\" é uma subclasse de \\"{parentType}\\"","useDictInstead":"Use Dict[T1, T2] para indicar um tipo de dicionário","useListInstead":"Use List[T] para indicar um tipo de lista ou Union[T1, T2] para indicar um tipo de união","useTupleInstead":"Use tuple[T1, ..., Tn] para indicar um tipo de tupla ou Union[T1, T2] para indicar um tipo de união","useTypeInstead":"Use Type[T] em vez disso","varianceMismatchForClass":"A variação do argumento de tipo \\"{typeVarName}\\" é incompatível com a classe base \\"{className}\\"","varianceMismatchForTypeAlias":"A variação do argumento de tipo \\"{typeVarName}\\" é incompatível com \\"{typeAliasParam}\\""}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.qps-ploc.json":
/*!**********************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.qps-ploc.json ***!
  \**********************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"[4i3uH][นั้Çrëætë Tÿpë §tµþẤğ倪İЂҰนั้ढूँ]","createTypeStubFor":"[oXYb0][นั้Çrëætë Tÿpë §tµþ Før \\"{møðµlëÑæmë}\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","executingCommand":"[AxS1Z][นั้Ëxëçµtïñg çømmæñðẤğ倪İЂҰक्นั้ढूँ]","filesToAnalyzeCount":"[94Ml3][นั้{çøµñt} fïlës tø æñælÿzëẤğ倪İЂҰक्र्นั้ढूँ]","filesToAnalyzeOne":"[2zuMu][นั้1 fïlë tø æñælÿzëẤğ倪İЂҰक्นั้ढूँ]","findingReferences":"[0UmwS][นั้Fïñðïñg rëfërëñçësẤğ倪İЂҰक्นั้ढूँ]","organizeImports":"[KhOyl][นั้Ørgæñïzë ÏmpørtsẤğ倪İЂҰนั้ढूँ]","renameShadowedFile":"[E02Ab][นั้Rëñæmë \\"{ølðFïlë}\\" tø \\"{ñëwFïlë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]"},"Completion":{"autoImportDetail":"[WdNQG][นั้Æµtø-ïmpørtẤğ倪İนั้ढूँ]","indexValueDetail":"[mX94Q][นั้Ïñðëx vælµëẤğ倪İนั้ढूँ]"},"Diagnostic":{"abstractMethodInvocation":"[fE8MD][นั้Mëthøð \\"{mëthøð}\\" çæññøt þë çællëð þëçæµsë ït ïs æþstræçt æñð µñïmplëmëñtëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","annotatedParamCountMismatch":"[VZvZc][นั้Pæræmëtër æññøtætïøñ çøµñt mïsmætçh: ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","annotatedTypeArgMissing":"[mTgtG][นั้Ëxpëçtëð øñë tÿpë ærgµmëñt æñð øñë ør mørë æññøtætïøñs før \\"Æññøtætëð\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","annotationFormatString":"[zaI8H][นั้Tÿpë æññøtætïøñs çæññøt µsë førmæt strïñg lïtëræls (f-strïñgs)Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","annotationNotSupported":"[xYlM8][นั้Tÿpë æññøtætïøñ ñøt sµppørtëð før thïs stætëmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","annotationSpansStrings":"[6Gg9x][นั้Tÿpë æññøtætïøñs çæññøt spæñ mµltïplë strïñg lïtërælsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","annotationStringEscape":"[MQdsm][นั้Tÿpë æññøtætïøñs çæññøt çøñtæïñ ësçæpë çhæræçtërsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","argAssignment":"[7pdVt][นั้Ærgµmëñt øf tÿpë \\"{ærgTÿpë}\\" çæññøt þë æssïgñëð tø pæræmëtër øf tÿpë \\"{pæræmTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","argAssignmentFunction":"[J08ms][นั้Ærgµmëñt øf tÿpë \\"{ærgTÿpë}\\" çæññøt þë æssïgñëð tø pæræmëtër øf tÿpë \\"{pæræmTÿpë}\\" ïñ fµñçtïøñ \\"{fµñçtïøñÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","argAssignmentParam":"[hEBRl][นั้Ærgµmëñt øf tÿpë \\"{ærgTÿpë}\\" çæññøt þë æssïgñëð tø pæræmëtër \\"{pæræmÑæmë}\\" øf tÿpë \\"{pæræmTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","argAssignmentParamFunction":"[0sIuD][นั้Ærgµmëñt øf tÿpë \\"{ærgTÿpë}\\" çæññøt þë æssïgñëð tø pæræmëtër \\"{pæræmÑæmë}\\" øf tÿpë \\"{pæræmTÿpë}\\" ïñ fµñçtïøñ \\"{fµñçtïøñÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","argMissingForParam":"[1oqiG][นั้Ærgµmëñt mïssïñg før pæræmëtër {ñæmë}Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","argMissingForParams":"[iAF8C][นั้Ærgµmëñts mïssïñg før pæræmëtërs {ñæmës}Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","argMorePositionalExpectedCount":"[q3jgC][นั้Ëxpëçtëð {ëxpëçtëð} mørë pøsïtïøñæl ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","argMorePositionalExpectedOne":"[DNcCo][นั้Ëxpëçtëð 1 mørë pøsïtïøñæl ærgµmëñtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","argPositional":"[XBHa9][นั้Ëxpëçtëð pøsïtïøñæl ærgµmëñtẤğ倪İЂҰक्र्तिृนั้ढूँ]","argPositionalExpectedCount":"[F5Y6t][นั้Ëxpëçtëð {ëxpëçtëð} pøsïtïøñæl ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","argPositionalExpectedOne":"[XW4kV][นั้Ëxpëçtëð 1 pøsïtïøñæl ærgµmëñtẤğ倪İЂҰक्र्तिृนั้ढूँ]","argTypePartiallyUnknown":"[Y02o3][นั้Ærgµmëñt tÿpë ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまนั้ढूँ]","argTypeUnknown":"[l0ccD][นั้Ærgµmëñt tÿpë ïs µñkñøwñẤğ倪İЂҰक्र्นั้ढूँ]","assertAlwaysTrue":"[5Weld][นั้Æssërt ëxprëssïøñ ælwæÿs ëvælµætës tø trµëẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","assertTypeArgs":"[QHRQ7][นั้\\"æssërt_tÿpë\\" ëxpëçts twø pøsïtïøñæl ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","assertTypeTypeMismatch":"[fc1Kk][นั้\\"æssërt_tÿpë\\" mïsmætçh: ëxpëçtëð \\"{ëxpëçtëð}\\" þµt rëçëïvëð \\"{rëçëïvëð}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","assignmentExprComprehension":"[F5OTr][นั้Æssïgñmëñt ëxprëssïøñ tærgët \\"{ñæmë}\\" çæññøt µsë sæmë ñæmë æs çømprëhëñsïøñ før tærgëtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","assignmentExprContext":"[U4d41][นั้Æssïgñmëñt ëxprëssïøñ mµst þë wïthïñ møðµlë, fµñçtïøñ ør læmþðæẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","assignmentExprInSubscript":"[mnJzw][นั้Æssïgñmëñt ëxprëssïøñs wïthïñ æ sµþsçrïpt ærë sµppørtëð øñlÿ ïñ Pÿthøñ 3.10 æñð ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","assignmentInProtocol":"[vey5h][นั้Ïñstæñçë ør çlæss værïæþlës wïthïñ æ Prøtøçøl çlæss mµst þë ëxplïçïtlÿ ðëçlærëð wïthïñ thë çlæss þøðÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","assignmentTargetExpr":"[22xbu][นั้Ëxprëssïøñ çæññøt þë æssïgñmëñt tærgëtẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","asyncNotInAsyncFunction":"[u0Y7U][นั้Üsë øf \\"æsÿñç\\" ñøt ælløwëð øµtsïðë øf æsÿñç fµñçtïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","awaitIllegal":"[2Wa68][นั้Üsë øf \\"æwæït\\" rëqµïrës Pÿthøñ 3.5 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","awaitNotAllowed":"[TpX77][นั้Tÿpë æññøtætïøñs çæññøt µsë \\"æwæït\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","awaitNotInAsync":"[qau2Q][นั้\\"æwæït\\" ælløwëð øñlÿ wïthïñ æsÿñç fµñçtïøñẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","backticksIllegal":"[V1LZI][นั้Ëxprëssïøñs sµrrøµñðëð þÿ þæçktïçks ærë ñøt sµppørtëð ïñ Pÿthøñ 3.x; µsë rëpr ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","baseClassCircular":"[frqWt][นั้Çlæss çæññøt ðërïvë frøm ïtsëlfẤğ倪İЂҰक्र्तिृนั้ढूँ]","baseClassFinal":"[C9i92][นั้ßæsë çlæss \\"{tÿpë}\\" ïs mærkëð fïñæl æñð çæññøt þë sµþçlæssëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","baseClassIncompatible":"[K3wZ2][นั้ßæsë çlæssës øf {tÿpë} ærë mµtµællÿ ïñçømpætïþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","baseClassInvalid":"[qULQr][นั้Ærgµmëñt tø çlæss mµst þë æ þæsë çlæssẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","baseClassMethodTypeIncompatible":"[2lM0z][นั้ßæsë çlæssës før çlæss \\"{çlæssTÿpë}\\" ðëfïñë mëthøð \\"{ñæmë}\\" ïñ ïñçømpætïþlë wæÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","baseClassUnknown":"[QQxIX][นั้ßæsë çlæss tÿpë ïs µñkñøwñ, øþsçµrïñg tÿpë øf ðërïvëð çlæssẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","baseClassVariableTypeIncompatible":"[YmxlD][นั้ßæsë çlæssës før çlæss \\"{çlæssTÿpë}\\" ðëfïñë værïæþlë \\"{ñæmë}\\" ïñ ïñçømpætïþlë wæÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","binaryOperationNotAllowed":"[1lzlz][นั้ßïñærÿ øpërætør ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","bindTypeMismatch":"[x4sbf][นั้Çøµlð ñøt þïñð mëthøð \\"{mëthøðÑæmë}\\" þëçæµsë \\"{tÿpë}\\" ïs ñøt æssïgñæþlë tø pæræmëtër \\"{pæræmÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","breakOutsideLoop":"[Ca4Ip][นั้\\"þrëæk\\" çæñ þë µsëð øñlÿ wïthïñ æ løøpẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","callableExtraArgs":"[M3UIb][นั้Ëxpëçtëð øñlÿ twø tÿpë ærgµmëñts tø \\"Çællæþlë\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","callableFirstArg":"[W1wTU][นั้Ëxpëçtëð pæræmëtër tÿpë lïst ør \\"...\\"Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","callableNotInstantiable":"[sJ0Q8][นั้Çæññøt ïñstæñtïætë tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","callableSecondArg":"[9c1cS][นั้Ëxpëçtëð rëtµrñ tÿpë æs sëçøñð tÿpë ærgµmëñt før \\"Çællæþlë\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","casePatternIsIrrefutable":"[NR6tj][นั้Ïrrëfµtæþlë pættërñ ïs ælløwëð øñlÿ før thë læst çæsë stætëmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","classAlreadySpecialized":"[Puetc][นั้Tÿpë \\"{tÿpë}\\" ïs ælrëæðÿ spëçïælïzëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","classDecoratorTypeUnknown":"[FhL8V][นั้Üñtÿpëð çlæss ðëçørætør øþsçµrës tÿpë øf çlæss; ïgñørïñg ðëçørætørẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","classDefinitionCycle":"[21Tlp][นั้Çlæss ðëfïñïtïøñ før \\"{ñæmë}\\" ðëpëñðs øñ ïtsëlfẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","classGetItemClsParam":"[A2iHF][นั้__çlæss_gëtïtëm__ øvërrïðë shøµlð tækë æ \\"çls\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","classMethodClsParam":"[aWMN3][นั้Çlæss mëthøðs shøµlð tækë æ \\"çls\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","classNotRuntimeSubscriptable":"[O9BL6][นั้§µþsçrïpt før çlæss \\"{ñæmë}\\" wïll gëñërætë rµñtïmë ëxçëptïøñ; ëñçløsë tÿpë æññøtætïøñ ïñ qµøtësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","classPatternBuiltInArgPositional":"[DOfs5][นั้Çlæss pættërñ æççëpts øñlÿ pøsïtïøñæl sµþ-pættërñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","classPatternPositionalArgCount":"[B65y5][นั้Tøø mæñÿ pøsïtïøñæl pættërñs før çlæss \\"{tÿpë}\\"; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","classPatternTypeAlias":"[AxDtv][นั้\\"{tÿpë}\\" çæññøt þë µsëð ïñ æ çlæss pættërñ þëçæµsë ït ïs æ spëçïælïzëð tÿpë ælïæsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","classPropertyDeprecated":"[Q6JgP][นั้Çlæss prøpërtïës ærë ðëprëçætëð ïñ Pÿthøñ 3.11 æñð wïll ñøt þë sµppørtëð ïñ Pÿthøñ 3.13Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","classTypeParametersIllegal":"[GybXD][นั้Çlæss tÿpë pæræmëtër sÿñtæx rëqµïrës Pÿthøñ 3.12 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","classVarFirstArgMissing":"[VtcEd][นั้Ëxpëçtëð æ tÿpë ærgµmëñt æftër \\"ÇlæssVær\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","classVarNotAllowed":"[BU07G][นั้\\"ÇlæssVær\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","classVarOverridesInstanceVar":"[UEaro][นั้Çlæss værïæþlë \\"{ñæmë}\\" øvërrïðës ïñstæñçë værïæþlë øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","classVarTooManyArgs":"[Mj1R5][นั้Ëxpëçtëð øñlÿ øñë tÿpë ærgµmëñt æftër \\"ÇlæssVær\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","classVarWithTypeVar":"[6mnjY][นั้\\"ÇlæssVær\\" tÿpë çæññøt ïñçlµðë tÿpë værïæþlësẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","clsSelfParamTypeMismatch":"[MBrCQ][นั้Tÿpë øf pæræmëtër \\"{ñæmë}\\" mµst þë æ sµpërtÿpë øf ïts çlæss \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","codeTooComplexToAnalyze":"[FNQd7][นั้Çøðë ïs tøø çømplëx tø æñælÿzë; rëðµçë çømplëxïtÿ þÿ rëfæçtørïñg ïñtø sµþrøµtïñës ør rëðµçïñg çøñðïtïøñæl çøðë pæthsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","collectionAliasInstantiation":"[rZb8i][นั้Tÿpë \\"{tÿpë}\\" çæññøt þë ïñstæñtïætëð, µsë \\"{ælïæs}\\" ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","comparisonAlwaysFalse":"[N16ve][นั้Çøñðïtïøñ wïll ælwæÿs ëvælµætë tø Fælsë sïñçë thë tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\" hævë ñø øvërlæpẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","comparisonAlwaysTrue":"[0TOLo][นั้Çøñðïtïøñ wïll ælwæÿs ëvælµætë tø Trµë sïñçë thë tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\" hævë ñø øvërlæpẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","comprehensionInDict":"[Orm2O][นั้Çømprëhëñsïøñ çæññøt þë µsëð wïth øthër ðïçtïøñærÿ ëñtrïësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","comprehensionInSet":"[YUnu9][นั้Çømprëhëñsïøñ çæññøt þë µsëð wïth øthër sët ëñtrïësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","concatenateContext":"[8tRy6][นั้\\"Çøñçætëñætë\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","concatenateParamSpecMissing":"[3s1CV][นั้£æst tÿpë ærgµmëñt før \\"Çøñçætëñætë\\" mµst þë æ Pæræm§pëç ør \\"...\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","concatenateTypeArgsMissing":"[aH5g8][นั้\\"Çøñçætëñætë\\" rëqµïrës æt lëæst twø tÿpë ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","conditionalOperandInvalid":"[HnbrG][นั้Ïñvælïð çøñðïtïøñæl øpëræñð øf tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","constantRedefinition":"[oRKBh][นั้\\"{ñæmë}\\" ïs çøñstæñt (þëçæµsë ït ïs µppërçæsë) æñð çæññøt þë rëðëfïñëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","constructorNoArgs":"[2g3jZ][นั้Ëxpëçtëð ñø ærgµmëñts tø \\"{tÿpë}\\" çøñstrµçtørẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","constructorParametersMismatch":"[WWloK][นั้Mïsmætçh þëtwëëñ sïgñætµrë øf __ñëw__ æñð __ïñït__ ïñ çlæss \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","containmentAlwaysFalse":"[e6PIv][นั้Ëxprëssïøñ wïll ælwæÿs ëvælµætë tø Fælsë sïñçë thë tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\" hævë ñø øvërlæpẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","containmentAlwaysTrue":"[8OhUO][นั้Ëxprëssïøñ wïll ælwæÿs ëvælµætë tø Trµë sïñçë thë tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\" hævë ñø øvërlæpẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","continueInFinally":"[RZIyI][นั้\\"çøñtïñµë\\" çæññøt þë µsëð wïthïñ æ fïñællÿ çlæµsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","continueOutsideLoop":"[6ACvd][นั้\\"çøñtïñµë\\" çæñ þë µsëð øñlÿ wïthïñ æ løøpẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","coroutineInConditionalExpression":"[ygK2r][นั้Çøñðïtïøñæl ëxprëssïøñ rëfërëñçës çørøµtïñë whïçh ælwæÿs ëvælµætës tø TrµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","dataClassBaseClassFrozen":"[jjiw4][นั้Æ ñøñ-frøzëñ çlæss çæññøt ïñhërït frøm æ çlæss thæt ïs frøzëñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","dataClassBaseClassNotFrozen":"[KOz4K][นั้Æ frøzëñ çlæss çæññøt ïñhërït frøm æ çlæss thæt ïs ñøt frøzëñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","dataClassConverterFunction":"[FxD8r][นั้Ærgµmëñt øf tÿpë \\"{ærgTÿpë}\\" ïs ñøt æ vælïð çøñvërtër før fïëlð \\"{fïëlðÑæmë}\\" øf tÿpë \\"{fïëlðTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","dataClassConverterOverloads":"[ZJ0SE][นั้Ñø øvërløæðs øf \\"{fµñçÑæmë}\\" ærë vælïð çøñvërtërs før fïëlð \\"{fïëlðÑæmë}\\" øf tÿpë \\"{fïëlðTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","dataClassFieldWithDefault":"[iJuju][นั้Fïëlðs wïthøµt ðëfæµlt vælµës çæññøt æppëær æftër fïëlðs wïth ðëfæµlt vælµësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","dataClassFieldWithPrivateName":"[miQYb][นั้Ðætæçlæss fïëlð çæññøt µsë prïvætë ñæmëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","dataClassFieldWithoutAnnotation":"[zq5t5][นั้Ðætæçlæss fïëlð wïthøµt tÿpë æññøtætïøñ wïll çæµsë rµñtïmë ëxçëptïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","dataClassPostInitParamCount":"[yl0Bg][นั้Ðætæçlæss __pøst_ïñït__ ïñçørrëçt pæræmëtër çøµñt; ñµmþër øf ÏñïtVær fïëlðs ïs {ëxpëçtëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","dataClassPostInitType":"[74TW4][นั้Ðætæçlæss __pøst_ïñït__ mëthøð pæræmëtër tÿpë mïsmætçh før fïëlð \\"{fïëlðÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","dataClassSlotsOverwrite":"[D17er][นั้__sløts__ ïs ælrëæðÿ ðëfïñëð ïñ çlæssẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","dataClassTransformExpectedBoolLiteral":"[y2upJ][นั้Ëxpëçtëð ëxprëssïøñ thæt stætïçællÿ ëvælµætës tø Trµë ør FælsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","dataClassTransformFieldSpecifier":"[xE1Cp][นั้Ëxpëçtëð tµplë øf çlæssës ør fµñçtïøñs þµt rëçëïvëð tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","dataClassTransformPositionalParam":"[Cu7w4][นั้Æll ærgµmëñts tø \\"ðætæçlæss_træñsførm\\" mµst þë këÿwørð ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","dataClassTransformUnknownArgument":"[hLQXL][นั้Ærgµmëñt \\"{ñæmë}\\" ïs ñøt sµppørtëð þÿ ðætæçlæss_træñsførmẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","dataProtocolInSubclassCheck":"[kIIkO][นั้Ðætæ prøtøçøls (whïçh ïñçlµðë ñøñ-mëthøð ættrïþµtës) ærë ñøt ælløwëð ïñ ïssµþçlæss çællsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","declaredReturnTypePartiallyUnknown":"[pDeOu][นั้Ðëçlærëð rëtµrñ tÿpë, \\"{rëtµrñTÿpë}\\", ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","declaredReturnTypeUnknown":"[XRFJs][นั้Ðëçlærëð rëtµrñ tÿpë ïs µñkñøwñẤğ倪İЂҰक्र्तिृนั้ढूँ]","defaultValueContainsCall":"[G3smw][นั้Fµñçtïøñ çælls æñð mµtæþlë øþjëçts ñøt ælløwëð wïthïñ pæræmëtër ðëfæµlt vælµë ëxprëssïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","defaultValueNotAllowed":"[SuRpb][นั้Pæræmëtër wïth \\"*\\" ør \\"**\\" çæññøt hævë ðëfæµlt vælµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","delTargetExpr":"[VLtXk][นั้Ëxprëssïøñ çæññøt þë ðëlëtëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","deprecatedClass":"[DIyRn][นั้Thë çlæss \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","deprecatedConstructor":"[jq4aQ][นั้Thë çøñstrµçtør før çlæss \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","deprecatedDescriptorDeleter":"[ljYHS][นั้Thë \\"__ðëlëtë__\\" mëthøð før ðësçrïptør \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","deprecatedDescriptorGetter":"[06Y3N][นั้Thë \\"__gët__\\" mëthøð  før ðësçrïptør \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","deprecatedDescriptorSetter":"[6nQQu][นั้Thë \\"__sët__\\" mëthøð  før ðësçrïptør \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","deprecatedFunction":"[GdF0l][นั้Thë fµñçtïøñ \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","deprecatedMethod":"[GxfND][นั้Thë mëthøð \\"{ñæmë}\\" ïñ çlæss \\"{çlæssÑæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","deprecatedPropertyDeleter":"[BUlI2][นั้Thë ðëlëtër før prøpërtÿ \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","deprecatedPropertyGetter":"[54BuI][นั้Thë gëttër før prøpërtÿ \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","deprecatedPropertySetter":"[EHGoz][นั้Thë sëttër før prøpërtÿ \\"{ñæmë}\\" ïs ðëprëçætëðẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","deprecatedType":"[IWdSs][นั้Thïs tÿpë ïs ðëprëçætëð æs øf Pÿthøñ {vërsïøñ}; µsë \\"{rëplæçëmëñt}\\" ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","dictExpandIllegalInComprehension":"[3B8LL][นั้Ðïçtïøñærÿ ëxpæñsïøñ ñøt ælløwëð ïñ çømprëhëñsïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","dictInAnnotation":"[0UcII][นั้Ðïçtïøñærÿ ëxprëssïøñ ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","dictKeyValuePairs":"[Hnd6W][นั้Ðïçtïøñærÿ ëñtrïës mµst çøñtæïñ këÿ/vælµë pæïrsẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","dictUnpackIsNotMapping":"[RhO60][นั้Ëxpëçtëð mæppïñg før ðïçtïøñærÿ µñpæçk øpërætørẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","dunderAllSymbolNotPresent":"[mlrcI][นั้\\"{ñæmë}\\" ïs spëçïfïëð ïñ __æll__ þµt ïs ñøt prësëñt ïñ møðµlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","duplicateArgsParam":"[bt3Os][นั้Øñlÿ øñë \\"*\\" pæræmëtër ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateBaseClass":"[HIzyw][นั้Ðµplïçætë þæsë çlæss ñøt ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateCapturePatternTarget":"[zq38Z][นั้Çæptµrë tærgët \\"{ñæmë}\\" çæññøt æppëær mørë thæñ øñçë wïthïñ thë sæmë pættërñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","duplicateCatchAll":"[6gO00][นั้Øñlÿ øñë çætçh-æll ëxçëpt çlæµsë ælløwëðẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","duplicateEnumMember":"[k9W8A][นั้Ëñµm mëmþër \\"{ñæmë}\\" ïs ælrëæðÿ ðëçlærëðẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","duplicateGenericAndProtocolBase":"[4EO4W][นั้Øñlÿ øñë Gëñërïç[...] ør Prøtøçøl[...] þæsë çlæss ælløwëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","duplicateImport":"[qgZGm][นั้\\"{ïmpørtÑæmë}\\" ïs ïmpørtëð mørë thæñ øñçëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","duplicateKeywordOnly":"[pbf3W][นั้Øñlÿ øñë \\"*\\" sëpærætør ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateKwargsParam":"[4QsUE][นั้Øñlÿ øñë \\"**\\" pæræmëtër ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateParam":"[s0XGf][นั้Ðµplïçætë pæræmëtër \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","duplicatePositionOnly":"[9hzW4][นั้Øñlÿ øñë \\"/\\" pæræmëtër ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateStarPattern":"[8quwQ][นั้Øñlÿ øñë \\"*\\" pættërñ ælløwëð ïñ æ pættërñ sëqµëñçëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","duplicateStarStarPattern":"[wScoI][นั้Øñlÿ øñë \\"**\\" ëñtrÿ ælløwëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","duplicateUnpack":"[wjeOP][นั้Øñlÿ øñë µñpæçk øpërætïøñ ælløwëð ïñ lïstẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","ellipsisAfterUnpacked":"[4EsWH][นั้\\"...\\" çæññøt þë µsëð wïth æñ µñpæçkëð TÿpëVærTµplë ør tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","ellipsisContext":"[Y4jK3][นั้\\"...\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","ellipsisSecondArg":"[pvXJA][นั้\\"...\\" ïs ælløwëð øñlÿ æs thë sëçøñð øf twø ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","enumClassOverride":"[2JsL1][นั้Ëñµm çlæss \\"{ñæmë}\\" ïs fïñæl æñð çæññøt þë sµþçlæssëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","exceptionGroupIncompatible":"[d0SLP][นั้Ëxçëptïøñ grøµp sÿñtæx (\\"ëxçëpt*\\") rëqµïrës Pÿthøñ 3.11 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","exceptionTypeIncorrect":"[G7AZt][นั้\\"{tÿpë}\\" ðøës ñøt ðërïvë frøm ßæsëËxçëptïøñẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","exceptionTypeNotClass":"[v1FmY][นั้\\"{tÿpë}\\" ïs ñøt æ vælïð ëxçëptïøñ çlæssẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","exceptionTypeNotInstantiable":"[PfdeG][นั้Çøñstrµçtør før ëxçëptïøñ tÿpë \\"{tÿpë}\\" rëqµïrës øñë ør mørë ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedAfterDecorator":"[rzMVF][นั้Ëxpëçtëð fµñçtïøñ ør çlæss ðëçlærætïøñ æftër ðëçørætørẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","expectedArrow":"[DrZKr][นั้Ëxpëçtëð \\"->\\" følløwëð þÿ rëtµrñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","expectedAsAfterException":"[FDdTe][นั้Ëxpëçtëð \\"æs\\" æftër ëxçëptïøñ tÿpëẤğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedAssignRightHandExpr":"[mPzHP][นั้Ëxpëçtëð ëxprëssïøñ tø thë rïght øf \\"=\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","expectedBinaryRightHandExpr":"[MgqnF][นั้Ëxpëçtëð ëxprëssïøñ tø thë rïght øf øpërætørẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","expectedBoolLiteral":"[bhZAe][นั้Ëxpëçtëð Trµë ør FælsëẤğ倪İЂҰक्र्นั้ढूँ]","expectedCase":"[kQ1sa][นั้Ëxpëçtëð \\"çæsë\\" stætëmëñtẤğ倪İЂҰक्र्นั้ढूँ]","expectedClassName":"[f0XRc][นั้Ëxpëçtëð çlæss ñæmëẤğ倪İЂҰक्นั้ढूँ]","expectedCloseBrace":"[MQHKY][นั้\\"{\\" wæs ñøt çløsëðẤğ倪İЂҰक्นั้ढूँ]","expectedCloseBracket":"[YfM0n][นั้\\"[\\" wæs ñøt çløsëðẤğ倪İЂҰक्นั้ढूँ]","expectedCloseParen":"[tAuag][นั้\\"(\\" wæs ñøt çløsëðẤğ倪İЂҰक्นั้ढूँ]","expectedColon":"[KmzHa][นั้Ëxpëçtëð \\":\\"Ấğ倪İЂนั้ढूँ]","expectedComplexNumberLiteral":"[dc2rM][นั้Ëxpëçtëð çømplëx ñµmþër lïtëræl før pættërñ mætçhïñgẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","expectedDecoratorExpr":"[415JG][นั้Ëxprëssïøñ førm ñøt sµppørtëð før ðëçørætør prïør tø Pÿthøñ 3.9Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","expectedDecoratorName":"[IKO4m][นั้Ëxpëçtëð ðëçørætør ñæmëẤğ倪İЂҰक्र्นั้ढूँ]","expectedDecoratorNewline":"[Bsyx3][นั้Ëxpëçtëð ñëw lïñë æt ëñð øf ðëçørætørẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","expectedDelExpr":"[u8JgL][นั้Ëxpëçtëð ëxprëssïøñ æftër \\"ðël\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","expectedElse":"[eROaU][นั้Ëxpëçtëð \\"ëlsë\\"Ấğ倪İЂҰนั้ढूँ]","expectedEquals":"[TXK4x][นั้Ëxpëçtëð \\"=\\"Ấğ倪İЂนั้ढूँ]","expectedExceptionClass":"[sYtUr][นั้Ïñvælïð ëxçëptïøñ çlæss ør øþjëçtẤğ倪İЂҰक्र्तिृนั้ढूँ]","expectedExceptionObj":"[w4tAQ][นั้Ëxpëçtëð ëxçëptïøñ øþjëçt, ëxçëptïøñ çlæss ør ÑøñëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","expectedExpr":"[iKSsw][นั้Ëxpëçtëð ëxprëssïøñẤğ倪İЂҰक्นั้ढूँ]","expectedFunctionAfterAsync":"[fWBMb][นั้Ëxpëçtëð fµñçtïøñ ðëfïñïtïøñ æftër \\"æsÿñç\\"Ấğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","expectedFunctionName":"[cR036][นั้Ëxpëçtëð fµñçtïøñ ñæmë æftër \\"ðëf\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedIdentifier":"[Lj4l5][นั้Ëxpëçtëð ïðëñtïfïërẤğ倪İЂҰक्นั้ढूँ]","expectedImport":"[FNK2F][นั้Ëxpëçtëð \\"ïmpørt\\"Ấğ倪İЂҰक्นั้ढूँ]","expectedImportAlias":"[mb4fF][นั้Ëxpëçtëð sÿmþøl æftër \\"æs\\"Ấğ倪İЂҰक्र्นั้ढूँ]","expectedImportSymbols":"[QUZ7S][นั้Ëxpëçtëð øñë ør mørë sÿmþøl ñæmës æftër ïmpørtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","expectedIn":"[9XkiC][นั้Ëxpëçtëð \\"ïñ\\"Ấğ倪İЂนั้ढूँ]","expectedInExpr":"[RXryp][นั้Ëxpëçtëð ëxprëssïøñ æftër \\"ïñ\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","expectedIndentedBlock":"[7ZvJC][นั้Ëxpëçtëð ïñðëñtëð þløçkẤğ倪İЂҰक्र्นั้ढूँ]","expectedMemberName":"[VvTAF][นั้Ëxpëçtëð mëmþër ñæmë æftër \\".\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","expectedModuleName":"[Jky7g][นั้Ëxpëçtëð møðµlë ñæmëẤğ倪İЂҰक्นั้ढूँ]","expectedNameAfterAs":"[KnNbR][นั้Ëxpëçtëð sÿmþøl ñæmë æftër \\"æs\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","expectedNamedParameter":"[ZsE8l][นั้Këÿwørð pæræmëtër mµst følløw \\"*\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","expectedNewline":"[bW0cY][นั้Ëxpëçtëð ñëwlïñëẤğ倪İЂҰนั้ढूँ]","expectedNewlineOrSemicolon":"[av2Gz][นั้§tætëmëñts mµst þë sëpærætëð þÿ ñëwlïñës ør sëmïçøløñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","expectedOpenParen":"[CLuzo][นั้Ëxpëçtëð \\"(\\"Ấğ倪İЂนั้ढूँ]","expectedParamName":"[b0il7][นั้Ëxpëçtëð pæræmëtër ñæmëẤğ倪İЂҰक्र्นั้ढूँ]","expectedPatternExpr":"[76AU4][นั้Ëxpëçtëð pættërñ ëxprëssïøñẤğ倪İЂҰक्र्तिृนั้ढूँ]","expectedPatternSubjectExpr":"[GUw9q][นั้Ëxpëçtëð pættërñ sµþjëçt ëxprëssïøñẤğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedPatternValue":"[Ah06c][นั้Ëxpëçtëð pættërñ vælµë ëxprëssïøñ øf thë førm \\"æ.þ\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","expectedReturnExpr":"[nyeYf][นั้Ëxpëçtëð ëxprëssïøñ æftër \\"rëtµrñ\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedSliceIndex":"[0HjFA][นั้Ëxpëçtëð ïñðëx ør slïçë ëxprëssïøñẤğ倪İЂҰक्र्तिृまนั้ढूँ]","expectedTypeNotString":"[FXeAr][นั้Ëxpëçtëð tÿpë þµt rëçëïvëð æ strïñg lïtërælẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","expectedTypeParameterName":"[aHX5Q][นั้Ëxpëçtëð tÿpë pæræmëtër ñæmëẤğ倪İЂҰक्र्तिृนั้ढूँ]","expectedYieldExpr":"[TrB0N][นั้Ëxpëçtëð ëxprëssïøñ ïñ ÿïëlð stætëmëñtẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","finalClassIsAbstract":"[qEcDN][นั้Çlæss \\"{tÿpë}\\" ïs mærkëð fïñæl æñð mµst ïmplëmëñt æll æþstræçt sÿmþølsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","finalContext":"[KT2Ma][นั้\\"Fïñæl\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","finalMethodOverride":"[rVyi2][นั้Mëthøð \\"{ñæmë}\\" çæññøt øvërrïðë fïñæl mëthøð ðëfïñëð ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","finalNonMethod":"[ITFlU][นั้Fµñçtïøñ \\"{ñæmë}\\" çæññøt þë mærkëð @fïñæl þëçæµsë ït ïs ñøt æ mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","finalReassigned":"[fgpqP][นั้\\"{ñæmë}\\" ïs ðëçlærëð æs Fïñæl æñð çæññøt þë rëæssïgñëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","finalRedeclaration":"[8jVSa][นั้\\"{ñæmë}\\" wæs prëvïøµslÿ ðëçlærëð æs FïñælẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","finalRedeclarationBySubclass":"[0VswQ][นั้\\"{ñæmë}\\" çæññøt þë rëðëçlærëð þëçæµsë pærëñt çlæss \\"{çlæssÑæmë}\\" ðëçlærës ït æs FïñælẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","finalTooManyArgs":"[9fleE][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"Fïñæl\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","finalUnassigned":"[PmdtN][นั้\\"{ñæmë}\\" ïs ðëçlærëð Fïñæl, þµt vælµë ïs ñøt æssïgñëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","formatStringBrace":"[j606J][นั้§ïñglë çløsë þræçë ñøt ælløwëð wïthïñ f-strïñg lïtëræl; µsë ðøµþlë çløsë þræçëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","formatStringBytes":"[1Xo44][นั้Førmæt strïñg lïtëræls (f-strïñgs) çæññøt þë þïñærÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","formatStringDebuggingIllegal":"[mQueA][นั้F-strïñg ðëþµggïñg spëçïfïër \\"=\\" rëqµïrës Pÿthøñ 3.8 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","formatStringEscape":"[lcP3H][นั้Ësçæpë sëqµëñçë (þæçkslæsh) ñøt ælløwëð ïñ ëxprëssïøñ pørtïøñ øf f-strïñg prïør tø Pÿthøñ 3.12Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","formatStringExpectedConversion":"[AjO2F][นั้Ëxpëçtëð æ çøñvërsïøñ spëçïfïër æftër \\"!\\" ïñ f-strïñgẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","formatStringIllegal":"[HhOeX][นั้Førmæt strïñg lïtëræls (f-strïñgs) rëqµïrë Pÿthøñ 3.6 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","formatStringInPattern":"[KqV2l][นั้Førmæt strïñg ñøt ælløwëð ïñ pættërñẤğ倪İЂҰक्र्तिृまนั้ढूँ]","formatStringNestedFormatSpecifier":"[OFqi6][นั้Ëxprëssïøñs ñëstëð tøø ðëëplÿ wïthïñ førmæt strïñg spëçïfïërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","formatStringNestedQuote":"[buq49][นั้§trïñgs ñëstëð wïthïñ æñ f-strïñg çæññøt µsë thë sæmë qµøtë çhæræçtër æs thë f-strïñg prïør tø Pÿthøñ 3.12Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","formatStringUnicode":"[RCCfD][นั้Førmæt strïñg lïtëræls (f-strïñgs) çæññøt þë µñïçøðëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","formatStringUnterminated":"[PnOZr][นั้Üñtërmïñætëð ëxprëssïøñ ïñ f-strïñg; ëxpëçtïñg \\"}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","functionDecoratorTypeUnknown":"[Gv66U][นั้Üñtÿpëð fµñçtïøñ ðëçørætør øþsçµrës tÿpë øf fµñçtïøñ; ïgñørïñg ðëçørætørẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","functionInConditionalExpression":"[9A68n][นั้Çøñðïtïøñæl ëxprëssïøñ rëfërëñçës fµñçtïøñ whïçh ælwæÿs ëvælµætës tø TrµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","functionTypeParametersIllegal":"[0JM96][นั้Fµñçtïøñ tÿpë pæræmëtër sÿñtæx rëqµïrës Pÿthøñ 3.12 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","futureImportLocationNotAllowed":"[IdoQY][นั้Ïmpørts frøm __fµtµrë__ mµst þë æt thë þëgïññïñg øf thë fïlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","generatorAsyncReturnType":"[dYKl9][นั้Rëtµrñ tÿpë øf æsÿñç gëñërætør fµñçtïøñ mµst þë çømpætïþlë wïth \\"ÆsÿñçGëñërætør[{ÿïëlðTÿpë}, Æñÿ]\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","generatorNotParenthesized":"[WmWZM][นั้Gëñërætør ëxprëssïøñs mµst þë pærëñthësïzëð ïf ñøt sølë ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","generatorSyncReturnType":"[ASD1z][นั้Rëtµrñ tÿpë øf gëñërætør fµñçtïøñ mµst þë çømpætïþlë wïth \\"Gëñërætør[{ÿïëlðTÿpë}, Æñÿ, Æñÿ]\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","genericBaseClassNotAllowed":"[fniUT][นั้\\"Gëñërïç\\" þæsë çlæss çæññøt þë µsëð wïth tÿpë pæræmëtër sÿñtæxẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","genericClassAssigned":"[iU1tH][นั้Gëñërïç çlæss tÿpë çæññøt þë æssïgñëðẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","genericClassDeleted":"[C942e][นั้Gëñërïç çlæss tÿpë çæññøt þë ðëlëtëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","genericInstanceVariableAccess":"[rpanq][นั้Æççëss tø gëñërïç ïñstæñçë værïæþlë thrøµgh çlæss ïs æmþïgµøµsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","genericNotAllowed":"[vnF07][นั้\\"Gëñërïç\\" ïs ñøt vælïð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","genericTypeAliasBoundTypeVar":"[S1NAS][นั้Gëñërïç tÿpë ælïæs wïthïñ çlæss çæññøt µsë þøµñð tÿpë værïæþlës {ñæmës}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","genericTypeArgMissing":"[OlCEv][นั้\\"Gëñërïç\\" rëqµïrës æt lëæst øñë tÿpë ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","genericTypeArgTypeVar":"[09E7H][นั้Tÿpë ærgµmëñt før \\"Gëñërïç\\" mµst þë æ tÿpë værïæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","genericTypeArgUnique":"[xHwpY][นั้Tÿpë ærgµmëñts før \\"Gëñërïç\\" mµst þë µñïqµëẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","globalReassignment":"[B2UyK][นั้\\"{ñæmë}\\" ïs æssïgñëð þëførë gløþæl ðëçlærætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","globalRedefinition":"[UZSMp][นั้\\"{ñæmë}\\" wæs ælrëæðÿ ðëçlærëð gløþælẤğ倪İЂҰक्र्तिृまนั้ढूँ]","implicitStringConcat":"[t0D1l][นั้Ïmplïçït strïñg çøñçætëñætïøñ ñøt ælløwëðẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","importCycleDetected":"[FFPSZ][นั้Çÿçlë ðëtëçtëð ïñ ïmpørt çhæïñẤğ倪İЂҰक्र्तिृนั้ढूँ]","importDepthExceeded":"[8G4s1][นั้Ïmpørt çhæïñ ðëpth ëxçëëðëð {ðëpth}Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","importResolveFailure":"[oBYA4][นั้Ïmpørt \\"{ïmpørtÑæmë}\\" çøµlð ñøt þë rësølvëðẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","importSourceResolveFailure":"[hjHFa][นั้Ïmpørt \\"{ïmpørtÑæmë}\\" çøµlð ñøt þë rësølvëð frøm søµrçëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","importSymbolUnknown":"[jY9ZH][นั้\\"{ñæmë}\\" ïs µñkñøwñ ïmpørt sÿmþølẤğ倪İЂҰक्र्तिृนั้ढूँ]","incompatibleMethodOverride":"[i45Ka][นั้Mëthøð \\"{ñæmë}\\" øvërrïðës çlæss \\"{çlæssÑæmë}\\" ïñ æñ ïñçømpætïþlë mæññërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","inconsistentIndent":"[gdrcy][นั้Üñïñðëñt æmøµñt ðøës ñøt mætçh prëvïøµs ïñðëñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","inconsistentTabs":"[I3Z6K][นั้Ïñçøñsïstëñt µsë øf tæþs æñð spæçës ïñ ïñðëñtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","initMustReturnNone":"[RlXyC][นั้Rëtµrñ tÿpë øf \\"__ïñït__\\" mµst þë ÑøñëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","initSubclassCallFailed":"[w22Kh][นั้Ïñçørrëçt këÿwørð ærgµmëñts før __ïñït_sµþçlæss__ mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","initSubclassClsParam":"[6CWuS][นั้__ïñït_sµþçlæss__ øvërrïðë shøµlð tækë æ \\"çls\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","initVarNotAllowed":"[Bb6V0][นั้\\"ÏñïtVær\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","instanceMethodSelfParam":"[dPZPj][นั้Ïñstæñçë mëthøðs shøµlð tækë æ \\"sëlf\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","instanceVarOverridesClassVar":"[cfYeg][นั้Ïñstæñçë værïæþlë \\"{ñæmë}\\" øvërrïðës çlæss værïæþlë øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","instantiateAbstract":"[IyeLb][นั้Çæññøt ïñstæñtïætë æþstræçt çlæss \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","instantiateProtocol":"[Xa6p2][นั้Çæññøt ïñstæñtïætë prøtøçøl çlæss \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","internalBindError":"[PnkgK][นั้Æñ ïñtërñæl ërrør øççµrrëð whïlë þïñðïñg fïlë \\"{fïlë}\\": {mëssægë}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","internalParseError":"[T91nL][นั้Æñ ïñtërñæl ërrør øççµrrëð whïlë pærsïñg fïlë \\"{fïlë}\\": {mëssægë}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","internalTypeCheckingError":"[9E5Bn][นั้Æñ ïñtërñæl ërrør øççµrrëð whïlë tÿpë çhëçkïñg fïlë \\"{fïlë}\\": {mëssægë}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","invalidIdentifierChar":"[Vpy5i][นั้Ïñvælïð çhæræçtër ïñ ïðëñtïfïërẤğ倪İЂҰक्र्तिृนั้ढूँ]","invalidStubStatement":"[sxuu1][นั้§tætëmëñt ïs mëæñïñglëss wïthïñ æ tÿpë stµþ fïlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","invalidTokenChars":"[n9Jty][นั้Ïñvælïð çhæræçtër \\"{tëxt}\\" ïñ tøkëñẤğ倪İЂҰक्र्तिृまนั้ढूँ]","isInstanceInvalidType":"[Q3jK3][นั้§ëçøñð ærgµmëñt tø \\"ïsïñstæñçë\\" mµst þë æ çlæss ør tµplë øf çlæssësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","isSubclassInvalidType":"[6Q7qf][นั้§ëçøñð ærgµmëñt tø \\"ïssµþçlæss\\" mµst þë æ çlæss ør tµplë øf çlæssësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","keyValueInSet":"[tmmyt][นั้Këÿ/vælµë pæïrs ærë ñøt ælløwëð wïthïñ æ sëtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","keywordArgInTypeArgument":"[BzcKx][นั้Këÿwørð ærgµmëñts çæññøt þë µsëð ïñ tÿpë ærgµmëñt lïstsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","keywordOnlyAfterArgs":"[RLvT4][นั้Këÿwørð-øñlÿ ærgµmëñt sëpærætør ñøt ælløwëð æftër \\"*\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","keywordParameterMissing":"[gTcAl][นั้Øñë ør mørë këÿwørð pæræmëtërs mµst følløw \\"*\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","keywordSubscriptIllegal":"[khu47][นั้Këÿwørð ærgµmëñts wïthïñ sµþsçrïpts ærë ñøt sµppørtëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","lambdaReturnTypePartiallyUnknown":"[Z5ML1][นั้Rëtµrñ tÿpë øf læmþðæ, \\"{rëtµrñTÿpë}\\", ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","lambdaReturnTypeUnknown":"[h4icY][นั้Rëtµrñ tÿpë øf læmþðæ ïs µñkñøwñẤğ倪İЂҰक्र्तिृนั้ढूँ]","listAssignmentMismatch":"[DZh64][นั้Ëxprëssïøñ wïth tÿpë \\"{tÿpë}\\" çæññøt þë æssïgñëð tø tærgët lïstẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","listInAnnotation":"[i5U8t][นั้£ïst ëxprëssïøñ ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","literalEmptyArgs":"[VkrFm][นั้Ëxpëçtëð øñë ør mørë tÿpë ærgµmëñts æftër \\"£ïtëræl\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","literalNotAllowed":"[FAk6E][นั้\\"£ïtëræl\\" çæññøt þë µsëð ïñ thïs çøñtëxt wïthøµt æ tÿpë ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","literalNotCallable":"[C75sx][นั้£ïtëræl tÿpë çæññøt þë ïñstæñtïætëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","literalUnsupportedType":"[10Yse][นั้Tÿpë ærgµmëñts før \\"£ïtëræl\\" mµst þë Ñøñë, æ lïtëræl vælµë (ïñt, þøøl, str, ør þÿtës), ør æñ ëñµm vælµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","matchIncompatible":"[9ljpM][นั้Mætçh stætëmëñts rëqµïrë Pÿthøñ 3.10 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","matchIsNotExhaustive":"[BJ8EI][นั้Çæsës wïthïñ mætçh stætëmëñt ðø ñøt ëxhæµstïvëlÿ hæñðlë æll vælµësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","maxParseDepthExceeded":"[5nAZx][นั้Mæxïmµm pærsë ðëpth ëxçëëðëð; þrëæk ëxprëssïøñ ïñtø smællër sµþ-ëxprëssïøñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","memberAccess":"[YP5V0][นั้Çæññøt æççëss mëmþër \\"{ñæmë}\\" før tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","memberDelete":"[o47cn][นั้Çæññøt ðëlëtë mëmþër \\"{ñæmë}\\" før tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","memberSet":"[JCDqa][นั้Çæññøt æssïgñ mëmþër \\"{ñæmë}\\" før tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","metaclassConflict":"[XgAJj][นั้Thë mëtæçlæss øf æ ðërïvëð çlæss mµst þë æ sµþçlæss øf thë mëtæçlæssës øf æll ïts þæsë çlæssësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","metaclassDuplicate":"[wrGuH][นั้Øñlÿ øñë mëtæçlæss çæñ þë prøvïðëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","metaclassIsGeneric":"[K5fXC][นั้Mëtæçlæss çæññøt þë gëñërïçẤğ倪İЂҰक्र्तिृนั้ढूँ]","methodNotDefined":"[ZuPf7][นั้\\"{ñæmë}\\" mëthøð ñøt ðëfïñëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","methodNotDefinedOnType":"[sEtO5][นั้\\"{ñæmë}\\" mëthøð ñøt ðëfïñëð øñ tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","methodOrdering":"[0M0tn][นั้Çæññøt çrëætë çøñsïstëñt mëthøð ørðërïñgẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","methodOverridden":"[2Bu15][นั้\\"{ñæmë}\\" øvërrïðës mëthøð øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\" wïth ïñçømpætïþlë tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","methodReturnsNonObject":"[9nnVb][นั้\\"{ñæmë}\\" mëthøð ðøës ñøt rëtµrñ æñ øþjëçtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","missingSuperCall":"[jNXGA][นั้Mëthøð \\"{mëthøðÑæmë}\\" ðøës ñøt çæll thë mëthøð øf thë sæmë ñæmë ïñ pærëñt çlæssẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","moduleAsType":"[p9N4B][นั้Møðµlë çæññøt þë µsëð æs æ tÿpëẤğ倪İЂҰक्र्तिृนั้ढूँ]","moduleNotCallable":"[YY0Jq][นั้Møðµlë ïs ñøt çællæþlëẤğ倪İЂҰक्र्นั้ढूँ]","moduleUnknownMember":"[tegoa][นั้\\"{mëmþërÑæmë}\\" ïs ñøt æ kñøwñ mëmþër øf møðµlë \\"{møðµlëÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","namedExceptAfterCatchAll":"[pMR1l][นั้Æ ñæmëð ëxçëpt çlæµsë çæññøt æppëær æftër çætçh-æll ëxçëpt çlæµsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","namedParamAfterParamSpecArgs":"[sF38r][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" çæññøt æppëær ïñ sïgñætµrë æftër Pæræm§pëç ærgs pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","namedTupleEmptyName":"[vnXqF][นั้Ñæmës wïthïñ æ ñæmëð tµplë çæññøt þë ëmptÿẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","namedTupleEntryRedeclared":"[0tiaC][นั้Çæññøt øvërrïðë \\"{ñæmë}\\" þëçæµsë pærëñt çlæss \\"{çlæssÑæmë}\\" ïs æ ñæmëð tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","namedTupleFirstArg":"[L5ZXq][นั้Ëxpëçtëð ñæmëð tµplë çlæss ñæmë æs fïrst ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","namedTupleMultipleInheritance":"[KYJOA][นั้Mµltïplë ïñhërïtæñçë wïth ÑæmëðTµplë ïs ñøt sµppørtëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","namedTupleNameKeyword":"[g6NTa][นั้Fïëlð ñæmës çæññøt þë æ këÿwørðẤğ倪İЂҰक्र्तिृนั้ढूँ]","namedTupleNameType":"[AxfdS][นั้Ëxpëçtëð twø-ëñtrÿ tµplë spëçïfÿïñg ëñtrÿ ñæmë æñð tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","namedTupleNameUnique":"[TQaej][นั้Ñæmës wïthïñ æ ñæmëð tµplë mµst þë µñïqµëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","namedTupleNoTypes":"[Fn6FF][นั้\\"ñæmëðtµplë\\" prøvïðës ñø tÿpës før tµplë ëñtrïës; µsë \\"ÑæmëðTµplë\\" ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","namedTupleSecondArg":"[SqoXY][นั้Ëxpëçtëð ñæmëð tµplë ëñtrÿ lïst æs sëçøñð ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","newClsParam":"[EUESX][นั้__ñëw__ øvërrïðë shøµlð tækë æ \\"çls\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","newTypeAnyOrUnknown":"[D4ZjA][นั้Thë sëçøñð ærgµmëñt tø ÑëwTÿpë mµst þë æ kñøwñ çlæss, ñøt Æñÿ ør ÜñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","newTypeBadName":"[cqWvO][นั้Thë fïrst ærgµmëñt tø ÑëwTÿpë mµst þë æ strïñg lïtërælẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","newTypeLiteral":"[4k8om][นั้ÑëwTÿpë çæññøt þë µsëð wïth £ïtëræl tÿpëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","newTypeNameMismatch":"[kQgMv][นั้ÑëwTÿpë mµst þë æssïgñëð tø æ værïæþlë wïth thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","newTypeNotAClass":"[ta6tZ][นั้Ëxpëçtëð çlæss æs sëçøñð ærgµmëñt tø ÑëwTÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","newTypeParamCount":"[6b2ro][นั้ÑëwTÿpë rëqµïrës twø pøsïtïøñæl ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","newTypeProtocolClass":"[1l02t][นั้ÑëwTÿpë çæññøt þë µsëð wïth strµçtµræl tÿpë (æ prøtøçøl ør TÿpëðÐïçt çlæss)Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","noOverload":"[IcBNQ][นั้Ñø øvërløæðs før \\"{ñæmë}\\" mætçh thë prøvïðëð ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","noReturnContainsReturn":"[nBLDq][นั้Fµñçtïøñ wïth ðëçlærëð rëtµrñ tÿpë \\"ÑøRëtµrñ\\" çæññøt ïñçlµðë æ rëtµrñ stætëmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","noReturnContainsYield":"[V3G36][นั้Fµñçtïøñ wïth ðëçlærëð rëtµrñ tÿpë \\"ÑøRëtµrñ\\" çæññøt ïñçlµðë æ ÿïëlð stætëmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","noReturnReturnsNone":"[O3XA6][นั้Fµñçtïøñ wïth ðëçlærëð rëtµrñ tÿpë \\"ÑøRëtµrñ\\" çæññøt rëtµrñ \\"Ñøñë\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","nonDefaultAfterDefault":"[mFFgP][นั้Ñøñ-ðëfæµlt ærgµmëñt følløws ðëfæµlt ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","nonLocalInModule":"[kmLlv][นั้Ñøñløçæl ðëçlærætïøñ ñøt ælløwëð æt møðµlë lëvëlẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","nonLocalNoBinding":"[WTA2d][นั้Ñø þïñðïñg før ñøñløçæl \\"{ñæmë}\\" føµñðẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","nonLocalReassignment":"[T1M6J][นั้\\"{ñæmë}\\" ïs æssïgñëð þëførë ñøñløçæl ðëçlærætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","nonLocalRedefinition":"[gwh1h][นั้\\"{ñæmë}\\" wæs ælrëæðÿ ðëçlærëð ñøñløçælẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","noneNotCallable":"[sIZ5J][นั้Øþjëçt øf tÿpë \\"Ñøñë\\" çæññøt þë çællëðẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","noneNotIterable":"[spDD0][นั้Øþjëçt øf tÿpë \\"Ñøñë\\" çæññøt þë µsëð æs ïtëræþlë vælµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","noneNotSubscriptable":"[Emzwj][นั้Øþjëçt øf tÿpë \\"Ñøñë\\" ïs ñøt sµþsçrïptæþlëẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","noneNotUsableWith":"[zlOOD][นั้Øþjëçt øf tÿpë \\"Ñøñë\\" çæññøt þë µsëð wïth \\"wïth\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","noneOperator":"[3U0d3][นั้Øpërætør \\"{øpërætør}\\" ñøt sµppørtëð før \\"Ñøñë\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","noneUnknownMember":"[4KvEX][นั้\\"{ñæmë}\\" ïs ñøt æ kñøwñ mëmþër øf \\"Ñøñë\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","notRequiredArgCount":"[uOeAb][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"ÑøtRëqµïrëð\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","notRequiredNotInTypedDict":"[Vl6XL][นั้\\"ÑøtRëqµïrëð\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","objectNotCallable":"[bzlKk][นั้Øþjëçt øf tÿpë \\"{tÿpë}\\" ïs ñøt çællæþlëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","obscuredClassDeclaration":"[ixjN9][นั้Çlæss ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","obscuredFunctionDeclaration":"[O71DX][นั้Fµñçtïøñ ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","obscuredMethodDeclaration":"[m04yf][นั้Mëthøð ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","obscuredParameterDeclaration":"[NaF76][นั้Pæræmëtër ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","obscuredTypeAliasDeclaration":"[0GZdR][นั้Tÿpë ælïæs ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","obscuredVariableDeclaration":"[HR10j][นั้Ðëçlærætïøñ \\"{ñæmë}\\" ïs øþsçµrëð þÿ æ ðëçlærætïøñ øf thë sæmë ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","operatorLessOrGreaterDeprecated":"[bNZp7][นั้Øpërætør \\"<>\\" ïs ñøt sµppørtëð ïñ Pÿthøñ 3; µsë \\"!=\\" ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","optionalExtraArgs":"[yW5W0][นั้Ëxpëçtëð øñë tÿpë ærgµmëñt æftër \\"Øptïøñæl\\"Ấğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","orPatternIrrefutable":"[peFRW][นั้Ïrrëfµtæþlë pættërñ ælløwëð øñlÿ æs thë læst sµþpættërñ ïñ æñ \\"ør\\" pættërñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","orPatternMissingName":"[OxMxP][นั้Æll sµþpættërñs wïthïñ æñ \\"ør\\" pættërñ mµst tærgët thë sæmë ñæmësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overlappingKeywordArgs":"[46dQE][นั้Tÿpëð ðïçtïøñærÿ øvërlæps wïth këÿwørð pæræmëtër: {ñæmës}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","overlappingOverload":"[SCQMv][นั้Øvërløæð {øþsçµrëð} før \\"{ñæmë}\\" wïll ñëvër þë µsëð þëçæµsë ïts pæræmëtërs øvërlæp øvërløæð {øþsçµrëðßÿ}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","overloadAbstractMismatch":"[54DCM][นั้Øvërløæðëð mëthøðs mµst æll þë æþstræçt ør ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","overloadClassMethodInconsistent":"[8y6vM][นั้Øvërløæðs før \\"{ñæmë}\\" µsë @çlæssmëthøð ïñçøñsïstëñtlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","overloadFinalInconsistencyImpl":"[0hpZY][นั้Øvërløæð før \\"{ñæmë}\\" ïs mærkëð @fïñæl þµt ïmplëmëñtætïøñ ïs ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overloadFinalInconsistencyNoImpl":"[Z6TSL][นั้Øvërløæð {ïñðëx} før \\"{ñæmë}\\" ïs mærkëð @fïñæl þµt øvërløæð 1 ïs ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overloadImplementationMismatch":"[dXlXE][นั้Øvërløæðëð ïmplëmëñtætïøñ ïs ñøt çøñsïstëñt wïth sïgñætµrë øf øvërløæð {ïñðëx}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","overloadReturnTypeMismatch":"[6BN74][นั้Øvërløæð {prëvÏñðëx} før \\"{ñæmë}\\" øvërlæps øvërløæð {ñëwÏñðëx} æñð rëtµrñs æñ ïñçømpætïþlë tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","overloadStaticMethodInconsistent":"[PKQvM][นั้Øvërløæðs før \\"{ñæmë}\\" µsë @stætïçmëthøð ïñçøñsïstëñtlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","overloadWithoutImplementation":"[mn33a][นั้\\"{ñæmë}\\" ïs mærkëð æs øvërløæð, þµt ñø ïmplëmëñtætïøñ ïs prøvïðëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overriddenMethodNotFound":"[YKdBy][นั้Mëthøð \\"{ñæmë}\\" ïs mærkëð æs øvërrïðë, þµt ñø þæsë mëthøð øf sæmë ñæmë ïs prësëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","overrideDecoratorMissing":"[2BnJq][นั้Mëthøð \\"{ñæmë}\\" ïs ñøt mærkëð æs øvërrïðë þµt ïs øvërrïðïñg æ mëthøð ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","paramAfterKwargsParam":"[wJZkp][นั้Pæræmëtër çæññøt følløw \\"**\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","paramAlreadyAssigned":"[srzhT][นั้Pæræmëtër \\"{ñæmë}\\" ïs ælrëæðÿ æssïgñëðẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","paramAnnotationMissing":"[1OYGc][นั้Tÿpë æññøtætïøñ ïs mïssïñg før pæræmëtër \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","paramAssignmentMismatch":"[Q8zha][นั้Ëxprëssïøñ øf tÿpë \\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø pæræmëtër øf tÿpë \\"{pæræmTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","paramNameMissing":"[ivXu4][นั้Ñø pæræmëtër ñæmëð \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","paramSpecArgsKwargsUsage":"[oVRV0][นั้\\"ærgs\\" æñð \\"kwærgs\\" mëmþërs øf Pæræm§pëç mµst þøth æppëær wïthïñ æ fµñçtïøñ sïgñætµrëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","paramSpecArgsMissing":"[rd6zO][นั้Ærgµmëñts før Pæræm§pëç \\"{tÿpë}\\" ærë mïssïñgẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","paramSpecArgsUsage":"[2U9SN][นั้\\"ærgs\\" mëmþër øf Pæræm§pëç ïs vælïð øñlÿ whëñ µsëð wïth *ærgs pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","paramSpecAssignedName":"[ww5mM][นั้Pæræm§pëç mµst þë æssïgñëð tø æ værïæþlë ñæmëð \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","paramSpecContext":"[y6xyK][นั้Pæræm§pëç ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","paramSpecDefaultNotTuple":"[6Tdff][นั้Ëxpëçtëð ëllïpsïs, æ tµplë ëxprëssïøñ, ør Pæræm§pëç før ðëfæµlt vælµë øf Pæræm§pëçẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","paramSpecFirstArg":"[W2Y3X][นั้Ëxpëçtëð ñæmë øf Pæræm§pëç æs fïrst ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","paramSpecKwargsUsage":"[2UE71][นั้\\"kwærgs\\" mëmþër øf Pæræm§pëç ïs vælïð øñlÿ whëñ µsëð wïth **kwærgs pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","paramSpecNotUsedByOuterScope":"[5Pk7H][นั้Pæræm§pëç \\"{ñæmë}\\" hæs ñø mëæñïñg ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","paramSpecScopedToReturnType":"[vVuXS][นั้Pæræm§pëç \\"{ñæmë}\\" ïs sçøpëð tø æ çællæþlë wïthïñ thë rëtµrñ tÿpë æñð çæññøt þë rëfërëñçëð ïñ thë fµñçtïøñ þøðÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","paramSpecUnknownArg":"[6zeYc][นั้Pæræm§pëç ðøës ñøt sµppørt mørë thæñ øñë ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","paramSpecUnknownMember":"[GhhiY][นั้\\"{ñæmë}\\" ïs ñøt æ kñøwñ mëmþër øf Pæræm§pëçẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","paramSpecUnknownParam":"[YADLo][นั้\\"{ñæmë}\\" ïs µñkñøwñ pæræmëtër tø Pæræm§pëçẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","paramTypeCovariant":"[USAuF][นั้Çøværïæñt tÿpë værïæþlë çæññøt þë µsëð ïñ pæræmëtër tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","paramTypePartiallyUnknown":"[1ShLP][นั้Tÿpë øf pæræmëtër \\"{pæræmÑæmë}\\" ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","paramTypeUnknown":"[fweDh][นั้Tÿpë øf pæræmëtër \\"{pæræmÑæmë}\\" ïs µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","parenthesizedContextManagerIllegal":"[NBxCb][นั้Pærëñthësës wïthïñ \\"wïth\\" stætëmëñt rëqµïrës Pÿthøñ 3.9 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","patternNeverMatches":"[lyG7p][นั้Pættërñ wïll ñëvër þë mætçhëð før sµþjëçt tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","positionArgAfterNamedArg":"[szCz2][นั้Pøsïtïøñæl ærgµmëñt çæññøt æppëær æftër këÿwørð ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","positionOnlyAfterArgs":"[Vqb7c][นั้Pøsïtïøñ-øñlÿ pæræmëtër sëpærætør ñøt ælløwëð æftër \\"*\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","positionOnlyAfterKeywordOnly":"[z1FIK][นั้\\"/\\" pæræmëtër mµst æppëær þëførë \\"*\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","positionOnlyAfterNon":"[iXb2r][นั้Pøsïtïøñ-øñlÿ pæræmëtër ñøt ælløwëð æftër pæræmëtër thæt ïs ñøt pøsïtïøñ-øñlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","positionOnlyFirstParam":"[bmnbs][นั้Pøsïtïøñ-øñlÿ pæræmëtër sëpærætør ñøt ælløwëð æs fïrst pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","positionOnlyIncompatible":"[Ick28][นั้Pøsïtïøñ-øñlÿ pæræmëtër sëpærætør rëqµïrës Pÿthøñ 3.8 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","privateImportFromPyTypedModule":"[VRdf4][นั้\\"{ñæmë}\\" ïs ñøt ëxpørtëð frøm møðµlë \\"{møðµlë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","privateUsedOutsideOfClass":"[3YBNL][นั้\\"{ñæmë}\\" ïs prïvætë æñð µsëð øµtsïðë øf thë çlæss ïñ whïçh ït ïs ðëçlærëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","privateUsedOutsideOfModule":"[TgDgt][นั้\\"{ñæmë}\\" ïs prïvætë æñð µsëð øµtsïðë øf thë møðµlë ïñ whïçh ït ïs ðëçlærëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","propertyOverridden":"[mwp5C][นั้\\"{ñæmë}\\" ïñçørrëçtlÿ øvërrïðës prøpërtÿ øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","propertyStaticMethod":"[qs3pr][นั้§tætïç mëthøðs ñøt ælløwëð før prøpërtÿ gëttër, sëttër ør ðëlëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","protectedUsedOutsideOfClass":"[z2Y7X][นั้\\"{ñæmë}\\" ïs prøtëçtëð æñð µsëð øµtsïðë øf thë çlæss ïñ whïçh ït ïs ðëçlærëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","protocolBaseClass":"[lv3rP][นั้Prøtøçøl çlæss \\"{çlæssTÿpë}\\" çæññøt ðërïvë frøm ñøñ-prøtøçøl çlæss \\"{þæsëTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","protocolBaseClassWithTypeArgs":"[tpYEx][นั้Tÿpë ærgµmëñts ærë ñøt ælløwëð wïth Prøtøçøl çlæss whëñ µsïñg tÿpë pæræmëtër sÿñtæxẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","protocolIllegal":"[jYjYe][นั้Üsë øf \\"Prøtøçøl\\" rëqµïrës Pÿthøñ 3.7 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","protocolNotAllowed":"[2GEt6][นั้\\"Prøtøçøl\\" çæññøt þë µsëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","protocolUnsafeOverlap":"[79LbC][นั้Çlæss øvërlæps \\"{ñæmë}\\" µñsæfëlÿ æñð çøµlð prøðµçë æ mætçh æt rµñtïmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","protocolVarianceContravariant":"[B4htZ][นั้Tÿpë værïæþlë \\"{værïæþlë}\\" µsëð ïñ gëñërïç prøtøçøl \\"{çlæss}\\" shøµlð þë çøñtræværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","protocolVarianceCovariant":"[Hcnn5][นั้Tÿpë værïæþlë \\"{værïæþlë}\\" µsëð ïñ gëñërïç prøtøçøl \\"{çlæss}\\" shøµlð þë çøværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","protocolVarianceInvariant":"[o8oB7][นั้Tÿpë værïæþlë \\"{værïæþlë}\\" µsëð ïñ gëñërïç prøtøçøl \\"{çlæss}\\" shøµlð þë ïñværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","pyrightCommentInvalidDiagnosticBoolValue":"[eaJY0][นั้Pÿrïght çømmëñt ðïrëçtïvë mµst þë følløwëð þÿ \\"=\\" æñð æ vælµë øf trµë ør fælsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","pyrightCommentInvalidDiagnosticSeverityValue":"[2YA7K][นั้Pÿrïght çømmëñt ðïrëçtïvë mµst þë følløwëð þÿ \\"=\\" æñð æ vælµë øf trµë, fælsë, ërrør, wærñïñg, ïñførmætïøñ, ør ñøñëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","pyrightCommentMissingDirective":"[yy6rB][นั้Pÿrïght çømmëñt mµst þë følløwëð þÿ æ ðïrëçtïvë (þæsïç ør strïçt) ør æ ðïægñøstïç rµlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","pyrightCommentNotOnOwnLine":"[mM2bV][นั้Pÿrïght çømmëñts µsëð tø çøñtrøl fïlë-lëvël sëttïñgs mµst æppëær øñ thëïr øwñ lïñëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","pyrightCommentUnknownDiagnosticRule":"[DFAZp][นั้\\"{rµlë}\\" ïs æñ µñkñøwñ ðïægñøstïç rµlë før pÿrïght çømmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","pyrightCommentUnknownDiagnosticSeverityValue":"[Tgt0Y][นั้\\"{vælµë}\\" ïs ïñvælïð vælµë før pÿrïght çømmëñt; ëxpëçtëð trµë, fælsë, ërrør, wærñïñg, ïñførmætïøñ, ør ñøñëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","pyrightCommentUnknownDirective":"[HD6T4][นั้\\"{ðïrëçtïvë}\\" ïs æñ µñkñøwñ ðïrëçtïvë før pÿrïght çømmëñt; ëxpëçtëð \\"strïçt\\" ør \\"þæsïç\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","readOnlyArgCount":"[B1Erm][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"RëæðØñlÿ\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","readOnlyNotInTypedDict":"[xJrLN][นั้\\"RëæðØñlÿ\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","recursiveDefinition":"[G3UUN][นั้Tÿpë øf \\"{ñæmë}\\" çøµlð ñøt þë ðëtërmïñëð þëçæµsë ït rëfërs tø ïtsëlfẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","relativeImportNotAllowed":"[JZqjC][นั้Rëlætïvë ïmpørts çæññøt þë µsëð wïth \\"ïmpørt .æ\\" førm; µsë \\"frøm . ïmpørt æ\\" ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","requiredArgCount":"[aZX4z][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"Rëqµïrëð\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","requiredNotInTypedDict":"[TArW6][นั้\\"Rëqµïrëð\\" ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","returnInAsyncGenerator":"[qb5pt][นั้Rëtµrñ stætëmëñt wïth vælµë ïs ñøt ælløwëð ïñ æsÿñç gëñërætørẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","returnMissing":"[kPevK][นั้Fµñçtïøñ wïth ðëçlærëð rëtµrñ tÿpë \\"{rëtµrñTÿpë}\\" mµst rëtµrñ vælµë øñ æll çøðë pæthsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","returnOutsideFunction":"[O4SJp][นั้\\"rëtµrñ\\" çæñ þë µsëð øñlÿ wïthïñ æ fµñçtïøñẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","returnTypeContravariant":"[KkMhh][นั้Çøñtræværïæñt tÿpë værïæþlë çæññøt þë µsëð ïñ rëtµrñ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","returnTypeMismatch":"[QYqHy][นั้Ëxprëssïøñ øf tÿpë \\"{ëxprTÿpë}\\" çæññøt þë æssïgñëð tø rëtµrñ tÿpë \\"{rëtµrñTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","returnTypePartiallyUnknown":"[261DZ][นั้Rëtµrñ tÿpë, \\"{rëtµrñTÿpë}\\", ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","returnTypeUnknown":"[II3Ix][นั้Rëtµrñ tÿpë ïs µñkñøwñẤğ倪İЂҰक्र्นั้ढूँ]","revealLocalsArgs":"[qKEIL][นั้Ëxpëçtëð ñø ærgµmëñts før \\"rëvëæl_løçæls\\" çællẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","revealLocalsNone":"[xOTfI][นั้Ñø løçæls ïñ thïs sçøpëẤğ倪İЂҰक्र्นั้ढूँ]","revealTypeArgs":"[Sdo9V][นั้Ëxpëçtëð æ sïñglë pøsïtïøñæl ærgµmëñt før \\"rëvëæl_tÿpë\\" çællẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","revealTypeExpectedTextArg":"[6cFBk][นั้Thë \\"ëxpëçtëð_tëxt\\" ærgµmëñt før fµñçtïøñ \\"rëvëæl_tÿpë\\" mµst þë æ str lïtëræl vælµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","revealTypeExpectedTextMismatch":"[ILnEV][นั้Tÿpë tëxt mïsmætçh; ëxpëçtëð \\"{ëxpëçtëð}\\" þµt rëçëïvëð \\"{rëçëïvëð}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","revealTypeExpectedTypeMismatch":"[3XS8T][นั้Tÿpë mïsmætçh; ëxpëçtëð \\"{ëxpëçtëð}\\" þµt rëçëïvëð \\"{rëçëïvëð}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","selfTypeContext":"[Hugyy][นั้\\"§ëlf\\" ïs ñøt vælïð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","selfTypeMetaclass":"[YvoBy][นั้\\"§ëlf\\" çæññøt þë µsëð wïthïñ æ mëtæçlæss (æ sµþçlæss øf \\"tÿpë\\")Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","selfTypeWithTypedSelfOrCls":"[sYgyY][นั้\\"§ëlf\\" çæññøt þë µsëð ïñ æ fµñçtïøñ wïth æ `sëlf` ør `çls` pæræmëtër thæt hæs æ tÿpë æññøtætïøñ øthër thæñ \\"§ëlf\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","setterGetterTypeMismatch":"[8ZD1z][นั้Prøpërtÿ sëttër vælµë tÿpë ïs ñøt æssïgñæþlë tø thë gëttër rëtµrñ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","singleOverload":"[YQVUc][นั้\\"{ñæmë}\\" ïs mærkëð æs øvërløæð, þµt æððïtïøñæl øvërløæðs ærë mïssïñgẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","slotsAttributeError":"[OF4rK][นั้\\"{ñæmë}\\" ïs ñøt spëçïfïëð ïñ __sløts__Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","slotsClassVarConflict":"[tcS3q][นั้\\"{ñæmë}\\" çøñflïçts wïth ïñstæñçë værïæþlë ðëçlærëð ïñ __sløts__Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","starPatternInAsPattern":"[ZFdWe][นั้§tær pættërñ çæññøt þë µsëð wïth \\"æs\\" tærgëtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","starPatternInOrPattern":"[y9LX3][นั้§tær pættërñ çæññøt þë ØRëð wïthïñ øthër pættërñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","starStarWildcardNotAllowed":"[Ll1UV][นั้** çæññøt þë µsëð wïth wïlðçærð \\"_\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","staticClsSelfParam":"[mO4QU][นั้§tætïç mëthøðs shøµlð ñøt tækë æ \\"sëlf\\" ør \\"çls\\" pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","stdlibModuleOverridden":"[AV6K3][นั้\\"{pæth}\\" ïs øvërrïðïñg thë stðlïþ møðµlë \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","stringNonAsciiBytes":"[dFNRn][นั้Ñøñ-Æ§ÇÏÏ çhæræçtër ñøt ælløwëð ïñ þÿtës strïñg lïtërælẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","stringNotSubscriptable":"[hKZT7][นั้§trïñg ëxprëssïøñ çæññøt þë sµþsçrïptëð ïñ tÿpë æññøtætïøñ; ëñçløsë ëñtïrë æññøtætïøñ ïñ qµøtësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","stringUnsupportedEscape":"[K2WsY][นั้Üñsµppørtëð ësçæpë sëqµëñçë ïñ strïñg lïtërælẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","stringUnterminated":"[jUKYA][นั้§trïñg lïtëræl ïs µñtërmïñætëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","stubFileMissing":"[Ua5GT][นั้§tµþ fïlë ñøt føµñð før \\"{ïmpørtÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","stubUsesGetAttr":"[KMBwK][นั้Tÿpë stµþ fïlë ïs ïñçømplëtë; \\"__gëtættr__\\" øþsçµrës tÿpë ërrørs før møðµlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","sublistParamsIncompatible":"[582LE][นั้§µþlïst pæræmëtërs ærë ñøt sµppørtëð ïñ Pÿthøñ 3.xẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","superCallArgCount":"[iLYq6][นั้Ëxpëçtëð ñø mørë thæñ twø ærgµmëñts tø \\"sµpër\\" çællẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","superCallFirstArg":"[HSEvD][นั้Ëxpëçtëð çlæss tÿpë æs fïrst ærgµmëñt tø \\"sµpër\\" çæll þµt rëçëïvëð \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","superCallSecondArg":"[dKoHi][นั้§ëçøñð ærgµmëñt tø \\"sµpër\\" çæll mµst þë øþjëçt ør çlæss thæt ðërïvës frøm \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","superCallZeroArgForm":"[0XO27][นั้Zërø-ærgµmëñt førm øf \\"sµpër\\" çæll ïs vælïð øñlÿ wïthïñ æ mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","superCallZeroArgFormStaticMethod":"[9hJPB][นั้Zërø-ærgµmëñt førm øf \\"sµpër\\" çæll ïs ñøt vælïð wïthïñ æ stætïç mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","symbolIsPossiblyUnbound":"[cUgue][นั้\\"{ñæmë}\\" ïs pøssïþlÿ µñþøµñðẤğ倪İЂҰक्र्तिृนั้ढूँ]","symbolIsUnbound":"[zhGl5][นั้\\"{ñæmë}\\" ïs µñþøµñðẤğ倪İЂҰक्นั้ढूँ]","symbolIsUndefined":"[qCm6F][นั้\\"{ñæmë}\\" ïs ñøt ðëfïñëðẤğ倪İЂҰक्र्นั้ढूँ]","symbolOverridden":"[JwRrv][นั้\\"{ñæmë}\\" øvërrïðës sÿmþøl øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","ternaryNotAllowed":"[5NH6C][นั้Tërñærÿ ëxprëssïøñ ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","totalOrderingMissingMethod":"[eYfjn][นั้Çlæss mµst ðëfïñë øñë øf \\"__lt__\\", \\"__lë__\\", \\"__gt__\\", ør \\"__gë__\\" tø µsë tøtæl_ørðërïñgẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","trailingCommaInFromImport":"[NcaZY][นั้Træïlïñg çømmæ ñøt ælløwëð wïthøµt sµrrøµñðïñg pærëñthësësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","tryWithoutExcept":"[6z9oA][นั้Trÿ stætëmëñt mµst hævë æt lëæst øñë ëxçëpt ør fïñællÿ çlæµsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","tupleAssignmentMismatch":"[xySRW][นั้Ëxprëssïøñ wïth tÿpë \\"{tÿpë}\\" çæññøt þë æssïgñëð tø tærgët tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","tupleInAnnotation":"[j2RAZ][นั้Tµplë ëxprëssïøñ ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","tupleIndexOutOfRange":"[aNqDv][นั้Ïñðëx {ïñðëx} ïs øµt øf ræñgë før tÿpë {tÿpë}Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeAliasIllegalExpressionForm":"[4u4ay][นั้Ïñvælïð ëxprëssïøñ førm før tÿpë ælïæs ðëfïñïtïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeAliasIsRecursiveDirect":"[r8PyZ][นั้Tÿpë ælïæs \\"{ñæmë}\\" çæññøt µsë ïtsëlf ïñ ïts ðëfïñïtïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeAliasNotInModuleOrClass":"[iQpDJ][นั้Æ TÿpëÆlïæs çæñ þë ðëfïñëð øñlÿ wïthïñ æ møðµlë ør çlæss sçøpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeAliasRedeclared":"[P036x][นั้\\"{ñæmë}\\" ïs ðëçlærëð æs æ TÿpëÆlïæs æñð çæñ þë æssïgñëð øñlÿ øñçëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeAliasStatementBadScope":"[C24Up][นั้Æ tÿpë stætëmëñt çæñ þë µsëð øñlÿ wïthïñ æ møðµlë ør çlæss sçøpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeAliasStatementIllegal":"[2EW0Q][นั้Tÿpë ælïæs stætëmëñt rëqµïrës Pÿthøñ 3.12 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeAliasTypeBaseClass":"[RIpMs][นั้Æ tÿpë ælïæs ðëfïñëð ïñ æ \\"tÿpë\\" stætëmëñt çæññøt þë µsëð æs æ þæsë çlæssẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typeAliasTypeMustBeAssigned":"[aV4Nn][นั้TÿpëÆlïæsTÿpë mµst þë æssïgñëð tø æ værïæþlë wïth thë sæmë ñæmë æs thë tÿpë ælïæsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeAliasTypeNameArg":"[dUUf1][นั้Fïrst ærgµmëñt tø TÿpëÆlïæsTÿpë mµst þë æ strïñg lïtëræl rëprësëñtïñg thë ñæmë øf thë tÿpë ælïæsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeAliasTypeNameMismatch":"[jW1bQ][นั้Ñæmë øf tÿpë ælïæs mµst mætçh thë ñæmë øf thë værïæþlë tø whïçh ït ïs æssïgñëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typeAliasTypeParamInvalid":"[RdHRE][นั้Tÿpë pæræmëtër lïst mµst þë æ tµplë çøñtæïñïñg øñlÿ TÿpëVær, TÿpëVærTµplë, ør Pæræm§pëçẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeAnnotationCall":"[7pNts][นั้Çæll ëxprëssïøñ ñøt ælløwëð ïñ tÿpë ëxprëssïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeAnnotationVariable":"[GeXWQ][นั้Værïæþlë ñøt ælløwëð ïñ tÿpë ëxprëssïøñẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeAnnotationWithCallable":"[JJENJ][นั้Tÿpë ærgµmëñt før \\"tÿpë\\" mµst þë æ çlæss; çællæþlës ærë ñøt sµppørtëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typeArgListExpected":"[2efoA][นั้Ëxpëçtëð Pæræm§pëç, ëllïpsïs, ør lïst øf tÿpësẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeArgListNotAllowed":"[oV7JF][นั้£ïst ëxprëssïøñ ñøt ælløwëð før thïs tÿpë ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeArgsExpectingNone":"[faycH][นั้Ëxpëçtëð ñø tÿpë ærgµmëñts før çlæss \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeArgsMismatchOne":"[BBe1n][นั้Ëxpëçtëð øñë tÿpë ærgµmëñt þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeArgsMissingForAlias":"[hk8aw][นั้Ëxpëçtëð tÿpë ærgµmëñts før gëñërïç tÿpë ælïæs \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeArgsMissingForClass":"[SkdfG][นั้Ëxpëçtëð tÿpë ærgµmëñts før gëñërïç çlæss \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeArgsTooFew":"[6PAb0][นั้Tøø fëw tÿpë ærgµmëñts prøvïðëð før \\"{ñæmë}\\"; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeArgsTooMany":"[NKF2Z][นั้Tøø mæñÿ tÿpë ærgµmëñts prøvïðëð før \\"{ñæmë}\\"; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeAssignmentMismatch":"[wwjSP][นั้Ëxprëssïøñ øf tÿpë \\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø ðëçlærëð tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typeAssignmentMismatchWildcard":"[qdgVA][นั้Ïmpørt sÿmþøl \\"{ñæmë}\\" hæs tÿpë \\"{søµrçëTÿpë}\\", whïçh çæññøt þë æssïgñëð tø ðëçlærëð tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeCallNotAllowed":"[OGMmG][นั้tÿpë() çæll shøµlð ñøt þë µsëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeCheckOnly":"[cSmKj][นั้\\"{ñæmë}\\" ïs mærkëð æs @tÿpë_çhëçk_øñlÿ æñð çæñ þë µsëð øñlÿ ïñ tÿpë æññøtætïøñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeCommentDeprecated":"[SRhVz][นั้Üsë øf tÿpë çømmëñts ïs ðëprëçætëð; µsë tÿpë æññøtætïøñ ïñstëæðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeExpectedClass":"[r0pdu][นั้Ëxpëçtëð tÿpë ëxprëssïøñ þµt rëçëïvëð \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeGuardArgCount":"[Zl47K][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"TÿpëGµærð\\" ør \\"TÿpëÏs\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeGuardParamCount":"[I3HUH][นั้Üsër-ðëfïñëð tÿpë gµærð fµñçtïøñs æñð mëthøðs mµst hævë æt lëæst øñë ïñpµt pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeIsReturnType":"[5bBbd][นั้Rëtµrñ tÿpë øf TÿpëÏs (\\"{rëtµrñTÿpë}\\") ïs ñøt çøñsïstëñt wïth vælµë pæræmëtër tÿpë (\\"{tÿpë}\\")Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeNotAwaitable":"[NZ9Yu][นั้\\"{tÿpë}\\" ïs ñøt æwæïtæþlëẤğ倪İЂҰक्र्นั้ढूँ]","typeNotIntantiable":"[f3xEe][นั้\\"{tÿpë}\\" çæññøt þë ïñstæñtïætëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeNotIterable":"[XMDzF][นั้\\"{tÿpë}\\" ïs ñøt ïtëræþlëẤğ倪İЂҰक्र्นั้ढूँ]","typeNotSpecializable":"[ZCsyD][นั้Çøµlð ñøt spëçïælïzë tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","typeNotSubscriptable":"[fpefi][นั้Øþjëçt øf tÿpë \\"{tÿpë}\\" ïs ñøt sµþsçrïptæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeNotSupportBinaryOperator":"[C0OGX][นั้Øpërætør \\"{øpërætør}\\" ñøt sµppørtëð før tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeNotSupportBinaryOperatorBidirectional":"[25nah][นั้Øpërætør \\"{øpërætør}\\" ñøt sµppørtëð før tÿpës \\"{lëftTÿpë}\\" æñð \\"{rïghtTÿpë}\\" whëñ ëxpëçtëð tÿpë ïs \\"{ëxpëçtëðTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeNotSupportUnaryOperator":"[f2pEG][นั้Øpërætør \\"{øpërætør}\\" ñøt sµppørtëð før tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeNotSupportUnaryOperatorBidirectional":"[Z51QN][นั้Øpërætør \\"{øpërætør}\\" ñøt sµppørtëð før tÿpë \\"{tÿpë}\\" whëñ ëxpëçtëð tÿpë ïs \\"{ëxpëçtëðTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeNotUsableWith":"[R7VpZ][นั้Øþjëçt øf tÿpë \\"{tÿpë}\\" çæññøt þë µsëð wïth \\"wïth\\" þëçæµsë ït ðøës ñøt ïmplëmëñt {mëthøð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeParameterBoundNotAllowed":"[iA0kz][นั้ßøµñð ør çøñstræïñt çæññøt þë µsëð wïth æ værïæðïç tÿpë pæræmëtër ør Pæræm§pëçẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typeParameterConstraintTuple":"[8wa57][นั้Tÿpë pæræmëtër çøñstræïñt mµst þë æ tµplë øf twø ør mørë tÿpësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeParameterExistingTypeParameter":"[M2QXP][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" ïs ælrëæðÿ ïñ µsëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeParameterNotDeclared":"[WD9B6][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" ïs ñøt ïñçlµðëð ïñ thë tÿpë pæræmëtër lïst før \\"{çøñtæïñër}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeParametersMissing":"[7nPE2][นั้Æt lëæst øñë tÿpë pæræmëtër mµst þë spëçïfïëðẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typePartiallyUnknown":"[K72xm][นั้Tÿpë øf \\"{ñæmë}\\" ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typeUnknown":"[flab2][นั้Tÿpë øf \\"{ñæmë}\\" ïs µñkñøwñẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeVarAssignedName":"[AnBke][นั้TÿpëVær mµst þë æssïgñëð tø æ værïæþlë ñæmëð \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarAssignmentMismatch":"[IYCuH][นั้Tÿpë \\"{tÿpë}\\" çæññøt þë æssïgñëð tø tÿpë værïæþlë \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarBoundAndConstrained":"[nSFES][นั้TÿpëVær çæññøt þë þøth þøµñð æñð çøñstræïñëðẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeVarBoundGeneric":"[scFkM][นั้TÿpëVær þøµñð tÿpë çæññøt þë gëñërïçẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typeVarConstraintGeneric":"[k7N05][นั้TÿpëVær çøñstræïñt tÿpë çæññøt þë gëñërïçẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeVarDefaultBoundMismatch":"[knxtI][นั้TÿpëVær ðëfæµlt tÿpë mµst þë æ sµþtÿpë øf thë þøµñð tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarDefaultConstraintMismatch":"[BlQvu][นั้TÿpëVær ðëfæµlt tÿpë mµst þë øñë øf thë çøñstræïñëð tÿpësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarDefaultIllegal":"[Z5lrX][นั้Tÿpë værïæþlë ðëfæµlt tÿpës rëqµïrë Pÿthøñ 3.13 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarDefaultInvalidTypeVar":"[bOQ21][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" hæs æ ðëfæµlt tÿpë thæt rëfërs tø øñë ør mørë tÿpë værïæþlës thæt ærë øµt øf sçøpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typeVarFirstArg":"[XBVgA][นั้Ëxpëçtëð ñæmë øf TÿpëVær æs fïrst ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typeVarNoMember":"[Trelb][นั้TÿpëVær \\"{tÿpë}\\" hæs ñø mëmþër \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeVarNotSubscriptable":"[3KoEm][นั้TÿpëVær \\"{tÿpë}\\" ïs ñøt sµþsçrïptæþlëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typeVarNotUsedByOuterScope":"[on7uQ][นั้Tÿpë værïæþlë \\"{ñæmë}\\" hæs ñø mëæñïñg ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarPossiblyUnsolvable":"[PP5xz][นั้Tÿpë værïæþlë \\"{ñæmë}\\" mæÿ gø µñsølvëð ïf çællër sµpplïës ñø ærgµmëñt før pæræmëtër \\"{pæræm}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarScopedToReturnType":"[AYNcY][นั้Tÿpë værïæþlë \\"{ñæmë}\\" ïs sçøpëð tø æ çællæþlë wïthïñ thë rëtµrñ tÿpë æñð çæññøt þë rëfërëñçëð ïñ thë fµñçtïøñ þøðÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeVarSingleConstraint":"[51MwX][นั้TÿpëVær mµst hævë æt lëæst twø çøñstræïñëð tÿpësẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typeVarTupleConstraints":"[ouP8u][นั้TÿpëVærTµplë çæññøt hævë vælµë çøñstræïñtsẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typeVarTupleContext":"[Q8vE2][นั้TÿpëVærTµplë ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typeVarTupleDefaultNotUnpacked":"[S2joz][นั้TÿpëVærTµplë ðëfæµlt tÿpë mµst þë æñ µñpæçkëð tµplë ør TÿpëVærTµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeVarTupleMustBeUnpacked":"[TA5HX][นั้Üñpæçk øpërætør ïs rëqµïrëð før TÿpëVærTµplë vælµëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeVarTupleUnknownParam":"[fOW23][นั้\\"{ñæmë}\\" ïs µñkñøwñ pæræmëtër tø TÿpëVærTµplëẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typeVarUnknownParam":"[veXvU][นั้\\"{ñæmë}\\" ïs µñkñøwñ pæræmëtër tø TÿpëVærẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typeVarUsedByOuterScope":"[GJ5N3][นั้TÿpëVær \\"{ñæmë}\\" ïs ælrëæðÿ ïñ µsë þÿ æñ øµtër sçøpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarUsedOnlyOnce":"[vSn0W][นั้TÿpëVær \\"{ñæmë}\\" æppëærs øñlÿ øñçë ïñ gëñërïç fµñçtïøñ sïgñætµrëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeVarVariance":"[1Dxdn][นั้TÿpëVær çæññøt þë þøth çøværïæñt æñð çøñtræværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeVarWithDefaultFollowsVariadic":"[h1V5a][นั้TÿpëVær \\"{tÿpëVærÑæmë}\\" hæs æ ðëfæµlt vælµë æñð çæññøt følløw TÿpëVærTµplë \\"{værïæðïçÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarWithoutDefault":"[w630R][นั้\\"{ñæmë}\\" çæññøt æppëær æftër \\"{øthër}\\" ïñ tÿpë pæræmëtër lïst þëçæµsë ït hæs ñø ðëfæµlt tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarsNotInGenericOrProtocol":"[ydmAV][นั้Gëñërïç[] ør Prøtøçøl[] mµst ïñçlµðë æll tÿpë værïæþlësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictAccess":"[55CCf][นั้Çøµlð ñøt æççëss ïtëm ïñ TÿpëðÐïçtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictAssignedName":"[Dkf5M][นั้TÿpëðÐïçt mµst þë æssïgñëð tø æ værïæþlë ñæmëð \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictBadVar":"[OL8Ox][นั้TÿpëðÐïçt çlæssës çæñ çøñtæïñ øñlÿ tÿpë æññøtætïøñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typedDictBaseClass":"[HxyA2][นั้Æll þæsë çlæssës før TÿpëðÐïçt çlæssës mµst ælsø þë TÿpëðÐïçt çlæssësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictBoolParam":"[GALOD][นั้Ëxpëçtëð \\"{ñæmë}\\" pæræmëtër tø hævë æ vælµë øf Trµë ør FælsëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typedDictClosedExtras":"[mlkJO][นั้ßæsë çlæss \\"{ñæmë}\\" ïs æ çløsëð TÿpëðÐïçt; ëxtræ ïtëms mµst þë tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typedDictClosedNoExtras":"[BCyXd][นั้ßæsë çlæss \\"{ñæmë}\\" ïs æ çløsëð TÿpëðÐïçt; ëxtræ ïtëms ærë ñøt ælløwëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictDelete":"[bdBu7][นั้Çøµlð ñøt ðëlëtë ïtëm ïñ TÿpëðÐïçtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictEmptyName":"[h45e7][นั้Ñæmës wïthïñ æ TÿpëðÐïçt çæññøt þë ëmptÿẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typedDictEntryName":"[NT4np][นั้Ëxpëçtëð strïñg lïtëræl før ðïçtïøñærÿ ëñtrÿ ñæmëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typedDictEntryUnique":"[nWy0L][นั้Ñæmës wïthïñ æ ðïçtïøñærÿ mµst þë µñïqµëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typedDictExtraArgs":"[0gX32][นั้Ëxtræ TÿpëðÐïçt ærgµmëñts ñøt sµppørtëðẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typedDictFieldNotRequiredRedefinition":"[rNYD1][นั้TÿpëðÐïçt ïtëm \\"{ñæmë}\\" çæññøt þë rëðëfïñëð æs ÑøtRëqµïrëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typedDictFieldReadOnlyRedefinition":"[8IFAz][นั้TÿpëðÐïçt ïtëm \\"{ñæmë}\\" çæññøt þë rëðëfïñëð æs RëæðØñlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictFieldRequiredRedefinition":"[lpw97][นั้TÿpëðÐïçt ïtëm \\"{ñæmë}\\" çæññøt þë rëðëfïñëð æs RëqµïrëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictFirstArg":"[OPlNk][นั้Ëxpëçtëð TÿpëðÐïçt çlæss ñæmë æs fïrst ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typedDictInitsubclassParameter":"[HMpfK][นั้TÿpëðÐïçt ðøës ñøt sµppørt __ïñït_sµþçlæss__ pæræmëtër \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictNotAllowed":"[UWg4F][นั้\\"TÿpëðÐïçt\\" çæññøt þë µsëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typedDictSecondArgDict":"[mwrv7][นั้Ëxpëçtëð ðïçt ør këÿwørð pæræmëtër æs sëçøñð pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictSecondArgDictEntry":"[oAT5Z][นั้Ëxpëçtëð sïmplë ðïçtïøñærÿ ëñtrÿẤğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictSet":"[30hTC][นั้Çøµlð ñøt æssïgñ ïtëm ïñ TÿpëðÐïçtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","unaccessedClass":"[dou8i][นั้Çlæss \\"{ñæmë}\\" ïs ñøt æççëssëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","unaccessedFunction":"[AdgDz][นั้Fµñçtïøñ \\"{ñæmë}\\" ïs ñøt æççëssëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","unaccessedImport":"[2a90g][นั้Ïmpørt \\"{ñæmë}\\" ïs ñøt æççëssëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","unaccessedSymbol":"[MmnM7][นั้\\"{ñæmë}\\" ïs ñøt æççëssëðẤğ倪İЂҰक्र्นั้ढूँ]","unaccessedVariable":"[n5l1e][นั้Værïæþlë \\"{ñæmë}\\" ïs ñøt æççëssëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","unannotatedFunctionSkipped":"[Ovgyl][นั้Æñælÿsïs øf fµñçtïøñ \\"{ñæmë}\\" ïs skïppëð þëçæµsë ït ïs µñæññøtætëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","unaryOperationNotAllowed":"[2WB31][นั้Üñærÿ øpërætør ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unexpectedAsyncToken":"[fKSJb][นั้Ëxpëçtëð \\"ðëf\\", \\"wïth\\" ør \\"før\\" tø følløw \\"æsÿñç\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","unexpectedExprToken":"[MtBsu][นั้Üñëxpëçtëð tøkëñ æt ëñð øf ëxprëssïøñẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","unexpectedIndent":"[uZUVS][นั้Üñëxpëçtëð ïñðëñtætïøñẤğ倪İЂҰक्र्นั้ढूँ]","unexpectedUnindent":"[yqwy4][นั้Üñïñðëñt ñøt ëxpëçtëðẤğ倪İЂҰक्นั้ढूँ]","unhashableDictKey":"[pIvHj][นั้Ðïçtïøñærÿ këÿ mµst þë hæshæþlëẤğ倪İЂҰक्र्तिृนั้ढूँ]","unhashableSetEntry":"[rWf72][นั้§ët ëñtrÿ mµst þë hæshæþlëẤğ倪İЂҰक्र्นั้ढूँ]","uninitializedAbstractVariables":"[SpCPH][นั้Værïæþlës ðëfïñëð ïñ æþstræçt þæsë çlæss ærë ñøt ïñïtïælïzëð ïñ fïñæl çlæss \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","uninitializedInstanceVariable":"[5pgFw][นั้Ïñstæñçë værïæþlë \\"{ñæmë}\\" ïs ñøt ïñïtïælïzëð ïñ thë çlæss þøðÿ ør __ïñït__ mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","unionForwardReferenceNotAllowed":"[MOLby][นั้Üñïøñ sÿñtæx çæññøt þë µsëð wïth strïñg øpëræñð; µsë qµøtës ærøµñð ëñtïrë ëxprëssïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","unionSyntaxIllegal":"[vbTDG][นั้Æltërñætïvë sÿñtæx før µñïøñs rëqµïrës Pÿthøñ 3.10 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unionTypeArgCount":"[vc6vA][นั้Üñïøñ rëqµïrës twø ør mørë tÿpë ærgµmëñtsẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","unionUnpackedTuple":"[owRjE][นั้Üñïøñ çæññøt ïñçlµðë æñ µñpæçkëð tµplëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","unionUnpackedTypeVarTuple":"[a6msY][นั้Üñïøñ çæññøt ïñçlµðë æñ µñpæçkëð TÿpëVærTµplëẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unnecessaryCast":"[QgPoI][นั้Üññëçëssærÿ \\"çæst\\" çæll; tÿpë ïs ælrëæðÿ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","unnecessaryIsInstanceAlways":"[gX4s7][นั้Üññëçëssærÿ ïsïñstæñçë çæll; \\"{tëstTÿpë}\\" ïs ælwæÿs æñ ïñstæñçë øf \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unnecessaryIsSubclassAlways":"[BzHtx][นั้Üññëçëssærÿ ïssµþçlæss çæll; \\"{tëstTÿpë}\\" ïs ælwæÿs æ sµþçlæss øf \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unnecessaryPyrightIgnore":"[7QhdX][นั้Üññëçëssærÿ \\"# pÿrïght: ïgñørë\\" çømmëñtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","unnecessaryPyrightIgnoreRule":"[0ESoQ][นั้Üññëçëssærÿ \\"# pÿrïght: ïgñørë\\" rµlë: \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unnecessaryTypeIgnore":"[IoWr9][นั้Üññëçëssærÿ \\"# tÿpë: ïgñørë\\" çømmëñtẤğ倪İЂҰक्र्तिृまนั้ढूँ]","unpackArgCount":"[bkAT1][นั้Ëxpëçtëð æ sïñglë tÿpë ærgµmëñt æftër \\"Üñpæçk\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unpackExpectedTypeVarTuple":"[CWX8o][นั้Ëxpëçtëð TÿpëVærTµplë ør tµplë æs tÿpë ærgµmëñt før ÜñpæçkẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unpackExpectedTypedDict":"[ha9qw][นั้Ëxpëçtëð TÿpëðÐïçt tÿpë ærgµmëñt før ÜñpæçkẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","unpackIllegalInComprehension":"[7a4pV][นั้Üñpæçk øpërætïøñ ñøt ælløwëð ïñ çømprëhëñsïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unpackInAnnotation":"[6gqFu][นั้Üñpæçk øpërætør ñøt ælløwëð ïñ tÿpë æññøtætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unpackInDict":"[eKn69][นั้Üñpæçk øpërætïøñ ñøt ælløwëð ïñ ðïçtïøñærïësẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unpackInSet":"[lKyO0][นั้Üñpæçk øpërætør ñøt ælløwëð wïthïñ æ sëtẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","unpackNotAllowed":"[MZq6e][นั้Üñpæçk ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","unpackOperatorNotAllowed":"[lMq2B][นั้Üñpæçk øpërætïøñ ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","unpackTuplesIllegal":"[RJvzW][นั้Üñpæçk øpërætïøñ ñøt ælløwëð ïñ tµplës prïør tø Pÿthøñ 3.8Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unpackedArgInTypeArgument":"[skxlo][นั้Üñpæçkëð ærgµmëñts çæññøt þë µsëð ïñ tÿpë ærgµmëñt lïstsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","unpackedArgWithVariadicParam":"[ZP3kP][นั้Üñpæçkëð ærgµmëñt çæññøt þë µsëð før TÿpëVærTµplë pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unpackedDictArgumentNotMapping":"[iSTnU][นั้Ærgµmëñt ëxprëssïøñ æftër ** mµst þë æ mæppïñg wïth æ \\"str\\" këÿ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","unpackedDictSubscriptIllegal":"[slATr][นั้Ðïçtïøñærÿ µñpæçk øpërætør ïñ sµþsçrïpt ïs ñøt ælløwëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","unpackedSubscriptIllegal":"[2CpZz][นั้Üñpæçk øpërætør ïñ sµþsçrïpt rëqµïrës Pÿthøñ 3.11 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unpackedTypeVarTupleExpected":"[tgdHs][นั้Ëxpëçtëð µñpæçkëð TÿpëVærTµplë; µsë Üñpæçk[{ñæmë1}] ør *{ñæmë2}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","unpackedTypedDictArgument":"[iCgjR][นั้Üñæþlë tø mætçh µñpæçkëð TÿpëðÐïçt ærgµmëñt tø pæræmëtërsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unreachableCode":"[bpJSK][นั้Çøðë ïs µñrëæçhæþlëẤğ倪İЂҰक्นั้ढूँ]","unreachableExcept":"[zFMWg][นั้Ëxçëpt çlæµsë ïs µñrëæçhæþlë þëçæµsë ëxçëptïøñ ïs ælrëæðÿ hæñðlëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","unsupportedDunderAllOperation":"[KsX0f][นั้Øpërætïøñ øñ \\"__æll__\\" ïs ñøt sµppørtëð, sø ëxpørtëð sÿmþøl lïst mæÿ þë ïñçørrëçtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","unusedCallResult":"[9IsV5][นั้Rësµlt øf çæll ëxprëssïøñ ïs øf tÿpë \\"{tÿpë}\\" æñð ïs ñøt µsëð; æssïgñ tø værïæþlë \\"_\\" ïf thïs ïs ïñtëñtïøñælẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","unusedCoroutine":"[nQUJ2][นั้Rësµlt øf æsÿñç fµñçtïøñ çæll ïs ñøt µsëð; µsë \\"æwæït\\" ør æssïgñ rësµlt tø værïæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","unusedExpression":"[ghmaU][นั้Ëxprëssïøñ vælµë ïs µñµsëðẤğ倪İЂҰक्र्นั้ढूँ]","varAnnotationIllegal":"[v2cs9][นั้Tÿpë æññøtætïøñs før værïæþlës rëqµïrës Pÿthøñ 3.6 ør ñëwër; µsë tÿpë çømmëñt før çømpætïþïlïtÿ wïth prëvïøµs vërsïøñsẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","variableFinalOverride":"[LcrNS][นั้Værïæþlë \\"{ñæmë}\\" ïs mærkëð Fïñæl æñð øvërrïðës ñøñ-Fïñæl værïæþlë øf sæmë ñæmë ïñ çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","variadicTypeArgsTooMany":"[1QX0D][นั้Tÿpë ærgµmëñt lïst çæñ hævë æt møst øñë µñpæçkëð TÿpëVærTµplë ør tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","variadicTypeParamTooManyAlias":"[43VIR][นั้Tÿpë ælïæs çæñ hævë æt møst øñë TÿpëVærTµplë tÿpë pæræmëtër þµt rëçëïvëð mµltïplë ({ñæmës})Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","variadicTypeParamTooManyClass":"[fboqC][นั้Gëñërïç çlæss çæñ hævë æt møst øñë TÿpëVærTµplë tÿpë pæræmëtër þµt rëçëïvëð mµltïplë ({ñæmës})Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","walrusIllegal":"[iR3y3][นั้Øpërætør \\":=\\" rëqµïrës Pÿthøñ 3.8 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","walrusNotAllowed":"[kdD5j][นั้Øpërætør \\":=\\" ïs ñøt ælløwëð ïñ thïs çøñtëxt wïthøµt sµrrøµñðïñg pærëñthësësẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","wildcardInFunction":"[NyGOv][นั้Wïlðçærð ïmpørt ñøt ælløwëð wïthïñ æ çlæss ør fµñçtïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","wildcardLibraryImport":"[Yk3ai][นั้Wïlðçærð ïmpørt frøm æ lïþrærÿ ñøt ælløwëðẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","wildcardPatternTypePartiallyUnknown":"[eRR5M][นั้Tÿpë çæptµrëð þÿ wïlðçærð pættërñ ïs pærtïællÿ µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","wildcardPatternTypeUnknown":"[Bo3gT][นั้Tÿpë çæptµrëð þÿ wïlðçærð pættërñ ïs µñkñøwñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","yieldFromIllegal":"[DkXto][นั้Üsë øf \\"ÿïëlð frøm\\" rëqµïrës Pÿthøñ 3.3 ør ñëwërẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","yieldFromOutsideAsync":"[ZONEz][นั้\\"ÿïëlð frøm\\" ñøt ælløwëð ïñ æñ æsÿñç fµñçtïøñẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","yieldOutsideFunction":"[2lDBQ][นั้\\"ÿïëlð\\" ñøt ælløwëð øµtsïðë øf æ fµñçtïøñ ør læmþðæẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","yieldWithinListCompr":"[3Rv4s][นั้\\"ÿïëlð\\" ñøt ælløwëð ïñsïðë æ lïst çømprëhëñsïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","zeroCaseStatementsFound":"[ArU3j][นั้Mætçh stætëmëñt mµst ïñçlµðë æt lëæst øñë çæsë stætëmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","zeroLengthTupleNotAllowed":"[3gVpF][นั้Zërø-lëñgth tµplë ïs ñøt ælløwëð ïñ thïs çøñtëxtẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]"},"DiagnosticAddendum":{"annotatedNotAllowed":"[Mws6g][นั้\\"Æññøtætëð\\" spëçïæl førm çæññøt þë µsëð wïth ïñstæñçë æñð çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","argParam":"[nmvvb][นั้Ærgµmëñt çørrëspøñðs tø pæræmëtër \\"{pæræmÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","argParamFunction":"[7Xwg8][นั้Ærgµmëñt çørrëspøñðs tø pæræmëtër \\"{pæræmÑæmë}\\" ïñ fµñçtïøñ \\"{fµñçtïøñÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","argsParamMissing":"[vg3b8][นั้Pæræmëtër \\"*{pæræmÑæmë}\\" hæs ñø çørrëspøñðïñg pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","argsPositionOnly":"[sNlU1][นั้Pøsïtïøñ-øñlÿ pæræmëtër mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","argumentType":"[JJxeD][นั้Ærgµmëñt tÿpë ïs \\"{tÿpë}\\"Ấğ倪İЂҰक्र्นั้ढूँ]","argumentTypes":"[Omlwm][นั้Ærgµmëñt tÿpës: ({tÿpës})Ấğ倪İЂҰक्र्นั้ढूँ]","assignToNone":"[z249G][นั้Tÿpë çæññøt þë æssïgñëð tø tÿpë \\"Ñøñë\\"Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","asyncHelp":"[2nasS][นั้Ðïð ÿøµ mëæñ \\"æsÿñç wïth\\"?Ấğ倪İЂҰक्र्นั้ढूँ]","baseClassIncompatible":"[oW6Ip][นั้ßæsë çlæss \\"{þæsëÇlæss}\\" ïs ïñçømpætïþlë wïth tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","baseClassIncompatibleSubclass":"[mMUCH][นั้ßæsë çlæss \\"{þæsëÇlæss}\\" ðërïvës frøm \\"{sµþçlæss}\\" whïçh ïs ïñçømpætïþlë wïth tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","baseClassOverriddenType":"[Hp8Sl][นั้ßæsë çlæss \\"{þæsëÇlæss}\\" prøvïðës tÿpë \\"{tÿpë}\\", whïçh ïs øvërrïððëñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","baseClassOverridesType":"[P7N4Y][นั้ßæsë çlæss \\"{þæsëÇlæss}\\" øvërrïðës wïth tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","bytesTypePromotions":"[qIXYb][นั้§ët ðïsæþlëßÿtësTÿpëPrømøtïøñs tø fælsë tø ëñæþlë tÿpë prømøtïøñ þëhævïør før \\"þÿtëærræÿ\\" æñð \\"mëmørÿvïëw\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","conditionalRequiresBool":"[k1G9a][นั้Mëthøð __þøøl__ før tÿpë \\"{øpëræñðTÿpë}\\" rëtµrñs tÿpë \\"{þøølRëtµrñTÿpë}\\" ræthër thæñ \\"þøøl\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","dataClassFieldLocation":"[vQxtf][นั้Fïëlð ðëçlærætïøñẤğ倪İЂҰक्นั้ढूँ]","dataClassFrozen":"[d4uiK][นั้\\"{ñæmë}\\" ïs frøzëñẤğ倪İЂҰक्นั้ढूँ]","dataProtocolUnsupported":"[7gIT2][นั้\\"{ñæmë}\\" ïs æ ðætæ prøtøçølẤğ倪İЂҰक्र्तिृนั้ढूँ]","descriptorAccessBindingFailed":"[RiEhE][นั้Fæïlëð tø þïñð mëthøð \\"{ñæmë}\\" før ðësçrïptør çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","descriptorAccessCallFailed":"[8EXvg][นั้Fæïlëð tø çæll mëthøð \\"{ñæmë}\\" før ðësçrïptør çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","finalMethod":"[zz1yN][นั้Fïñæl mëthøðẤğ倪İЂนั้ढूँ]","functionParamDefaultMissing":"[yWAIy][นั้Pæræmëtër \\"{ñæmë}\\" ïs mïssïñg ðëfæµlt ærgµmëñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","functionParamName":"[NrJqx][นั้Pæræmëtër ñæmë mïsmætçh: \\"{ðëstÑæmë}\\" vërsµs \\"{srçÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","functionParamPositionOnly":"[XOhUP][นั้Pøsïtïøñ-øñlÿ pæræmëtër mïsmætçh; pæræmëtër \\"{ñæmë}\\" ïs ñøt pøsïtïøñ-øñlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","functionReturnTypeMismatch":"[x4qH0][นั้Fµñçtïøñ rëtµrñ tÿpë \\"{søµrçëTÿpë}\\" ïs ïñçømpætïþlë wïth tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","functionTooFewParams":"[575uy][นั้Fµñçtïøñ æççëpts tøø fëw pøsïtïøñæl pæræmëtërs; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","functionTooManyParams":"[zj9vw][นั้Fµñçtïøñ æççëpts tøø mæñÿ pøsïtïøñæl pæræmëtërs; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","genericClassNotAllowed":"[MDEt3][นั้Gëñërïç tÿpë wïth tÿpë ærgµmëñts ñøt ælløwëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","incompatibleDeleter":"[LCJuj][นั้Prøpërtÿ ðëlëtër mëthøð ïs ïñçømpætïþlëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","incompatibleGetter":"[yds2G][นั้Prøpërtÿ gëttër mëthøð ïs ïñçømpætïþlëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","incompatibleSetter":"[GDoso][นั้Prøpërtÿ sëttër mëthøð ïs ïñçømpætïþlëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","initMethodLocation":"[D4O2l][นั้Thë __ïñït__ mëthøð ïs ðëfïñëð ïñ çlæss \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","initMethodSignature":"[EULjB][นั้§ïgñætµrë øf __ïñït__ ïs \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","initSubclassLocation":"[eEcCS][นั้Thë __ïñït_sµþçlæss__ mëthøð ïs ðëfïñëð ïñ çlæss \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","invariantSuggestionDict":"[OIoHo][นั้Çøñsïðër swïtçhïñg frøm \\"ðïçt\\" tø \\"Mæppïñg\\" whïçh ïs çøværïæñt ïñ thë vælµë tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","invariantSuggestionList":"[irYWI][นั้Çøñsïðër swïtçhïñg frøm \\"lïst\\" tø \\"§ëqµëñçë\\" whïçh ïs çøværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","invariantSuggestionSet":"[64U47][นั้Çøñsïðër swïtçhïñg frøm \\"sët\\" tø \\"Çøñtæïñër\\" whïçh ïs çøværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","keyNotRequired":"[K1bDP][นั้\\"{ñæmë}\\" ïs ñøt æ rëqµïrëð këÿ ïñ \\"{tÿpë}\\", sø æççëss mæÿ rësµlt ïñ rµñtïmë ëxçëptïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","keyReadOnly":"[dhAH3][นั้\\"{ñæmë}\\" ïs æ rëæð-øñlÿ këÿ ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","keyRequiredDeleted":"[YeZa5][นั้\\"{ñæmë}\\" ïs æ rëqµïrëð këÿ æñð çæññøt þë ðëlëtëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","keyUndefined":"[6mQGu][นั้\\"{ñæmë}\\" ïs ñøt æ ðëfïñëð këÿ ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","kwargsParamMissing":"[KHgb2][นั้Pæræmëtër \\"**{pæræmÑæmë}\\" hæs ñø çørrëspøñðïñg pæræmëtërẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","listAssignmentMismatch":"[fERKI][นั้Tÿpë \\"{tÿpë}\\" ïs ïñçømpætïþlë wïth tærgët lïstẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","literalAssignmentMismatch":"[17LiQ][นั้\\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","matchIsNotExhaustiveHint":"[3NR39][นั้Ïf ëxhæµstïvë hæñðlïñg ïs ñøt ïñtëñðëð, æðð \\"çæsë _: pæss\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","matchIsNotExhaustiveType":"[9RN1P][นั้Üñhæñðlëð tÿpë: \\"{tÿpë}\\"Ấğ倪İЂҰक्र्นั้ढूँ]","memberAssignment":"[1WFCt][นั้Ëxprëssïøñ øf tÿpë \\"{tÿpë}\\" çæññøt þë æssïgñëð tø mëmþër \\"{ñæmë}\\" øf çlæss \\"{çlæssTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","memberIsAbstract":"[l912U][นั้\\"{tÿpë}.{ñæmë}\\" ïs ñøt ïmplëmëñtëðẤğ倪İЂҰक्र्तिृまนั้ढूँ]","memberIsAbstractMore":"[dgfwa][นั้æñð {çøµñt} mørë...Ấğ倪İЂҰक्นั้ढूँ]","memberIsClassVarInProtocol":"[ZZeb4][นั้\\"{ñæmë}\\" ïs ðëfïñëð æs æ ÇlæssVær ïñ prøtøçølẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","memberIsFinalInProtocol":"[chVyJ][นั้\\"{ñæmë}\\" ïs mærkëð Fïñæl ïñ prøtøçølẤğ倪İЂҰक्र्तिृまนั้ढूँ]","memberIsInitVar":"[0SGIB][นั้Mëmþër \\"{ñæmë}\\" ïs æñ ïñït-øñlÿ fïëlðẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","memberIsInvariant":"[rBPX6][นั้\\"{ñæmë}\\" ïs ïñværïæñt þëçæµsë ït ïs mµtæþlëẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","memberIsNotClassVarInClass":"[bKhkE][นั้\\"{ñæmë}\\" mµst þë ðëfïñëð æs æ ÇlæssVær tø þë çømpætïþlë wïth prøtøçølẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","memberIsNotClassVarInProtocol":"[OAmE1][นั้\\"{ñæmë}\\" ïs ñøt ðëfïñëð æs æ ÇlæssVær ïñ prøtøçølẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","memberIsNotFinalInProtocol":"[Mw2lB][นั้\\"{ñæmë}\\" ïs ñøt mærkëð Fïñæl ïñ prøtøçølẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","memberIsWritableInProtocol":"[x53Kg][นั้\\"{ñæmë}\\" ïs wrïtæþlë ïñ prøtøçølẤğ倪İЂҰक्र्तिृนั้ढूँ]","memberSetClassVar":"[2pVfQ][นั้Mëmþër \\"{ñæmë}\\" çæññøt þë æssïgñëð thrøµgh æ çlæss ïñstæñçë þëçæµsë ït ïs æ ÇlæssVærẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","memberTypeMismatch":"[IHN4x][นั้\\"{ñæmë}\\" ïs æñ ïñçømpætïþlë tÿpëẤğ倪İЂҰक्र्तिृนั้ढूँ]","memberUnknown":"[7kDIF][นั้Mëmþër \\"{ñæmë}\\" ïs µñkñøwñẤğ倪İЂҰक्र्นั้ढूँ]","metaclassConflict":"[fjWW1][นั้Mëtæçlæss \\"{mëtæçlæss1}\\" çøñflïçts wïth \\"{mëtæçlæss2}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","missingDeleter":"[5IVNI][นั้Prøpërtÿ ðëlëtër mëthøð ïs mïssïñgẤğ倪İЂҰक्र्तिृまนั้ढूँ]","missingGetter":"[Mzn4K][นั้Prøpërtÿ gëttër mëthøð ïs mïssïñgẤğ倪İЂҰक्र्तिृนั้ढूँ]","missingSetter":"[goeIY][นั้Prøpërtÿ sëttër mëthøð ïs mïssïñgẤğ倪İЂҰक्र्तिृนั้ढूँ]","namedParamMissingInDest":"[dc07X][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" ïs mïssïñg ïñ ðëstïñætïøñẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","namedParamMissingInSource":"[N59fC][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" ïs mïssïñg ïñ søµrçëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","namedParamTypeMismatch":"[9CAV6][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" øf tÿpë \\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","namedTupleNotAllowed":"[gAlSp][นั้ÑæmëðTµplë çæññøt þë µsëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","newMethodLocation":"[n0dxL][นั้Thë __ñëw__ mëthøð ïs ðëfïñëð ïñ çlæss \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","newMethodSignature":"[NeWKO][นั้§ïgñætµrë øf __ñëw__ ïs \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","newTypeClassNotAllowed":"[JQmcY][นั้Çlæss çrëætëð wïth ÑëwTÿpë çæññøt þë µsëð wïth ïñstæñçë æñð çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","noOverloadAssignable":"[FJ88c][นั้Ñø øvërløæðëð fµñçtïøñ mætçhës tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","noneNotAllowed":"[Yn8Lx][นั้Ñøñë çæññøt þë µsëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","orPatternMissingName":"[kgiPM][นั้Mïssïñg ñæmës: {ñæmë}Ấğ倪İЂҰक्นั้ढूँ]","overloadIndex":"[vNPxL][นั้Øvërløæð {ïñðëx} ïs thë çløsëst mætçhẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","overloadNotAssignable":"[BA2kK][นั้Øñë ør mørë øvërløæðs øf \\"{ñæmë}\\" ïs ñøt æssïgñæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","overloadSignature":"[NPzwf][นั้Øvërløæð sïgñætµrë ïs ðëfïñëð hërëẤğ倪İЂҰक्र्तिृまนั้ढूँ]","overriddenMethod":"[CcUB2][นั้Øvërrïððëñ mëthøðẤğ倪İЂҰक्นั้ढूँ]","overriddenSymbol":"[cvpXz][นั้Øvërrïððëñ sÿmþølẤğ倪İЂҰक्นั้ढूँ]","overrideInvariantMismatch":"[uODzM][นั้Øvërrïðë tÿpë \\"{øvërrïðëTÿpë}\\" ïs ñøt thë sæmë æs þæsë tÿpë \\"{þæsëTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","overrideIsInvariant":"[j45KZ][นั้Værïæþlë ïs mµtæþlë sø ïts tÿpë ïs ïñværïæñtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","overrideNoOverloadMatches":"[vG14w][นั้Ñø øvërløæð sïgñætµrë ïñ øvërrïðë ïs çømpætïþlë wïth þæsë mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overrideNotClassMethod":"[t5OaH][นั้ßæsë mëthøð ïs ðëçlærëð æs æ çlæssmëthøð þµt øvërrïðë ïs ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","overrideNotInstanceMethod":"[e2Xo5][นั้ßæsë mëthøð ïs ðëçlærëð æs æñ ïñstæñçë mëthøð þµt øvërrïðë ïs ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overrideNotStaticMethod":"[Eu8Oy][นั้ßæsë mëthøð ïs ðëçlærëð æs æ stætïçmëthøð þµt øvërrïðë ïs ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","overrideOverloadNoMatch":"[smVSW][นั้Øvërrïðë ðøës ñøt hæñðlë æll øvërløæðs øf þæsë mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","overrideOverloadOrder":"[HrUeN][นั้Øvërløæðs før øvërrïðë mëthøð mµst þë ïñ thë sæmë ørðër æs thë þæsë mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","overrideParamKeywordNoDefault":"[yIoa8][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" mïsmætçh: þæsë pæræmëtër hæs ðëfæµlt ærgµmëñt vælµë, øvërrïðë pæræmëtër ðøës ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","overrideParamKeywordType":"[SAOAr][นั้Këÿwørð pæræmëtër \\"{ñæmë}\\" tÿpë mïsmætçh: þæsë pæræmëtër ïs tÿpë \\"{þæsëTÿpë}\\", øvërrïðë pæræmëtër ïs tÿpë \\"{øvërrïðëTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","overrideParamName":"[fRWyy][นั้Pæræmëtër {ïñðëx} ñæmë mïsmætçh: þæsë pæræmëtër ïs ñæmëð \\"{þæsëÑæmë}\\", øvërrïðë pæræmëtër ïs ñæmëð \\"{øvërrïðëÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","overrideParamNameExtra":"[HEG0d][นั้Pæræmëtër \\"{ñæmë}\\" ïs mïssïñg ïñ þæsëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","overrideParamNameMissing":"[PN8Rl][นั้Pæræmëtër \\"{ñæmë}\\" ïs mïssïñg ïñ øvërrïðëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","overrideParamNamePositionOnly":"[3yVlj][นั้Pæræmëtër {ïñðëx} mïsmætçh: þæsë pæræmëtër \\"{þæsëÑæmë}\\" ïs këÿwørð pæræmëtër, øvërrïðë pæræmëtër ïs pøsïtïøñ-øñlÿẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","overrideParamNoDefault":"[azvZD][นั้Pæræmëtër {ïñðëx} mïsmætçh: þæsë pæræmëtër hæs ðëfæµlt ærgµmëñt vælµë, øvërrïðë pæræmëtër ðøës ñøtẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overrideParamType":"[FXBcO][นั้Pæræmëtër {ïñðëx} tÿpë mïsmætçh: þæsë pæræmëtër ïs tÿpë \\"{þæsëTÿpë}\\", øvërrïðë pæræmëtër ïs tÿpë \\"{øvërrïðëTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","overridePositionalParamCount":"[jJZNP][นั้Pøsïtïøñæl pæræmëtër çøµñt mïsmætçh; þæsë mëthøð hæs {þæsëÇøµñt}, þµt øvërrïðë hæs {øvërrïðëÇøµñt}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overrideReturnType":"[mdPwX][นั้Rëtµrñ tÿpë mïsmætçh: þæsë mëthøð rëtµrñs tÿpë \\"{þæsëTÿpë}\\", øvërrïðë rëtµrñs tÿpë \\"{øvërrïðëTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","overrideType":"[ryAgb][นั้ßæsë çlæss ðëfïñës tÿpë æs \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","paramAssignment":"[HGg7D][นั้Pæræmëtër {ïñðëx}: tÿpë \\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","paramSpecMissingInOverride":"[AUge7][นั้Pæræm§pëç pæræmëtërs ærë mïssïñg ïñ øvërrïðë mëthøðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","paramType":"[hHLAX][นั้Pæræmëtër tÿpë ïs \\"{pæræmTÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","privateImportFromPyTypedSource":"[8gX6u][นั้Ïmpørt frøm \\"{møðµlë}\\" ïñstëæðẤğ倪İЂҰक्र्तिृนั้ढूँ]","propertyAccessFromProtocolClass":"[h75EJ][นั้Æ prøpërtÿ ðëfïñëð wïthïñ æ prøtøçøl çlæss çæññøt þë æççëssëð æs æ çlæss værïæþlëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","propertyMethodIncompatible":"[dWDwG][นั้Prøpërtÿ mëthøð \\"{ñæmë}\\" ïs ïñçømpætïþlëẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","propertyMethodMissing":"[xWlRK][นั้Prøpërtÿ mëthøð \\"{ñæmë}\\" ïs mïssïñg ïñ øvërrïðëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","propertyMissingDeleter":"[r2oGK][นั้Prøpërtÿ \\"{ñæmë}\\" hæs ñø ðëfïñëð ðëlëtërẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","propertyMissingSetter":"[Sr1R9][นั้Prøpërtÿ \\"{ñæmë}\\" hæs ñø ðëfïñëð sëttërẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","protocolIncompatible":"[4uTqc][นั้\\"{søµrçëTÿpë}\\" ïs ïñçømpætïþlë wïth prøtøçøl \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","protocolMemberMissing":"[Ad9PZ][นั้\\"{ñæmë}\\" ïs ñøt prësëñtẤğ倪İЂҰक्र्นั้ढूँ]","protocolRequiresRuntimeCheckable":"[c9ewn][นั้Prøtøçøl çlæss mµst þë @rµñtïmë_çhëçkæþlë tø þë µsëð wïth ïñstæñçë æñð çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","protocolSourceIsNotConcrete":"[DnLrN][นั้\\"{søµrçëTÿpë}\\" ïs ñøt æ çøñçrëtë çlæss tÿpë æñð çæññøt þë æssïgñëð tø tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","protocolUnsafeOverlap":"[fKiUM][นั้Ættrïþµtës øf \\"{ñæmë}\\" hævë thë sæmë ñæmës æs thë prøtøçølẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","pyrightCommentIgnoreTip":"[raFZN][นั้Üsë \\"# pÿrïght: ïgñørë[<ðïægñøstïç rµlës>] tø sµpprëss ðïægñøstïçs før æ sïñglë lïñëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","readOnlyAttribute":"[k9waY][นั้Ættrïþµtë \\"{ñæmë}\\" ïs rëæð-øñlÿẤğ倪İЂҰक्र्तिृนั้ढूँ]","seeClassDeclaration":"[8sx7n][นั้§ëë çlæss ðëçlærætïøñẤğ倪İЂҰक्นั้ढूँ]","seeDeclaration":"[K0X6p][นั้§ëë ðëçlærætïøñẤğ倪İЂҰนั้ढूँ]","seeFunctionDeclaration":"[1N6ig][นั้§ëë fµñçtïøñ ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]","seeMethodDeclaration":"[eJSye][นั้§ëë mëthøð ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]","seeParameterDeclaration":"[mBEpT][นั้§ëë pæræmëtër ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]","seeTypeAliasDeclaration":"[Pjnb8][นั้§ëë tÿpë ælïæs ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]","seeVariableDeclaration":"[M3EiY][นั้§ëë værïæþlë ðëçlærætïøñẤğ倪İЂҰक्र्นั้ढूँ]","tupleAssignmentMismatch":"[aLGep][นั้Tÿpë \\"{tÿpë}\\" ïs ïñçømpætïþlë wïth tærgët tµplëẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","tupleEntryTypeMismatch":"[ny8Sn][นั้Tµplë ëñtrÿ {ëñtrÿ} ïs ïñçørrëçt tÿpëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","tupleSizeIndeterminateSrc":"[EnNiw][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð ïñðëtërmïñætëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","tupleSizeIndeterminateSrcDest":"[lrxYh][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} ør mørë þµt rëçëïvëð ïñðëtërmïñætëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","tupleSizeMismatch":"[F2Yc7][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृนั้ढूँ]","tupleSizeMismatchIndeterminateDest":"[6vxdi][นั้Tµplë sïzë mïsmætçh; ëxpëçtëð {ëxpëçtëð} ør mørë þµt rëçëïvëð {rëçëïvëð}Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typeAliasInstanceCheck":"[29G7K][นั้Tÿpë ælïæs çrëætëð wïth \\"tÿpë\\" stætëmëñt çæññøt þë µsëð wïth ïñstæñçë æñð çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeAssignmentMismatch":"[VF9B4][นั้Tÿpë \\"{søµrçëTÿpë}\\" çæññøt þë æssïgñëð tø tÿpë \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeBound":"[AIZri][นั้Tÿpë \\"{søµrçëTÿpë}\\" ïs ïñçømpætïþlë wïth þøµñð tÿpë \\"{ðëstTÿpë}\\" før tÿpë værïæþlë \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeConstrainedTypeVar":"[qHztb][นั้Tÿpë \\"{tÿpë}\\" ïs ïñçømpætïþlë wïth çøñstræïñëð tÿpë værïæþlë \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまนั้ढूँ]","typeIncompatible":"[L3llJ][นั้\\"{søµrçëTÿpë}\\" ïs ïñçømpætïþlë wïth \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typeNotClass":"[DTm1E][นั้\\"{tÿpë}\\" ïs ñøt æ çlæssẤğ倪İЂҰक्र्นั้ढूँ]","typeNotStringLiteral":"[D7UY3][นั้\\"{tÿpë}\\" ïs ñøt æ strïñg lïtërælẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeOfSymbol":"[qlRHN][นั้Tÿpë øf \\"{ñæmë}\\" ïs \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","typeParamSpec":"[m23b5][นั้Tÿpë \\"{tÿpë}\\" ïs ïñçømpætïþlë wïth Pæræm§pëç \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeUnsupported":"[Dx3Cx][นั้Tÿpë \\"{tÿpë}\\" ïs µñsµppørtëðẤğ倪İЂҰक्र्तिृนั้ढूँ]","typeVarDefaultOutOfScope":"[05ALy][นั้Tÿpë værïæþlë \\"{ñæmë}\\" ïs ñøt ïñ sçøpëẤğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typeVarIsContravariant":"[kup2Y][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" ïs çøñtræværïæñt, þµt \\"{søµrçëTÿpë}\\" ïs ñøt æ sµpërtÿpë øf \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarIsCovariant":"[EeRng][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" ïs çøværïæñt, þµt \\"{søµrçëTÿpë}\\" ïs ñøt æ sµþtÿpë øf \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarIsInvariant":"[WLZaN][นั้Tÿpë pæræmëtër \\"{ñæmë}\\" ïs ïñværïæñt, þµt \\"{søµrçëTÿpë}\\" ïs ñøt thë sæmë æs \\"{ðëstTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typeVarNotAllowed":"[37OGF][นั้TÿpëVær ñøt ælløwëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typeVarTupleRequiresKnownLength":"[GGttd][นั้TÿpëVærTµplë çæññøt þë þøµñð tø æ tµplë øf µñkñøwñ lëñgthẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","typeVarUnnecessarySuggestion":"[k0XTd][นั้Üsë {tÿpë} ïñstëæðẤğ倪İЂҰक्นั้ढूँ]","typeVarUnsolvableRemedy":"[PaRa7][นั้Prøvïðë æñ øvërløæð thæt spëçïfïës thë rëtµrñ tÿpë whëñ thë ærgµmëñt ïs ñøt sµpplïëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","typeVarsMissing":"[R1SEV][นั้Mïssïñg tÿpë værïæþlës: {ñæmës}Ấğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictBaseClass":"[Zv6vP][นั้Çlæss \\"{tÿpë}\\" ïs ñøt æ TÿpëðÐïçtẤğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictClassNotAllowed":"[Vgl7x][นั้TÿpëðÐïçt çlæss ñøt ælløwëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictClosedExtraNotAllowed":"[zT7Rm][นั้Çæññøt æðð ïtëm \\"{ñæmë}\\"Ấğ倪İЂҰक्र्นั้ढूँ]","typedDictClosedExtraTypeMismatch":"[blC1e][นั้Çæññøt æðð ïtëm \\"{ñæmë}\\" wïth tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typedDictClosedFieldNotRequired":"[6rtDR][นั้Çæññøt æðð ïtëm \\"{ñæmë}\\" þëçæµsë ït mµst þë ÑøtRëqµïrëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","typedDictExtraFieldNotAllowed":"[kFDh9][นั้\\"{ñæmë}\\" ïs ñøt prësëñt ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictExtraFieldTypeMismatch":"[DnAhM][นั้Tÿpë øf \\"{ñæmë}\\" ïs ïñçømpætïþlë wïth tÿpë øf \\"__ëxtræ_ïtëms__\\" ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğนั้ढूँ]","typedDictFieldMissing":"[rNzn7][นั้\\"{ñæmë}\\" ïs mïssïñg frøm \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictFieldNotReadOnly":"[BJy1V][นั้\\"{ñæmë}\\" ïs ñøt rëæð-øñlÿ ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤนั้ढूँ]","typedDictFieldNotRequired":"[eqatW][นั้\\"{ñæmë}\\" ïs ñøt rëqµïrëð ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまนั้ढूँ]","typedDictFieldRequired":"[ckyH4][นั้\\"{ñæmë}\\" ïs rëqµïrëð ïñ \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृนั้ढूँ]","typedDictFieldTypeMismatch":"[XYIBH][นั้Tÿpë \\"{tÿpë}\\" ïs ñøt æssïgñæþlë tø ïtëm \\"{ñæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂนั้ढूँ]","typedDictFieldUndefined":"[UsDC9][นั้\\"{ñæmë}\\" ïs æñ µñðëfïñëð ïtëm ïñ tÿpë \\"{tÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typedDictFinalMismatch":"[tFb04][นั้\\"{søµrçëTÿpë}\\" ïs ïñçømpætïþlë wïth \\"{ðëstTÿpë}\\" þëçæµsë øf æ @fïñæl mïsmætçhẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","typedDictKeyAccess":"[67DLq][นั้Üsë [\\"{ñæmë}\\"] tø rëfërëñçë ïtëm ïñ TÿpëðÐïçtẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","typedDictNotAllowed":"[eTsPP][นั้TÿpëðÐïçt çæññøt þë µsëð før ïñstæñçë ør çlæss çhëçksẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","unhashableType":"[IJEeq][นั้Tÿpë \\"{tÿpë}\\" ïs ñøt hæshæþlëẤğ倪İЂҰक्र्तिृนั้ढूँ]","uninitializedAbstractVariable":"[uDuHt][นั้Ïñstæñçë værïæþlë \\"{ñæmë}\\" ïs ðëfïñëð ïñ æþstræçt þæsë çlæss \\"{çlæssTÿpë}\\" þµt ñøt ïñïtïælïzëðẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्นั้ढूँ]","unreachableExcept":"[3CSUL][นั้\\"{ëxçëptïøñTÿpë}\\" ïs æ sµþçlæss øf \\"{pærëñtTÿpë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰนั้ढूँ]","useDictInstead":"[LReB5][นั้Üsë Ðïçt[T1, T2] tø ïñðïçætë æ ðïçtïøñærÿ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]","useListInstead":"[RPu0E][นั้Üsë £ïst[T] tø ïñðïçætë æ lïst tÿpë ør Üñïøñ[T1, T2] tø ïñðïçætë æ µñïøñ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪นั้ढूँ]","useTupleInstead":"[jaFqC][นั้Üsë tµplë[T1, ..., Tñ] tø ïñðïçætë æ tµplë tÿpë ør Üñïøñ[T1, T2] tø ïñðïçætë æ µñïøñ tÿpëẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","useTypeInstead":"[Zig8D][นั้Üsë Tÿpë[T] ïñstëæðẤğ倪İЂҰक्นั้ढूँ]","varianceMismatchForClass":"[fqhIl][นั้Værïæñçë øf tÿpë ærgµmëñt \\"{tÿpëVærÑæmë}\\" ïs ïñçømpætïþlë wïth þæsë çlæss \\"{çlæssÑæmë}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्นั้ढूँ]","varianceMismatchForTypeAlias":"[YSiVx][นั้Værïæñçë øf tÿpë ærgµmëñt \\"{tÿpëVærÑæmë}\\" ïs ïñçømpætïþlë wïth \\"{tÿpëÆlïæsPæræm}\\"Ấğ倪İЂҰक्र्तिृまẤğ倪İЂҰक्र्तिृまẤğ倪İนั้ढूँ]"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.ru.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.ru.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Создать заглушку типа","createTypeStubFor":"Создать заглушку типа для \\"{moduleName}\\"","executingCommand":"Производится выполнение команды","filesToAnalyzeCount":"{count} файлов для анализа","filesToAnalyzeOne":"1 файл для анализа","findingReferences":"Производится поиск ссылок","organizeImports":"Упорядочение импорта","renameShadowedFile":"Переименовать \\"{oldFile}\\" в \\"{newFile}\\""},"Completion":{"autoImportDetail":"Автоматический импорт","indexValueDetail":"Значение индекса"},"Diagnostic":{"abstractMethodInvocation":"Невозможно вызвать метод \\"{method}\\", так как он является абстрактным и нереализованным","annotatedParamCountMismatch":"Несоответствие числа аннотаций параметра: ожидается {expected}, но получено {received}","annotatedTypeArgMissing":"Для \\"Annotated\\" ожидается один аргумент типа и одна или несколько заметок типа","annotationFormatString":"В заметках типа не могут использоваться строковые литералы формата (f-строки)","annotationNotSupported":"Заметка типа не поддерживается для этой инструкции","annotationSpansStrings":"Заметки с типом не могут охватывать несколько строковых литералов","annotationStringEscape":"Заметки с типом не могут содержать escape-символы","argAssignment":"Аргумент типа \\"{argType}\\" нельзя присвоить параметру типа \\"{paramType}\\"","argAssignmentFunction":"Аргумент типа \\"{argType}\\" нельзя присвоить параметру типа \\"{paramType}\\" в функции \\"{functionName}\\"","argAssignmentParam":"Аргумент типа \\"{argType}\\" нельзя присвоить параметру \\"{paramName}\\" типа \\"{paramType}\\"","argAssignmentParamFunction":"Аргумент типа \\"{argType}\\" нельзя присвоить параметру \\"{paramName}\\" типа \\"{paramType}\\" в функции \\"{functionName}\\"","argMissingForParam":"Отсутствует аргумент для параметра {name}","argMissingForParams":"Отсутствуют аргументы для параметров {names}","argMorePositionalExpectedCount":"Ожидаются еще позиционные аргументы: {expected}","argMorePositionalExpectedOne":"Ожидается еще 1 позиционный аргумент","argPositional":"Ожидается позиционный аргумент","argPositionalExpectedCount":"Ожидаемые позиционные аргументы: {expected}","argPositionalExpectedOne":"Ожидается 1 позиционный аргумент","argTypePartiallyUnknown":"Тип аргумента частично неизвестен","argTypeUnknown":"Тип аргумента неизвестен","assertAlwaysTrue":"Выражение assert всегда вычисляется как true","assertTypeArgs":"Для \\"assert_type\\" ожидается два позиционных аргумента","assertTypeTypeMismatch":"Несоответствие типов \\"assert_type\\": ожидается \\"{expected}\\", но получено \\"{received}\\"","assignmentExprComprehension":"Цель выражения назначения \\"{name}\\" не может использовать то же имя, что и понимание для целевого объекта","assignmentExprContext":"Выражение присваивания должно находиться в модуле, функции или лямбде","assignmentExprInSubscript":"Выражения назначения внутри оператора получения подстроки можно использовать в Python версии не ниже 3.10","assignmentInProtocol":"Переменные экземпляра или класса в классе Protocol должны быть явно объявлены в тексте класса","assignmentTargetExpr":"Выражение не может быть целевым объектом присваивания","asyncNotInAsyncFunction":"Использование \\"async\\" не разрешено вне асинхронной функции","awaitIllegal":"Инструкцию \\"await\\" можно использовать в Python версии не ранее 3.5","awaitNotAllowed":"Заметки типов не могут использовать \\"await\\"","awaitNotInAsync":"Ключевое слово \\"await\\" допускается только в асинхронной функции","backticksIllegal":"Выражения, окруженные одиночными обратными кавычками, не поддерживаются в Python 3.x; используйте вместо этого функцию repr","baseClassCircular":"Класс не может быть производным от себя","baseClassFinal":"Базовый класс \\"{type}\\" помечен как окончательный, и от него нельзя создать производный класс","baseClassIncompatible":"Базовые классы {type} взаимно несовместимы","baseClassInvalid":"Аргумент класса должен быть базовым классом","baseClassMethodTypeIncompatible":"Базовые классы класса \\"{classType}\\" определяют метод \\"{name}\\" несовместимым способом","baseClassUnknown":"Неизвестный тип базового класса скрывает тип производного класса","baseClassVariableTypeIncompatible":"Базовые классы класса \\"{classType}\\" определяют переменную \\"{name}\\" несовместимым способом","binaryOperationNotAllowed":"Бинарный оператор нельзя использовать в заметке типа","bindTypeMismatch":"Не удалось привязать метод \\"{methodName}\\", \\"{type}\\" не может быть назначен параметру \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" можно использовать только внутри цикла","callableExtraArgs":"В \\"Callable\\" ожидается только два аргумента типа","callableFirstArg":"Ожидается список типов параметров или \\"...\\"","callableNotInstantiable":"Невозможно создать экземпляр типа \\"{type}\\"","callableSecondArg":"В качестве аргумента второго типа для \\"Callable\\" ожидается возвращаемый тип","casePatternIsIrrefutable":"Неопровержимый шаблон допускается только для последнего оператора case","classAlreadySpecialized":"Тип \\"{type}\\" уже специализирован","classDecoratorTypeUnknown":"Нетипизированный декоратор класса скрывает тип класса. Игнорирование декоратора","classDefinitionCycle":"Определение класса для \\"{name}\\" зависит от себя","classGetItemClsParam":"Переопределение метода __class_getitem__ должно принимать параметр \\"cls\\"","classMethodClsParam":"Методы класса должны принимать параметр cls","classNotRuntimeSubscriptable":"Операция взятия подстроки для класса \\"{name}\\" создаст исключение среды выполнения; заключите заметку типа в кавычки","classPatternBuiltInArgPositional":"Шаблон класса принимает только позиционный вложенный шаблон","classPatternPositionalArgCount":"Слишком много позиционных шаблонов для класса \\"{type}\\"; ожидается {expected}, но получено {received}","classPatternTypeAlias":"\\"{type}\\" нельзя использовать в шаблоне класса, поскольку это псевдоним специализированного типа","classPropertyDeprecated":"Свойства класса упразднены в Python 3.11 и не будут поддерживаться в Python 3.13","classTypeParametersIllegal":"Синтаксис параметра типа класса может использоваться в Python версии не ниже 3.12.","classVarFirstArgMissing":"Ожидается аргумент типа после \\"ClassVar\\"","classVarNotAllowed":"Использование \\"ClassVar\\" в этом контексте не допускается","classVarOverridesInstanceVar":"Переменная класса \\"{name}\\" переопределяет переменную экземпляра с тем же именем в классе \\"{className}\\"","classVarTooManyArgs":"Ожидается только один аргумент типа после \\"ClassVar\\"","classVarWithTypeVar":"Тип \\"ClassVar\\" не может включать переменные типа","clsSelfParamTypeMismatch":"Тип параметра \\"{name}\\" должен быть супертипом своего класса \\"{classType}\\"","codeTooComplexToAnalyze":"Код слишком сложен для анализа; уменьшите сложность, разбив его на фрагменты (вложенные процедуры) или сократите количество условных конструкций","collectionAliasInstantiation":"Тип \\"{type}\\" не может быть создан, вместо этого используйте \\"{alias}\\"","comparisonAlwaysFalse":"Условие всегда будет оцениваться как ЛОЖЬ, поскольку типы \\"{leftType}\\" и \\"{rightType}\\" не перекрываются","comparisonAlwaysTrue":"Выражение всегда будет возвращать значение True, поскольку типы \\"{leftType}\\" и \\"{rightType}\\" не перекрываются","comprehensionInDict":"Понимание не может использоваться с другими записями словаря","comprehensionInSet":"Понимание не может использоваться с другими записями набора","concatenateContext":"\\"Concatenate\\" не допускается в этом контексте","concatenateParamSpecMissing":"Последний аргумент типа для \\"Concatenate\\" должен быть ParamSpec или \\"...\\"","concatenateTypeArgsMissing":"Для \\"Concatenate\\" требуется по крайней мере два аргумента типа","conditionalOperandInvalid":"Недопустимый условный операнд типа \\"{type}\\"","constantRedefinition":"\\"{name}\\" является константой (поскольку оно в верхнем регистре) и не может быть переопределено.","constructorNoArgs":"Для конструктора \\"{type}\\" не ожидается аргументов","constructorParametersMismatch":"Несоответствие подписи __new__ и __init__ в классе \\"{classType}\\"","containmentAlwaysFalse":"Выражение всегда будет оцениваться как ЛОЖЬ, так как типы \\"{leftType}\\" и \\"{rightType}\\" не перекрываются","containmentAlwaysTrue":"Выражение всегда будет оцениваться как ИСТИНА, так как типы \\"{leftType}\\" и \\"{rightType}\\" не перекрываются","continueInFinally":"Невозможно использовать \\"continue\\" в предложении finally","continueOutsideLoop":"Ключевое слово \\"continue\\" можно использовать только внутри цикла","coroutineInConditionalExpression":"Условное выражение ссылается на сопрограмму, которая всегда возвращает значение True","dataClassBaseClassFrozen":"Незафиксированный класс не может наследоваться от зафиксированного класса","dataClassBaseClassNotFrozen":"Незафиксированный класс не может наследоваться от зафиксированного класса","dataClassConverterFunction":"Аргумент типа \\"{argType}\\" не является допустимым преобразователем для поля \\"{fieldName}\\" типа \\"{fieldType}\\"","dataClassConverterOverloads":"Ни одна перегрузка \\"{funcName}\\" не является допустимым преобразователем поля \\"{fieldName}\\" типа \\"{fieldType}\\"","dataClassFieldWithDefault":"Поля без значений по умолчанию не могут отображаться после полей со значениями по умолчанию.","dataClassFieldWithPrivateName":"Поле класса данных не может использовать закрытое имя","dataClassFieldWithoutAnnotation":"Поле dataclass без заметки с типом вызовет исключение среды выполнения","dataClassPostInitParamCount":"Неверное число параметров в методе __post_init__ класса данных; ожидается число, соответствующее числу полей InitVar {expected}","dataClassPostInitType":"Тип параметра метода __post_init__ в классе данных не соответствует типу поля \\"{fieldName}\\"","dataClassSlotsOverwrite":"__slots__ уже определен в классе","dataClassTransformExpectedBoolLiteral":"Ожидается выражение, статически оцениваемое как ИСТИНА или ЛОЖЬ","dataClassTransformFieldSpecifier":"Ожидается кортеж классов или функций, но получен тип \\"{type}\\"","dataClassTransformPositionalParam":"Все аргументы \\"dataclass_transform\\" должны быть аргументами типа \\"ключевое слово\\"","dataClassTransformUnknownArgument":"Аргумент \\"{name}\\" не поддерживается в dataclass_transform","dataProtocolInSubclassCheck":"Протоколы данных (включающие атрибуты, не связанные с методами) запрещены в вызовах issubclass","declaredReturnTypePartiallyUnknown":"Объявленный тип возвращаемого значения \\"{returnType}\\" частично неизвестен","declaredReturnTypeUnknown":"Объявленный тип возвращаемого значения неизвестен","defaultValueContainsCall":"Вызовы функций и изменяемые объекты не разрешены в выражении значения параметра по умолчанию","defaultValueNotAllowed":"Параметр с \\"*\\" или \\"**\\" не может иметь значение по умолчанию","delTargetExpr":"Не удается удалить выражение","deprecatedClass":"Класс \\"{name}\\" является нерекомендуемым","deprecatedConstructor":"Конструктор для класса \\"{name}\\" больше не рекомендуется к использованию","deprecatedDescriptorDeleter":"Метод \\"__delete__\\" для дескриптора \\"{name}\\" не рекомендуется","deprecatedDescriptorGetter":"Метод \\"__get__\\" для дескриптора \\"{name}\\" не рекомендуется","deprecatedDescriptorSetter":"Метод \\"__set__\\" для дескриптора \\"{name}\\" не рекомендуется","deprecatedFunction":"Функция \\"{name}\\" больше не рекомендуется к использованию","deprecatedMethod":"Метод \\"{name}\\" в классе \\"{className}\\" не рекомендуется к использованию","deprecatedPropertyDeleter":"Метод удаления для свойства \\"{name}\\" не рекомендуется","deprecatedPropertyGetter":"Метод получения для свойства \\"{name}\\" не рекомендуется","deprecatedPropertySetter":"Метод задания для свойства \\"{name}\\" не рекомендуется","deprecatedType":"Этот тип больше не рекомендуется к использованию начиная с версии Python {version}; используйте вместо него \\"{replacement}\\"","dictExpandIllegalInComprehension":"Расширение словаря в понимании не допускается","dictInAnnotation":"Словарные выражения не разрешены в заметках типа","dictKeyValuePairs":"Записи словаря должны содержать пары \\"ключ-значение\\"","dictUnpackIsNotMapping":"Ожидается сопоставление для оператора распаковки словаря","dunderAllSymbolNotPresent":"\\"{name}\\" указано в методе __all__, но отсутствует в модуле","duplicateArgsParam":"Разрешен только один параметр \\"*\\"","duplicateBaseClass":"Дублирование базового класса не допускается","duplicateCapturePatternTarget":"Целевой объект захвата \\"{name}\\" не может появляться более одного раза в одном шаблоне","duplicateCatchAll":"В блоке except допускается только одно предложение catch-all","duplicateEnumMember":"Элемент перечислимого типа \\"{name}\\" уже объявлен","duplicateGenericAndProtocolBase":"Допускается только один базовый класс Generic[...] или Protocol[...]","duplicateImport":"\\"{importName}\\" импортируется несколько раз","duplicateKeywordOnly":"Разрешен только один разделитель \\"*\\"","duplicateKwargsParam":"Разрешен только один параметр \\"**\\"","duplicateParam":"Параметр \\"{name}\\" повторяется","duplicatePositionOnly":"Разрешен только один параметр \\"/\\"","duplicateStarPattern":"В последовательности шаблонов допускается только один шаблон \\"*\\"","duplicateStarStarPattern":"Допускается только одна запись \\"**\\"","duplicateUnpack":"В списке разрешена только одна операция распаковки","ellipsisAfterUnpacked":"\\"...\\" не может использоваться с распакованным элементом TypeVarTuple или кортежем","ellipsisContext":"\\"...\\" не допускается в данном контексте","ellipsisSecondArg":"\\"...\\" разрешается только в качестве второго из двух аргументов","enumClassOverride":"Перечислимый класс \\"{name}\\" является окончательным и не может иметь производных классов","exceptionGroupIncompatible":"Синтаксис группы исключений (\\"except*\\") можно использовать в Python версии не ранее 3.11","exceptionTypeIncorrect":"\\"{type}\\" не является производным от BaseException","exceptionTypeNotClass":"\\"{type}\\" не является допустимым классом исключений","exceptionTypeNotInstantiable":"Конструктору типа исключения \\"{type}\\" требуется один или несколько аргументов","expectedAfterDecorator":"Ожидаемая функция или объявление класса после декоратора","expectedArrow":"Ожидается \\"->\\", за которым следует заметка типа к возвращаемому типу","expectedAsAfterException":"Ожидается \\"as\\" после типа исключения","expectedAssignRightHandExpr":"Справа от \\"=\\" ожидается выражение","expectedBinaryRightHandExpr":"Справа от оператора ожидается выражение","expectedBoolLiteral":"Ожидается ИСТИНА или ЛОЖЬ","expectedCase":"Ожидается оператор case","expectedClassName":"Ожидается имя класса","expectedCloseBrace":"Для скобки \\"{\\" отсутствует закрывающая скобка","expectedCloseBracket":"Для скобки \\"[\\" отсутствует закрывающая скобка","expectedCloseParen":"Для скобки \\"(\\" отсутствует закрывающая скобка","expectedColon":"Ожидается \\":\\"","expectedComplexNumberLiteral":"Для сопоставления шаблонов ожидается сложный числовой литерал","expectedDecoratorExpr":"Форму выражения для декоратора можно использовать в Python версии не ниже 3.9","expectedDecoratorName":"Ожидается имя декоратора","expectedDecoratorNewline":"В конце декоратора ожидается символ перехода на новую строку","expectedDelExpr":"После \\"del\\" ожидается выражение","expectedElse":"Ожидается ключевое слово \\"else\\"","expectedEquals":"Ожидается \\"=\\"","expectedExceptionClass":"Недопустимый класс или объект исключения","expectedExceptionObj":"Ожидается объект исключения, класс исключения или значение None","expectedExpr":"Ожидается выражение","expectedFunctionAfterAsync":"Ожидается определение функции после \\"async\\"","expectedFunctionName":"После ключевого слова \\"def\\" ожидается имя функции","expectedIdentifier":"Ожидается идентификатор","expectedImport":"Ожидается \\"import\\"","expectedImportAlias":"После \\"as\\" ожидается символ","expectedImportSymbols":"После операторов импорта ожидается одно или несколько имен символов","expectedIn":"Ожидается \\"in\\"","expectedInExpr":"После ключевого слова \\"in\\" ожидается выражение","expectedIndentedBlock":"Ожидается блок с отступом","expectedMemberName":"После \\".\\" ожидается имя элемента","expectedModuleName":"Ожидаемое имя модуля","expectedNameAfterAs":"Ожидается имя символа после \\"as\\"","expectedNamedParameter":"За \\"*\\" должен следовать параметр типа \\"ключевое слово\\"","expectedNewline":"Ожидается новая строка","expectedNewlineOrSemicolon":"Операторы должны быть разделены символами перевода строки или точками с запятой","expectedOpenParen":"Ожидается \\"(\\"","expectedParamName":"Ожидается имя параметра","expectedPatternExpr":"Ожидается выражение шаблона","expectedPatternSubjectExpr":"Ожидаемое выражение субъекта шаблона","expectedPatternValue":"Ожидается выражение значения шаблона в форме \\"a.b\\"","expectedReturnExpr":"После \\"return\\" ожидается выражение","expectedSliceIndex":"Ожидается выражение индекса или среза","expectedTypeNotString":"Ожидался тип, но получен строковый литерал","expectedTypeParameterName":"Ожидаемое имя параметра типа","expectedYieldExpr":"Ожидаемое выражение в операторе yield","finalClassIsAbstract":"Класс \\"{type}\\" помечен как final (окончательный) и должен реализовать все абстрактные символы.","finalContext":"\\"Final\\" не допускается в данном контексте","finalMethodOverride":"Метод \\"{name}\\" не может переопределять окончательный метод, определенный в классе \\"{className}\\"","finalNonMethod":"Функцию \\"{name}\\" нельзя пометить как @окончательную, так как она не является методом","finalReassigned":"\\"{name}\\" объявляется окончательным и не может быть переназначено","finalRedeclaration":"\\"{name}\\" ранее объявлено как Final","finalRedeclarationBySubclass":"\\"{name}\\" невозможно повторно объявить, поскольку в родительском классе \\"{className}\\" он объявлен как final","finalTooManyArgs":"После \\"Final\\" ожидается один аргумент типа","finalUnassigned":"\\"{name}\\" объявлен как Final, но ему не присвоено значение","formatStringBrace":"Одиночная закрывающая скобка не допускается в литерале f-строки. Используйте двойную закрывающую скобку","formatStringBytes":"Строковые литералы формата (f-строки) не могут быть двоичными","formatStringDebuggingIllegal":"Для описателя отладки F-строки \\"=\\" требуется версия Python 3.8 или более новая","formatStringEscape":"Escape-последовательность (обратная косая черта) не разрешена в части выражения f-строки до версии Python 3.12","formatStringExpectedConversion":"После \\"!\\" в f-строке ожидался спецификатор преобразования","formatStringIllegal":"Для строковых литералов формата (f-строки) требуется версия Python 3.6 или более новая","formatStringInPattern":"Строка формата не разрешена в шаблоне","formatStringNestedFormatSpecifier":"В строке спецификации формата слишком высок уровень вложенности выражений","formatStringNestedQuote":"Строки, вложенные в f-строку, не могут использовать тот же символ кавычка, что и f-строка до Python 3.12","formatStringUnicode":"Строковые литералы формата (f-строки) не могут быть в кодировке Unicode","formatStringUnterminated":"Незавершенное выражение в f-строке; ожидается \\"}\\"","functionDecoratorTypeUnknown":"Нетипизированный декоратор функции скрывает тип функции; декоратор будет игнорирован","functionInConditionalExpression":"Условное выражение ссылается на функцию, которая всегда возвращает значение True","functionTypeParametersIllegal":"Для синтаксиса параметра типа функции требуется версия Python 3.12 или более новая","futureImportLocationNotAllowed":"Операторы импорта из __future__ должны находиться в начале файла","generatorAsyncReturnType":"Возвращаемый тип функции асинхронного генератора должен быть совместим с \\"AsyncGenerator[{yieldType}, Any]\\"","generatorNotParenthesized":"Выражения генератора следует взять в скобки, если аргументов больше одного","generatorSyncReturnType":"Возвращаемый тип функции генератора должен быть совместим с \\"Generator[{yieldType}, Any, Any]\\"","genericBaseClassNotAllowed":"Базовый класс \\"Generic\\" нельзя использовать с синтаксисом параметра типа","genericClassAssigned":"Универсальный тип класса невозможно присвоить","genericClassDeleted":"Не удается удалить универсальный тип класса","genericInstanceVariableAccess":"Доступ к универсальной переменной экземпляра через класс является неоднозначным","genericNotAllowed":"Ключевое слово \\"Generic\\" недопустимо в этом контексте","genericTypeAliasBoundTypeVar":"Псевдоним универсального типа в классе не может использовать переменные привязанного типа {names}","genericTypeArgMissing":"Для \\"Generic\\" требуется по крайней мере один аргумент типа","genericTypeArgTypeVar":"Аргумент типа для \\"Generic\\" должен быть переменной типа","genericTypeArgUnique":"Аргументы типа для \\"Generic\\" должны быть уникальными","globalReassignment":"Присвоение \\"{name}\\" происходит раньше глобального объявления","globalRedefinition":"Имя \\"{name}\\" уже объявлено ранее как глобальное","implicitStringConcat":"Неявное объединение строк не разрешено","importCycleDetected":"Обнаружен цикл в цепочке импорта","importDepthExceeded":"Глубина цепочки импорта превысила {depth}","importResolveFailure":"Не удается разрешить импорт \\"{importName}\\"","importSourceResolveFailure":"Не удается разрешить импорт \\"{importName}\\" из источника","importSymbolUnknown":"\\"{name}\\" — неизвестный символ импорта","incompatibleMethodOverride":"Метод \\"{name}\\" переопределяет класс \\"{className}\\" несовместимым образом","inconsistentIndent":"Сумма отступа не соответствует предыдущему отступу","inconsistentTabs":"Непоследовательное использование вкладок и пробелов в отступах","initMustReturnNone":"Метод \\"__init__\\" должен возвращать тип None","initSubclassCallFailed":"Неверные аргументы ключевых слов для метода __init_subclass__","initSubclassClsParam":"Переопределение метода __init_subclass__ должно принимать параметр \\"cls\\"","initVarNotAllowed":"Использование \\"InitVar\\" в этом контексте не допускается","instanceMethodSelfParam":"Методы экземпляра должны принимать параметр \\"self\\"","instanceVarOverridesClassVar":"Переменная экземпляра \\"{name}\\" переопределяет переменную класса с тем же именем в классе \\"{className}\\"","instantiateAbstract":"Не удается создать экземпляр абстрактного класса \\"{type}\\"","instantiateProtocol":"Не удается создать экземпляр класса протокола \\"{type}\\"","internalBindError":"При привязке файла \\"{file}\\" произошла внутренняя ошибка: {message}","internalParseError":"При разборе файла \\"{file}\\" произошла внутренняя ошибка: {message}","internalTypeCheckingError":"При проверке файла \\"{file}\\" произошла внутренняя ошибка: {message}","invalidIdentifierChar":"Недопустимый символ в идентификаторе","invalidStubStatement":"Инструкция не имеет смысла в файле-заглушке типа","invalidTokenChars":"Недопустимый символ \\"{text}\\" в маркере","isInstanceInvalidType":"Второй аргумент \\"isinstance\\" должен быть классом или кортежем классов","isSubclassInvalidType":"Второй аргумент в \\"issubclass\\" должен быть классом или кортежем классов","keyValueInSet":"Пары \\"ключ-значение\\" не допускаются в наборе","keywordArgInTypeArgument":"Аргументы ключевых слов нельзя использовать в списках аргументов типа","keywordOnlyAfterArgs":"Разделитель аргументов типа \\"только ключевое слово\\" не разрешен после параметра \\"*\\"","keywordParameterMissing":"За параметром \\"*\\" должен следовать один или несколько параметров ключевого слова.","keywordSubscriptIllegal":"Аргументы ключевых слов в нижних индексах не поддерживаются","lambdaReturnTypePartiallyUnknown":"Тип возвращаемого лямбдой значения \\"{returnType}\\" частично неизвестен","lambdaReturnTypeUnknown":"Тип значения, возвращаемого лямбдой, неизвестен","listAssignmentMismatch":"Выражение с типом \\"{type}\\" нельзя присвоить целевому списку","listInAnnotation":"Списочное выражение не разрешено в заметке типа","literalEmptyArgs":"Ожидается один или несколько аргументов типа после \\"Literal\\"","literalNotAllowed":"Невозможно использовать \\"Literal\\" в этом контексте без аргумента типа","literalNotCallable":"Не удается создать экземпляр типа литерала","literalUnsupportedType":"Аргументы типа для \\"Literal\\" должны иметь значение None, литеральное значение (int, bool, str или bytes) или значение перечислимого типа","matchIncompatible":"Операторы соответствия могут использоваться в Python версии не ниже 3.10","matchIsNotExhaustive":"Блоки case в операторе match обрабатывают не все множество возможных значений","maxParseDepthExceeded":"Превышена максимальная глубина разбора; разбейте выражение на составляющие выражения меньшего размера","memberAccess":"Не удается получить доступ к элементу \\"{name}\\" типа \\"{type}\\"","memberDelete":"Не удается удалить элемент \\"{name}\\" типа \\"{type}\\"","memberSet":"Не удается назначить элемент \\"{name}\\" для типа \\"{type}\\"","metaclassConflict":"Метакласс производного класса должен быть производным классом метаклассов всех его базовых классов","metaclassDuplicate":"Можно указать только один метакласс","metaclassIsGeneric":"Метакласс не может быть универсальным","methodNotDefined":"Метод \\"{name}\\" не определен","methodNotDefinedOnType":"Метод \\"{name}\\" не определен для типа \\"{type}\\"","methodOrdering":"Не удается создать согласованный порядок методов","methodOverridden":"\\"{name}\\" переопределяет метод с тем же именем в классе \\"{className}\\" с несовместимым типом \\"{type}\\"","methodReturnsNonObject":"Метод \\"{name}\\" не возвращает объект","missingSuperCall":"Метод \\"{methodName}\\" не вызывает метод с тем же именем в родительском классе","moduleAsType":"Модуль не может использоваться в качестве типа","moduleNotCallable":"Модуль не является вызываемым","moduleUnknownMember":"\\"{memberName}\\" не является известным элементом модуля \\"{moduleName}\\"","namedExceptAfterCatchAll":"Именованное предложение исключения не может стоять после предложения catch-all except","namedParamAfterParamSpecArgs":"Параметр ключевого слова \\"{name}\\" не может размещаться в сигнатуре после параметра аргументов ParamSpec","namedTupleEmptyName":"Имена в именованном кортеже не могут быть пустыми","namedTupleEntryRedeclared":"Не удается переопределить \\"{name}\\", так как родительский класс \\"{className}\\" является именованным кортежем","namedTupleFirstArg":"В качестве первого аргумента ожидалось имя именованного класса кортежа","namedTupleMultipleInheritance":"Множественное наследование для NamedTuple не поддерживается","namedTupleNameKeyword":"Имена полей не могут быть ключевыми словами","namedTupleNameType":"Ожидается двухфакторный кортеж с указанием имени и типа записи","namedTupleNameUnique":"Имена внутри именованного кортежа должны быть уникальными","namedTupleNoTypes":"\\"namedtuple\\" не предоставляет типов для записей кортежа; используйте вместо него \\"NamedTuple\\"","namedTupleSecondArg":"В качестве второго аргумента ожидается список записей именованного кортежа","newClsParam":"Переопределение метода __new__ должно принимать параметр \\"cls\\"","newTypeAnyOrUnknown":"Второй аргумент для NewType должен быть известным классом, а не вариантом \\"Любой\\" или \\"Неизвестный\\"","newTypeBadName":"Первый аргумент NewType должен быть строковым литералом","newTypeLiteral":"NewType нельзя использовать с типом литерала","newTypeNameMismatch":"NewType должен быть назначен переменной с тем же именем","newTypeNotAClass":"В NewType в качестве второго аргумента ожидается класс","newTypeParamCount":"Для NewType требуются два позиционных аргумента","newTypeProtocolClass":"NewType нельзя использовать со структурным типом (протокол или класс TypedDict)","noOverload":"Не существует перегрузок для \\"{name}\\", соответствующих указанным аргументам","noReturnContainsReturn":"Функция с объявленным типом возвращаемого значения \\"NoReturn\\" не может содержать оператор return","noReturnContainsYield":"Функция с объявленным типом возвращаемого значения \\"NoReturn\\" не может содержать инструкцию yield","noReturnReturnsNone":"Функция с объявленным типом возвращаемого значения \\"NoReturn\\" не может возвращать \\"None\\"","nonDefaultAfterDefault":"Аргумент, отличный от аргумента по умолчанию, следует за аргументом по умолчанию","nonLocalInModule":"Нелокальные объявления на уровне модулей не разрешены","nonLocalNoBinding":"Привязка для нелокального элемента \\"{name}\\" не найдена","nonLocalReassignment":"Назначение \\"{name}\\" происходит раньше нелокального объявления","nonLocalRedefinition":"\\"{name}\\" уже объявлено ранее как нелокальное","noneNotCallable":"Объект типа \\"None\\" не может быть вызван","noneNotIterable":"Объект типа \\"None\\" не может использоваться в качестве итерируемого значения","noneNotSubscriptable":"Объект типа \\"None\\" не подлежит подписке","noneNotUsableWith":"Объект типа \\"None\\" нельзя использовать с ключевым словом \\"with\\"","noneOperator":"Оператор \\"{operator}\\" не поддерживается для \\"None\\"","noneUnknownMember":"\\"{name}\\" не является известным элементом \\"None\\"","notRequiredArgCount":"После \\"NotRequired\\" ожидается один аргумент типа","notRequiredNotInTypedDict":"Использование \\"NotRequired\\" в этом контексте не допускается","objectNotCallable":"Объект типа \\"{type}\\" не является вызываемым","obscuredClassDeclaration":"Объявление класса \\"{name}\\" скрывается объявлением с тем же именем","obscuredFunctionDeclaration":"Объявление функции \\"{name}\\" скрывается объявлением с тем же именем","obscuredMethodDeclaration":"Объявление метода \\"{name}\\" скрывается объявлением с тем же именем","obscuredParameterDeclaration":"Объявление параметра \\"{name}\\" скрывается объявлением с тем же именем","obscuredTypeAliasDeclaration":"Объявление псевдонима типа \\"{name}\\" скрывается объявлением с тем же именем","obscuredVariableDeclaration":"Объявление \\"{name}\\" скрывается объявлением с тем же именем","operatorLessOrGreaterDeprecated":"Оператор \\"<>\\" не поддерживается в Python 3; используйте вместо него \\"!=\\"","optionalExtraArgs":"Ожидается один аргумент типа после \\"Optional\\"","orPatternIrrefutable":"Неопровержимый шаблон допускается только в качестве последнего вложенного шаблона в шаблоне \\"or\\"","orPatternMissingName":"Все вложенные шаблоны в шаблоне \\"or\\" должны быть привязаны к одним и тем же именам","overlappingKeywordArgs":"Типизированный словарь перекрывается с параметром ключевого слова: {names}","overlappingOverload":"Перегрузка {obscured} для \\"{name}\\" никогда не будет использоваться, так как ее параметры перекрывают перегрузку {obscuredBy}","overloadAbstractMismatch":"Все перегруженные методы должны быть абстрактными или не абстрактными","overloadClassMethodInconsistent":"Перегрузки для \\"{name}\\" используют @classmethod несогласованно","overloadFinalInconsistencyImpl":"Перегрузка для \\"{name}\\" помечена как @окончательная, но реализация — нет","overloadFinalInconsistencyNoImpl":"Перегрузка {index} для \\"{name}\\" помечена как @окончательная, но перегрузка 1 — нет","overloadImplementationMismatch":"Перегруженная реализация не согласована с сигнатурой перегрузки {index}","overloadReturnTypeMismatch":"Перегрузка {prevIndex} для \\"{name}\\" перекрывает перегрузку {newIndex} и возвращает несовместимый тип","overloadStaticMethodInconsistent":"Перегрузки для \\"{name}\\" используют @staticmethod несогласованно","overloadWithoutImplementation":"\\"{name}\\" помечен как перегруженный, но реализация не предоставлена","overriddenMethodNotFound":"Метод \\"{name}\\" помечен как переопределение, но базового метода с таким же именем нет.","overrideDecoratorMissing":"Метод \\"{name}\\" не помечен в качестве переопределения, но переопределяет метод в классе \\"{className}\\"","paramAfterKwargsParam":"Параметр не может следовать за параметром \\"**\\"","paramAlreadyAssigned":"Параметр \\"{name}\\" уже назначен.","paramAnnotationMissing":"Отсутствует заметка с типом для параметра \\"{name}\\"","paramAssignmentMismatch":"Выражение типа \\"{sourceType}\\" не может быть назначено параметру типа \\"{paramType}\\"","paramNameMissing":"Параметра с именем \\"{name}\\" не существует","paramSpecArgsKwargsUsage":"Элементы ParamSpec \\"args\\" и \\"kwargs\\" должны одновременно присутствовать в сигнатуре функции","paramSpecArgsMissing":"Отсутствуют аргументы для \\"{type}\\" ParamSpec","paramSpecArgsUsage":"Элемент \\"args\\" ParamSpec допустим только при использовании с параметром *args.","paramSpecAssignedName":"ParamSpec необходимо присвоить переменной с именем \\"{name}\\"","paramSpecContext":"ParamSpec не допускается в этом контексте","paramSpecDefaultNotTuple":"Для значения ParamSpec по умолчанию ожидается многоточие, выражение кортежа или ParamSpec","paramSpecFirstArg":"Ожидается имя ParamSpec в качестве первого аргумента","paramSpecKwargsUsage":"Элемент \\"kwargs\\" ParamSpec допустим только при использовании с параметром **kwargs.","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" не имеет смысла в этом контексте","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" относится к области вызываемого объекта в возвращаемом типе, и на него нельзя ссылаться в тексте функции.","paramSpecUnknownArg":"ParamSpec не поддерживает более одного аргумента","paramSpecUnknownMember":"\\"{name}\\" не является известным элементом ParamSpec","paramSpecUnknownParam":"\\"{name}\\" является неизвестным параметром для ParamSpec","paramTypeCovariant":"Переменную ковариантного типа нельзя использовать в типе параметра","paramTypePartiallyUnknown":"Тип параметра \\"{paramName}\\" частично неизвестен","paramTypeUnknown":"Тип параметра \\"{paramName}\\" неизвестен","parenthesizedContextManagerIllegal":"Для скобок в операторе \\"with\\" требуется версия Python 3.9 или более новая","patternNeverMatches":"Шаблон никогда не будет совпадать для типа субъекта \\"{type}\\"","positionArgAfterNamedArg":"Позиционный аргумент не может стоять после аргументов типа \\"ключевое слово\\"","positionOnlyAfterArgs":"Разделитель чисто позиционных параметров после параметра \\"*\\" не разрешен","positionOnlyAfterKeywordOnly":"Параметр \\"/\\" должен располагаться перед параметром \\"*\\"","positionOnlyAfterNon":"Чисто позиционный параметр не разрешен после параметра, который не является чисто позиционным","positionOnlyFirstParam":"Разделитель чисто позиционных параметров в качестве первого параметра не разрешен","positionOnlyIncompatible":"Разделитель чисто позиционных параметров можно использовать в Python версии не ниже 3.8","privateImportFromPyTypedModule":"\\"{name}\\" не экспортируется из модуля \\"{module}\\"","privateUsedOutsideOfClass":"Элемент \\"{name}\\" является закрытым, но используется вне класса, в котором объявлен","privateUsedOutsideOfModule":"\\"{name}\\" является закрытым, но используется вне модуля, в котором объявлен","propertyOverridden":"\\"{name}\\" неправильно переопределяет свойство с таким же именем в классе \\"{className}\\"","propertyStaticMethod":"Статические методы не разрешены в методах получения, задания и удаления свойств","protectedUsedOutsideOfClass":"\\"{name}\\" защищено и используется вне класса, в котором оно объявлено","protocolBaseClass":"Класс протокола \\"{classType}\\" не может быть производным от непротокольного класса \\"{baseType}\\"","protocolBaseClassWithTypeArgs":"Аргументы типа не допускаются с классом протокола при использовании синтаксиса параметра типа","protocolIllegal":"Ключевое слово \\"Protocol\\" можно использовать в Python версии не ниже 3.7","protocolNotAllowed":"Невозможно использовать \\"Protocol\\" в этом контексте","protocolUnsafeOverlap":"Класс небезопасно перекрывает \\"{name}\\" и может вызвать совпадение во время выполнения","protocolVarianceContravariant":"Переменная типа \\"{variable}\\", используемая в универсальном протоколе \\"{class}\\", должна быть контравариантной.","protocolVarianceCovariant":"Переменная типа \\"{variable}\\", используемая в универсальном протоколе \\"{class}\\", должна быть ковариантной","protocolVarianceInvariant":"Переменная типа \\"{variable}\\", используемая в универсальном протоколе \\"{class}\\", должна быть инвариантной","pyrightCommentInvalidDiagnosticBoolValue":"За директивой комментария Pyright должно следовать \\"=\\" и значение true или false","pyrightCommentInvalidDiagnosticSeverityValue":"За директивой комментария pyright должно следовать \\"=\\" и одно из следующих значений: true, false, error, warning, information или none","pyrightCommentMissingDirective":"После комментария pyright должна следовать директива (обычная или строгая) или правило диагностики","pyrightCommentNotOnOwnLine":"Комментарии Pyright, используемые для управления параметрами на уровне файлов, должны располагаться в отдельной строке","pyrightCommentUnknownDiagnosticRule":"Правило диагностики \\"{rule}\\" для комментария pyright неизвестно","pyrightCommentUnknownDiagnosticSeverityValue":"Значение \\"{value}\\" недопустимо для комментария pyright; ожидается одно из значений true, false, error, warning, information или none","pyrightCommentUnknownDirective":"\\"{directive}\\" является неизвестной директивой для комментария pyright; ожидается \\"strict\\" или \\"basic\\"","readOnlyArgCount":"Ожидается один аргумент типа после \\"ReadOnly\\"","readOnlyNotInTypedDict":"Использование \\"ReadOnly\\" в этом контексте не допускается","recursiveDefinition":"Не удалось определить тип \\"{name}\\", так как он ссылается на себя","relativeImportNotAllowed":"Операции импорта с относительным путем нельзя использовать с формой \\"import .a\\"; используйте вместо этого \\"from . import a\\"","requiredArgCount":"Ожидается один аргумент типа после \\"Required\\"","requiredNotInTypedDict":"Использование \\"Required\\" в этом контексте не допускается","returnInAsyncGenerator":"Оператор return со значением не допускается в асинхронном генераторе","returnMissing":"Функция с объявленным типом возвращаемого значения \\"{returnType}\\" должна возвращать значение во всех путях кода","returnOutsideFunction":"\\"return\\" можно использовать только внутри функции","returnTypeContravariant":"Переменная контравариантного типа не может использоваться в возвращаемом типе","returnTypeMismatch":"Выражение типа \\"{exprType}\\" не может быть назначено возвращаемому типу \\"{returnType}\\"","returnTypePartiallyUnknown":"Тип возвращаемого значения \\"{returnType}\\" частично неизвестен","returnTypeUnknown":"Тип возвращаемого значения неизвестен","revealLocalsArgs":"Не ожидаются аргументы для вызова \\"reveal_locals\\"","revealLocalsNone":"В этой области нет локальных элементов","revealTypeArgs":"Для вызова \\"reveal_type\\" ожидается один позиционный аргумент","revealTypeExpectedTextArg":"Аргумент \\"expected_text\\" для функции \\"reveal_type\\" должен быть значением литерала str","revealTypeExpectedTextMismatch":"Несоответствие текста в типе; ожидалось \\"{expected}\\", но получено \\"{received}\\"","revealTypeExpectedTypeMismatch":"Несоответствие типов; ожидается \\"{expected}\\", но получено \\"{received}\\"","selfTypeContext":"\'В этом контексте ключевое слово \\"Self\\" недопустимо","selfTypeMetaclass":"\\"Self\\" нельзя использовать в метаклассе (подкласс \\"type\\")","selfTypeWithTypedSelfOrCls":"Ключевое слово \\"Self\\" нельзя использовать в функции с параметром \\"self\\" или \\"cls\\" с заметкой типа, отличной от \\"Self\\".","setterGetterTypeMismatch":"Тип значения метода задания свойства нельзя присвоить типу возвращаемого значения метода получения","singleOverload":"Элемент \\"{name}\\" помечен как перегруженный, но дополнительные перегрузки отсутствуют","slotsAttributeError":"\\"{name}\\" не указано в __slots__","slotsClassVarConflict":"\\"{name}\\" конфликтует с переменной экземпляра, объявленной в __slots__","starPatternInAsPattern":"Шаблон \\"звездочка\\" не может использоваться с целевым объектом \\"as\\"","starPatternInOrPattern":"Шаблон \\"звездочка\\" не может быть аргументом операции OR в других шаблонах","starStarWildcardNotAllowed":"** нельзя использовать с символом подстановки \\"_\\"","staticClsSelfParam":"Статические методы не принимают в качестве параметра \\"self\\" и \\"cls\\"","stdlibModuleOverridden":"\\"{path}\\" переопределяет модуль stdlib \\"{name}\\"","stringNonAsciiBytes":"Символы, отличные от ASCII, не допускаются в строковом литерале байтов","stringNotSubscriptable":"От строкового выражения нельзя взять подстроку в заметке типа; заключите всю заметку в кавычки","stringUnsupportedEscape":"Неподдерживаемая escape-последовательность в строковом литерале","stringUnterminated":"В строковом литерале отсутствует символ конца строки","stubFileMissing":"Файл-заглушка для \\"{importName}\\" не найден","stubUsesGetAttr":"Файл-заглушка типа неполон; \\"__getattr__\\" скрывает ошибки типа для модуля","sublistParamsIncompatible":"Параметры вложенного списка не поддерживаются в Python 3.x","superCallArgCount":"Ожидается не более двух аргументов для вызова \\"super\\"","superCallFirstArg":"В качестве первого аргумента для вызова \\"super\\" ожидался тип класса, но получен \\"{type}\\"","superCallSecondArg":"Второй аргумент для вызова \\"super\\" должен быть объектом или классом, производным от \\"{type}\\"","superCallZeroArgForm":"Форма вызова \\"super\\" с нулевым аргументом допустима только внутри метода","superCallZeroArgFormStaticMethod":"Форма вызова \\"super\\" с нулевым аргументом недопустима в статическом методе","symbolIsPossiblyUnbound":"Элемент \\"{name}\\", возможно, не привязан","symbolIsUnbound":"Элемент \\"{name}\\" не привязан","symbolIsUndefined":"\\"{name}\\" не определено","symbolOverridden":"\\"{name}\\" переопределяет символ с тем же именем в классе \\"{className}\\"","ternaryNotAllowed":"Тернарное выражение не разрешено в заметке типа","totalOrderingMissingMethod":"Чтобы можно было использовать total_ordering, в классе должен быть определен один из операторов: \\"__lt__\\", \\"__le__\\", \\"__gt__\\" или \\"__ge__\\"","trailingCommaInFromImport":"Конечные запятые можно использовать только при заключении в скобки","tryWithoutExcept":"В операторе try должно быть хотя бы одно предложение exclude или finally.","tupleAssignmentMismatch":"Выражение с типом \\"{type}\\" не может быть назначено целевому кортежу","tupleInAnnotation":"Выражение кортежа не разрешено в заметке с типом","tupleIndexOutOfRange":"Индекс {index} выходит за пределы допустимого диапазона для типа {type}","typeAliasIllegalExpressionForm":"Недопустимая форма выражения для определения псевдонима типа","typeAliasIsRecursiveDirect":"Псевдоним типа \\"{name}\\" не может использовать себя в своем определении","typeAliasNotInModuleOrClass":"TypeAlias можно определить только внутри области модуля или класса","typeAliasRedeclared":"\\"{name}\\" объявлен как TypeAlias и может быть присвоен только один раз","typeAliasStatementBadScope":"Утверждение типа можно использовать только внутри области модуля или класса","typeAliasStatementIllegal":"Оператор псевдонима типа можно использовать в Python версии не ниже 3.12","typeAliasTypeBaseClass":"Псевдоним типа, определяемый в операторе \\"type\\", не может использоваться в качестве базового класса.","typeAliasTypeMustBeAssigned":"TypeAliasType должен быть назначен переменной с тем же именем, что и псевдоним типа","typeAliasTypeNameArg":"Первый аргумент TypeAliasType должен быть строковым литералом, представляющим имя псевдонима типа","typeAliasTypeNameMismatch":"Имя псевдонима типа должно соответствовать имени переменной, которой оно назначено","typeAliasTypeParamInvalid":"Список параметров типа должен быть кортежем, содержащим только TypeVar, TypeVarTuple или ParamSpec","typeAnnotationCall":"Выражение вызова не разрешено в выражении типа","typeAnnotationVariable":"Переменная не разрешена в выражении типа","typeAnnotationWithCallable":"Аргумент типа для \\"type\\" должен быть классом. Вызываемые объекты не поддерживаются","typeArgListExpected":"Ожидается ParamSpec, многоточие или список типов","typeArgListNotAllowed":"Выражение списка не разрешено для аргумента этого типа","typeArgsExpectingNone":"Для класса \\"{name}\\" не ожидается аргументов типа","typeArgsMismatchOne":"Ожидается один аргумент типа, но получено {received}","typeArgsMissingForAlias":"Для псевдонима универсального типа \\"{name}\\" ожидаются аргументы типа","typeArgsMissingForClass":"Ожидаются аргументы типа для универсального класса \\"{name}\\"","typeArgsTooFew":"Указано слишком мало аргументов типа для \\"{name}\\"; ожидалось {expected}, но получено {received}","typeArgsTooMany":"Для \\"{name}\\" предоставлено слишком много аргументов типа. Ожидается {expected}, но получено {received}","typeAssignmentMismatch":"Выражение типа \\"{sourceType}\\" нельзя присвоить объявленному типу \\"{destType}\\"","typeAssignmentMismatchWildcard":"Символ импорта \\"{name}\\" имеет тип \\"{sourceType}\\", который не может быть назначен объявленному типу \\"{destType}\\"","typeCallNotAllowed":"Вызов type() не разрешен в заметках типа","typeCheckOnly":"\\"{name}\\" помечено как @type_check_only и может использоваться только в заметках с типом","typeCommentDeprecated":"Комментарии типа больше не рекомендуются к использованию; вместо них используйте заметки типа","typeExpectedClass":"Ожидалось выражение типа, но получено \\"{type}\\"","typeGuardArgCount":"После \\"TypeGuard\\" или \\"TypeIs\\" ожидается один аргумент типа","typeGuardParamCount":"Определяемые пользователем функции и методы защиты типов должны иметь по крайней мере один входной параметр","typeIsReturnType":"Тип возвращаемого значения TypeIs (\\"{returnType}\\") не соответствует типу параметра значения (\\"{type}\\")","typeNotAwaitable":"\\"{type}\\" не является ожидаемым","typeNotIntantiable":"Не удается создать экземпляр \\"{type}\\"","typeNotIterable":"\\"{type}\\" не является итерируемым","typeNotSpecializable":"Не удалось специализировать тип \\"{type}\\"","typeNotSubscriptable":"Объект типа \\"{type}\\" не поддерживает операцию получения подстроки","typeNotSupportBinaryOperator":"Оператор \\"{operator}\\" не поддерживается для типов \\"{leftType}\\" и \\"{rightType}\\"","typeNotSupportBinaryOperatorBidirectional":"Оператор \\"{operator}\\" не поддерживается для типов \\"{leftType}\\" и \\"{rightType}\\", если ожидаемый тип является \\"{expectedType}\\"","typeNotSupportUnaryOperator":"Оператор \\"{operator}\\" не поддерживается для типа \\"{type}\\"","typeNotSupportUnaryOperatorBidirectional":"Оператор \\"{operator}\\" не поддерживается для типа \\"{type}\\", если ожидается тип \\"{expectedType}\\"","typeNotUsableWith":"Объект типа \\"{type}\\" нельзя использовать с ключевым словом \\"with\\", так как он не реализует метод {method}","typeParameterBoundNotAllowed":"Привязку или ограничение нельзя использовать с параметром типа variadic или ParamSpec","typeParameterConstraintTuple":"Ограничение параметра типа должно быть кортежем двух или более типов","typeParameterExistingTypeParameter":"Параметр типа \\"{name}\\" уже используется","typeParameterNotDeclared":"Параметр типа \\"{name}\\" не включен в список параметров типа для контейнера \\"{container}\\"","typeParametersMissing":"Необходимо указать хотя бы один параметр типа","typePartiallyUnknown":"Тип \\"{name}\\" частично неизвестен","typeUnknown":"Тип \\"{name}\\" неизвестен","typeVarAssignedName":"TypeVar необходимо присвоить переменной с именем \\"{name}\\"","typeVarAssignmentMismatch":"Тип \\"{type}\\" не может быть присвоен переменной типа \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar не может быть одновременно привязанным и ограниченным","typeVarBoundGeneric":"Тип привязки TypeVar не может быть универсальным","typeVarConstraintGeneric":"Тип ограничения TypeVar не может быть универсальным","typeVarDefaultBoundMismatch":"Тип по умолчанию TypeVar должен быть подтипом привязанного типа","typeVarDefaultConstraintMismatch":"Тип по умолчанию TypeVar должен быть одним из ограниченных типов","typeVarDefaultIllegal":"Для типов переменных по умолчанию требуется версия Python 3.13 или более новая","typeVarDefaultInvalidTypeVar":"Параметр типа \\"{name}\\" имеет тип по умолчанию, который ссылается на одну или несколько переменных типа, находящихся вне области","typeVarFirstArg":"В качестве первого аргумента ожидалось имя TypeVar","typeVarNoMember":"У \\"{type}\\" TypeVar нет элемента \\"{name}\\"","typeVarNotSubscriptable":"Невозможно взять подстроку от \\"{type}\\" TypeVar","typeVarNotUsedByOuterScope":"Переменная типа \\"{name}\\" не имеет смысла в этом контексте","typeVarPossiblyUnsolvable":"Переменная типа \\"{name}\\" может остаться нерешенной, если вызывающая сторона не указывает аргумент для параметра \\"{param}\\"","typeVarScopedToReturnType":"Переменная типа \\"{name}\\" относится к вызываемому объекту в возвращаемом типе, и на нее нельзя ссылаться в тексте функции.","typeVarSingleConstraint":"TypeVar должен иметь не менее двух ограниченных типов","typeVarTupleConstraints":"TypeVarTuple не может использовать ограничения значений","typeVarTupleContext":"TypeVarTuple не допускается в этом контексте","typeVarTupleDefaultNotUnpacked":"Тип по умолчанию TypeVarTuple должен быть распакованным кортежем или TypeVarTuple.","typeVarTupleMustBeUnpacked":"Для значения TypeVarTuple требуется оператор распаковки","typeVarTupleUnknownParam":"\\"{name}\\" является неизвестным параметром для TypeVarTuple","typeVarUnknownParam":"\\"{name}\\" является неизвестным параметром для TypeVar","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" уже используется внешней областью","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" появляется в сигнатуре универсальной функции только один раз","typeVarVariance":"TypeVar не может быть одновременно ковариантным и контравариантным","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" имеет значение по умолчанию и не может следовать за typeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" не может появиться после \\"{other}\\" в списке параметров типа, так как у него нет типа по умолчанию","typeVarsNotInGenericOrProtocol":"Generic[] и Protocol[] должны включать все переменные типа","typedDictAccess":"Не удалось получить доступ к элементу в TypedDict","typedDictAssignedName":"TypedDict необходимо присвоить переменной с именем \\"{name}\\"","typedDictBadVar":"Классы TypedDict могут содержать только заметки с типом","typedDictBaseClass":"Все базовые классы для классов TypedDict также должны быть классами TypedDict","typedDictBoolParam":"От параметра \\"{name}\\" ожидается значение True или False","typedDictClosedExtras":"Базовый класс \\"{name}\\" представляет собой закрытый TypedDict; дополнительные элементы должны иметь тип \\"{type}\\"","typedDictClosedNoExtras":"Базовый класс \\"{name}\\" представляет собой закрытый TypedDict; дополнительные элементы не разрешены","typedDictDelete":"Не удалось удалить элемент в TypedDict","typedDictEmptyName":"Имена в TypedDict не могут быть пустыми","typedDictEntryName":"Для имени записи словаря ожидается строковый литерал","typedDictEntryUnique":"Имена в словаре должны быть уникальными","typedDictExtraArgs":"Дополнительные аргументы TypedDict не поддерживаются","typedDictFieldNotRequiredRedefinition":"Элемент TypedDict \\"{name}\\" нельзя переопределить как необязательный","typedDictFieldReadOnlyRedefinition":"Элемент TypedDict \\"{name}\\" нельзя переопределить как доступный только для чтения","typedDictFieldRequiredRedefinition":"Элемент TypedDict \\"{name}\\" нельзя переопределить как обязательный","typedDictFirstArg":"В качестве первого аргумента ожидается имя класса TypedDict","typedDictInitsubclassParameter":"TypedDict не поддерживает параметр __init_subclass__ \\"{name}\\"","typedDictNotAllowed":"Невозможно использовать \\"TypedDict\\" в этом контексте","typedDictSecondArgDict":"В качестве второго параметра ожидается словарь или ключевое слово","typedDictSecondArgDictEntry":"Ожидается простая запись словаря","typedDictSet":"Не удалось назначить элемент в TypedDict","unaccessedClass":"Нет доступа к классу \\"{name}\\"","unaccessedFunction":"Доступ к функции \\"{name}\\" не производится","unaccessedImport":"Доступ к импорту \\"{name}\\" не производится","unaccessedSymbol":"Доступ к \\"{name}\\" не осуществляется","unaccessedVariable":"Доступ к переменной \\"{name}\\" не производится","unannotatedFunctionSkipped":"Анализ функции \\"{name}\\" пропущен, так как она не аннотирована.","unaryOperationNotAllowed":"Унарный оператор нельзя использовать в заметке типа","unexpectedAsyncToken":"После \\"async\\" ожидается \\"def\\", \\"with\\" или \\"for\\"","unexpectedExprToken":"Непредвиденный токен в конце выражения","unexpectedIndent":"Непредвиденный отступ","unexpectedUnindent":"Отступ не ожидается","unhashableDictKey":"Ключ словаря должен быть хэшируемым","unhashableSetEntry":"Запись набора должна быть хэшируемой","uninitializedAbstractVariables":"Переменные, определенные в абстрактном базовом классе, не инициализированы в окончательном классе \\"{classType}\\"","uninitializedInstanceVariable":"Переменная экземпляра \\"{name}\\" не инициализирована ни в тексте класса, ни в методе __init__","unionForwardReferenceNotAllowed":"Синтаксис объединения не может использоваться со строковым операндом; заключите всё выражение в кавычки","unionSyntaxIllegal":"Альтернативный синтаксис объединений можно использовать в версии Python не ниже 3.10","unionTypeArgCount":"Для объединения требуется два или более аргумента типа","unionUnpackedTuple":"Объединение не может включать распакованный кортеж","unionUnpackedTypeVarTuple":"Объединение не может включать распакованный TypeVarTuple","unnecessaryCast":"Ненужный вызов \\"cast\\"; тип уже является \\"{type}\\"","unnecessaryIsInstanceAlways":"Ненужный вызов isinstance; \\"{testType}\\" всегда является экземпляром \\"{classType}\\"","unnecessaryIsSubclassAlways":"Ненужный вызов issubclass. \\"{testType}\\" всегда является подклассом \\"{classType}\\"","unnecessaryPyrightIgnore":"Ненужный комментарий \\"# pyright: ignore\\"","unnecessaryPyrightIgnoreRule":"Ненужное правило \\"# pyright: ignore\\": \\"{name}\\"","unnecessaryTypeIgnore":"Ненужный комментарий \\"# type: ignore\\"","unpackArgCount":"Ожидается один аргумент типа после \\"Unpack\\"","unpackExpectedTypeVarTuple":"В качестве аргумента типа для распаковки ожидается элемент TypeVarTuple или кортеж","unpackExpectedTypedDict":"Ожидается аргумент типа TypedDict для распаковки","unpackIllegalInComprehension":"Операция распаковки в понимании не разрешена","unpackInAnnotation":"Оператор распаковки нельзя использовать в заметке типа","unpackInDict":"Операция распаковки в словарях не разрешена","unpackInSet":"Оператор распаковки не разрешен в наборе","unpackNotAllowed":"Распаковка допускается в этом контексте","unpackOperatorNotAllowed":"Операция распаковки допускается в этом контексте","unpackTuplesIllegal":"Операцию распаковки в кортежах можно использовать в Python версии не ниже 3.8","unpackedArgInTypeArgument":"Неупакованные аргументы нельзя использовать в списках аргументов типа","unpackedArgWithVariadicParam":"Невозможно использовать распакованный аргумент для параметра TypeVarTuple","unpackedDictArgumentNotMapping":"Выражение аргумента после ** должно быть сопоставлением с типом ключа \\"str\\".","unpackedDictSubscriptIllegal":"Оператор распаковки словаря не допускается внутри операции взятия подстроки","unpackedSubscriptIllegal":"Оператор распаковки в операции взятия подстроки можно использовать в Python версии не ниже 3.11","unpackedTypeVarTupleExpected":"Ожидается распакованный TypeVarTuple; используйте Unpack[{name1}] или *{name2}","unpackedTypedDictArgument":"Не удалось сопоставить распакованный аргумент TypedDict с параметрами","unreachableCode":"Код недоступен","unreachableExcept":"Предложение Except недоступно, так как исключение уже обработано","unsupportedDunderAllOperation":"Операция на \\"__all__\\" не поддерживается, поэтому список экспортируемых символов может быть неправильным","unusedCallResult":"Результат выражения вызова принадлежит к типу \\"{type}\\" и не используется. Назначьте переменной \\"_\\", если это сделано намеренно","unusedCoroutine":"Результат вызова асинхронной функции не используется; добавьте ключевое слово \\"await\\" или присвойте результат переменной","unusedExpression":"Значение выражения не используется","varAnnotationIllegal":"Заметки типа для переменных можно использовать в Python версии не ниже 3.6. Для совместимости с более ранними версиями используйте комментарий к типу.","variableFinalOverride":"Переменная \\"{name}\\" помечена как Final и переопределяет неокончательную переменную с тем же именем в классе \\"{className}\\"","variadicTypeArgsTooMany":"Список аргументов типа может содержать не более одного распакованного элемента TypeVarTuple или кортежа","variadicTypeParamTooManyAlias":"Псевдоним типа может иметь не более одного параметра типа TypeVarTuple, но получил несколько ({names})","variadicTypeParamTooManyClass":"Универсальный класс может иметь не более одного параметра типа TypeVarTuple, но получил несколько ({names})","walrusIllegal":"Оператор \\":=\\" может использоваться в Python версии не ниже 3.8","walrusNotAllowed":"Оператор \\":=\\" не допускается в этом контексте без окружающих круглых скобок","wildcardInFunction":"Импорт с подстановочными знаками в классе или функции запрещен","wildcardLibraryImport":"Импорт подстановочных знаков из библиотеки запрещен","wildcardPatternTypePartiallyUnknown":"Тип, захваченный шаблоном подстановки, частично неизвестен","wildcardPatternTypeUnknown":"Тип, захваченный шаблоном подстановки, неизвестен","yieldFromIllegal":"\\"Yield from\\" можно использовать в Python версии не ниже 3.3","yieldFromOutsideAsync":"\\"yield from\\" не допускается в асинхронной функции","yieldOutsideFunction":"\\"yield\\" не допускается за пределами функции или лямбда-выражении","yieldWithinListCompr":"\\"yield\\" не допускается внутри понимания списка","zeroCaseStatementsFound":"Операторе match должен включать по крайней мере один оператор case","zeroLengthTupleNotAllowed":"Кортеж нулевой длины не допускается в этом контексте"},"DiagnosticAddendum":{"annotatedNotAllowed":"Специальную форму \\"С заметками\\" нельзя использовать с проверками экземпляра и класса","argParam":"Аргумент соответствует параметру \\"{paramName}\\"","argParamFunction":"Аргумент соответствует параметру \\"{paramName}\\" функции \\"{functionName}\\"","argsParamMissing":"У параметра \\"*{paramName}\\" нет соответствующего параметра","argsPositionOnly":"Несоответствие параметров только положения. Ожидается {expected}, но получено {received}","argumentType":"Аргумент принадлежит к типу \\"{type}\\"","argumentTypes":"Типы аргументов: ({types})","assignToNone":"Этот тип нельзя присвоить типу \\"None\\"","asyncHelp":"Вы имели в виду \\"async with\\"?","baseClassIncompatible":"Базовый класс \\"{baseClass}\\" несовместим с типом \\"{type}\\"","baseClassIncompatibleSubclass":"Базовый класс \\"{baseClass}\\" является производным от \\"{subclass}\\", который несовместим с типом \\"{type}\\"","baseClassOverriddenType":"Базовый класс \\"{baseClass}\\" предоставляет тип \\"{type}\\", который переопределен","baseClassOverridesType":"Базовый класс \\"{baseClass}\\" переопределяет тип \\"{type}\\"","bytesTypePromotions":"Установите для параметра DisableBytesTypePromotions значение ЛОЖЬ, чтобы включить повышение типа для \\"bytearray\\" и \\"memoryview\\"","conditionalRequiresBool":"Метод __bool__ для типа \\"{operandType}\\" возвращает тип \\"{boolReturnType}\\", а не \\"bool\\"","dataClassFieldLocation":"Объявление поля","dataClassFrozen":"Элемент \\"{name}\\" зафиксирован","dataProtocolUnsupported":"\\"{name}\\" является протоколом данных","descriptorAccessBindingFailed":"Не удалось привязать метод \\"{name}\\" для класса дескриптора \\"{className}\\"","descriptorAccessCallFailed":"Не удалось вызвать метод \\"{name}\\" для класса дескриптора \\"{className}\\"","finalMethod":"Окончательный метод","functionParamDefaultMissing":"В параметре \\"{name}\\" отсутствует аргумент по умолчанию.","functionParamName":"Несоответствие имени параметра: \\"{destName}\\" и \\"{srcName}\\"","functionParamPositionOnly":"Несоответствие исключительно позиционных параметров; параметр \\"{name}\\" не является исключительно позиционным","functionReturnTypeMismatch":"Тип возвращаемого значения функции \\"{sourceType}\\" несовместим с типом \\"{destType}\\"","functionTooFewParams":"Функция принимает слишком мало позиционных параметров; ожидалось {expected}, но получено {received}","functionTooManyParams":"Функция принимает слишком много позиционных параметров; ожидалось {expected}, но получено {received}","genericClassNotAllowed":"Универсальный тип с аргументами типа запрещен для проверок экземпляров или классов","incompatibleDeleter":"Метод удаления свойства является несовместимым","incompatibleGetter":"Несовместимый метод получения свойств","incompatibleSetter":"Метод задания свойства является несовместимым","initMethodLocation":"Метод __init__ определен в классе \\"{type}\\"","initMethodSignature":"Сигнатура __init__ — \\"{type}\\"","initSubclassLocation":"Метод __init_subclass__ определен в классе \\"{name}\\"","invariantSuggestionDict":"Рассмотрите возможность перехода с \\"dict\\" на \\"Mapping\\", являющийся ковариантным по типу значения.","invariantSuggestionList":"Рассмотрите возможность перехода с \\"list\\" на \\"Sequence\\", являющийся ковариантным.","invariantSuggestionSet":"Рассмотрите возможность переключения с \\"set\\" на \\"Container\\", который является ковариантным","keyNotRequired":"\\"{name}\\" не является обязательным ключом в \\"{type}\\", поэтому доступ может вызвать исключение во время выполнения","keyReadOnly":"\\"{name}\\" является ключом только для чтения в \\"{type}\\"","keyRequiredDeleted":"\\"{name}\\" является обязательным ключом и не подлежит удалению","keyUndefined":"\\"{name}\\" не является определенным ключом в \\"{type}\\"","kwargsParamMissing":"У параметра \\"**{paramName}\\" нет соответствующего параметра","listAssignmentMismatch":"Тип \\"{type}\\" несовместим с целевым списком","literalAssignmentMismatch":"\\"{sourceType}\\" нельзя присвоить типу \\"{destType}\\"","matchIsNotExhaustiveHint":"Если не предполагается исчерпывающая обработка, добавьте \\"case _: pass\\"","matchIsNotExhaustiveType":"Тип \\"{type}\\" не обрабатывается","memberAssignment":"Выражение типа \\"{type}\\" не может быть назначено элементу \\"{name}\\" класса \\"{classType}\\"","memberIsAbstract":"Отсутствует реализация \\"{type}.{name}\\".","memberIsAbstractMore":"и еще {{count}}","memberIsClassVarInProtocol":"\\"{name}\\" определено как класс ClassVar в протоколе","memberIsFinalInProtocol":"\\"{name}\\" помечено в протоколе как Final","memberIsInitVar":"Элемент \\"{name}\\" является полем только для инициализации","memberIsInvariant":"Элемент \\"{name}\\" инвариантен, поскольку помечен как mutable","memberIsNotClassVarInClass":"Необходимо определить \\"{name}\\" как ClassVar для совместимости с протоколом.","memberIsNotClassVarInProtocol":"\\"{name}\\" не определено как класс ClassVar в протоколе","memberIsNotFinalInProtocol":"\\"{name}\\" не помечен как окончательный в протоколе","memberIsWritableInProtocol":"\\"{name}\\" доступно для записи в протоколе","memberSetClassVar":"Элемент \\"{name}\\" не может быть назначен через экземпляр класса, так как это ClassVar","memberTypeMismatch":"\\"{name}\\" является несовместимым типом","memberUnknown":"Элемент \\"{name}\\" неизвестен","metaclassConflict":"Метакласс \\"{metaclass1}\\" конфликтует с \\"{metaclass2}\\"","missingDeleter":"Отсутствует метод удаления свойства","missingGetter":"Отсутствует метод получения свойства","missingSetter":"Отсутствует метод установки свойств","namedParamMissingInDest":"В целевом объекте отсутствует параметр ключевого слова \\"{name}\\"","namedParamMissingInSource":"В источнике нет параметра ключевого слова \\"{name}\\"","namedParamTypeMismatch":"Параметр ключевого слова {name} типа \\"{sourceType}\\" нельзя присвоить типу \\"{destType}\\"","namedTupleNotAllowed":"NamedTuple не может использоваться для проверок экземпляров или классов","newMethodLocation":"Метод __new__ определен в классе \\"{type}\\"","newMethodSignature":"Сигнатура метода __new__ требует \\"{type}\\"","newTypeClassNotAllowed":"Класс, созданный с NewType, нельзя использовать с проверками экземпляров и классов","noOverloadAssignable":"Нет перегруженной функции, соответствующей типу \\"{type}\\"","noneNotAllowed":"Их невозможно использовать для проверок экземпляров или классов","orPatternMissingName":"Отсутствуют имена: {name}","overloadIndex":"Наилучшее совпадение: {index} перегрузки","overloadNotAssignable":"Одна или несколько перегрузок \\"{name}\\" не подлежат присвоению","overloadSignature":"Здесь определена сигнатура перегрузки","overriddenMethod":"Переопределенный метод","overriddenSymbol":"Переопределенный символ","overrideInvariantMismatch":"Тип переопределения \\"{overrideType}\\" не совпадает с базовым типом \\"{baseType}\\"","overrideIsInvariant":"Переменная изменяема, поэтому ее тип является инвариантным","overrideNoOverloadMatches":"В переопределении нет сигнатуры перегрузки, совместимой с базовым методом","overrideNotClassMethod":"Базовый метод объявлен как classmethod, а его переопределение — нет","overrideNotInstanceMethod":"Базовый метод объявлен как метод экземпляра, а его переопределение — нет","overrideNotStaticMethod":"Базовый метод объявлен как статический, а его переопределение — нет","overrideOverloadNoMatch":"Переопределение не обрабатывает все перегрузки базового метода","overrideOverloadOrder":"Перегрузки в методе переопределения должны располагаться в том же порядке, что и в базовом методе","overrideParamKeywordNoDefault":"Несоответствие параметра ключевого слова \\"{name}\\": базовый параметр содержит значение аргумента по умолчанию, параметр переопределения — нет","overrideParamKeywordType":"Несоответствие типа параметра ключевого слова \\"{name}\\": базовый параметр имеет тип \\"{baseType}\\", параметр переопределения имеет тип \\"{overrideType}\\"","overrideParamName":"Несоответствие имени параметра {index}: базовый параметр называется \\"{baseName}\\", параметр переопределения называется \\"{overrideName}\\"","overrideParamNameExtra":"Параметр \\"{name}\\" отсутствует в базовом классе","overrideParamNameMissing":"Параметр \\"{name}\\" отсутствует в переопределении","overrideParamNamePositionOnly":"Несоответствие параметра {index}: базовый параметр \\"{baseName}\\" является параметром ключевого слова, параметр переопределения предназначен только для позиции","overrideParamNoDefault":"Несоответствие параметра {index}: базовый параметр содержит значение аргумента по умолчанию, параметр переопределения — нет","overrideParamType":"Несоответствие типа параметра {index}: базовый параметр имеет тип \\"{baseType}\\", параметр переопределения имеет тип \\"{overrideType}\\"","overridePositionalParamCount":"Несоответствие позиционного подсчета параметров. Базовый метод содержит {baseCount}, но переопределение содержит {overrideCount}","overrideReturnType":"Несоответствие типа возвращаемого значения: базовый метод возвращает тип \\"{baseType}\\", а переопределение — \\"{overrideType}\\"","overrideType":"Базовый класс определяет тип как \\"{type}\\"","paramAssignment":"Параметр {index}: тип \\"{sourceType}\\" нельзя присвоить типу \\"{destType}\\"","paramSpecMissingInOverride":"В методе переопределения отсутствуют параметры ParamSpec.","paramType":"Параметр принадлежит к типу \\"{paramType}\\"","privateImportFromPyTypedSource":"Вместо этого используйте импорт из \\"{module}\\"","propertyAccessFromProtocolClass":"Свойство, определенное в классе протокола, не может быть доступно как переменная класса.","propertyMethodIncompatible":"Метод свойства \\"{name}\\" несовместим","propertyMethodMissing":"Метод свойства \\"{name}\\" отсутствует в переопределении","propertyMissingDeleter":"Для свойства \\"{name}\\" не определен метод удаления","propertyMissingSetter":"Для свойства \\"{name}\\" не определен метод задания","protocolIncompatible":"\\"{sourceType}\\" несовместим с протоколом \\"{destType}\\"","protocolMemberMissing":"\\"{name}\\" отсутствует.","protocolRequiresRuntimeCheckable":"Класс протокола должен быть @runtime_checkable, чтобы его можно было использовать при проверках экземпляров и классов","protocolSourceIsNotConcrete":"\\"{sourceType}\\" не является конкретным типом класса и не может быть присвоен типу \\"{destType}\\"","protocolUnsafeOverlap":"Атрибуты \\"{name}\\" используют те же имена, что и протокол","pyrightCommentIgnoreTip":"Для подавления диагностики в одной строке используйте конструкцию \\"# pyright: ignore[<правила диагностики>]","readOnlyAttribute":"Атрибут \\"{name}\\" доступен только для чтения","seeClassDeclaration":"См. объявление класса","seeDeclaration":"См. объявление","seeFunctionDeclaration":"См. объявление функции","seeMethodDeclaration":"См. объявление метода","seeParameterDeclaration":"Просмотреть объявление параметра","seeTypeAliasDeclaration":"Просмотреть объявление псевдонима типа","seeVariableDeclaration":"Просмотреть объявление переменной","tupleAssignmentMismatch":"Тип \\"{type}\\" несовместим с целевым кортежем","tupleEntryTypeMismatch":"Запись кортежа {entry} имеет неверный тип","tupleSizeIndeterminateSrc":"Несоответствие размеров кортежа: ожидается \\"{expected}\\", но получено неопределенное значение","tupleSizeIndeterminateSrcDest":"Несоответствие размеров кортежа: ожидается {expected} или больше, но получено неопределенное значение","tupleSizeMismatch":"Несоответствие размеров кортежа: ожидается \\"{expected}\\", но получено \\"{received}\\"","tupleSizeMismatchIndeterminateDest":"Несоответствие размеров кортежа: ожидается {expected} или больше, но получено {received}","typeAliasInstanceCheck":"Псевдоним типа, создаваемый оператором \\"type\\", не может использоваться с проверками экземпляра и класса.","typeAssignmentMismatch":"Тип \\"{sourceType}\\" нельзя присвоить типу \\"{destType}\\"","typeBound":"Тип \\"{sourceType}\\" несовместим с привязанным типом \\"{destType}\\" для переменной типа \\"{name}\\"","typeConstrainedTypeVar":"Тип \\"{type}\\" несовместим с переменной ограниченного типа \\"{name}\\"","typeIncompatible":"\\"{sourceType}\\" несовместим с \\"{destType}\\"","typeNotClass":"\\"{type}\\" не является классом.","typeNotStringLiteral":"\\"{type}\\" не является строковым литералом","typeOfSymbol":"Тип \\"{name}\\" является \\"{type}\\"","typeParamSpec":"Тип \\"{type}\\" несовместим с ParamSpec \\"{name}\\"","typeUnsupported":"Тип \\"{type}\\" не поддерживается","typeVarDefaultOutOfScope":"Переменная типа \\"{name}\\" лежит за пределами области","typeVarIsContravariant":"Параметр типа \\"{name}\\" является контравариантным, но \\"{sourceType}\\" не является супертипом \\"{destType}\\"","typeVarIsCovariant":"Параметр типа \\"{name}\\" является ковариантным, но \\"{sourceType}\\" не является подтипом \\"{destType}\\"","typeVarIsInvariant":"Параметр типа \\"{name}\\" является инвариантным, но \\"{sourceType}\\" не совпадает с \\"{destType}\\"","typeVarNotAllowed":"TypeVar не допускается для проверок экземпляров или классов","typeVarTupleRequiresKnownLength":"TypeVarTuple не может граничить с кортежем неизвестной длины","typeVarUnnecessarySuggestion":"Вместо этого используйте {type}","typeVarUnsolvableRemedy":"Укажите перегрузку, которая указывает тип возвращаемого значения, если аргумент не передается","typeVarsMissing":"Отсутствуют переменные типа: {names}","typedDictBaseClass":"Класс \\"{type}\\" не является TypedDict","typedDictClassNotAllowed":"Класс TypedDict не допускается для проверок экземпляров или классов","typedDictClosedExtraNotAllowed":"Не удается добавить элемент \\"{name}\\"","typedDictClosedExtraTypeMismatch":"Не удается добавить элемент \\"{name}\\" типа \\"{type}\\"","typedDictClosedFieldNotRequired":"Не удается добавить элемент \\"{name}\\", так как он должен быть помечен как необязательный","typedDictExtraFieldNotAllowed":"Элемент \\"{name}\\" отсутствует в типе \\"{type}\\"","typedDictExtraFieldTypeMismatch":"Тип элемента \\"{name}\\" несовместим с типом \\"__extra_items__\\" в \\"{type}\\"","typedDictFieldMissing":"\\"{name}\\" отсутствует в \\"{type}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" не является элементом \\"{type}\\" только для чтения","typedDictFieldNotRequired":"\\"{name}\\" не является обязательным в \\"{type}\\"","typedDictFieldRequired":"\\"{name}\\" является обязательным в \\"{type}\\"","typedDictFieldTypeMismatch":"Тип \\"{type}\\" нельзя присвоить полю \\"{name}\\"","typedDictFieldUndefined":"Элемент \\"{name}\\" не определен в типе \\"{type}\\"","typedDictFinalMismatch":"\\"{sourceType}\\" несовместим с \\"{destType}\\" из-за несоответствия окончательности","typedDictKeyAccess":"Использовать [\\"{name}\\"] для ссылки на элемент в TypedDict","typedDictNotAllowed":"TypedDict не может использоваться для проверок экземпляров или классов","unhashableType":"Тип \\"{type}\\" не является хэшируемым","uninitializedAbstractVariable":"Переменная экземпляра \\"{name}\\" определена в абстрактном базовом классе \\"{classType}\\", но не инициализирована","unreachableExcept":"\\"{exceptionType}\\" является подклассом \\"{parentType}\\"","useDictInstead":"Используйте Dict[T1, T2] для указания типа словаря","useListInstead":"Используйте List[T] для указания типа списка или Union[T1, T2] для указания типа объединения","useTupleInstead":"Используйте конструкцию tuple[T1, ..., Tn], чтобы указать тип кортежа, или Union[T1, T2], чтобы указать тип объединения","useTypeInstead":"Используйте вместо этого Type[T]","varianceMismatchForClass":"Вариант аргумента типа \\"{typeVarName}\\" несовместим с базовым классом \\"{className}\\"","varianceMismatchForTypeAlias":"Отклонение аргумента типа \\"{typeVarName}\\" несовместимо с \\"{typeAliasParam}\\""}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.tr.json":
/*!****************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.tr.json ***!
  \****************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"Tür Saplaması Oluştur","createTypeStubFor":"\\"{moduleName}\\" için Tür Saplaması Oluştur","executingCommand":"Komut yürütülüyor","filesToAnalyzeCount":"analiz edilecek {count} dosya var","filesToAnalyzeOne":"Analiz edilecek 1 dosya","findingReferences":"Başvurular bulunuyor","organizeImports":"İçeri Aktarmaları Düzenle","renameShadowedFile":"\\"{oldFile}\\" dosyasını \\"{newFile}\\" olarak yeniden adlandır"},"Completion":{"autoImportDetail":"Otomatik içeri aktarma","indexValueDetail":"Dizin değeri"},"Diagnostic":{"abstractMethodInvocation":"\\"{method}\\" metodu soyut veya uygulanmamış olduğundan çağrılamaz","annotatedParamCountMismatch":"Parametre ek açıklama sayısı uyuşmazlığı: {expected} bekleniyordu ancak {received} alındı","annotatedTypeArgMissing":"\\"Annotated\\" için bir tür bağımsız değişkeni ve bir veya daha fazla ek açıklama bekleniyordu","annotationFormatString":"Tür ek açıklamaları biçim dizesi sabit değerlerini (f-strings) kullanamaz","annotationNotSupported":"Tür ek açıklaması bu deyim için desteklenmiyor","annotationSpansStrings":"Tür ek açıklamaları birden çok dize sabit değerine yayılamaz","annotationStringEscape":"Tür ek açıklamaları kaçış karakterleri içeremez","argAssignment":"\\"{argType}\\" türünde bağımsız değişken, \\"{paramType}\\" türündeki parametreye atanamaz","argAssignmentFunction":"\\"{argType}\\" türünde bağımsız değişken, \\"{functionName}\\" işlevi içinde \\"{paramType}\\" türündeki parametreye atanamaz","argAssignmentParam":"\\"{argType}\\" türünde bağımsız değişken, \\"{paramName}\\" türündeki \\"{paramType}\\" parametresine atanamaz","argAssignmentParamFunction":"\\"{argType}\\" türünde bağımsız değişken, \\"{functionName}\\" işlevi içinde \\"{paramName}\\" türündeki \\"{paramType}\\" parametresine atanamaz","argMissingForParam":"{name} parametresi için bağımsız değişken eksik","argMissingForParams":"{names} parametrelerinin bağımsız değişkenleri eksik","argMorePositionalExpectedCount":"{expected} tane daha konumsal bağımsız değişken bekleniyordu","argMorePositionalExpectedOne":"1 tane daha konumsal bağımsız değişken bekleniyordu","argPositional":"Konumsal bağımsız değişken bekleniyordu","argPositionalExpectedCount":"{expected} konumsal bağımsız değişken bekleniyordu","argPositionalExpectedOne":"1 konumsal bağımsız değişken bekleniyordu","argTypePartiallyUnknown":"Bağımsız değişken türü kısmen bilinmiyor","argTypeUnknown":"Bağımsız değişken türü bilinmiyor","assertAlwaysTrue":"Assert ifadesi her zaman true olarak değerlendirilir","assertTypeArgs":"\\"assert_type\\" iki konumsal bağımsız değişken bekliyor","assertTypeTypeMismatch":"\\"assert_type\\" uyuşmuyor; \\"{expected}\\" bekleniyordu ancak \\"{received}\\" alındı","assignmentExprComprehension":"\\"{name}\\" atama ifadesi hedefi, hedef için anlama ile aynı adı kullanamaz","assignmentExprContext":"Atama ifadesi modül, işlev veya lambda içinde olmalıdır","assignmentExprInSubscript":"Bir alt simge içindeki atama ifadeleri yalnızca Python 3.10 ve daha yeni sürümlerinde desteklenir","assignmentInProtocol":"Protokol sınıfı içindeki örnek veya sınıf değişkenleri sınıf gövdesi içinde açıkça bildirilmelidir","assignmentTargetExpr":"İfade, atama hedefi olamaz","asyncNotInAsyncFunction":"Zaman uyumsuz işlevin dışında \\"async\\" kullanımına izin verilmez","awaitIllegal":"\\"await\\" kullanımı için Python 3.5 veya daha yeni bir sürümü gerekiyor","awaitNotAllowed":"Tür ek açıklamaları \\"await\\" kullanamaz","awaitNotInAsync":"\\"await\\" öğesi yalnızca zaman uyumsuz işlev içinde kullanılabilir","backticksIllegal":"Eski kesme işaretleri arasında yer almayan ifadeler Python3.x’de desteklenmiyor; bunun yerine repr kullanın","baseClassCircular":"Sınıf kendi türevi olamaz","baseClassFinal":"\\"{type}\\" temel sınıfı final olarak işaretlendi ve alt sınıf olamaz","baseClassIncompatible":"{type} türündeki temel sınıflar karşılıklı olarak uyumsuzdur","baseClassInvalid":"Sınıfın bağımsız değişkeni bir temel sınıf olmalıdır","baseClassMethodTypeIncompatible":"\\"{classType}\\" sınıfına ait temel sınıflar, \\"{name}\\" metodunu uyumsuz bir şekilde tanımlıyor","baseClassUnknown":"Temel sınıf türü bilinmiyor, türetilmiş sınıfı gizliyor","baseClassVariableTypeIncompatible":"\\"{classType}\\" sınıfı için temel sınıflar, \\"{name}\\" değişkenini uyumsuz bir şekilde tanımlıyor","binaryOperationNotAllowed":"Tür ek açıklamasında ikili işleç kullanılamaz","bindTypeMismatch":"\\"{type}\\", \\"{paramName}\\" parametresine atanamadığından \\"{methodName}\\" metodu bağlanamadı","breakOutsideLoop":"\\"break\\" yalnızca bir döngü içinde kullanılabilir","callableExtraArgs":"\\"Callable\\" için yalnızca iki tür bağımsız değişkeni bekleniyordu","callableFirstArg":"Parametre türü listesi veya \\"...\\" bekleniyordu","callableNotInstantiable":"\\"{type}\\" türünün örneği oluşturulamıyor","callableSecondArg":"\\"Callable\\" için ikinci tür bağımsız değişkeni olarak dönüş türü bekleniyordu","casePatternIsIrrefutable":"Reddedilemez desene yalnızca son case deyimi için izin verilir","classAlreadySpecialized":"\\"{type}\\" türü zaten özelleştirilmiş","classDecoratorTypeUnknown":"Türü belirtilmemiş sınıf dekoratörü sınıf türünü gizliyor; dekoratör yoksayılıyor","classDefinitionCycle":"\\"{name}\\" için sınıf tanımı kendisine bağımlı","classGetItemClsParam":"__class_getitem__ geçersiz kılması bir \\"cls\\" parametresi almalı","classMethodClsParam":"Sınıf metotları bir \\"cls\\" parametresi almalıdır","classNotRuntimeSubscriptable":"\\"{name}\\" sınıfına ait alt simge çalışma zamanı özel durumunu oluşturur; tür ek açıklamalarını tırnak içine alın","classPatternBuiltInArgPositional":"Sınıf deseni yalnızca konumsal alt desen kabul eder","classPatternPositionalArgCount":"\\"{type}\\" sınıfı için çok fazla konumsal desen var; {expected} bekleniyordu ancak {received} alındı","classPatternTypeAlias":"\\"{type}\\" özel bir tür diğer adı olduğundan sınıf deseninde kullanılamaz","classPropertyDeprecated":"Sınıf özellikleri Python 3.11\'de kullanım dışıdır ve Python 3.13\'te desteklenmez","classTypeParametersIllegal":"Sınıf türü parametresi söz dizimi için Python 3.12 veya daha yeni bir sürümü gerekiyor","classVarFirstArgMissing":"\\"ClassVar\\" sonrasında tür bağımsız değişkeni bekleniyordu","classVarNotAllowed":"Bu bağlamda \\"ClassVar\\" kullanımına izin verilmiyor","classVarOverridesInstanceVar":"\\"{name}\\" sınıf değişkeni \\"{className}\\" sınıfındaki aynı ada sahip örnek değişkenini geçersiz kılıyor","classVarTooManyArgs":"\\"ClassVar\\" sonrasında yalnızca bir tür bağımsız değişkeni bekleniyordu","classVarWithTypeVar":"\\"ClassVar\\" türü tür değişkenleri içeremez","clsSelfParamTypeMismatch":"\\"{name}\\" parametre türü, \\"{classType}\\" sınıfının üst türü olmalıdır","codeTooComplexToAnalyze":"Kod analiz edilemeyecek kadar karmaşık; alt yordamlara ayırarak yeniden düzenleyip veya koşullu kod yollarını azaltarak karmaşıklığı azaltın","collectionAliasInstantiation":"\\"{type}\\" türündeki örnek oluşturulamıyor, bunun yerine \\"{alias}\\" kullanın","comparisonAlwaysFalse":"\\"{leftType}\\" türleri ve \\"{rightType}\\" türleri çakışmadığından koşul her zaman False olarak değerlendirilir","comparisonAlwaysTrue":"\\"{leftType}\\" ve \\"{rightType}\\" türleri çakışmadığından ifade her zaman True olarak değerlendirilir","comprehensionInDict":"Anlama diğer küme girdileri ile kullanılamaz","comprehensionInSet":"Anlama diğer küme girdileri ile kullanılamaz","concatenateContext":"Bu bağlamda \\"Concatenate\\" kullanılamaz","concatenateParamSpecMissing":"\\"Concatenate\\" için son tür bağımsız değişkeni bir ParamSpec veya \\"...\\" olmalıdır","concatenateTypeArgsMissing":"\\"Birleştirme\\" en az iki tür bağımsız değişken gerektirir","conditionalOperandInvalid":"\\"{type}\\" türündeki koşullu işlenen geçersiz","constantRedefinition":"\\"{name}\\" sabit (büyük harf olduğundan) ve yeniden tanımlanamaz","constructorNoArgs":"\\"{type}\\" oluşturucusu için bağımsız değişken beklenmiyordu","constructorParametersMismatch":"\\"{classType}\\" sınıfındaki __new__ ve __init__ imzaları arasında uyuşmazlık var","containmentAlwaysFalse":"\\"{leftType}\\" türleri ve \\"{rightType}\\" türleri çakışmadığından ifade her zaman False olarak değerlendirilir","containmentAlwaysTrue":"\\"{leftType}\\" türleri ve \\"{rightType}\\" türleri çakışmadığından ifade her zaman True olarak değerlendirilir","continueInFinally":"\\"continue\\" finally yan tümcesi içinde kullanılamaz","continueOutsideLoop":"\\"continue\\" yalnızca bir döngü içinde kullanılabilir","coroutineInConditionalExpression":"Koşullu ifade, her zaman True olarak değerlendirilen eş yordama başvurur","dataClassBaseClassFrozen":"Dondurulmuş olmayan bir sınıf dondurulmuş bir sınıftan devralamaz","dataClassBaseClassNotFrozen":"Dondurulmuş sınıf, dondurulmuş olmayan bir sınıftan devralamaz","dataClassConverterFunction":"\\"{argType}\\" türündeki bağımsız değişken, \\"{fieldName}\\" türündeki \\"{fieldType}\\" alanı için geçerli bir dönüştürücü değil","dataClassConverterOverloads":"\\"{funcName}\\" işlevinin aşırı yüklemelerinden hiçbiri \\"{fieldType}\\" türündeki \\"{fieldName}\\" alanı için geçerli dönüştürücüler değil","dataClassFieldWithDefault":"Varsayılan değerleri olmayan alanlar, varsayılan değerleri olan alanlardan sonra gelemez","dataClassFieldWithPrivateName":"Veri sınıfı alanı özel ad kullanamıyor","dataClassFieldWithoutAnnotation":"Tür ek açıklaması olmayan veri sınıfı alanı çalışma zamanı özel durumuna neden olur","dataClassPostInitParamCount":"Veri sınıfı __post_init__ parametre sayısı yanlış; InitVar alanlarının sayısı {expected}","dataClassPostInitType":"Veri sınıfı __post_init__ metodu parametre türü ile \\"{fieldName}\\" alanı uyuşmuyor","dataClassSlotsOverwrite":"__slots__ zaten sınıfta tanımlı","dataClassTransformExpectedBoolLiteral":"Statik olarak True veya False olarak değerlendirilen ifade bekleniyordu","dataClassTransformFieldSpecifier":"Sınıfların veya işlevlerin demeti bekleniyordu ancak \\"{type}\\" türü alındı","dataClassTransformPositionalParam":"\\"dataclass_transform\\" için tüm bağımsız değişkenlerin anahtar sözcük bağımsız değişkenleri olması gerekiyor","dataClassTransformUnknownArgument":"\\"{name}\\" bağımsız değişkeni, dataclass_transform tarafından desteklenmiyor","dataProtocolInSubclassCheck":"issubclass çağrılarında veri protokollerine (yöntem dışı öznitelikler dahil) izin verilmez","declaredReturnTypePartiallyUnknown":"Bildirilen \\"{returnType}\\" dönüş türü kısmen bilinmiyor","declaredReturnTypeUnknown":"Bildirilen dönüş türü bilinmiyor","defaultValueContainsCall":"Parametre varsayılan değer ifadesinde işlev çağrılarına ve değiştirilebilir nesnelere izin verilmez","defaultValueNotAllowed":"\\"*\\" veya \\"**\\" olan parametre varsayılan değere sahip olamaz","delTargetExpr":"İfade silinemiyor","deprecatedClass":"\\"{name}\\" sınıfı kullanım dışı","deprecatedConstructor":"\\"{name}\\" sınıfının oluşturucusu kullanım dışı","deprecatedDescriptorDeleter":"\\"{name}\\" tanımlayıcısı için \\"__delete__\\" yöntemi kullanım dışı","deprecatedDescriptorGetter":"\\"{name}\\" tanımlayıcısı için \\"__get__\\" yöntemi kullanım dışı","deprecatedDescriptorSetter":"\\"{name}\\" tanımlayıcısı için \\"__set__\\" yöntemi kullanım dışı","deprecatedFunction":"\\"{name}\\" işlevi kullanım dışı","deprecatedMethod":"\\"{className}\\" sınıfındaki \\"{name}\\" yöntemi kullanım dışı","deprecatedPropertyDeleter":"\\"{name}\\" özelliği silicisi kullanım dışı","deprecatedPropertyGetter":"\\"{name}\\" özelliği alıcısı kullanım dışı","deprecatedPropertySetter":"\\"{name}\\" özelliği ayarlayıcısı kullanım dışı","deprecatedType":"Bu tür Python {version} sürümünden itibaren kullanım dışı; bunun yerine \\"{replacement}\\" kullanın","dictExpandIllegalInComprehension":"Sözlük genişletmeye anlamada izin verilmiyor","dictInAnnotation":"Tür ek açıklamasında sözlük ifadesi kullanılamaz","dictKeyValuePairs":"Sözlük girdileri anahtar/değer çiftleri içermelidir","dictUnpackIsNotMapping":"Sözlük açma işleci için eşleme bekleniyordu","dunderAllSymbolNotPresent":"\\"{name}\\" __all__ ile belirtildi ancak modülde yok","duplicateArgsParam":"Yalnızca bir \\"*\\" parametresi kullanılabilir","duplicateBaseClass":"Yinelenen temel sınıfa izin verilmiyor","duplicateCapturePatternTarget":"\\"{name}\\" yakalama hedefi, aynı desen içinde birden çok kez bulunamaz","duplicateCatchAll":"Yalnızca bir catch-all except yan tümcesine izin verilir","duplicateEnumMember":"\\"{name}\\" sabit listesi üyesi zaten bildirildi","duplicateGenericAndProtocolBase":"Yalnızca bir Genel[...] veya Protocol[...] temel sınıfı kullanılabilir","duplicateImport":"\\"{importName}\\" birden çok kez içeri aktarıldı","duplicateKeywordOnly":"Yalnızca bir \\"*\\" ayırıcısı kullanılabilir","duplicateKwargsParam":"Yalnızca bir \\"**\\" parametresine izin verilir","duplicateParam":"\\"{name}\\" yinelenen parametresi","duplicatePositionOnly":"Yalnızca bir \\"/\\" parametresine izin verilir","duplicateStarPattern":"Desen dizisinde yalnızca bir \\"*\\" desenine izin verilir","duplicateStarStarPattern":"Yalnızca bir \\"**\\" girdisine izin verilir","duplicateUnpack":"Listede yalnızca bir paket açma işlemine izin veriliyor","ellipsisAfterUnpacked":"\\"...\\" paketlenmemiş TypeVarTuple veya tuple ile kullanılamaz","ellipsisContext":"\\"...\\" kullanımına bu bağlamda izin verilmiyor","ellipsisSecondArg":"\\"...\\" yalnızca iki bağımsız değişkenin ikincisi olarak kullanılabilir","enumClassOverride":"\\"{name}\\" sabit listesi sınıfı final niteliğinde ve alt sınıf olamaz","exceptionGroupIncompatible":"Özel durum grubu söz dizimi (\\"except*\\") için Python 3.11 veya daha yeni bir sürümü gerekiyor","exceptionTypeIncorrect":"\\"{type}\\", BaseException türevi değil","exceptionTypeNotClass":"\\"{type}\\" geçerli bir özel durum sınıfı değil","exceptionTypeNotInstantiable":"\\"{type}\\" özel durum türü oluşturucusu bir veya daha fazla bağımsız değişken gerektiriyor","expectedAfterDecorator":"Dekoratörden sonra işlev veya sınıf bildirimi bekleniyordu","expectedArrow":"Dönüş türü ek açıklaması sonrasında \\"->\\" bekleniyordu","expectedAsAfterException":"Özel durum türünden sonra \\"as\\" bekleniyordu","expectedAssignRightHandExpr":"\\"=\\" öğesinin sağ tarafında ifade bekleniyordu","expectedBinaryRightHandExpr":"İşlecin sağında ifade bekleniyordu","expectedBoolLiteral":"True veya False bekleniyor","expectedCase":"\\"case\\" deyimi bekleniyordu","expectedClassName":"Sınıf adı bekleniyordu","expectedCloseBrace":"\\"{\\" kapatılmadı","expectedCloseBracket":"\\"[\\" kapatılmadı","expectedCloseParen":"\\"(\\" kapatılmadı","expectedColon":"\\":\\" bekleniyordu","expectedComplexNumberLiteral":"Desen eşleme için karmaşık sayı sabit değeri bekleniyordu","expectedDecoratorExpr":"İfade formu Python 3.9\'dan önceki dekoratör için desteklenmiyor","expectedDecoratorName":"Dekoratör adı bekleniyordu","expectedDecoratorNewline":"Dekoratör sonunda yeni satır bekleniyordu","expectedDelExpr":"\\"del\\" sonrasında ifade bekleniyordu","expectedElse":"\\"else\\" bekleniyordu","expectedEquals":"\\"=\\" bekleniyordu","expectedExceptionClass":"Geçersiz özel durum sınıfı veya nesnesi","expectedExceptionObj":"Özel durum nesnesi, özel durum sınıfı veya None bekleniyordu","expectedExpr":"İfade bekleniyor","expectedFunctionAfterAsync":"\\"async\\" sonrasında işlev tanımı bekleniyordu","expectedFunctionName":"\\"def\\" sonrasında işlev adı bekleniyordu","expectedIdentifier":"Tanımlayıcı bekleniyordu","expectedImport":"\\"import\\" bekleniyordu","expectedImportAlias":"\\"as\\" sonrasında sembol bekleniyordu","expectedImportSymbols":"İçeri aktarmadan sonra bir veya daha fazla sembol adı bekleniyordu","expectedIn":"\\"in\\" bekleniyordu","expectedInExpr":"\\"in\\" sonrasında ifade bekleniyordu","expectedIndentedBlock":"Girintili blok bekleniyordu","expectedMemberName":"\\".\\" sonrasında üye adı bekleniyordu","expectedModuleName":"Modül adı bekleniyordu","expectedNameAfterAs":"\\"as\\" sonrasında sembol adı bekleniyordu","expectedNamedParameter":"Anahtar sözcük parametresi, \\"*\\" sonrasında gelmelidir","expectedNewline":"Yeni satır bekleniyordu","expectedNewlineOrSemicolon":"Deyimler yeni satırlarla veya noktalı virgüllerle ayrılarak belirtilmelidir","expectedOpenParen":"\\"(\\" bekleniyordu","expectedParamName":"Parametre adı bekleniyordu","expectedPatternExpr":"Desen ifadesi bekleniyordu","expectedPatternSubjectExpr":"Beklenen desen konusu ifadesi","expectedPatternValue":"\\"a.b\\" biçiminde bir desen değeri ifadesi bekleniyordu","expectedReturnExpr":"\\"return\\" sonrasında ifade bekleniyordu","expectedSliceIndex":"Dizin veya dilim ifadesi bekleniyordu","expectedTypeNotString":"Tür bekleniyordu ancak sabit değerli dize alındı","expectedTypeParameterName":"Beklenen tür parametresi adı","expectedYieldExpr":"Yield deyiminde ifade bekleniyordu","finalClassIsAbstract":"\\"{type}\\" sınıfı son olarak işaretlendi ve tüm soyut sembolleri uygulamalıdır","finalContext":"Bu bağlamda \\"Final\\" kullanılamaz","finalMethodOverride":"\\"{name}\\" yöntemi \\"{className}\\" sınıfı içinde tanımlanan final metodu geçersiz kılamaz","finalNonMethod":"\\"{name}\\" işlevi bir yöntem olmadığından @final olarak işaretlenemez","finalReassigned":"\\"{name}\\" Son olarak bildirildi ve yeniden atanamaz","finalRedeclaration":"\\"{name}\\" daha önce Final olarak bildirildi","finalRedeclarationBySubclass":"\\"{name}\\", \\"{className}\\" sınıf adı bu adı Final olarak bildirdiğinden yeniden bildirilemez","finalTooManyArgs":"\\"Final\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","finalUnassigned":"\\"{name}\\" Final olarak bildirildi, ancak değer atanmadı","formatStringBrace":"f dizesi sabit değerinde tek bir kapatma küme ayracı kullanılamaz; çift sağ ayraç kullanın","formatStringBytes":"Biçim dizesi sabit değerleri (f-strings) ikili olamaz","formatStringDebuggingIllegal":"F dizesi hata ayıklama belirticisi \\"=\\", Python 3.8 veya daha yeni bir sürüm gerektirir","formatStringEscape":"Python 3.12 öncesinde f dizesinin ifade bölümünde kaçış sırasına (ters eğik çizgi) izin verilmez","formatStringExpectedConversion":"f-string\'de \\"!\\" öğesinden sonra bir dönüştürme tanımlayıcısı bekleniyordu","formatStringIllegal":"Biçim dizesi sabit değerleri (f dizeleri) Python 3.6 veya daha yeni bir sürüm gerektirir","formatStringInPattern":"Desende biçim dizesine izin verilmiyor","formatStringNestedFormatSpecifier":"İfadeler biçim dizesi belirticisi içinde çok derin iç içe geçmiş","formatStringNestedQuote":"F dizesi içinde iç içe geçmiş dizeler Python 3.12\'den önceki f dizesiyle aynı tırnak karakterini kullanamaz","formatStringUnicode":"Biçim dizesi sabit değerleri (f-strings) unicode olamaz","formatStringUnterminated":"F dizesi içinde sonlandırılmamış ifade; \\"}\\" bekleniyor","functionDecoratorTypeUnknown":"Türü belirsiz işlev dekoratörü işlevin türünü gizler; dekoratör yoksayılıyor","functionInConditionalExpression":"Koşullu ifade, her zaman True olarak değerlendirilen işleve başvurur","functionTypeParametersIllegal":"İşlev türü parametre sözdizimi Python 3.12 veya daha yeni bir sürüm gerektirir","futureImportLocationNotAllowed":"__future__ içeri aktarmaları dosyanın başında olmalıdır","generatorAsyncReturnType":"Zaman uyumsuz oluşturucu işlevinin dönüş türü \\"AsyncGenerator[{yieldType}, Any]\\" ile uyumlu olmalıdır","generatorNotParenthesized":"Tek bağımsız değişken olmadıklarında oluşturucu ifadeleri ayraç içine alınmalıdır","generatorSyncReturnType":"Oluşturucu işlevinin dönüş türü \\"Generator[{yieldType}, Any, Any]\\" ile uyumlu olmalıdır","genericBaseClassNotAllowed":"\\"Generic\\" temel sınıfı, tür parametresi sözdizimiyle kullanılamaz","genericClassAssigned":"Genel sınıf türü atanamıyor","genericClassDeleted":"Genel sınıf türü silinemiyor","genericInstanceVariableAccess":"Sınıf üzerinden genel örnek değişkenine erişim belirsiz","genericNotAllowed":"\\"Generic\\" bu bağlamda geçerli değil","genericTypeAliasBoundTypeVar":"Sınıf içindeki genel tür diğer adı {names} bağlı tür değişkenlerini kullanamıyor","genericTypeArgMissing":"\\"Generic\\" en az bir tür bağımsız değişkeni gerektirir","genericTypeArgTypeVar":"\\"Generic\\" için tür bağımsız değişkeni bir tür değişkeni olmalıdır","genericTypeArgUnique":"\\"Generic\\" için tür bağımsız değişkenleri benzersiz olmalıdır","globalReassignment":"\\"{name}\\" genel bildirimden önce atanmış","globalRedefinition":"\\"{name}\\" zaten genel olarak bildirildi","implicitStringConcat":"Örtük dize birleştirmesine izin verilmiyor","importCycleDetected":"İçeri aktarma zincirinde döngü algılandı","importDepthExceeded":"İçeri aktarma zinciri derinliği {depth} sınırını aştı","importResolveFailure":"\\"{importName}\\" adlı içeri aktarma çözümlenemedi","importSourceResolveFailure":"\\"{importName}\\" adlı içeri aktarma kaynaktan çözümlenemedi","importSymbolUnknown":"\\"{name}\\" alma simgesi bilinmiyor","incompatibleMethodOverride":"\\"{name}\\" metodu \\"{className}\\" sınıfını uyumsuz bir şekilde geçersiz kılıyor","inconsistentIndent":"Girintisiz miktar önceki girintiyle eşleşmiyor","inconsistentTabs":"Girinti içinde sekmelerin ve boşlukların kullanımı tutarsız","initMustReturnNone":"\\"__init__\\" dönüş türü None olmalıdır","initSubclassCallFailed":"__init_subclass__ yöntemi için yanlış anahtar bağımsız değişkenleri","initSubclassClsParam":"__init_subclass__ geçersiz kılması bir \\"cls\\" parametresi almalı","initVarNotAllowed":"\\"InitVar\\" öğesi bu bağlamda kullanılamaz","instanceMethodSelfParam":"Örnek metotları bir \\"self\\" parametresi almalıdır","instanceVarOverridesClassVar":"\\"{name}\\" örnek değişkeni \\"{className}\\" sınıfındaki aynı ada sahip sınıf değişkenini geçersiz kılıyor","instantiateAbstract":"\\"{type}\\" soyut sınıfı örneği oluşturulamıyor","instantiateProtocol":"\\"{type}\\" protokol sınıfının örneği oluşturulamıyor","internalBindError":"\\"{file}\\" dosyası bağlanırken dahili bir hata oluştu: {message}","internalParseError":"\\"{file}\\" dosyası ayrıştırılırken dahili bir hata oluştu: {message}","internalTypeCheckingError":"\\"{file}\\" dosyası tür denetimi gerçekleştirilirken dahili bir hata oluştu: {message}","invalidIdentifierChar":"Tanımlayıcıda geçersiz karakter","invalidStubStatement":"Deyim, bir tür saplama dosyası içinde anlamsız","invalidTokenChars":"Belirteçte geçersiz \\"{text}\\" karakteri var","isInstanceInvalidType":"\\"isinstance\\" için ikinci bağımsız değişken bir sınıf veya sınıf demeti olmalıdır","isSubclassInvalidType":"\\"issubclass\\" için ikinci bağımsız değişken bir sınıf veya sınıflar demeti olmalıdır","keyValueInSet":"Küme içinde anahtar/değer çiftlerine izin verilmiyor","keywordArgInTypeArgument":"Anahtar sözcük bağımsız değişkenleri tür bağımsız değişken listelerinde kullanılamaz","keywordOnlyAfterArgs":"\\"*\\" parametresinden sonra keyword-only bağımsız değişken ayırıcısı kullanılamaz","keywordParameterMissing":"Bir veya daha fazla anahtar sözcük parametresi \\"*\\" parametresini izlemeli","keywordSubscriptIllegal":"Alt simge içindeki anahtar sözcük bağımsız değişkenleri desteklenmiyor","lambdaReturnTypePartiallyUnknown":"Lambdanın \\"{returnType}\\" dönüş türü kısmen bilinmiyor","lambdaReturnTypeUnknown":"Lambdanın dönüş türü bilinmiyor","listAssignmentMismatch":"\\"{type}\\" türündeki ifade hedef listesine atanamaz","listInAnnotation":"Tür ek açıklamasında liste ifadesi kullanılamaz","literalEmptyArgs":"\\"Literal\\" sonrasında bir veya daha fazla tür bağımsız değişkeni bekleniyordu","literalNotAllowed":"\\"Değişmez değer\\" bir tür bağımsız değişken olmadan bu bağlamda kullanılamaz","literalNotCallable":"Değişmez tür örneği oluşturulamıyor","literalUnsupportedType":"\\"Literal\\" için tür bağımsız değişkenleri None, bir sabit değer (int, bool, str veya bytes) veya bir sabit listesi değeri olmalıdır","matchIncompatible":"Eşleme deyimleri için Python 3.10 veya daha yeni bir sürümü gerekiyor","matchIsNotExhaustive":"Eşleme deyimindeki durumlar değerlerin tümünü karşılayamıyor","maxParseDepthExceeded":"Maksimum ayrıştırma derinliği aşıldı; ifadeyi daha küçük alt ifadelere bölün","memberAccess":"\\"{type}\\" türü için \\"{name}\\" üyesine erişilemiyor","memberDelete":"\\"{type}\\" türü için \\"{name}\\" üyesi silinemiyor","memberSet":"\\"{type}\\" türü için \\"{name}\\" üyesi atanamıyor","metaclassConflict":"Türetilmiş sınıfın meta sınıfı, tüm temel sınıflarının meta sınıflarının bir alt sınıfı olmalıdır","metaclassDuplicate":"Yalnızca bir meta sınıfı sağlanmalıdır","metaclassIsGeneric":"Meta sınıfı genel olamaz","methodNotDefined":"\\"{name}\\" metodu tanımlanmadı","methodNotDefinedOnType":"\\"{name}\\" metodu \\"{type}\\" türü üzerinde tanımlanmadı","methodOrdering":"Tutarlı metot sıralaması oluşturulamıyor","methodOverridden":"\\"{name}\\", uyumsuz \\"{type}\\" türüne sahip \\"{className}\\" sınıfında aynı ad metodunu geçersiz kılar","methodReturnsNonObject":"\\"{name}\\" metodu bir nesne döndürmez","missingSuperCall":"\\"{methodName}\\" metodu üst sınıftaki aynı ada sahip metodu çağıramaz","moduleAsType":"Modül tür olarak kullanılamaz","moduleNotCallable":"Modül çağrılabilir değil","moduleUnknownMember":"\\"{memberName}\\", \\"{moduleName}\\" modülünün bilinen bir üyesi değil","namedExceptAfterCatchAll":"Adlandırılmış except yan tümcesi, catch-all except yan tümcesinden sonra gelemez","namedParamAfterParamSpecArgs":"\\"{name}\\" anahtar sözcük parametresi ParamSpec args parametresinden sonra imzada yer alamaz","namedTupleEmptyName":"Adlandırılmış demet içindeki adlar boş olamaz","namedTupleEntryRedeclared":"Üst sınıf \\"{name}\\" adlandırılmış bir demet olduğundan \\"{className}\\" geçersiz kılınamıyor","namedTupleFirstArg":"İlk bağımsız değişken olarak adlandırılmış demet sınıf adı bekleniyordu","namedTupleMultipleInheritance":"NamedTuple bulunan birden çok devralma desteklenmiyor","namedTupleNameKeyword":"Alan adları anahtar sözcük olamaz","namedTupleNameType":"Girdi adını ve türünü belirten iki girdili demet bekleniyordu","namedTupleNameUnique":"Adlandırılmış demet içindeki adlar benzersiz olmalıdır","namedTupleNoTypes":"\\"namedtuple\\" demet girdileri için tür sağlamaz; bunun yerine \\"NamedTuple\\" kullanın","namedTupleSecondArg":"İkinci bağımsız değişken olarak adlandırılmış demet girdi listesi bekleniyordu","newClsParam":"__new__ geçersiz kılması bir \\"cls\\" parametresi almalı","newTypeAnyOrUnknown":"NewType\'ın ikinci bağımsız değişkeni Any veya Unknown değil, bilinen bir sınıf olmalıdır","newTypeBadName":"NewType için ilk bağımsız değişken bir sabit değerli dize olmalıdır","newTypeLiteral":"NewType Literal türüyle kullanılamaz","newTypeNameMismatch":"NewType, aynı ada sahip bir değişkene atanmalıdır","newTypeNotAClass":"NewType için ikinci bağımsız değişken olarak sınıf bekleniyordu","newTypeParamCount":"NewType için iki konumsal bağımsız değişken gerekiyor","newTypeProtocolClass":"NewType yapısal türle (protokol veya TypedDict sınıfı) kullanılamaz","noOverload":"\\"{name}\\" için aşırı yüklemelerin hiçbiri sağlanan bağımsız değişkenlerle eşleşmiyor","noReturnContainsReturn":"Bildirilen dönüş türü \\"NoReturn\\" olan işlev bir return deyimi içeremez","noReturnContainsYield":"Bildirilen dönüş türü \\"NoReturn\\" olan işlev bir yield deyimi içeremez","noReturnReturnsNone":"Bildirilen \\"NoReturn\\" döndürme türüne sahip işlev \\"None\\" döndüremez","nonDefaultAfterDefault":"Varsayılan olmayan bağımsız değişken varsayılan bağımsız değişkeni izler","nonLocalInModule":"Modül düzeyinde yerel olmayan bildirim kullanılamaz","nonLocalNoBinding":"Yerel olmayan \\"{name}\\" öğesi için bağlama bulunamadı","nonLocalReassignment":"\\"{name}\\" yerel olmayan bildirimden önce atanmış","nonLocalRedefinition":"\\"{name}\\" zaten yerel olmayan olarak bildirildi","noneNotCallable":"\\"None\\" türündeki nesne çağrılamaz","noneNotIterable":"\\"None\\" türündeki nesne, yeniden kullanılabilir değer olarak kullanılamaz","noneNotSubscriptable":"\\"None\\" türündeki nesne alt simgeleştirilebilir değil","noneNotUsableWith":"\\"None\\" türündeki nesne \\"with\\" ile kullanılamaz","noneOperator":"\\"{operator}\\" işleci \\"None\\" için desteklenmiyor","noneUnknownMember":"\\"{name}\\" bilinen bir \\"None\\" üyesi değil","notRequiredArgCount":"\\"NotRequired\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","notRequiredNotInTypedDict":"Bu bağlamda \\"NotRequired\\" kullanımına izin verilmiyor","objectNotCallable":"\\"{type}\\" türündeki nesne çağrılamaz","obscuredClassDeclaration":"\\"{name}\\" sınıf bildirimi aynı ada sahip bir bildirim tarafından gizlendi","obscuredFunctionDeclaration":"\\"{name}\\" işlev bildirimi aynı ada sahip bir bildirim tarafından gizlendi","obscuredMethodDeclaration":"\\"{name}\\" metot bildirimi aynı ada sahip bir bildirim tarafından gizlendi","obscuredParameterDeclaration":"\\"{name}\\" parametre bildirimi aynı ada sahip bir bildirim tarafından gizlendi","obscuredTypeAliasDeclaration":"\\"{name}\\" tür diğer ad bildirimi aynı ada sahip bir bildirim tarafından etkisiz kılındı","obscuredVariableDeclaration":"\\"{name}\\" bildirimi aynı ada sahip bir bildirim tarafından gizlendi","operatorLessOrGreaterDeprecated":"\\"<>\\" işleci Python 3\'de desteklenmiyor; bunun yerine \\"!=\\" kullanın","optionalExtraArgs":"\\"optional\\" sonrasında bir tür bağımsız değişkeni bekleniyordu","orPatternIrrefutable":"Reddedilemez desene yalnızca \\"or\\" deseninde son alt desen olarak izin verilir","orPatternMissingName":"Bir \\"or\\" deseni içindeki tüm alt desenlerde aynı adlar hedeflenmeli","overlappingKeywordArgs":"Türü belirlenmiş sözlük anahtar sözcük parametresiyle çakışıyor: {names}","overlappingOverload":"Parametreleri {obscuredBy} aşırı yüklemesi ile çakıştığından \\"{name}\\" {obscured} aşırı yüklemesi hiçbir zaman kullanılmayacak","overloadAbstractMismatch":"Aşırı yüklenmiş metotların tümü soyut olmalı veya tümü olmamalıdır","overloadClassMethodInconsistent":"\\"{name}\\" için aşırı yüklemeler, @classmethod yöntemini tutarlı kullanıyor","overloadFinalInconsistencyImpl":"\\"{name}\\" için aşırı yükleme @final olarak işaretlendi ancak uygulama işaretlenmedi","overloadFinalInconsistencyNoImpl":"\\"{name}\\" için aşırı yükleme {index} @final olarak işaretlendi ancak aşırı yükleme 1 işaretlenmedi","overloadImplementationMismatch":"Aşırı yüklenmiş uygulama, {index} aşırı yükleme imzası ile tutarlı değil","overloadReturnTypeMismatch":"\\"{name}\\" için {prevIndex} aşırı yüklemesi {newIndex} aşırı yüklemesi ile çakışıyor ve uyumsuz bir tür döndürüyor","overloadStaticMethodInconsistent":"\\"{name}\\" için aşırı yüklemeler, @staticmethod yöntemini tutarsız kullanıyor","overloadWithoutImplementation":"\\"{name}\\" aşırı yük olarak işaretlendi, ancak uygulama sağlanmadı","overriddenMethodNotFound":"\\"{name}\\" metodu geçersiz kılma olarak işaretlendi, ancak aynı ada sahip bir temel metot yok","overrideDecoratorMissing":"\\"{name}\\" metodu geçersiz kılma olarak işaretlenmedi ancak \\"{className}\\" sınıfındaki bir metodu geçersiz kılıyor","paramAfterKwargsParam":"Parametre \\"**\\" parametresini izleyemez","paramAlreadyAssigned":"\\"{name}\\" parametresi zaten atanmış","paramAnnotationMissing":"\\"{name}\\" parametresi için tür ek açıklaması eksik","paramAssignmentMismatch":"\\"{sourceType}\\" türündeki ifade, \\"{paramType}\\" türündeki parametreye atanamaz","paramNameMissing":"\\"{name}\\" adlı parametre yok","paramSpecArgsKwargsUsage":"ParamSpec\'in \\"args\\" ve \\"kwargs\\" üyeleri bir işlev imzasında görünmelidir","paramSpecArgsMissing":"ParamSpec \\"{type}\\" bağımsız değişkenleri eksik","paramSpecArgsUsage":"ParamSpec\'in \\"args\\" üyesi yalnızca *args parametresiyle kullanıldığında geçerlidir","paramSpecAssignedName":"ParamSpec, \\"{name}\\" adlı bir değişkene atanmalı","paramSpecContext":"ParamSpec bu bağlamda kullanılamaz","paramSpecDefaultNotTuple":"ParamSpec varsayılan değeri için üç nokta, demet ifadesi veya ParamSpec bekleniyordu","paramSpecFirstArg":"İlk bağımsız değişken olarak ParamSpec adı bekleniyordu","paramSpecKwargsUsage":"ParamSpec\'in \\"kwargs\\" üyesi yalnızca *kwargs parametresiyle kullanıldığında geçerlidir","paramSpecNotUsedByOuterScope":"\\"{name}\\" adlı ParamSpec bu bağlamda bir anlam ifade etmiyor","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" dönüş türü içinde çağrılabilir kapsamına alındı ve işlev gövdesinde başvurulamaz","paramSpecUnknownArg":"ParamSpec birden fazla bağımsız değişkeni desteklemiyor","paramSpecUnknownMember":"\\"{name}\\", ParamSpec’ın bilinen bir üyesi değil","paramSpecUnknownParam":"\\"{name}\\", ParamSpec için bilinmeyen bir parametre","paramTypeCovariant":"Kovaryant türü değişkeni parametre türünde kullanılamaz","paramTypePartiallyUnknown":"\\"{paramName}\\" parametresinin türü kısmen bilinmiyor","paramTypeUnknown":"\\"{paramName}\\" parametresinin türü bilinmiyor","parenthesizedContextManagerIllegal":"\\"with\\" deyimindeki parantezler Python 3.9 veya daha yeni bir sürüm gerektirir","patternNeverMatches":"Desen, \\"{type}\\" konu türü ile hiçbir zaman eşleşmez","positionArgAfterNamedArg":"Konumsal bağımsız değişken anahtar sözcük bağımsız değişkenlerden sonra gelemez","positionOnlyAfterArgs":"\\"*\\" parametresinden sonra yalnızca konum parametre ayırıcısı kullanılamaz","positionOnlyAfterKeywordOnly":"\\"/\\" parametresi \\"*\\" parametresinden önce gelmelidir","positionOnlyAfterNon":"Yalnızca konum parametresi olmayan parametreden sonra yalnızca konum parametresine izin verilmez","positionOnlyFirstParam":"Yalnızca konum parametre ayırıcısı ilk parametre olarak kullanılamaz","positionOnlyIncompatible":"Yalnızca konum parametre ayırıcısı için Python 3.8 veya daha yeni bir sürümü gerekiyor","privateImportFromPyTypedModule":"\\"{name}\\" \\"{module}\\" modülünden dışarı aktarılamadı","privateUsedOutsideOfClass":"\\"{name}\\" özeldir ve bildirildiği sınıfın dışında kullanılır","privateUsedOutsideOfModule":"\\"{name}\\" özeldir ve bildirildiği modülün dışında kullanılır","propertyOverridden":"\\"{name}\\", \\"{className}\\" sınıfında aynı ad özelliğini geçersiz kılar","propertyStaticMethod":"Static metotlar özellik alıcı, ayarlayıcı veya silici için kullanılamaz","protectedUsedOutsideOfClass":"\\"{name}\\" korumalıdır ve içinde bildirildiği sınıfın dışında kullanılır","protocolBaseClass":"Protokol sınıfı \\"{classType}\\", protokol olmayan \\"{baseType}\\" sınıfı türevi olamaz","protocolBaseClassWithTypeArgs":"Tür parametresi söz dizimi kullanılırken, tür bağımsız değişkenlerinin Protokol sınıfıyla kullanılmasına izin verilmez","protocolIllegal":"\\"Protocol\\" kullanımı için Python 3.7 veya daha yeni bir sürümü gerekiyor","protocolNotAllowed":"\\"Protokol\\" bu bağlamda kullanılamaz","protocolUnsafeOverlap":"Sınıf, \\"{name}\\" ile güvenli olmayan bir şekilde çakışıyor ve çalışma zamanında bir eşleşme üretebilir","protocolVarianceContravariant":"\\"{class}\\" genel protokolünde kullanılan \\"{variable}\\" tür değişkeni, değişken karşıtı olmalıdır","protocolVarianceCovariant":"\\"{class}\\" genel protokolünde kullanılan \\"{variable}\\" tür değişkeni birlikte değişen olmalıdır","protocolVarianceInvariant":"\\"{class}\\" genel protokolünde kullanılan \\"{variable}\\" tür değişkeni sabit olmalıdır","pyrightCommentInvalidDiagnosticBoolValue":"Pyright açıklama yönergesinden sonra \\"=\\" ve true veya false değeri olmalıdır","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright açıklama yönergesinden sonra \\"=\\" ve true, false, error, warning, information veya none değeri girilmelidir","pyrightCommentMissingDirective":"Pyright açıklaması sonrasında bir yönerge (temel veya katı) veya tanılama kuralı gelmelidir","pyrightCommentNotOnOwnLine":"Dosya düzeyi ayarları kontrol etmek için kullanılan pyright açıklamaları kendi satırlarında görünmelidir","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\", pyright açıklaması için bilinmeyen bir tanılama kuralı","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" pyright açıklaması için geçersiz değer; true, false, error, warning, information veya none bekleniyordu","pyrightCommentUnknownDirective":"\\"{directive}\\", pyright açıklaması için bilinmeyen bir yönergedir; \\"strict\\" veya \\"basic\\" bekleniyordu","readOnlyArgCount":"\\"ReadOnly\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","readOnlyNotInTypedDict":"Bu bağlamda \\"ReadOnly\\" kullanımına izin verilmiyor","recursiveDefinition":"Kendine başvurduğundan \\"{name}\\" türü belirlenemedi","relativeImportNotAllowed":"Göreli içeri aktarmalar \\"import .a\\" formuyla kullanılamaz; bunun yerine \\"from . import a\\" kullanın","requiredArgCount":"\\"Required\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","requiredNotInTypedDict":"Bu bağlamda \\"Required\\" kullanımına izin verilmiyor","returnInAsyncGenerator":"Zaman uyumsuz oluşturucuda değer içeren dönüş deyimine izin verilmez","returnMissing":"Bildirilen \\"{returnType}\\" döndürme türüne sahip işlev, tüm kod yollarında değer döndürmelidir","returnOutsideFunction":"\\"return\\" yalnızca bir işlev içinde kullanılabilir","returnTypeContravariant":"Değişken karşıtı tür değişkeni dönüş türünde kullanılamaz","returnTypeMismatch":"\\"{exprType}\\" türündeki ifade \\"{returnType}\\" dönüş türüne atanamaz","returnTypePartiallyUnknown":"\\"{returnType}\\" dönüş türü kısmen bilinmiyor","returnTypeUnknown":"Dönüş türü bilinmiyor","revealLocalsArgs":"\\"reveal_locals\\" çağrısı için bağımsız değişken beklenmiyordu","revealLocalsNone":"Bu kapsamda yerel öğe yok","revealTypeArgs":"\\"reveal_type\\" çağrısı için tek bir konumsal bağımsız değişken bekleniyordu","revealTypeExpectedTextArg":"\\"reveal_type\\" bağımsız değişkeni için \\"expected_text\\" argümanı bir str sabit değeri olmalıdır","revealTypeExpectedTextMismatch":"Tür uyuşmazlığı; \\"{expected}\\" bekleniyordu ancak \\"{received}\\" alındı","revealTypeExpectedTypeMismatch":"Tür uyuşmazlığı; \\"{expected}\\" bekleniyordu ancak \\"{received}\\" alındı","selfTypeContext":"\\"Self\\" bu bağlamda geçerli değil","selfTypeMetaclass":"\\"Self\\" bir meta sınıfı (\\"type\\" alt sınıfı) içinde kullanılamaz","selfTypeWithTypedSelfOrCls":"\\"Self\\", \\"Self\\" dışında bir tür ek açıklamasına sahip bir `self` veya `cls` parametresine sahip bir işlevde kullanılamaz","setterGetterTypeMismatch":"Özellik ayarlayıcısı değer türü alıcı dönüş türüne atanamaz","singleOverload":"\\"{name}\\" aşırı yükleme olarak işaretlenmiş, ancak ek aşırı yüklemeler eksik","slotsAttributeError":"\\"{name}\\", __slots__ içinde belirtilmedi","slotsClassVarConflict":"\\"{name}\\", __slots__ içinde bildirilen örnek değişkenle çakışıyor","starPatternInAsPattern":"Yıldız deseni \\"as\\" hedefiyle kullanılamaz","starPatternInOrPattern":"Yıldız deseni diğer desenlerde ORed olamaz","starStarWildcardNotAllowed":"\\"_\\" joker karakteriyle ** kullanılamaz","staticClsSelfParam":"Static metotları \\"self\\" veya \\"cls\\" parametresi almamalıdır","stdlibModuleOverridden":"\\"{path}\\", \\"{name}\\" stdlib modülünü geçersiz kılıyor","stringNonAsciiBytes":"ASCII olmayan karaktere bayt sabit değerli dizesinde izin verilmez","stringNotSubscriptable":"Tür ek açıklamasında dize ifadesi alt simge olarak belirtilemez; ek açıklamanın tamamını tırnak içine alın","stringUnsupportedEscape":"Dize sabit değerinde desteklenmeyen kaçış dizisi","stringUnterminated":"Sabit değerli dize sonlandırılmamış","stubFileMissing":"\\"{importName}\\" için saplama dosyası bulunamadı","stubUsesGetAttr":"Tür saplama dosyası eksik; \\"__getattr__\\" modül için tür hatalarını gizliyor","sublistParamsIncompatible":"Alt liste parametreleri Python 3.x\'te desteklenmez","superCallArgCount":"\\"super\\" çağrısı için ikiden fazla bağımsız değişken beklenmiyordu","superCallFirstArg":"\\"super\\" çağrısının ilk bağımsız değişkeni olarak sınıf türü bekleniyordu ancak \\"{type}\\" alındı","superCallSecondArg":"\\"super\\" çağrısının ikinci bağımsız değişkeni, \\"{type}\\" türünden türetilen nesne veya sınıf olmalıdır","superCallZeroArgForm":"\\"super\\" çağrısının zero-argument biçimi yalnızca bir metot içinde geçerlidir","superCallZeroArgFormStaticMethod":"\\"super\\" çağrısının zero-argument biçimi statik bir metot içinde geçerli değildir","symbolIsPossiblyUnbound":"\\"{name}\\" büyük olasılıkla bağlı değil","symbolIsUnbound":"\\"{name}\\" bağlı değil","symbolIsUndefined":"\\"{name}\\" tanımlanmadı","symbolOverridden":"\\"{name}\\", \\"{className}\\" sınıfında aynı ada sahip sembolü geçersiz kılar","ternaryNotAllowed":"Tür ek açıklamasında üçlü ifade kullanılamaz","totalOrderingMissingMethod":"total_ordering kullanmak için sınıfta \\"__lt__\\", \\"__le__\\", \\"__gt__\\" veya \\"__ge__\\" metotlarından biri tanımlanmalıdır","trailingCommaInFromImport":"Çevreleyen parantezler olmadan sondaki virgüle izin verilmez","tryWithoutExcept":"Try deyimi en az bir except veya finally yan tümcesi içermelidir","tupleAssignmentMismatch":"\\"{type}\\" türündeki ifade hedef demetine atanamaz","tupleInAnnotation":"Tür ek açıklamasında demet ifadesine izin verilmiyor","tupleIndexOutOfRange":"{index} dizini {type} türü için aralık dışında","typeAliasIllegalExpressionForm":"Tür diğer ad tanımı için geçersiz ifade form","typeAliasIsRecursiveDirect":"Tür diğer adı \\"{name}\\", tanımında kendisini kullanamaz","typeAliasNotInModuleOrClass":"TypeAlias yalnızca bir modül veya sınıf kapsamında tanımlanabilir","typeAliasRedeclared":"\\"{name}\\" bir TypeAlias olarak bildirilmiş ve yalnızca bir kez atanabilir","typeAliasStatementBadScope":"Tür deyimi, yalnızca bir modül veya sınıf kapsamında kullanılabilir","typeAliasStatementIllegal":"Tür diğer adı deyimi için Python 3.12 veya daha yeni bir sürümü gerekiyor","typeAliasTypeBaseClass":"Bir “type” deyiminde tanımlanan tür diğer adı temel sınıf olarak kullanılamaz","typeAliasTypeMustBeAssigned":"TypeAliasType, tür diğer adıyla aynı ada sahip bir değişkene atanmalıdır","typeAliasTypeNameArg":"TypeAliasType için ilk bağımsız değişken, tür diğer adının adını temsil eden bir sabit değerli dize olmalıdır","typeAliasTypeNameMismatch":"Tür diğer adının atandığı değişkenin adıyla eşleşmesi gerekiyor","typeAliasTypeParamInvalid":"Tür parametresi listesi yalnızca TypeVar, TypeVarTuple veya ParamSpec içeren bir demet olmalıdır","typeAnnotationCall":"Tür ifadesinde çağrı ifadesine izin verilmiyor","typeAnnotationVariable":"Tür ifadesinde değişkene izin verilmiyor","typeAnnotationWithCallable":"“Tür” için tür bağımsız değişkeni bir sınıf olmalıdır; çağrılabilir öğeler desteklenmiyor","typeArgListExpected":"ParamSpec, üç nokta veya tür listesi bekleniyordu","typeArgListNotAllowed":"Bu tür bağımsız değişkeni için liste ifadesine izin verilmiyor","typeArgsExpectingNone":"\\"{name}\\" sınıfı için tür bağımsız değişkeni beklenmiyordu","typeArgsMismatchOne":"Bir tane tür bağımsız değişkeni bekleniyordu ancak {received} alındı","typeArgsMissingForAlias":"\\"{name}\\" genel tür diğer adı için tür bağımsız değişkenleri bekleniyordu","typeArgsMissingForClass":"\\"{name}\\" genel sınıf adı için tür bağımsız değişkenleri bekleniyordu","typeArgsTooFew":"\\"{name}\\" için çok az tür bağımsız değişkeni sağlandı; {expected} bekleniyordu ancak {received} alındı","typeArgsTooMany":"\\"{name}\\" için çok fazla tür bağımsız değişkeni sağlandı; {expected} bekleniyordu ancak {received} alındı","typeAssignmentMismatch":"\\"{sourceType}\\" türündeki ifade, \\"{destType}\\" bildirilen türüne atanamaz","typeAssignmentMismatchWildcard":"\\"{name}\\" içeri aktarma sembolü \\"{sourceType}\\" türüne sahip ve bu tür, \\"{destType}\\" bildirilen türüne atanamaz","typeCallNotAllowed":"Tür ek açıklamasında type() çağrısı kullanılmamalıdır","typeCheckOnly":"\\"{name}\\", @type_check_only olarak işaretlendi ve yalnızca tür ek açıklamalarında kullanılabilir","typeCommentDeprecated":"Tür açıklamalarının kullanımı kullanım dışı; bunun yerine tür ek açıklaması kullanın","typeExpectedClass":"Tür ifadesi bekleniyordu ancak \\"{type}\\" alındı","typeGuardArgCount":"\\"TypeGuard\\" veya \\"Typels\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","typeGuardParamCount":"Kullanıcı tanımlı tür koruma işlevleri ve metotlarında en az bir giriş parametresi olmalıdır","typeIsReturnType":"TypeIs dönüş türü (\\"{returnType}\\"), değer parametresi türü (\\"{type}\\") ile tutarlı değil","typeNotAwaitable":"\\"{type}\\" beklenemez","typeNotIntantiable":"\\"{type}\\" örneği oluşturulamıyor","typeNotIterable":"\\"{type}\\" yeniden kullanılamaz","typeNotSpecializable":"\\"{type}\\" türü özelleştirilemedi","typeNotSubscriptable":"\\"{type}\\" türündeki nesne alt simgeleştirilebilir değil","typeNotSupportBinaryOperator":"İşleç \\"{operator}\\", \\"{leftType}\\" ve \\"{rightType}\\" türleri için desteklenmiyor","typeNotSupportBinaryOperatorBidirectional":"\\"{operator}\\" işleci, beklenen tür \\"{expectedType}\\" olduğunda \\"{leftType}\\" ve \\"{rightType}\\" türleri için desteklenmez","typeNotSupportUnaryOperator":"\\"{operator}\\" işleci \\"{type}\\" türü için desteklenmiyor","typeNotSupportUnaryOperatorBidirectional":"\\"{operator}\\" işleci, beklenen tür \\"{expectedType}\\" olduğunda \\"{type}\\" türü için desteklenmiyor","typeNotUsableWith":"{method} metodunu uygulamadığından \\"{type}\\" türündeki nesne \\"with\\" ile kullanılamaz","typeParameterBoundNotAllowed":"Sınır veya kısıtlama, değişen tür parametresi veya ParamSpec ile kullanılamaz","typeParameterConstraintTuple":"Tür parametresi kısıtlaması iki veya daha fazla türde bir demet olmalıdır","typeParameterExistingTypeParameter":"\\"{name}\\" tür parametresi zaten kullanılıyor","typeParameterNotDeclared":"\\"{name}\\" tür parametresi \\"{container}\\" öğesine ait tür parametreleri listesinde yok","typeParametersMissing":"En az bir tür parametresi belirtilmelidir","typePartiallyUnknown":"\\"{name}\\" türü kısmen bilinmiyor","typeUnknown":"\\"{name}\\" türü bilinmiyor","typeVarAssignedName":"TypeVar, \\"{name}\\" adlı bir değişkene atanmalı","typeVarAssignmentMismatch":"\\"{type}\\" türü \\"{name}\\" tür değişkenine atanamaz","typeVarBoundAndConstrained":"TypeVar hem bağlı hem de kısıtlanmış olamaz","typeVarBoundGeneric":"TypeVar bağlı türü genel olamaz","typeVarConstraintGeneric":"TypeVar kısıtlama türü genel olamaz","typeVarDefaultBoundMismatch":"TypeVar varsayılan türü, bağlı türün bir alt türü olmalıdır","typeVarDefaultConstraintMismatch":"TypeVar varsayılan türü kısıtlanmış türlerden biri olmalıdır","typeVarDefaultIllegal":"Tür değişkeni varsayılan türleri Python 3.13 veya daha yeni bir sürüm gerektirir","typeVarDefaultInvalidTypeVar":"\\"{name}\\" tür parametresi, kapsam dışı bir veya daha fazla tür değişkenine başvuran varsayılan bir türe sahip","typeVarFirstArg":"İlk bağımsız değişken olarak TypeVar adı bekleniyordu","typeVarNoMember":"TypeVar \\"{type}\\" \\"{name}\\" adlı üyesine sahip değil","typeVarNotSubscriptable":"TypeVar \\"{type}\\" alt yazılabilir değil","typeVarNotUsedByOuterScope":"\\"{name}\\" tür değişkeni bu bağlamda bir anlam ifade etmiyor","typeVarPossiblyUnsolvable":"\\"{name}\\" tür değişkeni, çağıran \\"{param}\\" parametresi için bağımsız değişken sağlamazsa çözümlenemeyebilir","typeVarScopedToReturnType":"\\"{name}\\" tür değişkeni, dönüş türü içinde çağrılabilir kapsamına alındı ve işlev gövdesinde başvurulamaz","typeVarSingleConstraint":"TypeVar en az iki kısıtlanmış türe sahip olmalıdır","typeVarTupleConstraints":"TypeVarTuple değer kısıtlamalarına sahip olamaz","typeVarTupleContext":"TypeVarTuple bu bağlamda kullanılamaz","typeVarTupleDefaultNotUnpacked":"TypeVarTuple varsayılan türü, paketlenmemiş bir demet veya TypeVarTuple olmalıdır","typeVarTupleMustBeUnpacked":"TypeVarTuple değeri için Paket açma işleci gereklidir","typeVarTupleUnknownParam":"\\"{name}\\", TypeVar için bilinmeyen bir parametre","typeVarUnknownParam":"\\"{name}\\", TypeVar için bilinmeyen bir parametre","typeVarUsedByOuterScope":"TypeVar \\"{name}\\" zaten bir dış kapsam tarafından kullanılıyor","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" genel işlev imzasında yalnızca bir kez görünür","typeVarVariance":"TypeVar hem birlikte değişken hem de değişken karşıtı olamaz","typeVarWithDefaultFollowsVariadic":"\\"{typeVarName}\\" TypeVar alanı bir varsayılan değer içerir ve \\"{variadicName}\\" TypeVarTuple alanına uyamaz","typeVarWithoutDefault":"\\"{name}\\" varsayılan türe sahip olmadığından tür parametresi listesinde \\"{other}\\" sonrasında bulunamaz","typeVarsNotInGenericOrProtocol":"Generic[] veya Protocol[] tüm tür değişkenlerini içermeli","typedDictAccess":"TypedDict\'da öğeye erişilemedi","typedDictAssignedName":"TypedDict, \\"{name}\\" adlı bir değişkene atanmalı","typedDictBadVar":"TypedDict sınıfları yalnızca tür ek açıklamaları içerebilir","typedDictBaseClass":"TypedDict sınıfları için tüm temel sınıflar da TypedDict sınıfları olmalıdır","typedDictBoolParam":"True veya False değeri olması için \\"{name}\\" parametresi bekleniyordu","typedDictClosedExtras":"\\"{name}\\" temel sınıfı kapalı bir TypedDict öğesidir; ek öğeler \\"{type}\\" türünde olmalıdır","typedDictClosedNoExtras":"\\"{name}\\" temel sınıfı kapalı bir TypedDict öğesidir; ek öğelere izin verilmiyor","typedDictDelete":"TypedDict\'da öğe silinemedi","typedDictEmptyName":"TypedDict içindeki adlar boş olamaz","typedDictEntryName":"Sözlük girdisi adı için sabit değerli dize bekleniyordu","typedDictEntryUnique":"Sözlük içindeki adlar benzersiz olmalıdır","typedDictExtraArgs":"Ekstra TypedDict bağımsız değişkenleri desteklenmiyor","typedDictFieldNotRequiredRedefinition":"\\"{name}\\" TypedDict öğesi NotRequired olarak yeniden tanımlanamaz","typedDictFieldReadOnlyRedefinition":"\\"{name}\\" TypedDict öğesi ReadOnly olarak yeniden tanımlanamaz","typedDictFieldRequiredRedefinition":"\\"{name}\\" TypedDict öğesi Required olarak yeniden tanımlanamaz","typedDictFirstArg":"Birinci bağımsız değişken olarak TypedDict sınıf adı bekleniyordu","typedDictInitsubclassParameter":"TypedDict, \\"{name}\\" __init_subclass__ parametresini desteklemez","typedDictNotAllowed":"\\"TypedDict\\" bu bağlamda kullanılamaz","typedDictSecondArgDict":"İkinci parametre olarak sözlük veya anahtar sözcük parametresi bekleniyordu","typedDictSecondArgDictEntry":"Basit sözlük girişi bekleniyordu","typedDictSet":"TypedDict içinde öğe atanamadı","unaccessedClass":"\\"{name}\\" sınıfına erişilemiyor","unaccessedFunction":"\\"{name}\\" işlevine erişilemiyor","unaccessedImport":"\\"{name}\\" içeri aktarma işlemine erişilemiyor","unaccessedSymbol":"\\"{name}\\" öğesine erişilemiyor","unaccessedVariable":"\\"{name}\\" değişkenine erişilemiyor","unannotatedFunctionSkipped":"\\"{name}\\" işlevinin analizi, açıklanmadığından atlandı","unaryOperationNotAllowed":"Tür ek açıklamasında birli işleç kullanılamaz","unexpectedAsyncToken":"\\"async\\" öğesinin ardından \\"def\\", \\"with\\" veya \\"for\\" bekleniyordu","unexpectedExprToken":"İfadenin sonunda beklenmeyen belirteç","unexpectedIndent":"Beklenmeyen girinti","unexpectedUnindent":"Girintiyi kaldırma beklenmiyordu","unhashableDictKey":"Sözlük anahtarı karmalanabilir olmalıdır","unhashableSetEntry":"Küme girdisi karmalanabilir olmalıdır","uninitializedAbstractVariables":"Soyut temel sınıfta tanımlanan değişkenler \\"{classType}\\" final sınıfında başlatılmaz","uninitializedInstanceVariable":"\\"{name}\\" örnek değişkeni sınıf gövdesinde veya __init__ metodunda başlatılmadı","unionForwardReferenceNotAllowed":"Union söz dizimi dize işleneni ile kullanılamaz; ifadenin tamamını tırnak içine alın","unionSyntaxIllegal":"Union işlemlerinde alternatif söz dizimi kullanılabilmesi için Python 3.10 veya daha yeni bir sürümü gerekiyor","unionTypeArgCount":"Union için iki veya daha fazla tür bağımsız değişkeni gerekiyor","unionUnpackedTuple":"Birleşim, paketlenmemiş bir demet içeremez","unionUnpackedTypeVarTuple":"Birleşim, paketlenmemiş bir TypeVarTuple içeremez","unnecessaryCast":"Gereksiz \\"cast\\" çağrısı; tür zaten \\"{type}\\"","unnecessaryIsInstanceAlways":"Gereksiz isinstance çağrısı; \\"{testType}\\" her zaman bir \\"{classType}\\" örneğidir","unnecessaryIsSubclassAlways":"Gereksiz issubclass çağrısı; \\"{testType}\\" her zaman \\"{classType}\\" sınıf türünün bir alt sınıfıdır","unnecessaryPyrightIgnore":"Gereksiz \\"# pyright: ignore\\" açıklaması","unnecessaryPyrightIgnoreRule":"\\"# pyright: ignore\\" rule: \\"{name}\\" gereksiz","unnecessaryTypeIgnore":"Gereksiz \\"# type: yoksay\\" açıklaması","unpackArgCount":"\\"Unpack\\" sonrasında tek bir tür bağımsız değişken bekleniyordu","unpackExpectedTypeVarTuple":"Unpack için tür bağımsız değişkeni olarak TypeVarTuple veya tuple bekleniyordu","unpackExpectedTypedDict":"Unpack için TypedDict tür bağımsız değişkeni bekleniyordu","unpackIllegalInComprehension":"Anlamada paket açma işlemi kullanılamaz","unpackInAnnotation":"Tür ek açıklamasında paket açma işlecine izin verilmiyor","unpackInDict":"Sözlüklerde paket açma işlemi kullanılamaz","unpackInSet":"Paket açma işlecine küme içinde izin verilmiyor","unpackNotAllowed":"Bu bağlamda paketi açma işlemine izin verilmiyor","unpackOperatorNotAllowed":"Bu bağlamda paket açma işlemi kullanılamaz","unpackTuplesIllegal":"Python 3.8\'den önceki demetler içinde paket açma işlemi kullanılamıyor","unpackedArgInTypeArgument":"Paketlenmemiş bağımsız değişkenler tür bağımsız değişkeni listelerinde kullanılamaz","unpackedArgWithVariadicParam":"Paketlenmemiş bağımsız değişken, TypeVarTuple parametresi için kullanılamaz","unpackedDictArgumentNotMapping":"** sonrasındaki bağımsız değişken ifadesi \\"str\\" anahtar türüne sahip bir eşleme olmalıdır","unpackedDictSubscriptIllegal":"Alt simgede sözlük açma işlecine izin verilmiyor","unpackedSubscriptIllegal":"Alt simgede açma işleci için Python 3.11 veya daha yeni bir sürümü gerekiyor","unpackedTypeVarTupleExpected":"Paketlenmemiş TypeVarTuple bekleniyordu; Unpack[{name1}] veya *{name2} kullanın","unpackedTypedDictArgument":"Paketlenmemiş TypedDict bağımsız değişkeni parametrelerle eşlenemiyor","unreachableCode":"Koda ulaşılamıyor","unreachableExcept":"Özel durum zaten işlenmiş olduğundan özel durum yan tümcesi erişilebilir değil","unsupportedDunderAllOperation":"\\"__all__\\" üzerinde işlem desteklenmiyor, bu nedenle dışarı aktarılan sembol listesi yanlış olabilir","unusedCallResult":"Çağrı ifadesinin sonucu \\"{type}\\" türünde ve kullanılmıyor; bilerek yapıldıysa \\"_\\" değişkenine atayın","unusedCoroutine":"Zaman uyumsuz işlev çağrısının sonucu kullanılmıyor; \\"await\\" kullanın veya sonucu değişkene atayın","unusedExpression":"İfade değeri kullanılmadı","varAnnotationIllegal":"Değişkenler için tür ek açıklamaları Python 3.6 veya daha yeni bir sürümünü gerektiriyor; önceki sürümlerle uyumluluk için tür açıklaması kullanın","variableFinalOverride":"\\"{name}\\" değişkeni Final olarak işaretlendi ve \\"{className}\\" sınıfı içinde aynı ada sahip Final olmayan değişkeni geçersiz kılıyor","variadicTypeArgsTooMany":"Tür bağımsız değişkeni listesinde en fazla bir paketlenmemiş TypeVarTuple veya tuple olabilir","variadicTypeParamTooManyAlias":"Tür diğer adı en fazla bir TypeVarTuple tür parametresine sahip olabilir ancak birden fazlası {names}) alındı","variadicTypeParamTooManyClass":"Genel sınıf en fazla bir TypeVarTuple tür parametresine sahip olabilir ancak birden fazlası {names}) alındı","walrusIllegal":"\\":=\\" işleci için Python 3.8 veya daha yeni bir sürümü gerekiyor","walrusNotAllowed":"Çevreleyen parantezler olmadan bu bağlamda \\":=\\" işlecine izin verilmiyor","wildcardInFunction":"Bir sınıf veya işlev içinde joker karakteri içeri aktarmaya izin verilmiyor","wildcardLibraryImport":"Kitaplıktan joker karakter aktarmaya izin verilmiyor","wildcardPatternTypePartiallyUnknown":"Joker karakter deseni tarafından yakalanan tür kısmen bilinmiyor","wildcardPatternTypeUnknown":"Joker karakter deseni tarafından yakalanan tür bilinmiyor","yieldFromIllegal":"\\"yield from\\" kullanımı için Python 3.3 veya daha yeni bir sürümü gerekiyor","yieldFromOutsideAsync":"Zaman uyumsuz bir işlevde \\"yield from\\" öğesine izin verilmez","yieldOutsideFunction":"\\"yield\\", işlev veya lambda dışında kullanılamaz","yieldWithinListCompr":"Liste anlama içinde \\"yield\\" kullanılamaz","zeroCaseStatementsFound":"Match deyimi en az bir case deyimi içermeli","zeroLengthTupleNotAllowed":"Bu bağlamda sıfır uzunluklu demete izin verilmiyor"},"DiagnosticAddendum":{"annotatedNotAllowed":"“Not eklenmiş” özel biçimi, örnek ve sınıf denetimleriyle kullanılamaz","argParam":"Bağımsız değişken \\"{paramName}\\" parametresine karşılık gelir","argParamFunction":"Bağımsız değişken, \\"{functionName}\\" işlevinde \\"{paramName}\\" parametresine karşılık gelir","argsParamMissing":"\\"*{paramName}\\" parametresine karşılık gelen bir parametre yok","argsPositionOnly":"Yalnızca konum parametresi uyuşmazlığı; {expected} bekleniyordu ancak {received} alındı","argumentType":"Bağımsız değişken türü \\"{type}\\"","argumentTypes":"Bağımsız değişken türleri: ({types})","assignToNone":"\\"None\\" türüne tür atanamaz","asyncHelp":"\\"async with\\" mi demek istediniz?","baseClassIncompatible":"\\"{baseClass}\\" temel sınıfı \\"{type}\\" türüyle uyumlu değil","baseClassIncompatibleSubclass":"\\"{baseClass}\\" temel sınıfı, \\"{type}\\" türüyle uyumlu olmayan \\"{subclass}\\" alt sınıfından türetiliyor","baseClassOverriddenType":"\\"{baseClass}\\" temel sınıfı geçersiz kılınan \\"{type}\\" türünü sağlar","baseClassOverridesType":"Temel sınıf \\"{baseClass}\\", \\"{type}\\" türünü geçersiz kılıyor","bytesTypePromotions":"“bytearray” ve “memoryview” için tür yükseltme davranışını etkinleştirmek için disableBytesTypePromotions seçeneğini “false” olarak ayarlayın","conditionalRequiresBool":"\\"{operandType}\\" türü için __bool__ metodu \\"bool\\" yerine \\"{boolReturnType}\\" türü döndürür","dataClassFieldLocation":"Alan bildirimi","dataClassFrozen":"\\"{name}\\" donduruldu","dataProtocolUnsupported":"\\"{name}\\" bir veri protokolü","descriptorAccessBindingFailed":"Tanımlayıcı sınıf \\"{className}\\" için \\"{name}\\" yöntemi bağlanamadı","descriptorAccessCallFailed":"Tanımlayıcı sınıf \\"{className}\\" için \\"{name}\\" yöntemi çağrılamadı","finalMethod":"Final metodu","functionParamDefaultMissing":"\\"{name}\\" parametresinde varsayılan bağımsız değişken eksik","functionParamName":"Parametre adı uyuşmazlığı: \\"{destName}\\" ve \\"{srcName}\\"","functionParamPositionOnly":"Yalnızca konum parametresi uyuşmazlığı; \\"{name}\\" parametresi yalnızca konum değil","functionReturnTypeMismatch":"\\"{sourceType}\\" işlev dönüş türü, \\"{destType}\\" türüyle uyumsuz","functionTooFewParams":"İşlev çok az konumsal parametre kabul ediyor; {expected} bekleniyordu ancak {received} alındı","functionTooManyParams":"İşlev çok fazla konumsal parametre kabul ediyor; {expected} bekleniyordu ancak {received} alındı","genericClassNotAllowed":"Örnek veya sınıf denetimleri için tür bağımsız değişkenlerine sahip genel türe izin verilmiyor","incompatibleDeleter":"Özellik silici metodu uyumsuz","incompatibleGetter":"Özellik alıcısı metodu uyumsuz","incompatibleSetter":"Özellik ayarlayıcı metodu uyumsuz","initMethodLocation":"\\"{type}\\" sınıfı içinde __init__ metodu tanımlandı","initMethodSignature":"__init__ imzası \\"{type}\\"","initSubclassLocation":"__init_subclass__ yöntemi \\"{name}\\" sınıfı içinde tanımlandı","invariantSuggestionDict":"“dict” öğesinden değer türünde eş değişken olan “Mapping” öğesine geçmeyi deneyin","invariantSuggestionList":"“list” öğesinden eş değişken olan “Sequence” öğesine geçmeyi deneyin","invariantSuggestionSet":"“Küme” öğesinden eş değişken olan “Kapsayıcı” öğesine geçmeyi deneyin","keyNotRequired":"\\"{name}\\", \\"{type}\\" türünde gerekli bir anahtar olmadığından çalışma zamanı özel durumuna neden olabilir","keyReadOnly":"\\"{name}\\", \\"{type}\\" içinde salt okunur","keyRequiredDeleted":"\\"{name}\\" gerekli bir anahtar olduğundan silinemez","keyUndefined":"\\"{name}\\", \\"{type}\\" içinde tanımlı bir anahtar değil","kwargsParamMissing":"\\"**{paramName}\\" parametresine karşılık gelen bir parametre yok","listAssignmentMismatch":"\\"{type}\\" türü hedef listeyle uyumsuz","literalAssignmentMismatch":"\\"{sourceType}\\" \\"{destType}\\" türüne atanamaz","matchIsNotExhaustiveHint":"Tümlemeli işleme amaçlanmadıysa \\"case _: pass\\" ekleyin","matchIsNotExhaustiveType":"\\"{type}\\" türü işlenmemiş","memberAssignment":"\\"{type}\\" türündeki ifade, \\"{classType}\\" sınıfının \\"{name}\\" üyesine atanamaz","memberIsAbstract":"\\"{type}.{name}\\" uygulanmadı","memberIsAbstractMore":"ve +{count} tane daha...","memberIsClassVarInProtocol":"\\"{name}\\", protokolde ClassVar olarak tanımlandı","memberIsFinalInProtocol":"\\"{name}\\" protokolde Final olarak işaretlendi","memberIsInitVar":"\\"{name}\\" üyesi bir init-only alanıdır","memberIsInvariant":"\\"{name}\\" değiştirilebilir olduğundan sabit ayarlanır","memberIsNotClassVarInClass":"\\"{name}\\" protokolle uyumlu olması için ClassVar olarak tanımlanmalıdır","memberIsNotClassVarInProtocol":"\\"{name}\\" protokolde ClassVar olarak tanımlanmadı","memberIsNotFinalInProtocol":"\\"{name}\\", protokolde Final olarak işaretlenmedi","memberIsWritableInProtocol":"\\"{name}\\" protokolde yazılabilir","memberSetClassVar":"\\"{name}\\" üyesi bir ClassVar olduğundan sınıf örneği aracılığıyla atanamaz","memberTypeMismatch":"\\"{name}\\" uyumsuz bir tür","memberUnknown":"\\"{name}\\" üyesi bilinmiyor","metaclassConflict":"Metaclass \\"{metaclass1}\\", \\"{metaclass2}\\" ile çakışıyor","missingDeleter":"Özellik silici metodu eksik","missingGetter":"Özellik alıcı metodu eksik","missingSetter":"Özellik ayarlayıcı metodu eksik","namedParamMissingInDest":"Hedefte \\"{name}\\" anahtar sözcük parametresi eksik","namedParamMissingInSource":"Kaynakta \\"{name}\\" anahtar sözcük parametresi eksik","namedParamTypeMismatch":"\\"{sourceType}\\" türündeki \\"{name}\\" anahtar sözcük parametresi, \\"{destType}\\" türüne atanamıyor","namedTupleNotAllowed":"NamedTuple örnek veya sınıf kontrolleri için kullanılamaz","newMethodLocation":"\\"{type}\\" sınıfı içinde __new__ metodu tanımlandı","newMethodSignature":"__new__ imzası \\"{type}\\"","newTypeClassNotAllowed":"NewType ile oluşturulan sınıf, örnek ve sınıf denetimleriyle kullanılamaz","noOverloadAssignable":"Aşırı yüklenmiş işlevlerden hiçbiri \\"{type}\\" türüyle uyuşmuyor","noneNotAllowed":"Örnek veya sınıf denetimleri için hiçbiri kullanılamaz","orPatternMissingName":"Eksik adlar: {name}","overloadIndex":"Aşırı yükleme {index} en yakın eşleşmedir","overloadNotAssignable":"Bir veya daha fazla \\"{name}\\" aşırı yüklemesi atanabilir değil","overloadSignature":"Aşırı yükleme imzası burada tanımlı","overriddenMethod":"Geçersiz kılınan metot","overriddenSymbol":"Geçersiz kılınan simge","overrideInvariantMismatch":"\\"{overrideType}\\" geçersiz kılma türü \\"{baseType}\\" temel türüyle aynı değil","overrideIsInvariant":"Değişken değişebilir, bu nedenle türü sabit","overrideNoOverloadMatches":"Geçersiz kılmadaki hiçbir aşırı yükleme imzası temel metotla uyumlu değil","overrideNotClassMethod":"Temel metot bir örnek metodu olarak bildirilir, ancak geçersiz kılma bu şekilde bildirilmez","overrideNotInstanceMethod":"Temel metot bir örnek metodu olarak bildirilir, ancak geçersiz kılma bu şekilde bildirilmez","overrideNotStaticMethod":"Temel metot bir staticmethod olarak bildirilir, ancak geçersiz kılma bu şekilde bildirilmez","overrideOverloadNoMatch":"Geçersiz kılma temel yöntemin tüm aşırı yüklemelerini işlemez","overrideOverloadOrder":"Geçersiz kılma metoduna ait aşırı yüklemeler temel metotla aynı sırada olmalıdır","overrideParamKeywordNoDefault":"\\"{name}\\" anahtar sözcük parametresi eşleşmiyor: Temel parametrede varsayılan bağımsız değişken değer var, geçersiz kılma parametresinde yok","overrideParamKeywordType":"\\"{name}\\" anahtar sözcük parametresi tür uyuşmazlığı: temel parametre \\"{baseType}\\" türünde, geçersiz kılma parametresi \\"{overrideType}\\" türünde","overrideParamName":"{index} parametresi ad uyuşmazlığı: temel parametre adı \\"{baseName}\\", geçersiz kılma parametresinin adı \\"{overrideName}\\"","overrideParamNameExtra":"Temelde \\"{name}\\" parametresi eksik","overrideParamNameMissing":"Geçersiz kılmada \\"{name}\\" parametresi eksik","overrideParamNamePositionOnly":"{index} parametresi eşleşmiyor: \\"{baseName}\\" temel parametresi, anahtar sözcük parametresidir, geçersiz kılma parametresi ise yalnızca konumdur","overrideParamNoDefault":"{index} parametresi eşleşmiyor: Temel parametrede varsayılan bağımsız değişken değer var, geçersiz kılma parametresinde yok","overrideParamType":"\\"{index}\\" parametresi tür uyuşmazlığı: temel parametre \\"{baseType}\\" türünde, geçersiz kılma parametresi \\"{overrideType}\\" türünde","overridePositionalParamCount":"Konumsal parametre sayısı uyuşmazlığı; temel metotta {baseCount} var, ancak geçersiz kılmada {overrideCount} var","overrideReturnType":"Dönüş türü uyuşmazlığı: temel metot tür \\"{baseType}\\" türü döndürür, geçersiz kılma ise \\"{overrideType}\\" türü döndürür","overrideType":"Temel sınıf, türü \\"{type}\\" olarak tanımlar","paramAssignment":"Parametre {index}: tür \\"{sourceType}\\", \\"{destType}\\" türüne atanamıyor","paramSpecMissingInOverride":"Geçersiz kılma metodunda ParamSpec parametreleri eksik","paramType":"Parametre türü \\"{paramType}\\"","privateImportFromPyTypedSource":"Bunun yerine \\"{module}\\" üzerinden içeri aktarın","propertyAccessFromProtocolClass":"Protokol sınıfı içinde tanımlanan bir özelliğe sınıf değişkeni olarak erişilemez","propertyMethodIncompatible":"\\"{name}\\" özellik metodu uyumsuz","propertyMethodMissing":"Geçersiz kılmada \\"{name}\\" özellik metodu eksik","propertyMissingDeleter":"\\"{name}\\" özelliği tanımlı bir siliciye sahip değil","propertyMissingSetter":"\\"{name}\\" özelliği tanımlı bir ayarlayıcıya sahip değil","protocolIncompatible":"\\"{sourceType}\\", \\"{destType}\\" protokol ayarlarıyla uyumsuz","protocolMemberMissing":"\\"{name}\\" yok","protocolRequiresRuntimeCheckable":"Protokol sınıfının örnekle ve sınıf denetimleriyle birlikte kullanılabilmesi için @runtime_checkable olması gerekir","protocolSourceIsNotConcrete":"\\"{sourceType}\\" somut bir sınıf türü değil ve \\"{destType}\\" türüne atanamaz","protocolUnsafeOverlap":"\\"{name}\\" öznitelikleri protokolle aynı adlara sahip","pyrightCommentIgnoreTip":"Tek bir satır için tanılamayı durdurmak için \\"# pyright: ignore[<diagnostic rules>] kullanın","readOnlyAttribute":"\\"{name}\\" özniteliği salt okunur","seeClassDeclaration":"Sınıf bildirimine bakın","seeDeclaration":"Bildirime bakın","seeFunctionDeclaration":"İşlev bildirimine bakın","seeMethodDeclaration":"Metot bildirimine bakın","seeParameterDeclaration":"Parametre bildirimine bakın","seeTypeAliasDeclaration":"Tür diğer adı bildirimine bakın","seeVariableDeclaration":"Değişken bildirimine bakın","tupleAssignmentMismatch":"\\"{type}\\" türü hedef demet ile uyumsuz","tupleEntryTypeMismatch":"{entry} demet girdisi doğru türde değil","tupleSizeIndeterminateSrc":"Demet boyutu uyuşmuyor; {expected} bekleniyordu ancak indeterminate alındı","tupleSizeIndeterminateSrcDest":"Demet boyutu uyuşmuyor; {expected} veya daha büyük bir değer bekleniyordu ancak belirsiz bir değer alındı","tupleSizeMismatch":"Demet boyutu uyuşmuyor; {expected} bekleniyordu ancak {received} alındı","tupleSizeMismatchIndeterminateDest":"Demet boyutu uyuşmuyor; {expected} veya daha büyük bir değer bekleniyordu ancak {received} alındı","typeAliasInstanceCheck":"“Type” deyimi ile oluşturulan tür diğer adı örnek ve sınıf denetimleri kullanılamaz","typeAssignmentMismatch":"\\"{sourceType}\\" türü \\"{destType}\\" türüne atanamaz","typeBound":"\\"{sourceType}\\" türü, \\"{name}\\" tür değişkeni için \\"{destType}\\" bağlı türü ile uyumlu değil","typeConstrainedTypeVar":"\\"{type}\\" türü, \\"{name}\\" kısıtlanmış tür değişkeni değişkeniyle uyumlu değil","typeIncompatible":"\\"{sourceType}\\", \\"{destType}\\" ile uyumlu değil","typeNotClass":"\\"{type}\\" bir sınıf değil","typeNotStringLiteral":"\\"{type}\\" bir sabit değeri dize değil","typeOfSymbol":"\\"{name}\\" türü \\"{type}\\"","typeParamSpec":"\\"{type}\\" türü \\"{name}\\" ParamSpec ile uyumlu değil","typeUnsupported":"\\"{type}\\" türü desteklenmiyor","typeVarDefaultOutOfScope":"\\"{name}\\" tür değişkeni kapsamda değil","typeVarIsContravariant":"\\"{name}\\" tür parametresi bir karşıt değişken ancak \\"{sourceType}\\", \\"{destType}\\" öğesinin bir üst türü değil","typeVarIsCovariant":"\\"{name}\\" tür parametresi bir eşdeğişken ancak \\"{sourceType}\\", \\"{destType}\\" öğesinin bir alt türü değil","typeVarIsInvariant":"\\"{name}\\" tür parametresi bir değişmez değer ancak \\"{sourceType}\\", \\"{destType}\\" ile aynı değil","typeVarNotAllowed":"Örnek veya sınıf denetimleri için TypeVar\'a izin verilmiyor","typeVarTupleRequiresKnownLength":"TypeVarTuple, uzunluğu bilinmeyen bir demete bağlanamaz","typeVarUnnecessarySuggestion":"Bunun yerine {type} kullanın","typeVarUnsolvableRemedy":"Bağımsız değişken sağlanmamışken dönüş türünü belirten bir aşırı yükleme belirtin","typeVarsMissing":"Eksik tür değişkenleri: {names}","typedDictBaseClass":"\\"{type}\\" sınıfı bir TypedDict değil","typedDictClassNotAllowed":"Örnek veya sınıf denetimleri için TypedDict sınıfına izin verilmiyor","typedDictClosedExtraNotAllowed":"\\"{name}\\" öğesi eklenemiyor","typedDictClosedExtraTypeMismatch":"\\"{type}\\" türündeki \\"{name}\\" öğesi eklenemiyor","typedDictClosedFieldNotRequired":"NotRequired olması gerektiğinden \\"{name}\\" öğesi eklenemiyor","typedDictExtraFieldNotAllowed":"\\"{name}\\" öğesi \\"{type}\\" türünde mevcut değil","typedDictExtraFieldTypeMismatch":"\\"{name}\\" türü, \\"{type}\\" altındaki \\"__extra_items__\\" türüyle uyumlu değil","typedDictFieldMissing":"\\"{type}\\" için \\"{name}\\" eksik","typedDictFieldNotReadOnly":"\\"{name}\\", \\"{type}\\" içinde salt okunur değil","typedDictFieldNotRequired":"\\"{type}\\" içinde \\"{name}\\" gerekli değil","typedDictFieldRequired":"\\"{type}\\" içinde \\"{name}\\" gerekiyor","typedDictFieldTypeMismatch":"\\"{type}\\" türü \\"{name}\\" öğesine atanamaz","typedDictFieldUndefined":"\\"{name}\\", \\"{type}\\" türündeki tanımsız bir öğedir","typedDictFinalMismatch":"\\"{sourceType}\\" @final uyumsuzluğu nedeniyle \\"{destType}\\" ile uyumsuz","typedDictKeyAccess":"TypedDict’te öğeye başvurmak için [\\"{name}\\"] değerini kullanın","typedDictNotAllowed":"TypedDict örnek veya sınıf kontrolleri için kullanılamaz","unhashableType":"\\"{type}\\" türü karmalanabilir değil","uninitializedAbstractVariable":"\\"{name}\\" örnek değişkeni, \\"{classType}\\" soyut temel sınıfında tanımlandı ancak başlatılmadı","unreachableExcept":"\\"{exceptionType}\\", \\"{parentType}\\" üst öğesinin bir alt sınıfı","useDictInstead":"Sözlük türünü belirtmek için Dict[T1, T2] kullanın","useListInstead":"Liste türü belirtmek için List[T] veya birleşim türü belirtmek için Union[T1, T2] kullanın","useTupleInstead":"Demet türünü belirtmek için Tuple[T1, ..., Tn] veya birleşim türünü belirtmek için Union[T1, T2] kullanın","useTypeInstead":"Bunun yerine Type[T] kullanın","varianceMismatchForClass":"\\"{typeVarName}\\" tür bağımsız değişkeni \\"{className}\\" taban sınıfıyla uyumsuz","varianceMismatchForTypeAlias":"\\"{typeVarName}\\" tür bağımsız değişkeninin varyansı, \\"{typeAliasParam}\\" ile uyumsuz"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.zh-cn.json":
/*!*******************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.zh-cn.json ***!
  \*******************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"创建类型存根","createTypeStubFor":"为“{moduleName}”创建类型存根","executingCommand":"正在执行命令","filesToAnalyzeCount":"要分析的 {count} 个文件","filesToAnalyzeOne":"1 个要分析的文件","findingReferences":"正在查找引用","organizeImports":"整理 Import","renameShadowedFile":"将“{oldFile}”重命名为“{newFile}”"},"Completion":{"autoImportDetail":"自动导入","indexValueDetail":"索引值"},"Diagnostic":{"abstractMethodInvocation":"无法调用方法“{method}”，因为它是抽象的且未实施","annotatedParamCountMismatch":"参数批注计数不匹配: 应为 {expected}，但收到 {received}","annotatedTypeArgMissing":"“Annotated”应为一个类型参数和一个或多个批注","annotationFormatString":"类型批注不能使用格式字符串文本 (f 字符串)","annotationNotSupported":"此语句不支持类型批注","annotationSpansStrings":"类型批注不能跨越多个字符串文本","annotationStringEscape":"类型批注不能包含转义字符","argAssignment":"无法将“{argType}”类型的参数分配给“{paramType}”类型的参数","argAssignmentFunction":"无法将\\"{argType}\\"类型的参数分配给函数\\"{functionName}\\"中的\\"{paramType}\\"类型参数","argAssignmentParam":"无法将“{argType}”类型的参数分配给“{paramType}”类型的参数“{paramName}”","argAssignmentParamFunction":"无法将“{argType}”类型的参数分配给函数“{functionName}”中类型为“{paramType}”的参数“{paramName}”","argMissingForParam":"参数 {name} 缺少参数","argMissingForParams":"参数 {names} 缺少参数","argMorePositionalExpectedCount":"预期还有 {expected} 个位置参数","argMorePositionalExpectedOne":"应为 1 个以上位置参数","argPositional":"应为位置参数","argPositionalExpectedCount":"应为 {expected} 个位置参数","argPositionalExpectedOne":"应为 1 个位置参数","argTypePartiallyUnknown":"参数类型部分未知","argTypeUnknown":"参数类型未知","assertAlwaysTrue":"断言表达式的计算结果始终为 true","assertTypeArgs":"“assert_type”需要两个位置参数","assertTypeTypeMismatch":"“assert_type”不匹配:应为“{expected}”，但收到“{received}”","assignmentExprComprehension":"赋值表达式目标“{name}”不能使用与目标理解相同的名称","assignmentExprContext":"赋值表达式必须在模块、函数或 lambda 中","assignmentExprInSubscript":"仅在 Python 3.10 和更高版本中支持下标中的赋值表达式","assignmentInProtocol":"协议类中的实例或类变量必须在类主体内显式声明","assignmentTargetExpr":"表达式不能是赋值目标","asyncNotInAsyncFunction":"异步函数之外不允许使用“async”","awaitIllegal":"使用 “await” 需要 Python 3.5 或更高版本","awaitNotAllowed":"类型注释不能使用“await”","awaitNotInAsync":"仅允许在异步函数内使用“await”","backticksIllegal":"Python 3.x 中不支持由反引号环绕的表达式；请改用 repr","baseClassCircular":"类不能从自身派生","baseClassFinal":"基类“{type}”被标记为最终类，不能为子类","baseClassIncompatible":"{type} 的基类相互不兼容","baseClassInvalid":"类的参数必须是基类","baseClassMethodTypeIncompatible":"类“{classType}”的基类以不兼容的方式定义方法“{name}”","baseClassUnknown":"基类类型未知，隐蔽派生类的类型","baseClassVariableTypeIncompatible":"类“{classType}”的基类以不兼容的方式定义变量“{name}”","binaryOperationNotAllowed":"类型注释中不允许使用二进制运算符","bindTypeMismatch":"无法绑定方法“{methodName}”，因为“{type}”不能分配给参数“{paramName}”","breakOutsideLoop":"“break”只能在循环中使用","callableExtraArgs":"\\"Callable\\"应只有两个类型参数","callableFirstArg":"应为参数类型列表或“...”","callableNotInstantiable":"无法实例化类型“{type}”","callableSecondArg":"返回类型应为\\"Callable\\"的第二个类型参数","casePatternIsIrrefutable":"仅最后一个 case 语句允许使用无可辩驳的模式","classAlreadySpecialized":"类型\\"{type}\\"已专用化","classDecoratorTypeUnknown":"非类型化类修饰器遮盖类类型;忽略修饰器","classDefinitionCycle":"“{name}”的类定义取决于自身","classGetItemClsParam":"__class_getitem__替代应采用“cls”参数","classMethodClsParam":"类方法应采用“cls”参数","classNotRuntimeSubscriptable":"类“{name}”的下标将生成运行时异常；将类型批注括在引号中","classPatternBuiltInArgPositional":"类模式仅接受位置子模式","classPatternPositionalArgCount":"类“{type}”的位置模式太多; 应为 {expected}，但收到了 {received}","classPatternTypeAlias":"无法在类模式中使用“{type}”，因为它是专用类型别名","classPropertyDeprecated":"类属性在 Python 3.11 中已弃用，在 Python 3.13 中将不受支持","classTypeParametersIllegal":"类类型参数语法需要 Python 3.12 或更高版本","classVarFirstArgMissing":"\\"ClassVar\\"后应为类型参数","classVarNotAllowed":"此上下文中不允许使用“ClassVar”","classVarOverridesInstanceVar":"类变量\\"{name}\\"替代类\\"{className}\\"中的同名实例变量","classVarTooManyArgs":"“ClassVar”后应只有一个类型参数","classVarWithTypeVar":"“ClassVar”类型不能包含类型变量","clsSelfParamTypeMismatch":"参数“{name}”的类型必须是类“{classType}”的超类型","codeTooComplexToAnalyze":"代码太复杂，无法分析；通过重构为子例程或减少条件代码路径来降低复杂性","collectionAliasInstantiation":"无法实例化类型“{type}”，请改用“{alias}”","comparisonAlwaysFalse":"条件的计算结果始终为 False，因为类型“{leftType}”和“{rightType}”没有重叠","comparisonAlwaysTrue":"条件的计算结果始终为 True，因为类型“{leftType}”和“{rightType}”没有重叠","comprehensionInDict":"理解不能与其他字典条目一起使用","comprehensionInSet":"理解不能与其他集条目一起使用","concatenateContext":"此上下文中不允许使用“Concatenate”","concatenateParamSpecMissing":"“Concatenate”的最后一个类型参数必须是 ParamSpec 或 \\"...\\"","concatenateTypeArgsMissing":"“Concatenate” 至少需要两个类型参数","conditionalOperandInvalid":"类型“{type}”的条件操作数无效","constantRedefinition":"“{name}”是常量 (因为它是大写)且无法重新定义","constructorNoArgs":"\\"{type}\\"构造函数不应有参数","constructorParametersMismatch":"类“{classType}”中__new__和__init__的签名不匹配","containmentAlwaysFalse":"表达式的计算结果始终为 False，因为类型“{leftType}”和“{rightType}”没有重叠","containmentAlwaysTrue":"表达式的计算结果始终为 True，因为类型“{leftType}”和“{rightType}”没有重叠","continueInFinally":"“continue”不能在 finally 子句中使用","continueOutsideLoop":"“continue”只能在循环中使用","coroutineInConditionalExpression":"始终计算结果为 True 的条件表达式引用协同例程","dataClassBaseClassFrozen":"非冻结类不能从已冻结类继承","dataClassBaseClassNotFrozen":"冻结类不能从未冻结的类继承","dataClassConverterFunction":"类型“{argType}”的参数不是类型为“{fieldType}”的字段“{fieldName}”的有效转换器","dataClassConverterOverloads":"“{funcName}”的重载不是类型为“{fieldType}”的字段“{fieldName}”的有效转换器","dataClassFieldWithDefault":"没有默认值的字段不能出现在具有默认值的字段之后","dataClassFieldWithPrivateName":"数据类字段不能使用专用名称","dataClassFieldWithoutAnnotation":"不带类型批注的数据类字段将导致运行时异常","dataClassPostInitParamCount":"数据类__post_init__参数计数不正确；InitVar 字段数为 {expected}","dataClassPostInitType":"数据类__post_init__方法参数类型不匹配 \\"{fieldName}\\"字段","dataClassSlotsOverwrite":"__slots__已在类中定义","dataClassTransformExpectedBoolLiteral":"静态计算结果为 True 或 False 的预期表达式","dataClassTransformFieldSpecifier":"应为类或函数的元组，但收到的类型\\"{type}\\"","dataClassTransformPositionalParam":"“dataclass_transform”的所有参数都必须是关键字参数","dataClassTransformUnknownArgument":"dataclass_transform不支持参数“{name}”","dataProtocolInSubclassCheck":"issubclass 调用中不允许使用数据协议(包括非方法属性)","declaredReturnTypePartiallyUnknown":"声明的返回类型“{returnType}”部分未知","declaredReturnTypeUnknown":"声明的返回类型未知","defaultValueContainsCall":"参数默认值表达式中不允许函数调用和可变对象","defaultValueNotAllowed":"“*”或“**”的参数不能有默认值","delTargetExpr":"无法删除表达式","deprecatedClass":"类\\"{name}\\"已弃用","deprecatedConstructor":"类\\"{name}\\"的构造函数已弃用","deprecatedDescriptorDeleter":"已弃用描述符“{name}”的“__delete__”方法","deprecatedDescriptorGetter":"已弃用描述符“{name}”的“__get__”方法","deprecatedDescriptorSetter":"已弃用描述符“{name}”的“__set__”方法","deprecatedFunction":"函数“{name}”已弃用","deprecatedMethod":"类“{className}”中的“{name}”方法已弃用","deprecatedPropertyDeleter":"已弃用属性“{name}”的删除程序","deprecatedPropertyGetter":"已弃用属性“{name}”的 getter","deprecatedPropertySetter":"已弃用属性“{name}”的资源库","deprecatedType":"自 Python {version} 起，此类型已弃用；请改用“{replacement}”","dictExpandIllegalInComprehension":"理解中不允许字典扩展","dictInAnnotation":"类型批注中不允许使用字典表达式","dictKeyValuePairs":"字典条目必须包含键/值对","dictUnpackIsNotMapping":"字典解包运算符的预期映射","dunderAllSymbolNotPresent":"\\"{name}\\"已在__all__中指定，但在模块中不存在","duplicateArgsParam":"只允许一个 \\"*\\" 参数","duplicateBaseClass":"不允许重复的基类","duplicateCapturePatternTarget":"捕获目标“{name}”不能在同一模式中出现多次","duplicateCatchAll":"仅允许一个 catch-all except 子句","duplicateEnumMember":"枚举成员\\"{name}\\"已声明","duplicateGenericAndProtocolBase":"只允许一个泛型[...]或协议[...]基类","duplicateImport":"已多次导入“{importName}”","duplicateKeywordOnly":"只允许一个“*”分隔符","duplicateKwargsParam":"仅允许一个 “**” 参数","duplicateParam":"参数“{name}”重复","duplicatePositionOnly":"只允许一个“/”参数","duplicateStarPattern":"模式序列中只允许一个“*”模式","duplicateStarStarPattern":"只允许一个“**”条目","duplicateUnpack":"列表中仅允许一个解包操作","ellipsisAfterUnpacked":"“...”不能与未打包的 TypeVarTuple 或元组一起使用","ellipsisContext":"不允许在此上下文中使用 \\"...\\"","ellipsisSecondArg":"仅允许 \\"...\\" 作为两个参数中的第二个参数","enumClassOverride":"枚举类“{name}”是最终类，不能为子类","exceptionGroupIncompatible":"异常组语法 (\\"except*\\") 需要 Python 3.11 或更高版本","exceptionTypeIncorrect":"\\"{type}\\" 不是派生自 BaseException","exceptionTypeNotClass":"“{type}”不是有效的异常类","exceptionTypeNotInstantiable":"异常类型\\"{type}\\"的构造函数需要一个或多个参数","expectedAfterDecorator":"修饰器后应有函数或类声明","expectedArrow":"应为“->”，后跟返回类型批注","expectedAsAfterException":"异常类型后应为“as”","expectedAssignRightHandExpr":"应为 “=” 右侧的表达式","expectedBinaryRightHandExpr":"应为运算符右侧的表达式","expectedBoolLiteral":"应为 True 或 False","expectedCase":"应为 “case” 语句","expectedClassName":"预期的类名","expectedCloseBrace":"\\"{\\" 未关闭","expectedCloseBracket":"“[”未关闭","expectedCloseParen":"\\"(\\" 未关闭","expectedColon":"应为 \\":\\"","expectedComplexNumberLiteral":"模式匹配的预期复数文本","expectedDecoratorExpr":"Python 3.9 之前的修饰器不支持表达式窗体","expectedDecoratorName":"预期的修饰器名称","expectedDecoratorNewline":"修饰器末尾应有新行","expectedDelExpr":"\\"del\\"后应为表达式","expectedElse":"应为 \\"else\\"","expectedEquals":"应为 \\"=\\"","expectedExceptionClass":"异常类或对象无效","expectedExceptionObj":"应为异常对象、异常类或 None","expectedExpr":"应为表达式","expectedFunctionAfterAsync":"\\"async\\"后面应有函数定义","expectedFunctionName":"“def”后应为函数名称","expectedIdentifier":"预期标识符","expectedImport":"应为 \\"import\\"","expectedImportAlias":"应为 “as” 后面的符号","expectedImportSymbols":"导入后应有一个或多个符号名称","expectedIn":"应为 \\"in\\"","expectedInExpr":"\\"in\\"后应为表达式","expectedIndentedBlock":"应为缩进块","expectedMemberName":"应为“.”后的成员名称。","expectedModuleName":"预期模块名称","expectedNameAfterAs":"\\"as\\" 后应有符号名","expectedNamedParameter":"关键字参数必须跟在 “*” 之后","expectedNewline":"需要换行符","expectedNewlineOrSemicolon":"语句必须用换行符或分号分隔","expectedOpenParen":"应为 \\"(\\"","expectedParamName":"应为参数名称","expectedPatternExpr":"预期的模式表达式","expectedPatternSubjectExpr":"预期的模式主题表达式","expectedPatternValue":"应为 “a.b”形式的模式值表达式","expectedReturnExpr":"“return” 后应有表达式","expectedSliceIndex":"预期索引或切片表达式","expectedTypeNotString":"应为类型，但收到字符串文本","expectedTypeParameterName":"应为类型参数名称","expectedYieldExpr":"yield 语句中的预期表达式","finalClassIsAbstract":"类“{type}”被标记为 final，并且必须实现所有抽象符号","finalContext":"不允许在此上下文中使用 \\"Final\\"","finalMethodOverride":"方法\\"{name}\\"无法替代在类\\"{className}\\"中定义的最终方法","finalNonMethod":"不能将函数“{name}”标记为 @final，因为它不是方法","finalReassigned":"\\"{name}\\"声明为 Final，无法重新分配","finalRedeclaration":"\\"{name}\\"以前声明为 Final","finalRedeclarationBySubclass":"无法重新声明“{name}”，因为父类“{className}”将其声明为 Final","finalTooManyArgs":"“Final”后应为单个类型参数","finalUnassigned":"“{name}”声明为“最终”，但未分配值","formatStringBrace":"f 字符串文本中不允许使用单个右大括号；使用双右大括号","formatStringBytes":"格式字符串文本(f 字符串)不能为二进制","formatStringDebuggingIllegal":"F 字符串调试说明符“=”需要 Python 3.8 或更高版本","formatStringEscape":"Python 3.12 之前 f 字符串的表达式部分中不允许使用转义序列(反斜杠)","formatStringExpectedConversion":"在 f 字符串中应为 \\"!\\" 之后的转换说明符","formatStringIllegal":"格式化字符串文本(f 字符串)需要 Python 3.6 或更高版本","formatStringInPattern":"模式中不允许使用格式字符串","formatStringNestedFormatSpecifier":"表达式嵌套在格式字符串说明符内太深","formatStringNestedQuote":"嵌套在 f 字符串中的字符串不能使用与 Python 3.12 之前的 f 字符串相同的引号字符","formatStringUnicode":"格式字符串文本(f 字符串)不能为 unicode","formatStringUnterminated":"f 字符串中未终止的表达式；应为 \\"}\\"","functionDecoratorTypeUnknown":"非类型化函数修饰器遮盖函数类型；忽略修饰器","functionInConditionalExpression":"始终计算结果为 True 的条件表达式引用函数","functionTypeParametersIllegal":"函数类型参数语法需要 Python 3.12 或更高版本","futureImportLocationNotAllowed":"从__future__导入必须位于文件的开头","generatorAsyncReturnType":"异步生成器函数的返回类型必须与 \\"AsyncGenerator[{yieldType}, Any]\\" 兼容","generatorNotParenthesized":"如果不是唯一参数，生成器表达式必须带圆括号","generatorSyncReturnType":"生成器函数的返回类型必须与 \\"Generator[{yieldType}, Any, Any]\\"兼容","genericBaseClassNotAllowed":"“Generic” 基类不能与类型参数语法一起使用","genericClassAssigned":"无法分配泛型类类型","genericClassDeleted":"无法删除泛型类类型","genericInstanceVariableAccess":"通过类访问泛型实例变量是不明确的","genericNotAllowed":"\\"Generic\\" 在此上下文中无效","genericTypeAliasBoundTypeVar":"类中的泛型类型别名不能使用绑定类型变量 {names}","genericTypeArgMissing":"“Generic”至少需要一个类型参数","genericTypeArgTypeVar":"“Generic”的类型参数必须是类型变量","genericTypeArgUnique":"“Generic”的类型参数必须是唯一","globalReassignment":"在全局声明之前分配了“{name}”","globalRedefinition":"“{name}”已声明为全局","implicitStringConcat":"不允许隐式字符串串联","importCycleDetected":"在导入链中检测到的周期数","importDepthExceeded":"导入链深度超过 {depth}","importResolveFailure":"无法解析导入“{importName}”","importSourceResolveFailure":"无法从源解析导入“{importName}”","importSymbolUnknown":"“{name}”是未知的导入符号","incompatibleMethodOverride":"方法“{name}”以不兼容的方式替代类“{className}”","inconsistentIndent":"取消缩进量与以前的缩进不匹配","inconsistentTabs":"缩进中制表符和空格的使用不一致","initMustReturnNone":"“__init__”的返回类型必须为 None","initSubclassCallFailed":"__init_subclass__ 方法的关键字参数不正确","initSubclassClsParam":"__init_subclass__替代应采用“cls”参数","initVarNotAllowed":"此上下文中不允许使用“InitVar”","instanceMethodSelfParam":"实例方法应采用 “self” 参数","instanceVarOverridesClassVar":"实例变量\\"{name}\\"替代类\\"{className}\\"中的同名类变量","instantiateAbstract":"无法实例化抽象类“{type}”","instantiateProtocol":"无法实例化协议类“{type}”","internalBindError":"绑定文件“{file}”时发生内部错误:{message}","internalParseError":"分析文件“{file}”时发生内部错误:{message}","internalTypeCheckingError":"类型检查文件“{file}”时发生内部错误:{message}","invalidIdentifierChar":"标识符中的字符无效","invalidStubStatement":"语句在类型存根文件中无意义","invalidTokenChars":"令牌中的字符\\"{text}\\"无效","isInstanceInvalidType":"“isinstance” 的第二个参数必须是类的类或元组","isSubclassInvalidType":"“issubclass”的第二个参数必须是类的类或元组","keyValueInSet":"不允许在集内使用键/值对","keywordArgInTypeArgument":"关键字参数不能在类型参数列表中使用","keywordOnlyAfterArgs":"“*”参数后不允许使用仅限关键字的参数分隔符","keywordParameterMissing":"一个或多个关键字参数必须遵循 \\"*\\"参数","keywordSubscriptIllegal":"不支持下标中的关键字参数","lambdaReturnTypePartiallyUnknown":"lambda 的返回类型“{returnType}”部分未知","lambdaReturnTypeUnknown":"lambda 的返回类型未知","listAssignmentMismatch":"无法将 \\"{type}\\" 类型的表达式分配给目标列表","listInAnnotation":"类型批注中不允许使用列表表达式","literalEmptyArgs":"“Literal”后应有一个或多个类型参数","literalNotAllowed":"如果没有类型参数，则 \\"Literal\\" 不能用于此上下文","literalNotCallable":"无法实例化文本类型","literalUnsupportedType":"“Literal” 的类型参数必须是 None、int、bool、str 或 bytes)(文本值，或者是枚举值","matchIncompatible":"匹配语句需要 Python 3.10 或更高版本","matchIsNotExhaustive":"match 语句中的事例不会彻底处理所有值","maxParseDepthExceeded":"超出最大分析深度;将表达式分解为较小的子表达式","memberAccess":"无法存取类型“{type}”的成员“{name}”","memberDelete":"无法删除类型\\"{type}\\"的成员\\"{name}\\"","memberSet":"无法为类型“{type}”分配成员“{name}”","metaclassConflict":"派生类的元类必须是其所有基类的元类的子类","metaclassDuplicate":"只能提供一个元类","metaclassIsGeneric":"元类不能是泛型","methodNotDefined":"未定义“{name}”方法","methodNotDefinedOnType":"未在类型\\"{type}\\"上定义\\"{name}\\"方法","methodOrdering":"无法创建一致的方法排序","methodOverridden":"“{name}”在类型“{type}”不兼容的类“{className}”中替代同名的方法","methodReturnsNonObject":"“{name}”方法不返回对象","missingSuperCall":"方法“{methodName}”在父类中不调用同名方法","moduleAsType":"模块不能用作类型","moduleNotCallable":"模块不可调用","moduleUnknownMember":"“{memberName}”不是模块“{moduleName}”的已知成员","namedExceptAfterCatchAll":"在 catch-all(除子句外)后不能出现命名的 except 子句","namedParamAfterParamSpecArgs":"关键字参数“{name}”不能出现在 ParamSpec args 参数之后的签名中","namedTupleEmptyName":"命名元组中的名称不能为空","namedTupleEntryRedeclared":"无法重写“{name}”，因为父类“{className}”是命名的元组","namedTupleFirstArg":"应将命名元组类名称作为第一个参数","namedTupleMultipleInheritance":"不支持使用 NamedTuple 进行多个继承","namedTupleNameKeyword":"字段名称不能是关键字","namedTupleNameType":"应为指定条目名称和类型的双条目元组","namedTupleNameUnique":"命名元组中的名称必须唯一","namedTupleNoTypes":"“namedtuple”不提供元组条目的类型；请改用“NamedTuple”","namedTupleSecondArg":"应将命名元组条目列表作为第二个参数","newClsParam":"__new__替代应采用“cls”参数","newTypeAnyOrUnknown":"NewType 的第二个参数必须是已知类，而不是“任何”或“未知”","newTypeBadName":"NewType 的第一个参数必须是字符串文本","newTypeLiteral":"NewType 不能与文本类型一起使用","newTypeNameMismatch":"必须将 NewType 分配给同名变量","newTypeNotAClass":"应为 NewType 的第二个参数的类","newTypeParamCount":"NewType 需要两个位置参数","newTypeProtocolClass":"NewType 不能与结构类型(协议或 TypedDict 类)一起使用","noOverload":"“{name}”的重载与提供的参数不匹配","noReturnContainsReturn":"声明返回类型为“NoReturn”的函数不能包含 return 语句","noReturnContainsYield":"声明的返回类型为 “NoReturn” 的函数不能包含 yield 语句","noReturnReturnsNone":"所声明的返回类型为 \\"NoReturn\\" 的函数无法返回 \\"None\\"","nonDefaultAfterDefault":"非默认参数遵循默认参数","nonLocalInModule":"模块级别不允许使用非本地声明","nonLocalNoBinding":"找不到非本地“{name}”的绑定","nonLocalReassignment":"在非本地声明之前分配了“{name}”","nonLocalRedefinition":"\\"{name}\\"已声明为非本地","noneNotCallable":"无法调用类型为“None”的对象","noneNotIterable":"类型为“None”的对象不能用作可迭代值","noneNotSubscriptable":"类型为“None”的对象不可下标","noneNotUsableWith":"类型为“None”的对象不能与“with”一起使用","noneOperator":"“None”不支持运算符\\"{operator}\\"","noneUnknownMember":"“{name}”不是“None”的已知成员","notRequiredArgCount":"“NotRequired” 之后应为单个类型参数","notRequiredNotInTypedDict":"此上下文中不允许使用“NotRequired”","objectNotCallable":"类型为“{type}”的对象不可调用","obscuredClassDeclaration":"类声明\\"{name}\\"被同名的声明遮蔽","obscuredFunctionDeclaration":"函数声明“{name}”被同名声明遮盖","obscuredMethodDeclaration":"方法声明“{name}”被同名声明遮盖","obscuredParameterDeclaration":"参数声明“{name}”被同名声明遮盖","obscuredTypeAliasDeclaration":"类型别名声明“{name}”被同名声明遮盖","obscuredVariableDeclaration":"声明“{name}”被同名声明遮盖","operatorLessOrGreaterDeprecated":"Python 3 不支持运算符“<>”；请改用 \\"!=\\"","optionalExtraArgs":"\\"Optional\\"后面应有一个类型参数","orPatternIrrefutable":"无可辩驳的模式仅允许作为 \\"or\\"模式中的最后一个子模式","orPatternMissingName":"“or”模式中的所有子节点必须以相同的名称为目标","overlappingKeywordArgs":"类型化字典与以下关键字参数重叠: {names}","overlappingOverload":"永远不会使用“{name}”的重载 {obscured}，因为其参数与重载 {obscuredBy} 重叠","overloadAbstractMismatch":"重载的方法必须全部为抽象方法或不为抽象方法","overloadClassMethodInconsistent":"“{name}”的重载使用 @classmethod 的方式不一致","overloadFinalInconsistencyImpl":"“{name}”的重载被标记为 @final，但实施未被标记","overloadFinalInconsistencyNoImpl":"“{name}”的重载 {index} 被标记为 @final，但重载 1 未被标记","overloadImplementationMismatch":"重载实现与重载 {index} 的签名不一致","overloadReturnTypeMismatch":"“{name}”的重载 {prevIndex} 与重载 {newIndex} 重叠，并返回不兼容的类型","overloadStaticMethodInconsistent":"“{name}”的重载使用 @staticmethod 的方式不一致","overloadWithoutImplementation":"\\"{name}\\"标记为重载，但未提供实现","overriddenMethodNotFound":"方法\\"{name}\\"标记为替代，但不存在同名的基方法","overrideDecoratorMissing":"方法\\"{name}\\"未标记为替代，但正在替代类\\"{className}\\"中的方法","paramAfterKwargsParam":"参数不能跟随“**”参数","paramAlreadyAssigned":"已分配参数“{name}”","paramAnnotationMissing":"参数“{name}”缺少类型批注","paramAssignmentMismatch":"无法将\\"{sourceType}\\"类型的表达式分配给\\"{paramType}\\"类型的参数","paramNameMissing":"没有名为“{name}”的参数","paramSpecArgsKwargsUsage":"ParamSpec 的“args”和“kwargs”成员必须同时出现在函数签名中","paramSpecArgsMissing":"缺少 ParamSpec“{type}”的参数","paramSpecArgsUsage":"ParamSpec 的 “args” 成员仅在与 *args 参数一起使用时有效","paramSpecAssignedName":"必须将 ParamSpec 分配给名为“{name}”的变量","paramSpecContext":"此上下文中不允许使用 ParamSpec","paramSpecDefaultNotTuple":"ParamSpec 的默认值应为省略号、元组表达式或 ParamSpec","paramSpecFirstArg":"ParamSpec 作为第一个参数的预期名称","paramSpecKwargsUsage":"ParamSpec 的“kwargs”成员仅在与 **kwargs 参数一起使用时有效","paramSpecNotUsedByOuterScope":"ParamSpec“{name}”在此上下文中没有意义","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\"在返回类型内的作用域为可调用，不能在函数体中引用","paramSpecUnknownArg":"ParamSpec 不支持多个参数","paramSpecUnknownMember":"“{name}”不是 ParamSpec 的已知成员","paramSpecUnknownParam":"“{name}”是 ParamSpec 的未知参数","paramTypeCovariant":"不能在参数类型中使用协变类型变量","paramTypePartiallyUnknown":"参数\\"{paramName}\\"的类型部分未知","paramTypeUnknown":"参数“{paramName}”的类型未知","parenthesizedContextManagerIllegal":"“with”语句中的括号需要 Python 3.9 或更高版本","patternNeverMatches":"主题类型“{type}”的模式永远不会匹配","positionArgAfterNamedArg":"位置参数不能出现在关键字参数之后","positionOnlyAfterArgs":"“*”参数后不允许使用仅位置参数分隔符","positionOnlyAfterKeywordOnly":"“/”参数必须出现在“*”参数之前","positionOnlyAfterNon":"非仅位置参数后面不允许仅位置参数","positionOnlyFirstParam":"不允许将仅位置参数分隔符用作第一个参数","positionOnlyIncompatible":"仅位置参数分隔符需要 Python 3.8 或更高版本","privateImportFromPyTypedModule":"未从模块“{module}”导出“{name}”","privateUsedOutsideOfClass":"\\"{name}\\"是专用的，在声明它的类之外使用","privateUsedOutsideOfModule":"“{name}”是专用的，在声明它的模块外部使用","propertyOverridden":"“{name}”错误地替代类“{className}”中同名的属性","propertyStaticMethod":"属性 getter、setter 或 deleter 不允许使用静态方法","protectedUsedOutsideOfClass":"“{name}”在声明它的类之外受到保护并被使用","protocolBaseClass":"协议类“{classType}”不能派生自非协议类“{baseType}”","protocolBaseClassWithTypeArgs":"使用类型参数语法时，协议类不允许使用类型参数","protocolIllegal":"使用 \\"Protocol\\" 需要 Python 3.7 或更高版本","protocolNotAllowed":"\\"Protocol\\" 不能用于此上下文","protocolUnsafeOverlap":"类与“{name}”不安全地重叠，并且可能在运行时生成匹配项","protocolVarianceContravariant":"泛型协议“{class}”中使用的类型变量“{variable}”应为逆变","protocolVarianceCovariant":"泛型协议“{class}”中使用的类型变量“{variable}”应为协变","protocolVarianceInvariant":"泛型协议“{class}”中使用的类型变量“{variable}”应为固定变量","pyrightCommentInvalidDiagnosticBoolValue":"Pyright 注释指令后面必须跟有“=”和 true 或 false 值","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright 注释指令后面必须跟有“=”，并且值为 true、false、error、warning、information 或 none","pyrightCommentMissingDirective":"Pyright 注释后面必须是指令(基本或严格)或诊断规则","pyrightCommentNotOnOwnLine":"用于控制文件级设置的 Pyright 注释必须显示在其自己的行上","pyrightCommentUnknownDiagnosticRule":"“{rule}”是 pyright 注释的未知诊断规则","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\"是 pyright 注释的无效值；应为 true、false、error、warning、information 或 none","pyrightCommentUnknownDirective":"\\"{directive}\\"是 pyright 注释的未知指令；应为 “strict” 或 “basic”","readOnlyArgCount":"“ReadOnly”后应为单个类型参数","readOnlyNotInTypedDict":"此上下文中不允许使用“ReadOnly”","recursiveDefinition":"无法确定“{name}”的类型，因为它引用其自身","relativeImportNotAllowed":"相对导入不能与“import .a”窗体一起使用；改用 \\"from . import a\\"","requiredArgCount":"\\"Required\\"后应为单个类型参数","requiredNotInTypedDict":"此上下文中不允许使用\\"Required\\"","returnInAsyncGenerator":"异步生成器中不允许返回值为值的语句","returnMissing":"所声明的返回类型为“{returnType}”的函数必须在所有代码路径上返回值","returnOutsideFunction":"“return”只能在函数中使用","returnTypeContravariant":"逆变类型变量不能用于返回类型","returnTypeMismatch":"无法将类型“{exprType}”的表达式分配给返回类型“{returnType}”","returnTypePartiallyUnknown":"返回类型“{returnType}”部分未知","returnTypeUnknown":"返回类型未知","revealLocalsArgs":"“reveal_locals”调用应没有参数","revealLocalsNone":"此范围内没有局部变量","revealTypeArgs":"“reveal_type”调用应为单个位置参数","revealTypeExpectedTextArg":"函数“reveal_type”的“expected_text”参数必须是 str 文本值","revealTypeExpectedTextMismatch":"类型文本不匹配；应为\\"{expected}\\"但收到\\"{received}\\"","revealTypeExpectedTypeMismatch":"类型不匹配;应为“{expected}”，但收到“{received}”","selfTypeContext":"“Self”在此上下文中无效","selfTypeMetaclass":"“Self”不能在元类(“type”的子类)中使用","selfTypeWithTypedSelfOrCls":"“Self”不能在具有“self”或“cls”参数的函数中使用，该参数的类型批注不是“Self”","setterGetterTypeMismatch":"属性资源库值类型不可分配给 getter 返回类型","singleOverload":"“{name}”被标记为重载，但缺少其他重载","slotsAttributeError":"未在__slots__中指定“{name}”","slotsClassVarConflict":"\\"{name}\\"与__slots__中声明的实例变量冲突","starPatternInAsPattern":"星形模式不能与“as”目标一起使用","starPatternInOrPattern":"在其他模式中，星形图案不能为 ORed","starStarWildcardNotAllowed":"** 不能与通配符“_”一起使用","staticClsSelfParam":"静态方法不应采用“self”或“cls”参数","stdlibModuleOverridden":"\\"{path}\\"正在替代 stdlib 模块\\"{name}\\"","stringNonAsciiBytes":"不允许使用非 ASCII 字符(以字节为单位)字符串文本","stringNotSubscriptable":"字符串表达式不能在类型批注中下标；将整个批注括在引号中","stringUnsupportedEscape":"字符串文本中不受支持的转义序列","stringUnterminated":"字符串文本未终止","stubFileMissing":"找不到“{importName}”的存根文件","stubUsesGetAttr":"类型存根文件不完整；“__getattr__”会遮盖模块的类型错误","sublistParamsIncompatible":"Python 3.x 不支持子列表参数","superCallArgCount":"“super” 调用应不超过两个参数","superCallFirstArg":"应将类类型作为“super”调用的第一个参数，但收到“{type}”","superCallSecondArg":"“super”调用的第二个参数必须是派生自“{type}”的对象或类","superCallZeroArgForm":"“Super”调用的零参数形式仅在方法中有效","superCallZeroArgFormStaticMethod":"“super”调用的零参数形式在静态方法中无效","symbolIsPossiblyUnbound":"“{name}”可能未绑定","symbolIsUnbound":"“{name}”未绑定","symbolIsUndefined":"未定义“{name}”","symbolOverridden":"“{name}”替代类“{className}”中的同名符号","ternaryNotAllowed":"类型注释中不允许使用三元表达式","totalOrderingMissingMethod":"类必须定义“__lt__”、“__le__”、“__gt__”或“__ge__”之一才能使用total_ordering","trailingCommaInFromImport":"不允许使用尾随逗号，没有括号","tryWithoutExcept":"Try 语句必须至少有一个 except 或 finally 子句","tupleAssignmentMismatch":"无法将类型为“{type}”的表达式分配给目标元组","tupleInAnnotation":"类型批注中不允许元组表达式","tupleIndexOutOfRange":"类型 {type} 的索引 {index} 超出范围","typeAliasIllegalExpressionForm":"类型别名定义的表达式形式无效","typeAliasIsRecursiveDirect":"类型别名“{name}”不能在其定义中使用自身","typeAliasNotInModuleOrClass":"TypeAlias 只能在模块或类范围内定义","typeAliasRedeclared":"“{name}”声明为 TypeAlias，只能分配一次","typeAliasStatementBadScope":"type 语句只能在模块或类范围内使用","typeAliasStatementIllegal":"类型别名语句需要 Python 3.12 或更高版本","typeAliasTypeBaseClass":"\\"type\\" 语句中定义的类型别名不能用作基类","typeAliasTypeMustBeAssigned":"必须将 TypeAliasType 分配给与类型别名同名的变量","typeAliasTypeNameArg":"TypeAliasType 的第一个参数必须是表示类型别名名称的字符串文本","typeAliasTypeNameMismatch":"类型别名的名称必须与分配到的变量的名称匹配","typeAliasTypeParamInvalid":"类型参数列表必须是仅包含 TypeVar、TypeVarTuple 或 ParamSpec 的元组","typeAnnotationCall":"类型表达式中不允许使用调用表达式","typeAnnotationVariable":"类型表达式中不允许使用变量","typeAnnotationWithCallable":"“type”的类型参数必须为类; 不支持可调用项","typeArgListExpected":"应为 ParamSpec、省略号或类型列表","typeArgListNotAllowed":"不允许此类型参数使用列表表达式","typeArgsExpectingNone":"类“{name}”不应有类型参数","typeArgsMismatchOne":"应为一个类型参数，但收到 {received}","typeArgsMissingForAlias":"泛型类型别名“{name}”的预期类型参数","typeArgsMissingForClass":"泛型类“{name}”的预期类型参数","typeArgsTooFew":"为“{name}”提供的类型参数太少；应为 {expected}，但收到 {received}","typeArgsTooMany":"为“{name}”提供的类型参数太多；应为 {expected}，但收到 {received}","typeAssignmentMismatch":"无法将类型“{sourceType}”的表达式分配给声明的类型“{destType}”","typeAssignmentMismatchWildcard":"导入符号“{name}”的类型为“{sourceType}”，无法将其分配给声明的类型“{destType}”","typeCallNotAllowed":"type() 调用不应用于类型批注","typeCheckOnly":"“{name}”标记为 @type_check_only，并且只能在类型注释中使用","typeCommentDeprecated":"已弃用类型注释；请改用类型批注","typeExpectedClass":"应为类型表达式，但收到“{type}”","typeGuardArgCount":"“TypeGuard”或“TypeIs”后应为单个类型参数","typeGuardParamCount":"用户定义的类型防护函数和方法必须至少有一个输入参数","typeIsReturnType":"TypeIs 的返回类型(“{returnType}”)与值参数类型(“{type}”)不一致","typeNotAwaitable":"“{type}”不可等待","typeNotIntantiable":"无法实例化\\"{type}\\"","typeNotIterable":"“{type}”不可迭代","typeNotSpecializable":"无法专用化类型“{type}”","typeNotSubscriptable":"类型为“{type}”的对象不可下标","typeNotSupportBinaryOperator":"类型“{leftType}”和“{rightType}”不支持运算符“{operator}”","typeNotSupportBinaryOperatorBidirectional":"预期类型为“{expectedType}”时，类型“{leftType}”和“{rightType}”不支持运算符“{operator}”","typeNotSupportUnaryOperator":"类型“{type}”不支持运算符“{operator}”","typeNotSupportUnaryOperatorBidirectional":"预期类型为 \\"{expectedType}\\"时，类型\\"{type}\\"不支持运算符\\"{operator}\\"","typeNotUsableWith":"\\"{type}\\"类型的对象不能与 “with” 一起使用，因为它未实现{method}","typeParameterBoundNotAllowed":"绑定或约束不能与 variadic 类型参数或 ParamSpec 一起使用","typeParameterConstraintTuple":"类型参数约束必须是两个或更多类型的元组","typeParameterExistingTypeParameter":"类型参数\\"{name}\\"已在使用中","typeParameterNotDeclared":"类型参数“{name}”未包含在“{container}”的类型参数列表中","typeParametersMissing":"必须至少指定一个类型参数","typePartiallyUnknown":"“{name}”的类型部分未知","typeUnknown":"\\"{name}\\"类型未知","typeVarAssignedName":"必须将 TypeVar 分配给名为“{name}”的变量","typeVarAssignmentMismatch":"无法将类型\\"{type}\\"分配给类型变量\\"{name}\\"","typeVarBoundAndConstrained":"TypeVar 不能同时绑定和约束","typeVarBoundGeneric":"TypeVar 绑定类型不能是泛型","typeVarConstraintGeneric":"TypeVar 约束类型不能是泛型","typeVarDefaultBoundMismatch":"TypeVar 默认类型必须是绑定类型的子类型","typeVarDefaultConstraintMismatch":"TypeVar 默认类型必须是受约束类型之一","typeVarDefaultIllegal":"类型变量默认类型需要 Python 3.13 或更高版本","typeVarDefaultInvalidTypeVar":"类型参数“{name}”的默认类型是指超出范围的一个或多个类型变量","typeVarFirstArg":"TypeVar 作为第一个参数的预期名称","typeVarNoMember":"TypeVar \\"{type}\\"没有成员\\"{name}\\"","typeVarNotSubscriptable":"TypeVar“{type}”不可下标","typeVarNotUsedByOuterScope":"类型变量“{name}”在此上下文中没有意义","typeVarPossiblyUnsolvable":"如果调用方没有为参数提供参数\\"{param}\\"，则类型变量\\"{name}\\"可能无法解析","typeVarScopedToReturnType":"类型变量\\"{name}\\"在返回类型内的作用域为可调用，不能在函数体中引用","typeVarSingleConstraint":"TypeVar 必须至少有两种约束类型","typeVarTupleConstraints":"TypeVarTuple 不能有值约束","typeVarTupleContext":"此上下文中不允许使用 TypeVarTuple","typeVarTupleDefaultNotUnpacked":"TypeVarTuple 默认类型必须是未打包的元组或 TypeVarTuple","typeVarTupleMustBeUnpacked":"TypeVarTuple 值需要解包运算符","typeVarTupleUnknownParam":"“{name}”是 TypeVarTuple 的未知参数","typeVarUnknownParam":"typeVar 的\\"{name}\\"是未知参数","typeVarUsedByOuterScope":"TypeVar“{name}”已被外部作用域使用","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" 在泛型函数签名中仅显示一次","typeVarVariance":"TypeVar 不能同时为协变和逆变","typeVarWithDefaultFollowsVariadic":"TypeVar“{typeVarName}”具有默认值，并且不能遵循 TypeVarTuple“{variadicName}”","typeVarWithoutDefault":"“{name}”不能出现在类型参数列表的“{other}”后面，因为它没有默认类型","typeVarsNotInGenericOrProtocol":"Generic[] 或 Protocol[] 必须包括所有类型变量","typedDictAccess":"无法存取 TypedDict 中的项","typedDictAssignedName":"必须将 TypedDict 分配给名为“{name}”的变量","typedDictBadVar":"TypedDict 类只能包含类型批注","typedDictBaseClass":"TypedDict 类的所有基类也必须是 TypedDict 类","typedDictBoolParam":"预期“{name}”参数的值为 True 或 False","typedDictClosedExtras":"基类“{name}”是已关闭的 TypedDict；额外的项必须是类型“{type}”","typedDictClosedNoExtras":"基类“{name}”是已关闭的 TypedDict；不允许使用额外的项","typedDictDelete":"无法删除 TypedDict 中的项","typedDictEmptyName":"TypedDict 中的名称不能为空","typedDictEntryName":"字典条目名称的预期字符串文本","typedDictEntryUnique":"字典中的名称必须唯一","typedDictExtraArgs":"不支持额外的 TypedDict 参数","typedDictFieldNotRequiredRedefinition":"无法将 TypedDict 项“{name}”重新定义为 NotRequired","typedDictFieldReadOnlyRedefinition":"无法将 TypedDict 项“{name}”重新定义为 ReadOnly","typedDictFieldRequiredRedefinition":"无法将 TypedDict 项“{name}”重新定义为 Required","typedDictFirstArg":"应将 TypedDict 类名作为第一个参数","typedDictInitsubclassParameter":"TypedDict 不支持 __init_subclass__ parameter“{name}”","typedDictNotAllowed":"\\"TypedDict\\" 不能用于此上下文","typedDictSecondArgDict":"预期的 dict 或关键字参数作为第二个参数","typedDictSecondArgDictEntry":"应为简单字典条目","typedDictSet":"无法在 TypedDict 中分配项","unaccessedClass":"未存取类“{name}”","unaccessedFunction":"无法存取函数\\"{name}\\"","unaccessedImport":"未存取导入“{name}”","unaccessedSymbol":"未存取“{name}”","unaccessedVariable":"无法存取变量“{name}”","unannotatedFunctionSkipped":"已跳过对函数“{name}”的分析，因为它未被批注","unaryOperationNotAllowed":"类型注释中不允许使用一元运算符","unexpectedAsyncToken":"“def”、“with” 或 “for” 应跟随 “async”","unexpectedExprToken":"表达式末尾出现意外标记","unexpectedIndent":"意外缩进","unexpectedUnindent":"不应取消缩进","unhashableDictKey":"字典密钥必须可哈希","unhashableSetEntry":"设置条目必须是可哈希","uninitializedAbstractVariables":"抽象基类中定义的变量未在最终类“{classType}”中初始化","uninitializedInstanceVariable":"未在类体或__init__方法中初始化实例变量“{name}”","unionForwardReferenceNotAllowed":"联合语法不能与字符串操作数一起使用;在整个表达式周围使用引号","unionSyntaxIllegal":"联合的替代语法需要 Python 3.10 或更高版本","unionTypeArgCount":"联合需要两个或更多类型参数","unionUnpackedTuple":"并集不能包含未打包的元组","unionUnpackedTypeVarTuple":"并集不能包含未打包的 TypeVarTuple","unnecessaryCast":"不必要的 \\"cast\\" 调用；类型已为“{type}”","unnecessaryIsInstanceAlways":"不必要的 isinstance 调用；“{testType}”始终是“{classType}”的实例","unnecessaryIsSubclassAlways":"不必要的 issubclass 调用；“{testType}”始终是“{classType}”的子类","unnecessaryPyrightIgnore":"不必要的 \\"# pyright: ignore\\" 注释","unnecessaryPyrightIgnoreRule":"不必要的 \\"# pyright: ignore\\"规则: \\"{name}\\"","unnecessaryTypeIgnore":"不必要的 \\"# type: ignore\\" 注释","unpackArgCount":"\\"Unpack\\"后应为单个类型参数","unpackExpectedTypeVarTuple":"需要 TypeVarTuple 或元组作为 Unpack 的类型参数","unpackExpectedTypedDict":"解包的预期 TypedDict 类型参数","unpackIllegalInComprehension":"在理解中不允许解包操作","unpackInAnnotation":"类型批注中不允许解压缩运算符","unpackInDict":"字典中不允许解压缩操作","unpackInSet":"集内不允许解包运算符","unpackNotAllowed":"此上下文中不允许解包","unpackOperatorNotAllowed":"此上下文中不允许解压缩操作","unpackTuplesIllegal":"Python 3.8 之前的元组中不允许解包操作","unpackedArgInTypeArgument":"无法在类型参数列表中使用未打包的参数","unpackedArgWithVariadicParam":"未打包的参数不能用于 TypeVarTuple 参数","unpackedDictArgumentNotMapping":"** 后面的参数表达式必须是具有“str”键类型的映射","unpackedDictSubscriptIllegal":"不允许在下标中使用字典解包运算符","unpackedSubscriptIllegal":"下标中的解包运算符需要 Python 3.11 或更高版本","unpackedTypeVarTupleExpected":"应为未打包的 TypeVarTuple；使用 Unpack[{name1}] 或 *{name2}","unpackedTypedDictArgument":"无法将解压缩的 TypedDict 参数与参数匹配","unreachableCode":"代码无法访问","unreachableExcept":"无法访问 Except 子句，因为已处理异常","unsupportedDunderAllOperation":"不支持对“__all__”执行操作，因此导出的符号列表可能不正确","unusedCallResult":"调用表达式的结果类型为 \\"{type}\\" 且未使用；如果这是有意为之，则分配给变量 “_”","unusedCoroutine":"未使用异步函数调用的结果；使用 “await” 或将结果分配给变量","unusedExpression":"表达式值未使用","varAnnotationIllegal":"变量的类型批注需要 Python 3.6 或更高版本；使用类型注释与以前的版本兼容","variableFinalOverride":"变量\\"{name}\\"被标记为 Final，并替代类\\"{className}\\"中同名的非 Final 变量","variadicTypeArgsTooMany":"类型参数列表最多可以有一个未打包的 TypeVarTuple 或元组","variadicTypeParamTooManyAlias":"类型别名最多可以有一个 TypeVarTuple 类型参数，但收到多个 ({names})","variadicTypeParamTooManyClass":"泛型类最多可以有一个 TypeVarTuple 类型参数，但收到多个 ({names})","walrusIllegal":"运算符 \\":=\\" 需要 Python 3.8 或更高版本","walrusNotAllowed":"此上下文中不允许使用运算符 \\":=\\"，且不带括号","wildcardInFunction":"类或函数中不允许使用通配符导入","wildcardLibraryImport":"不允许从库中导入通配符","wildcardPatternTypePartiallyUnknown":"通配符模式捕获的类型部分未知","wildcardPatternTypeUnknown":"通配符模式捕获的类型未知","yieldFromIllegal":"使用“yield from”需要 Python 3.3 或更高版本","yieldFromOutsideAsync":"异步函数中不允许使用“yield from”","yieldOutsideFunction":"不允许在函数或 lambda 之外使用“yield”","yieldWithinListCompr":"不允许在列表理解中使用“yield”","zeroCaseStatementsFound":"Match 语句必须至少包含一个 case 语句","zeroLengthTupleNotAllowed":"此上下文中不允许使用零长度元组"},"DiagnosticAddendum":{"annotatedNotAllowed":"“已批注”特殊窗体不能与实例和类检查一起使用","argParam":"参数对应于参数“{paramName}”","argParamFunction":"参数对应于函数“{functionName}”中的参数“{paramName}”","argsParamMissing":"参数“*{paramName}”没有相应的参数","argsPositionOnly":"仅位置参数不匹配；应为 {expected}，但收到 {received}","argumentType":"参数类型为“{type}”","argumentTypes":"参数类型:({types})","assignToNone":"无法将类型分配给类型“None”","asyncHelp":"是否表示“async with”?","baseClassIncompatible":"基类“{baseClass}”与类型“{type}”不兼容","baseClassIncompatibleSubclass":"基类“{baseClass}”派生自与类型“{type}”不兼容的“{subclass}”","baseClassOverriddenType":"基类\\"{baseClass}\\"提供被替代的类型\\"{type}\\"","baseClassOverridesType":"基类“{baseClass}”替代类型{type}”","bytesTypePromotions":"将 disableBytesTypePromotions 设置为 false，以启用“bytearray”和“memoryview”的类型提升行为","conditionalRequiresBool":"类型“{operandType}”的方法__bool__返回类型“{boolReturnType}”而不是“bool”","dataClassFieldLocation":"字段声明","dataClassFrozen":"\\"{name}\\"已冻结","dataProtocolUnsupported":"“{name}”是数据协议","descriptorAccessBindingFailed":"无法绑定描述符类“{className}”的方法“{name}”","descriptorAccessCallFailed":"无法为描述符类“{className}”调用方法“{name}”","finalMethod":"Final 方法","functionParamDefaultMissing":"参数“{name}”缺少默认参数","functionParamName":"参数名称不匹配: \\"{destName}\\" versus \\"{srcName}\\"","functionParamPositionOnly":"仅位置参数不匹配; 参数“{name}”并非仅限位置","functionReturnTypeMismatch":"函数返回类型\\"{sourceType}\\"与类型\\"{destType}\\"不兼容","functionTooFewParams":"函数接受的位置参数太少；应为 {expected}，但收到 {received}","functionTooManyParams":"函数接受太多位置参数；应为 {expected}，但收到 {received}","genericClassNotAllowed":"不允许对实例或类检查使用具有类型参数的泛型类型","incompatibleDeleter":"属性deleter 方法不兼容","incompatibleGetter":"属性 getter 方法不兼容","incompatibleSetter":"属性 setter 方法不兼容","initMethodLocation":"__init__方法已在类“{type}”中定义","initMethodSignature":"__init__的签名为“{type}”","initSubclassLocation":"__init_subclass__ 方法在类“{name}”中定义","invariantSuggestionDict":"请考虑从 “dict” 切换到 “Mapping”(在值类型中为协变)","invariantSuggestionList":"考虑从“list”切换到“Sequence”(协变)","invariantSuggestionSet":"请考虑从“set”切换到“Container”，后者是协变的","keyNotRequired":"“{type}”中“{name}”不是必需的密钥，因此访问可能会导致运行时异常","keyReadOnly":"“{name}”是“{type}”中的只读密钥","keyRequiredDeleted":"“{name}”是必需的密钥，无法删除","keyUndefined":"“{name}”不是“{type}”中定义的密钥","kwargsParamMissing":"参数“**{paramName}”没有相应的参数","listAssignmentMismatch":"类型“{type}”与目标列表不兼容","literalAssignmentMismatch":"无法将“{sourceType}”分配给类型“{destType}”","matchIsNotExhaustiveHint":"如果未进行详尽处理，请添加\\"case _: pass\\"","matchIsNotExhaustiveType":"未处理的类型: \\"{type}\\"","memberAssignment":"无法将\\"{type}\\"类型的表达式分配给类\\"{classType}\\"的成员\\"{name}\\"","memberIsAbstract":"未实现“{type}.{name}”","memberIsAbstractMore":"还有 {count} 个...","memberIsClassVarInProtocol":"“{name}”在协议中定义为 ClassVar","memberIsFinalInProtocol":"\\"{name}\\"在协议中标记为 Final","memberIsInitVar":"成员“{name}”是仅初始字段","memberIsInvariant":"“{name}”是固定的，因为它是可变的","memberIsNotClassVarInClass":"“{name}”必须定义为 ClassVar 才能与协议兼容","memberIsNotClassVarInProtocol":"“{name}”未在协议中定义为 ClassVar","memberIsNotFinalInProtocol":"“{name}”未在协议中标记为 Final","memberIsWritableInProtocol":"“{name}”在协议中是可写入的","memberSetClassVar":"无法通过类实例分配成员“{name}”，因为它是 ClassVar","memberTypeMismatch":"\\"{name}\\"是不兼容的类型","memberUnknown":"成员\\"{name}\\"未知","metaclassConflict":"元类“{metaclass1}”与“{metaclass2}”存在冲突","missingDeleter":"缺少属性 deleter方法","missingGetter":"缺少属性 getter 方法","missingSetter":"缺少属性 setter 方法","namedParamMissingInDest":"源中缺少关键字参数 \\"{name}\\"","namedParamMissingInSource":"源中缺少关键字参数“{name}”","namedParamTypeMismatch":"无法将\\"{sourceType}\\"类型的关键字参数\\"{name}\\"分配给类型\\"{destType}\\"","namedTupleNotAllowed":"不能对实例或类检查使用 NamedTuple","newMethodLocation":"__new__方法已在类“{type}”中定义","newMethodSignature":"__new__的签名为“{type}”","newTypeClassNotAllowed":"不能将使用 NewType 创建的类用于实例和类检查","noOverloadAssignable":"没有重载函数与类型“{type}”匹配","noneNotAllowed":"不能对实例或类检查使用 None","orPatternMissingName":"缺少名称: {name}","overloadIndex":"重载 {index} 是最接近的匹配项","overloadNotAssignable":"无法分配“{name}”的一个或多个重载","overloadSignature":"此处定义了重载签名","overriddenMethod":"替代的方法","overriddenSymbol":"替代符号","overrideInvariantMismatch":"替代类型“{overrideType}”与基类型“{baseType}”不同","overrideIsInvariant":"变量是可变的，因此其类型是固定的","overrideNoOverloadMatches":"替代中没有与基本方法兼容的重载签名","overrideNotClassMethod":"基方法声明为 classmethod，但替代不是","overrideNotInstanceMethod":"基方法声明为实例方法，但替代不是","overrideNotStaticMethod":"基方法声明为 staticmethod，但替代不是","overrideOverloadNoMatch":"替代不处理基方法的所有重载","overrideOverloadOrder":"替代方法的重载必须与基方法的顺序相同","overrideParamKeywordNoDefault":"关键字参数\\"{name}\\"不匹配: 基参数具有默认参数值，替代参数不匹配","overrideParamKeywordType":"关键字参数“{name}”类型不匹配: 基参数是类型“{baseType}”，替代参数为类型“{overrideType}”","overrideParamName":"参数{index}名称不匹配: 基参数命名为 \\"{baseName}\\"，替代参数命名为 \\"{overrideName}\\"","overrideParamNameExtra":"基数中缺少参数“{name}”","overrideParamNameMissing":"替代中缺少参数“{name}”","overrideParamNamePositionOnly":"参数 {index} 不匹配: 基参数“{baseName}”是关键字参数，替代参数为仅位置参数","overrideParamNoDefault":"参数 {index} 不匹配: 基参数具有默认参数值，替代参数不匹配","overrideParamType":"参数 {index} 类型不匹配: 基参数为类型“{baseType}”，替代参数为类型“{overrideType}”","overridePositionalParamCount":"位置参数计数不匹配；基方法具有 {baseCount}，但替代具有 {overrideCount}","overrideReturnType":"返回类型不匹配:基方法返回类型\\"{baseType}\\"，替代返回类型\\"{overrideType}\\"","overrideType":"基类将类型定义为\\"{type}\\"","paramAssignment":"参数 {index}: 无法将类型“{sourceType}”分配给类型“{destType}”","paramSpecMissingInOverride":"替代方法中缺少 ParamSpec 参数","paramType":"参数类型为“{paramType}”","privateImportFromPyTypedSource":"改为从\\"{module}\\"导入","propertyAccessFromProtocolClass":"不能以类变量形式存取协议类中定义的属性","propertyMethodIncompatible":"属性方法\\"{name}\\"不兼容","propertyMethodMissing":"替代中缺少属性方法“{name}”","propertyMissingDeleter":"属性“{name}”没有定义的删除程序","propertyMissingSetter":"属性“{name}”没有定义的资源库","protocolIncompatible":"“{sourceType}”与协议“{destType}”不兼容","protocolMemberMissing":"“{name}”不存在","protocolRequiresRuntimeCheckable":"协议类必须为 @runtime_checkable 才能用于实例和类检查","protocolSourceIsNotConcrete":"“{sourceType}”不是具体类类型，无法分配给类型“{destType}”","protocolUnsafeOverlap":"“{name}”的属性与协议具有相同的名称","pyrightCommentIgnoreTip":"使用 \\"# pyright: ignore[<diagnostic rules>] 取消单行诊断","readOnlyAttribute":"属性“{name}”为只读","seeClassDeclaration":"查看类声明","seeDeclaration":"参见声明","seeFunctionDeclaration":"请参阅函数声明","seeMethodDeclaration":"请参阅方法声明","seeParameterDeclaration":"请参阅参数声明","seeTypeAliasDeclaration":"请参阅类型别名声明","seeVariableDeclaration":"查看变量声明","tupleAssignmentMismatch":"类型\\"{type}\\"与目标元组不兼容","tupleEntryTypeMismatch":"元组条目 {entry} 的类型不正确","tupleSizeIndeterminateSrc":"元组大小不匹配；应为 {expected}，但收到不确定的","tupleSizeIndeterminateSrcDest":"元组大小不匹配；应为 {expected} 或更多，但收到不确定的值","tupleSizeMismatch":"元组大小不匹配；应为 {expected}，但收到 {received}","tupleSizeMismatchIndeterminateDest":"元组大小不匹配；应为 {expected} 或更多，但收到 {received}","typeAliasInstanceCheck":"使用 \\"type\\" 语句创建的类型别名不能与实例和类检查一起使用","typeAssignmentMismatch":"无法将类型“{sourceType}”分配给类型“{destType}”","typeBound":"类型\\"{sourceType}\\"与类型变量\\"{destType}\\"的绑定类型\\"{name}\\"不兼容","typeConstrainedTypeVar":"类型\\"{type}\\"与受约束的类型变量\\"{name}\\"不兼容","typeIncompatible":"“{sourceType}”与“{destType}”不兼容","typeNotClass":"“{type}”不是类","typeNotStringLiteral":"“{type}”不是字符串文本","typeOfSymbol":"“{name}”的类型为“{type}”","typeParamSpec":"类型“{type}”与 ParamSpec“{name}”不兼容","typeUnsupported":"类型“{type}”不受支持","typeVarDefaultOutOfScope":"类型变量“{name}”不在范围内","typeVarIsContravariant":"类型参数 \\"{name}\\" 是逆变的，但 \\"{sourceType}\\" 不是 \\"{destType}\\" 的超类型","typeVarIsCovariant":"类型参数 \\"{name}\\" 是协变的，但 \\"{sourceType}\\" 不是 \\"{destType}\\" 的子类型","typeVarIsInvariant":"类型参数 \\"{name}\\" 是固定的，但 \\"{sourceType}\\" 与 \\"{destType}\\" 不同","typeVarNotAllowed":"不允许对实例或类检查使用 TypeVar","typeVarTupleRequiresKnownLength":"TypeVarTuple 不能绑定到长度未知的元组","typeVarUnnecessarySuggestion":"请改用 {type}","typeVarUnsolvableRemedy":"提供一个重载，该重载指定未提供参数时的返回类型","typeVarsMissing":"缺少类型变量: {names}","typedDictBaseClass":"类“{type}”不是 TypedDict","typedDictClassNotAllowed":"不允许对实例或类检查使用 TypedDict 类","typedDictClosedExtraNotAllowed":"无法添加项“{name}”","typedDictClosedExtraTypeMismatch":"无法添加类型为“{type}”的项“{name}”","typedDictClosedFieldNotRequired":"无法添加项“{name}”，因为它必须是 NotRequired","typedDictExtraFieldNotAllowed":"“{type}”中不存在“{name}”","typedDictExtraFieldTypeMismatch":"“{name}”的类型与“{type}”中的 “__extra_items__” 类型不兼容","typedDictFieldMissing":"\\"{type}\\"中缺少\\"{name}\\"","typedDictFieldNotReadOnly":"\\"{name}\\"在\\"{type}\\"中不是只读的","typedDictFieldNotRequired":"“{type}”中不需要“{name}”","typedDictFieldRequired":"\\"{type}\\"中需要\\"{name}\\"","typedDictFieldTypeMismatch":"类型“{type}”不可分配给项“{name}”","typedDictFieldUndefined":"“{name}”是类型“{type}”中的未定义项","typedDictFinalMismatch":"\\"{sourceType}\\"与\\"{destType}\\"不兼容，因为@final不匹配","typedDictKeyAccess":"使用 [\\"{name}\\"] 引用 TypedDict 中的项","typedDictNotAllowed":"不能对实例或类检查使用 TypedDict","unhashableType":"类型“{type}”不可哈希","uninitializedAbstractVariable":"实例变量“{name}”在抽象基类“{classType}”中定义，但未初始化","unreachableExcept":"“{exceptionType}”是“{parentType}”的子类","useDictInstead":"使用 Dict[T1, T2] 指示字典类型","useListInstead":"使用 List[T] 指示列表类型或 Union[T1, T2] 以指示联合类型","useTupleInstead":"使用 tuple[T1, ..., Tn] 指示元组类型或使用 Union[T1, T2] 指示联合类型","useTypeInstead":"改用类型[T]","varianceMismatchForClass":"类型参数\\"{typeVarName}\\"的差异与基类\\"{className}\\"不兼容","varianceMismatchForTypeAlias":"类型参数\\"{typeVarName}\\"的差异与\\"{typeAliasParam}\\"不兼容"}}');

/***/ }),

/***/ "../pyright-internal/src/localization/package.nls.zh-tw.json":
/*!*******************************************************************!*\
  !*** ../pyright-internal/src/localization/package.nls.zh-tw.json ***!
  \*******************************************************************/
/***/ ((module) => {

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"CodeAction":{"createTypeStub":"建立類型虛設常式","createTypeStubFor":"建立 \\"{moduleName}\\" 的類型虛設常式","executingCommand":"執行命令","filesToAnalyzeCount":"要分析的 {count} 個檔案","filesToAnalyzeOne":"1 個要分析的檔案","findingReferences":"尋找參考","organizeImports":"整理匯入","renameShadowedFile":"將 \\"{oldFile}\\" 重新命名為 \\"{newFile}\\""},"Completion":{"autoImportDetail":"自動匯入","indexValueDetail":"索引值"},"Diagnostic":{"abstractMethodInvocation":"無法呼叫方法 \\"{method}\\"，因為它是抽象且未執行","annotatedParamCountMismatch":"參數註釋計數不符: 應為 {expected}，但收到 {received}","annotatedTypeArgMissing":"預期 \\"Annotated\\" 有一個類型引數和一或多個註釋","annotationFormatString":"類型註釋不能使用格式字串常值 (f-strings)","annotationNotSupported":"此陳述式不支援類型註釋","annotationSpansStrings":"型別註釋無法跨越多個字串常值","annotationStringEscape":"型別註釋不可包含逸出字元","argAssignment":"類型 \\"{argType}\\" 的引數不能指派至類型 \\"{paramType}\\" 的參數","argAssignmentFunction":"類型 \\"{argType}\\" 的引數不能指派至函式 \\"{functionName}\\" 中類型 \\"{paramType}\\" 的參數","argAssignmentParam":"類型 \\"{argType}\\" 的引數不能指派至類型 \\"{paramType}\\" 的參數 \\"{paramName}\\"","argAssignmentParamFunction":"類型 \\"{argType}\\" 的引數不能指派至函式 \\"{functionName}\\" 中類型 \\"{paramType}\\" 的參數 \\"{paramName}\\"","argMissingForParam":"參數 {name} 遺漏引數","argMissingForParams":"參數 {names} 的引數遺失","argMorePositionalExpectedCount":"預期有另 {expected} 個位置引數","argMorePositionalExpectedOne":"預期有另 1 個位置引數","argPositional":"預期為位置引數","argPositionalExpectedCount":"預期有 {expected} 個位置引數","argPositionalExpectedOne":"預期為 1 個位置引數","argTypePartiallyUnknown":"引數型別為部分未知","argTypeUnknown":"引數類型未知","assertAlwaysTrue":"Assert 運算式一律會評估為 true","assertTypeArgs":"\\"assert_type\\" 需要兩個位置引數","assertTypeTypeMismatch":"\\"assert_type\\" 不符: 預期為 \\"{expected}\\"，但收到 \\"{received}\\"","assignmentExprComprehension":"指派運算式目標 \\"{name}\\" 不能使用與目標 comprehension 相同的名稱","assignmentExprContext":"Assignment 運算式必須在模組、函式或 Lambda 內","assignmentExprInSubscript":"下標內的 Assignment 運算式僅在 Python 3.10 和更新版本中支援","assignmentInProtocol":"必須在類別主體內明確宣告通訊協定類別內的執行個體或類別變數","assignmentTargetExpr":"運算式不能是指派目標","asyncNotInAsyncFunction":"不允許在非同步函式之外使用 \\"async\\"","awaitIllegal":"使用 \\"await\\" 需要 Python 3.5 或更新版本","awaitNotAllowed":"類型註釋不能使用 “await”","awaitNotInAsync":"只在非同步函式內允許 \\"await\\"","backticksIllegal":"Python 3.x 中不支援以反引號括住的運算式; 請改為使用 repr","baseClassCircular":"類別無法從本身衍生","baseClassFinal":"基底類別 \\"{type}\\" 標示為 Final，且不能設為子類別","baseClassIncompatible":"{type} 的基底類別互不相容","baseClassInvalid":"類別的引數必須是基底類別","baseClassMethodTypeIncompatible":"類別 \\"{classType}\\" 的基底類別以不相容的方式定義方法 \\"{name}\\"","baseClassUnknown":"基底類別類型未知，遮蔽衍生類別的類型","baseClassVariableTypeIncompatible":"類別 \\"{classType}\\" 的基底類別以不相容的方式定義變數 \\"{name}\\"","binaryOperationNotAllowed":"類型註釋中不允許二元運算子","bindTypeMismatch":"無法繫結方法 \\"{methodName}\\"，因為 \\"{type}\\" 無法指派給參數 \\"{paramName}\\"","breakOutsideLoop":"\\"break\\" 只能在迴圈內使用","callableExtraArgs":"預期 \\"Callable\\" 只有兩個類型引數","callableFirstArg":"預期為參數類型清單或 \\"...\\"","callableNotInstantiable":"不能具現化類型 \\"{type}\\"","callableSecondArg":"預期為傳回類型作為 \\"Callable\\" 的第二個類型引數","casePatternIsIrrefutable":"僅允許最後一個案例陳述式使用無法推翻的模式","classAlreadySpecialized":"類型 \\"{type}\\" 已特殊化","classDecoratorTypeUnknown":"不具型別的類別裝飾項目會掩蓋類別的型別; 略過裝飾項目","classDefinitionCycle":"\\"{name}\\" 的類別定義視其本身而定","classGetItemClsParam":"__class_getitem__ 覆寫應接受 \\"cls\\" 參數","classMethodClsParam":"類別方法應採用 \\"cls\\" 參數","classNotRuntimeSubscriptable":"類別 \\"{name}\\" 的下標會產生執行階段例外; 以引號括住類型註釋","classPatternBuiltInArgPositional":"類別模式僅接受位置子模式","classPatternPositionalArgCount":"類別 \\"{type}\\" 的位置模式太多;預期 {expected} 但收到 {received}","classPatternTypeAlias":"無法在類別模式中使用 \\"{type}\\"，因為它是特殊的型別別名","classPropertyDeprecated":"類別屬性在 Python 3.11 中已取代，在 Python 3.13 中將不受支援","classTypeParametersIllegal":"類別類型參數語法需要 Python 3.12 或更新版本","classVarFirstArgMissing":"\\"ClassVar\\" 後面應有一個型別引數","classVarNotAllowed":"此內容中不允許 \\"ClassVar\\"","classVarOverridesInstanceVar":"類別變數 \\"{name}\\" 會覆寫類別 \\"{className}\\" 中相同名稱的執行個體變數","classVarTooManyArgs":"\\"ClassVar\\" 後面應只能有一個型別引數","classVarWithTypeVar":"\\"ClassVar\\" 型別不能包含型別變數","clsSelfParamTypeMismatch":"參數 \\"{name}\\" 的型別必須是其類別 \\"{classType}\\" 的超級型別","codeTooComplexToAnalyze":"程式碼太複雜而無法分析; 重構為副常式或減少條件式程式碼路徑，以降低複雜性","collectionAliasInstantiation":"無法將型別 \\"{type}\\" 具現化，請改用 \\"{alias}\\"","comparisonAlwaysFalse":"條件一律會評估為 False，因為類型 \\"{leftType}\\" 和 \\"{rightType}\\" 沒有重疊","comparisonAlwaysTrue":"條件一律會評估為 True，因為類型 \\"{leftType}\\" 和 \\"{rightType}\\" 沒有重疊","comprehensionInDict":"理解不能與其他字典項目搭配使用","comprehensionInSet":"Comprehension 無法與其他集合輸入項目一起使用","concatenateContext":"此內容中不允許 \\"Concatenate\\"","concatenateParamSpecMissing":"\\"Concatenate\\" 的最後一個類型引數必須是 ParamSpec 或 \\"...\\"","concatenateTypeArgsMissing":"\\"Concatenate\\" 至少需要兩個型別引數","conditionalOperandInvalid":"型別 \\"{type}\\" 的條件運算元無效","constantRedefinition":"\\"{name}\\" 是常數 (因為它是大寫) 且無法重新定義","constructorNoArgs":"預期 \\"{type}\\" 建構函式沒有引數","constructorParametersMismatch":"類別 \\"{classType}\\" 中__new__與__init__的簽章不相符","containmentAlwaysFalse":"運算式一律會評估為 False，因為型別 \\"{leftType}\\" 和 \\"{rightType}\\" 沒有重疊","containmentAlwaysTrue":"運算式一律會評估為 True，因為型別 \\"{leftType}\\" 和 \\"{rightType}\\" 沒有重疊","continueInFinally":"\\"continue\\" 不能在 finally 子句內使用","continueOutsideLoop":"\\"continue\\" 只能在 loop 內使用","coroutineInConditionalExpression":"條件運算式參考協同程式，一律評估為 True","dataClassBaseClassFrozen":"未凍結的類別無法繼承已凍結的類別","dataClassBaseClassNotFrozen":"凍結的類別不能從未凍結的類別繼承","dataClassConverterFunction":"類型 \\"{argType}\\" 的引數不是類型 \\"{fieldType}\\" 欄位 \\"{fieldName}\\" 的有效轉換程式","dataClassConverterOverloads":"\\"{funcName}\\" 沒有任何多載是類型 \\"{fieldType}\\" 欄位 \\"{fieldName}\\" 的有效轉換程式","dataClassFieldWithDefault":"沒有預設值的欄位無法出現在具有預設值的欄位後面","dataClassFieldWithPrivateName":"Dataclass 欄位不能使用私人名稱","dataClassFieldWithoutAnnotation":"沒有型別註釋的 Dataclass 欄位會造成執行階段例外狀況","dataClassPostInitParamCount":"Dataclass __post_init__ 不正確的參數計數; InitVar 欄位數目為 {expected}","dataClassPostInitType":"欄位 \\"{fieldName}\\" 的 Dataclass __post_init__ 方法參數類型不符","dataClassSlotsOverwrite":"__slots__已定義在類別中","dataClassTransformExpectedBoolLiteral":"應為靜態評估為 True 或 False 的運算式","dataClassTransformFieldSpecifier":"應為類別或函式的元組，但收到的型別為 \\"{type}\\"","dataClassTransformPositionalParam":"\\"dataclass_transform\\" 的所有引數都必須是關鍵字引數","dataClassTransformUnknownArgument":"dataclass_transform 不支援引數 \\"{name}\\"","dataProtocolInSubclassCheck":"issubclass 呼叫中不允許資料通訊協定 (包含非方法屬性)","declaredReturnTypePartiallyUnknown":"宣告的傳回類型 \\"{returnType}\\" 部分未知","declaredReturnTypeUnknown":"宣告的傳回類型未知","defaultValueContainsCall":"參數預設值運算式內不允許函式呼叫和可變物件","defaultValueNotAllowed":"具有 \\"*\\" 或 \\"**\\" 的參數不能有預設值","delTargetExpr":"無法刪除運算式","deprecatedClass":"類別 \\"{name}\\" 已淘汰","deprecatedConstructor":"類別 \\"{name}\\" 的建構函式已取代","deprecatedDescriptorDeleter":"描述項 \\"{name}\\" 的 \\"__delete__\\" 方法已被取代","deprecatedDescriptorGetter":"描述項 \\"{name}\\" 的 \\"__get__\\" 方法已被取代","deprecatedDescriptorSetter":"描述項 \\"{name}\\" 的 \\"__set__\\" 方法已被取代","deprecatedFunction":"函式 \\"{name}\\" 已取代","deprecatedMethod":"類別 \\"{className}\\" 中的方法 \\"{name}\\" 已取代","deprecatedPropertyDeleter":"屬性 \\"{name}\\" 的 deleter 已被取代","deprecatedPropertyGetter":"屬性 \\"{name}\\" 的 getter 已被取代","deprecatedPropertySetter":"屬性 \\"{name}\\" 的 setter 已被取代","deprecatedType":"此類型已隨著 Python {version} 取代; 請改為使用 \\"{replacement}\\"","dictExpandIllegalInComprehension":"理解中不允許字典擴充","dictInAnnotation":"類型註釋中不允許字典運算式","dictKeyValuePairs":"字典項目必須包含金鑰/值組","dictUnpackIsNotMapping":"預期為字典解壓縮運算子的對應","dunderAllSymbolNotPresent":"\\"{name}\\" 已在 __all__ 中指定，但在模組中不存在","duplicateArgsParam":"只允許一個 \\"*\\" 參數","duplicateBaseClass":"不允許重複的基底類別","duplicateCapturePatternTarget":"擷取目標 \\"{name}\\" 不能在相同模式中出現一次以上","duplicateCatchAll":"只允許一個 catch-all 例外子句","duplicateEnumMember":"已宣告列舉成員 \\"{name}\\"","duplicateGenericAndProtocolBase":"只允許一個 Generic[...] 或 Protocol[...] 基底類別","duplicateImport":"\\"{importName}\\" 已匯入多次","duplicateKeywordOnly":"只允許一個 \\"*\\" 分隔符號","duplicateKwargsParam":"只允許一個 \\"**\\" 參數","duplicateParam":"重複的參數 \\"{name}\\"","duplicatePositionOnly":"僅允許一個 \\"/\\" 參數","duplicateStarPattern":"模式序列中僅允許一個 \\"*\\" 模式","duplicateStarStarPattern":"僅允許輸入一個 \\"**\\"","duplicateUnpack":"清單中僅允許一個解除封裝作業","ellipsisAfterUnpacked":"\\"...\\" 不能與解壓縮的 TypeVarTuple 或 tuple 一起使用","ellipsisContext":"此內容中不允許 \\"...\\"","ellipsisSecondArg":"\\"...\\" 只允許做為兩個引數的第二個","enumClassOverride":"列舉類別 \\"{name}\\" 為 Final，且不能設為子類別","exceptionGroupIncompatible":"例外群組語法 (\\"except*\\") 需要 Python 3.11 或更新版本","exceptionTypeIncorrect":"\\"{type}\\" 不是衍生自 BaseException","exceptionTypeNotClass":"\\"{type}\\" 不是有效的例外類別","exceptionTypeNotInstantiable":"例外類型 \\"{type}\\" 的建構函式需要一或多個引數","expectedAfterDecorator":"裝飾項目後面應有函式或類別宣告","expectedArrow":"預期為 \\"->\\"，後面接著傳回類型註釋","expectedAsAfterException":"例外狀況型別後面應有 \\"as\\"","expectedAssignRightHandExpr":"\\"=\\" 右側預期為運算式","expectedBinaryRightHandExpr":"運算子右側預期為運算式","expectedBoolLiteral":"應為 True 或 False","expectedCase":"預期為 \\"case\\" 陳述式","expectedClassName":"預期為類別名稱","expectedCloseBrace":"\\"{\\" 未關閉","expectedCloseBracket":"\\"[\\" 未關閉","expectedCloseParen":"\\"(\\" 未關閉","expectedColon":"預期為 \\":\\"","expectedComplexNumberLiteral":"模式比對預期為複數常值","expectedDecoratorExpr":"Python 3.9 之前的裝飾項目不支援運算式格式","expectedDecoratorName":"預期為裝飾項目名稱","expectedDecoratorNewline":"預期裝飾項目結尾為換行符號","expectedDelExpr":"\\"del\\" 後預期為運算式","expectedElse":"預期為 \\"else\\"","expectedEquals":"預期為 \\"=\\"","expectedExceptionClass":"不正確的例外狀況類別或物件","expectedExceptionObj":"預期為例外物件、例外類別或 None","expectedExpr":"應為運算式","expectedFunctionAfterAsync":"\\"async\\" 後面應有函式定義","expectedFunctionName":"\\"def\\" 後預期為函式名稱","expectedIdentifier":"應為識別碼","expectedImport":"預期為 \\"import\\"","expectedImportAlias":"\\"as\\" 之後預期為符號","expectedImportSymbols":"預期匯入後為一或多個符號名稱","expectedIn":"預期為 \\"in\\"","expectedInExpr":"\\"in\\" 後預期為運算式","expectedIndentedBlock":"預期為縮排區塊","expectedMemberName":"\\".\\" 後預期為成員名稱。","expectedModuleName":"應為模組名稱","expectedNameAfterAs":"\\"as\\" 後面應有符號名稱","expectedNamedParameter":"關鍵字參數必須接著 \\"*\\"","expectedNewline":"預期為換行符號","expectedNewlineOrSemicolon":"陳述式必須以換行符號或分號分隔","expectedOpenParen":"應為 \\"(\\"","expectedParamName":"預期為參數名稱","expectedPatternExpr":"預期為模式運算式","expectedPatternSubjectExpr":"應為模式主體運算式","expectedPatternValue":"預期為格式 \\"a.b\\" 的模式值運算式","expectedReturnExpr":"\\"return\\" 後預期為運算式","expectedSliceIndex":"應為索引或切片運算式","expectedTypeNotString":"預期為類型，但收到字串常值","expectedTypeParameterName":"應為型別參數名稱","expectedYieldExpr":"yield 陳述式中應有運算式","finalClassIsAbstract":"類別 \\"{type}\\" 標示為 Final，且必須實作所有抽象符號","finalContext":"此內容中不允許 \\"Final\\"","finalMethodOverride":"方法 \\"{name}\\" 不能覆寫類別 \\"{className}\\" 中定義的 Final 方法","finalNonMethod":"無法將函式 \\"{name}\\" 標示為 @final，因為它不是方法","finalReassigned":"\\"{name}\\" 已宣告為 Final，因此無法重新指派","finalRedeclaration":"\\"{name}\\" 先前已宣告為 Final","finalRedeclarationBySubclass":"不能重新宣告 \\"{name}\\"，因為父類別 \\"{className}\\" 將其宣告為 Final","finalTooManyArgs":"預期 \\"Final\\" 之後為單一類型引數","finalUnassigned":"\\"{name}\\" 宣告為 Final，但未指派值","formatStringBrace":"F 字串常值內不允許單一右大括弧; 請使用雙右大括弧","formatStringBytes":"格式字串常值 (f-strings) 不可為二進位","formatStringDebuggingIllegal":"F 字串偵錯指定名稱 \\"=\\" 需要 Python 3.8 或較新的版本","formatStringEscape":"Python 3.12 之前的 f 字串運算式部分不允許逸出序列 (反斜線)","formatStringExpectedConversion":"預期 f-string 中的 \\"!\\" 後為轉換指定元","formatStringIllegal":"格式字串常值 (f-strings) 需要 Python 3.6 或較新的版本","formatStringInPattern":"模式中不允許格式字串","formatStringNestedFormatSpecifier":"運算式在格式字串指定元內巢狀太深","formatStringNestedQuote":"f 字串內的巢狀字串無法使用與 Python 3.12 之前的 f 字串相同的引號字元","formatStringUnicode":"格式字串常值 (f-strings) 不能是 Unicode","formatStringUnterminated":"f 字串中有未結束的運算式; 應有 \\"}\\"","functionDecoratorTypeUnknown":"非類型化函式修飾項目會遮蔽函式的類型; 忽略裝飾項目","functionInConditionalExpression":"條件運算式參考函式，一律評估為 True","functionTypeParametersIllegal":"函式型別參數語法需要 Python 3.12 或較新的版本","futureImportLocationNotAllowed":"來自 __future__ 的匯入必須位於檔案的開頭","generatorAsyncReturnType":"非同步產生器函式的傳回類型必須與 \\"AsyncGenerator[{yieldType}, Any]\\" 相容","generatorNotParenthesized":"如果不是唯一引數，則必須將產生器運算式用括弧括住","generatorSyncReturnType":"產生器函式的傳回類型必須與 \\"Generator[{yieldType}, Any, Any]\\" 相容","genericBaseClassNotAllowed":"\\"Generic\\" 基底類別不能與型別參數語法一起使用","genericClassAssigned":"不能指派一般類別類型","genericClassDeleted":"無法刪除一般類別型別","genericInstanceVariableAccess":"透過類別存取泛型執行個體變數不明確","genericNotAllowed":"\\"Generic\\" 在此內容中無效","genericTypeAliasBoundTypeVar":"類別內的一般類型別名不能使用繫結類型變數 {names}","genericTypeArgMissing":"\\"Generic\\" 至少需要一個類型引數","genericTypeArgTypeVar":"\\"Generic\\" 的類型引數必須是類型變數","genericTypeArgUnique":"\\"Generic\\" 的類型引數必須是唯一的","globalReassignment":"\\"{name}\\" 在 global 宣告之前指派","globalRedefinition":"\\"{name}\\" 已宣告為 global","implicitStringConcat":"不允許隱含字串串連","importCycleDetected":"在匯入鏈結中偵測到迴圈","importDepthExceeded":"匯入鏈結深度超過 {depth}","importResolveFailure":"無法解析匯入 \\"{importName}\\"","importSourceResolveFailure":"無法從來源解析匯入 \\"{importName}\\"","importSymbolUnknown":"\\"{name}\\" 是未知的匯入符號","incompatibleMethodOverride":"方法 \\"{name}\\" 會以不相容的方式覆寫類別 \\"{className}\\"","inconsistentIndent":"取消縮排量與先前縮排不符","inconsistentTabs":"在縮排中使用 Tab 字元和空格不一致","initMustReturnNone":"\\"__init__\\" 的傳回類型必須為 None","initSubclassCallFailed":"__init_subclass__ 方法不正確的關鍵字引數","initSubclassClsParam":"__init_subclass__ 覆寫應接受 \\"cls\\" 參數","initVarNotAllowed":"此內容中不允許 \\"InitVar\\"","instanceMethodSelfParam":"執行個體方法應該採用 \\"self\\" 參數","instanceVarOverridesClassVar":"執行個體變數 \\"{name}\\" 覆寫類別 \\"{className}\\" 中相同名稱的類別變數","instantiateAbstract":"無法將抽象類別 \\"{type}\\" 具現化","instantiateProtocol":"無法將通訊協定類別 \\"{type}\\" 具現化","internalBindError":"繫結檔案 \\"{file}\\" 時發生內部錯誤: {message}","internalParseError":"剖析檔案 \\"{file}\\" 時發生內部錯誤: {message}","internalTypeCheckingError":"類型檢查檔案 \\"{file}\\" 時發生內部錯誤: {message}","invalidIdentifierChar":"識別碼中的字元無效","invalidStubStatement":"陳述式在類型虛設常式檔案內沒有意義","invalidTokenChars":"權杖中的字元 \\"{text}\\" 無效","isInstanceInvalidType":"\\"isinstance\\" 的第二個引數必須是類別或類別的元組","isSubclassInvalidType":"\\"issubclass\\" 的第二個引數必須是類別的類別或 Tuple","keyValueInSet":"組合內不允許金鑰/值組","keywordArgInTypeArgument":"關鍵字引數無法用於型別引數清單","keywordOnlyAfterArgs":"\\"*\\" 參數之後不允許僅限關鍵字的引數分隔符號","keywordParameterMissing":"一或多個關鍵字參數必須接在 \\"*\\" 參數後面","keywordSubscriptIllegal":"不支援下標內的關鍵字引數","lambdaReturnTypePartiallyUnknown":"Lambda 的傳回類型 \\"{returnType}\\" 部分未知","lambdaReturnTypeUnknown":"Lambda 的傳回類型未知","listAssignmentMismatch":"類型 \\"{type}\\" 的運算式不能指派至目標清單","listInAnnotation":"類型註釋中不允許清單運算式","literalEmptyArgs":"\\"Literal\\" 後面應有一或多個型別引數","literalNotAllowed":"沒有類型參數，\\"Literal\\" 不能在此內容中使用","literalNotCallable":"常值類型不能具現化","literalUnsupportedType":"\\"Literal\\" 的類型引數必須是 None、常值 (int、bool、str 或 bytes) 或列舉值","matchIncompatible":"比對陳述式需要 Python 3.10 或更新版本","matchIsNotExhaustive":"match 陳述式內的案例並未完整處理所有值","maxParseDepthExceeded":"超過剖析深度上限; 將運算式分成較小的子運算式","memberAccess":"不能存取類型 \\"{type}\\" 的成員 \\"{name}\\"","memberDelete":"不能刪除類型 \\"{type}\\" 的成員 \\"{name}\\"","memberSet":"無法指派型別 \\"{type}\\" 的成員 \\"{name}\\"","metaclassConflict":"衍生類別的變換類型必須是其所有基底類別的變換類型的子類別","metaclassDuplicate":"只能提供一個變換類型","metaclassIsGeneric":"變換類型不能是一般","methodNotDefined":"\\"{name}\\" 方法未定義","methodNotDefinedOnType":"類型 \\"{type}\\" 上未定義 \\"{name}\\" 方法","methodOrdering":"不能建立一致的方法順序","methodOverridden":"\\"{name}\\" 以不相容型別 \\"{type}\\" 覆寫類別 \\"{className}\\" 中具有相同名稱的方法","methodReturnsNonObject":"\\"{name}\\" 方法未傳回物件","missingSuperCall":"方法 \\"{methodName}\\" 未呼叫父類別中相同名稱的方法","moduleAsType":"模組不能當作型別來使用","moduleNotCallable":"模組無法呼叫","moduleUnknownMember":"\\"{memberName}\\" 不是模組 \\"{moduleName}\\" 的已知成員","namedExceptAfterCatchAll":"catch-all except 子句後面不能出現具名 except 子句","namedParamAfterParamSpecArgs":"關鍵字參數 \\"{name}\\" 不能在簽章中出現在 ParamSpec args 參數之後","namedTupleEmptyName":"具名元組內的名稱不可為空白","namedTupleEntryRedeclared":"無法覆寫 \\"{name}\\"，因為父代類別 \\"{className}\\" 是具名的 Tuple","namedTupleFirstArg":"預期為具名 Tuple 類別名稱作為第一個引數","namedTupleMultipleInheritance":"不支援使用 NamedTuple 的多重繼承","namedTupleNameKeyword":"欄位名稱不能是關鍵字","namedTupleNameType":"指定項目名稱和類型預期有兩個項目 Tuple","namedTupleNameUnique":"具名 Tuple 內的名稱必須是唯一的","namedTupleNoTypes":"\\"namedtuple\\" 未提供 Tuple 項目的類型; 請改為使用 \\"NamedTuple\\"","namedTupleSecondArg":"預期為具名 Tuple 項目清單作為第二個引數","newClsParam":"__new__ 覆寫應接受 \\"cls\\" 參數","newTypeAnyOrUnknown":"NewType 的第二個引數必須是已知的類別，不能是 Any 或 Unknown","newTypeBadName":"NewType 的第一個引數必須是字串常值","newTypeLiteral":"NewType 不能與常值類型搭配使用","newTypeNameMismatch":"NewType 必須指派給名稱相同的變數","newTypeNotAClass":"預期類別為 NewType 的第二個引數","newTypeParamCount":"NewType 需要兩個位置引數","newTypeProtocolClass":"NewType 無法與結構類型 (通訊協定或 TypedDict 類別) 搭配使用","noOverload":"\\"{name}\\" 沒有任何多載符合提供的引數","noReturnContainsReturn":"宣告傳回類型為 \\"NoReturn\\" 的函式不能包含 return 陳述式","noReturnContainsYield":"宣告傳回類型為 \\"NoReturn\\" 的函式不能包含 yield 陳述式","noReturnReturnsNone":"宣告類型為 \\"NoReturn\\" 的函式不能傳回 \\"None\\"","nonDefaultAfterDefault":"非預設引數遵循預設引數","nonLocalInModule":"模組層級不允許 nonlocal 宣告","nonLocalNoBinding":"找不到 nonlocal \\"{name}\\" 的繫結","nonLocalReassignment":"\\"{name}\\" 在 nonlocal 宣告之前指派","nonLocalRedefinition":"\\"{name}\\" 已宣告為 nonlocal","noneNotCallable":"無法呼叫型別 \\"None\\" 的物件","noneNotIterable":"類型 \\"None\\" 的物件不能作為可疊代的值","noneNotSubscriptable":"型別 \\"None\\" 的物件不能下標","noneNotUsableWith":"類型 \\"None\\" 的物件不能與 \\"with\\" 搭配使用","noneOperator":"\\"None\\" 不支援運算子 \\"{operator}\\"","noneUnknownMember":"\\"{name}\\" 不是 \\"None\\" 的已知成員","notRequiredArgCount":"預期 \\"NotRequired\\" 之後為單一類型引數","notRequiredNotInTypedDict":"此內容中不允許 \\"NotRequired\\"","objectNotCallable":"類型 \\"{type}\\" 的物件無法呼叫","obscuredClassDeclaration":"類別宣告 \\"{name}\\" 已被相同名稱的宣告遮蔽","obscuredFunctionDeclaration":"函式宣告 \\"{name}\\" 被相同名稱的宣告遮蔽","obscuredMethodDeclaration":"方法宣告 \\"{name}\\" 被相同名稱的宣告遮蔽","obscuredParameterDeclaration":"參數宣告 \\"{name}\\" 被相同名稱的宣告遮蔽","obscuredTypeAliasDeclaration":"類型別名宣告 \\"{name}\\" 被相同名稱的宣告遮蔽","obscuredVariableDeclaration":"宣告 \\"{name}\\" 被相同名稱的宣告遮蔽","operatorLessOrGreaterDeprecated":"Python 3 中不支援運算子 \\"<>\\"; 請改為使用 \\"!=\\"","optionalExtraArgs":"\\"Optional\\" 後面應有一個型別引數","orPatternIrrefutable":"無法推翻的模式僅允許作為 \\"or\\" 模式中的最後一個子模式","orPatternMissingName":"\\"or\\" 模式內的所有子模式都必須以相同的名稱為目標","overlappingKeywordArgs":"輸入的字典與關鍵字參數重疊:: {names}","overlappingOverload":"\\"{name}\\" 的多載 {obscured} 將永遠不會使用，因為它的參數與多載 {obscuredBy} 重疊","overloadAbstractMismatch":"多載方法必須全為抽象或不抽象","overloadClassMethodInconsistent":"\\"{name}\\" 的多載不一致地使用 @classmethod","overloadFinalInconsistencyImpl":"\\"{name}\\" 的多載已標示為 @final 但未實作","overloadFinalInconsistencyNoImpl":"\\"{name}\\" 的多載 {index} 標示為 @final 但多載 1 未標示","overloadImplementationMismatch":"多載的實作與多載 {index} 的簽章不一致","overloadReturnTypeMismatch":"\\"{name}\\" 的多載 {prevIndex} 與多載 {newIndex} 重疊，並傳回不相容的類型","overloadStaticMethodInconsistent":"\\"{name}\\" 的多載不一致地使用 @staticmethod","overloadWithoutImplementation":"\\"{name}\\" 標示為多載，但未提供實作","overriddenMethodNotFound":"方法 \\"{name}\\" 已標示為覆寫，但不存在相同名稱的基底方法","overrideDecoratorMissing":"方法 \\"{name}\\" 未標示為覆寫，但正在覆寫類別 \\"{className}\\" 中的方法","paramAfterKwargsParam":"參數無法接在 \\"**\\" 參數後面","paramAlreadyAssigned":"已指派參數 \\"{name}\\"","paramAnnotationMissing":"參數 \\"{name}\\" 遺漏了型別註釋","paramAssignmentMismatch":"無法將型別 \\"{sourceType}\\" 的運算式指派給型別 \\"{paramType}\\" 的參數","paramNameMissing":"沒有名為 \\"{name}\\" 的參數","paramSpecArgsKwargsUsage":"ParamSpec 的 \\"args\\" 和 \\"kwargs\\" 成員都必須出現在函式簽章內","paramSpecArgsMissing":"ParamSpec \\"{type}\\" 的引數遺失","paramSpecArgsUsage":"只有搭配 *args 參數使用時，ParamSpec 的 \\"args\\" 成員才有效","paramSpecAssignedName":"ParamSpec 必須指派至名為 \\"{name}\\" 的變數","paramSpecContext":"此內容中不允許 ParamSpec","paramSpecDefaultNotTuple":"ParamSpec 的預設值必須是省略符號、元組運算式或 ParamSpec","paramSpecFirstArg":"應以 ParamSpec 的名稱作為第一個引數","paramSpecKwargsUsage":"ParamSpec 的 \\"kwargs\\" 成員只有在與 **kwargs 參數搭配使用時有效","paramSpecNotUsedByOuterScope":"ParamSpec \\"{name}\\" 在此內容中沒有意義","paramSpecScopedToReturnType":"ParamSpec \\"{name}\\" 的範圍為傳回型別內的可呼叫項目，無法在函式主體中參考","paramSpecUnknownArg":"ParamSpec 不支援一個以上的引數","paramSpecUnknownMember":"\\"{name}\\" 不是 ParamSpec 的已知成員","paramSpecUnknownParam":"\\"{name}\\" 對 ParamSpec 是未知的參數","paramTypeCovariant":"不能在參數類型中使用共變數類型變數","paramTypePartiallyUnknown":"參數 \\"{paramName}\\" 的類型部分未知","paramTypeUnknown":"參數 \\"{paramName}\\" 的類型未知","parenthesizedContextManagerIllegal":"\\"with\\" 陳述式內的括弧需要 Python 3.9 或較新的版本","patternNeverMatches":"模式永遠不會符合主體類型 \\"{type}\\"","positionArgAfterNamedArg":"位置引數不能出現在關鍵字引數之後","positionOnlyAfterArgs":"\\"*\\" 參數之後不允許 Position-only 參數分隔符號","positionOnlyAfterKeywordOnly":"\\"/\\" 參數必須出現在 \\"*\\" 參數之前","positionOnlyAfterNon":"非 Position-only 參數之後不允許 Position-only 參數","positionOnlyFirstParam":"不允許 Position-only 參數分隔符號作為第一個參數","positionOnlyIncompatible":"Position-only 參數分隔符號需要 Python 3.8 或更新版本","privateImportFromPyTypedModule":"\\"{name}\\" 未從模組 \\"{module}\\" 匯出","privateUsedOutsideOfClass":"\\"{name}\\" 為私人，並用於宣告其所在的類別之外","privateUsedOutsideOfModule":"\\"{name}\\" 為私人，並用於宣告其所在的模組之外","propertyOverridden":"\\"{name}\\" 不正確地覆寫了類別 \\"{className}\\" 中相同名稱的屬性","propertyStaticMethod":"屬性 getter、setter 或 deleter 不允許靜態方法","protectedUsedOutsideOfClass":"\\"{name}\\" 受到保護，並用於其宣告所在的類別之外","protocolBaseClass":"通訊協定類別 \\"{classType}\\" 不能衍生自非通訊協定類別 \\"{baseType}\\"","protocolBaseClassWithTypeArgs":"使用型別參數語法時，通訊協定類別不允許使用型別引數","protocolIllegal":"使用 \\"Protocol\\" 需要 Python 3.7 或更新版本","protocolNotAllowed":"\\"Protocol\\" 不能用在此內容中","protocolUnsafeOverlap":"類別以不安全方式重疊 \\"{name}\\"，且可能會在運行時間產生相符專案","protocolVarianceContravariant":"一般通訊協定 \\"{class}\\" 中使用的型別變數 \\"{variable}\\" 必須為逆變數","protocolVarianceCovariant":"一般通訊協定 \\"{class}\\" 中使用的型別變數 \\"{variable}\\" 必須為共變數","protocolVarianceInvariant":"一般通訊協定 \\"{class}\\" 中使用的型別變數 \\"{variable}\\" 必須為不變數","pyrightCommentInvalidDiagnosticBoolValue":"Pyright 註解指示詞後面必須接著 \\"=\\"，且值為 true 或 false","pyrightCommentInvalidDiagnosticSeverityValue":"Pyright 註解指示詞後面必須接著 \\"=\\"，且值為 true、false、error、warning、information 或 none","pyrightCommentMissingDirective":"Pyright 註解後面必須接著指示詞 (basic 或 strict) 或診斷規則","pyrightCommentNotOnOwnLine":"用來控制檔案層級設定的 Pyright 註解必須出現在自己的行上","pyrightCommentUnknownDiagnosticRule":"\\"{rule}\\" 是 pyright 註解未知的診斷規則","pyrightCommentUnknownDiagnosticSeverityValue":"\\"{value}\\" 是 pyright 註解無效的值; 預期為 true、false、error、warning、information 或 none","pyrightCommentUnknownDirective":"\\"{directive}\\" 是 pyright 註解未知的指示詞; 預期為 \\"strict\\" 或 \\"basic\\"","readOnlyArgCount":"\\"ReadOnly\\" 後面應有單一型別引數","readOnlyNotInTypedDict":"此內容中不允許 \\"ReadOnly\\"","recursiveDefinition":"無法判斷 \\"{name}\\" 型別，因為它參照了自己","relativeImportNotAllowed":"相對匯入不能與 \\"import .a\\" 格式搭配使用; 請改為使用 \\"from . import a\\"","requiredArgCount":"\\"Required\\" 後面應有單一型別引數","requiredNotInTypedDict":"此內容中不允許 \\"Required\\"","returnInAsyncGenerator":"非同步產生器中不允許具有值的 return 陳述式","returnMissing":"宣告類型為 \\"{returnType}\\" 的函式必須在所有程式碼路徑上傳回值","returnOutsideFunction":"\\"return\\" 只能在函式內使用","returnTypeContravariant":"逆變數型別變數不能用在傳回型別中","returnTypeMismatch":"類型 \\"{exprType}\\" 的運算式不能指派至傳回類型 \\"{returnType}\\"","returnTypePartiallyUnknown":"傳回類型 \\"{returnType}\\" 部分未知","returnTypeUnknown":"傳回類型未知","revealLocalsArgs":"\\"reveal_locals\\" 呼叫不應有任何引數","revealLocalsNone":"此範圍中沒有任何 locals","revealTypeArgs":"\\"reveal_type\\" 呼叫預期為單一位置引數","revealTypeExpectedTextArg":"函式 \\"reveal_type\\" 的 \\"expected_text\\" 引數必須是 str 常值","revealTypeExpectedTextMismatch":"類型文字不符; 預期為 \\"{expected}\\"，但收到 \\"{received}\\"","revealTypeExpectedTypeMismatch":"型別不符; 應為 \\"{expected}\\"，但收到 \\"{received}\\"","selfTypeContext":"\\"Self\\" 在此內容中無效","selfTypeMetaclass":"“Self” 不能用於 Metaclass 内 (“type” 的子類別)","selfTypeWithTypedSelfOrCls":"\\"Self\\" 不能用在具有 `self` 或 `cls` 參數的函式中，其類型註釋不是 \\"Self\\"","setterGetterTypeMismatch":"屬性 setter 數值類型不能指派至 getter 傳回類型","singleOverload":"\\"{name}\\" 標示為多載，但遺失其他多載","slotsAttributeError":"未在__slots__中指定 \\"{name}\\"","slotsClassVarConflict":"\\"{name}\\" 與在 __slots__ 中宣告的執行個體變數衝突","starPatternInAsPattern":"星形模式不能與 \\"as\\" 目標搭配使用","starPatternInOrPattern":"星形模式不能在其他模式內使用 OR","starStarWildcardNotAllowed":"** 不能與萬用字元 \\"_\\" 搭配使用","staticClsSelfParam":"靜態方法不應採用 \\"self\\" 或 \\"cls\\" 參數","stdlibModuleOverridden":"\\"{path}\\" 正在覆寫 stdlib 模組 \\"{name}\\"","stringNonAsciiBytes":"位元組字串常值中不允許非 ASCII 字元","stringNotSubscriptable":"字串運算式不能在類型註釋中下標; 以引號括住整個註釋","stringUnsupportedEscape":"字串常值中不支援的逸出序列","stringUnterminated":"字串常值未結束","stubFileMissing":"找不到 \\"{importName}\\" 的虛設常式檔案","stubUsesGetAttr":"類型虛設常式檔案不完整; \\"__getattr__\\" 會遮蔽模組的類型錯誤","sublistParamsIncompatible":"Python 3.x 不支援子清單參數","superCallArgCount":"\\"super\\" 呼叫不應有兩個以上的引數","superCallFirstArg":"預期的類別類型為 \\"super\\" 呼叫的第一個引數，但收到 \\"{type}\\"","superCallSecondArg":"\\"super\\" 呼叫的第二個引數必須是衍生自 \\"{type}\\" 的物件或類別","superCallZeroArgForm":"\\"super\\" 呼叫的零引數形式只在方法內有效","superCallZeroArgFormStaticMethod":"\\"super\\" 呼叫的零引數形式在靜態方法內無效","symbolIsPossiblyUnbound":"\\"{name}\\" 可能未繫結","symbolIsUnbound":"\\"{name}\\" 未繫結","symbolIsUndefined":"\\"{name}\\" 未定義","symbolOverridden":"\\"{name}\\" 會覆寫類別 \\"{className}\\" 中相同名稱的符號","ternaryNotAllowed":"類型註釋中不允許三元運算式","totalOrderingMissingMethod":"類別必須定義 \\"__lt__\\"、\\"__le__\\"、\\"__gt__\\" 或 \\"__ge__\\" 其中一個，才能使用 total_ordering","trailingCommaInFromImport":"後置逗號不允許未使用括弧","tryWithoutExcept":"Try 陳述式必須至少有一個 except 或 finally 子句","tupleAssignmentMismatch":"無法將型別 \\"{type}\\" 的運算式指派至目標元組","tupleInAnnotation":"型別註釋中不允許元組運算式","tupleIndexOutOfRange":"索引 {index} 超過類型 {type} 的範圍","typeAliasIllegalExpressionForm":"類型別名定義無效的運算式格式","typeAliasIsRecursiveDirect":"型別別名 \\"{name}\\" 無法在其定義中使用它自己","typeAliasNotInModuleOrClass":"TypeAlias 只能在模組或類別範圍內定義","typeAliasRedeclared":"\\"{name}\\" 宣告為 TypeAlias，且只能指派一次","typeAliasStatementBadScope":"類型陳述式只能在模組或類別範圍內使用","typeAliasStatementIllegal":"類型別名陳述式需要 Python 3.12 或更新版本","typeAliasTypeBaseClass":"\\"type\\" 陳述式中定義的類型別名不能做為基底類別使用","typeAliasTypeMustBeAssigned":"TypeAliasType 必須指派給與型別別名相同的變數","typeAliasTypeNameArg":"TypeAliasType 的第一個引數必須是代表型別別名名稱的字串常值","typeAliasTypeNameMismatch":"類型別名的名稱必須與指派它的變數名稱相符","typeAliasTypeParamInvalid":"型別參數清單必須是只包含 TypeVar、TypeVarTuple 或 ParamSpec 的元組","typeAnnotationCall":"型別運算式中不允許呼叫運算式","typeAnnotationVariable":"型別運算式中不允許變數","typeAnnotationWithCallable":"\\"type\\" 的類型引數必須是類別; 不支援可呼叫項目","typeArgListExpected":"預期為 ParamSpec、省略符號或類型清單","typeArgListNotAllowed":"此型別引數不允許清單運算式","typeArgsExpectingNone":"預期類別 \\"{name}\\" 沒有類型引數","typeArgsMismatchOne":"預期為一個類型引數，但收到 {received}","typeArgsMissingForAlias":"預期為一般類型別名 \\"{name}\\" 的類型引數","typeArgsMissingForClass":"應為一般類別 \\"{name}\\" 的型別引數","typeArgsTooFew":"為 \\"{name}\\" 提供太少類型引數; 預期為 {expected} 但收到 {received}","typeArgsTooMany":"已為 \\"{name}\\" 提供太多型別引數; 應為 {expected} 但收到 {received}","typeAssignmentMismatch":"類型 \\"{sourceType}\\" 的運算式不能指派至宣告的類型 \\"{destType}\\"","typeAssignmentMismatchWildcard":"匯入符號 \\"{name}\\" 具有類型 \\"{sourceType}\\"，無法指派給宣告的類型 \\"{destType}\\"","typeCallNotAllowed":"不應在類型註釋中使用 type() 呼叫","typeCheckOnly":"\\"{name}\\" 已標示為 @type_check_only，只能在型別註釋中使用","typeCommentDeprecated":"使用類型註解已取代; 請改為使用類型註釋","typeExpectedClass":"預期為類型運算式，但收到 \\"{type}\\"","typeGuardArgCount":"預期 \\"TypeGuard\\" 或 \\"TypeIs\\" 之後為單一類型引數","typeGuardParamCount":"使用者定義的類型防護函式和方法至少必須有一個輸入參數","typeIsReturnType":"TypeIs 的傳回類型 (\\"{returnType}\\") 與值參數類型 (\\"{type}\\") 不一致","typeNotAwaitable":"\\"{type}\\" 不可等候","typeNotIntantiable":"\\"{type}\\" 不能具現化","typeNotIterable":"\\"{type}\\" 無法疊代","typeNotSpecializable":"無法將型別 \\"{type}\\" 特殊化","typeNotSubscriptable":"類型 \\"{type}\\" 的物件不能下標","typeNotSupportBinaryOperator":"型別 \\"{leftType}\\" 和 \\"{rightType}\\" 不支援運算子 \\"{operator}\\"","typeNotSupportBinaryOperatorBidirectional":"當預期的型別為 \\"{expectedType}\\" 時，型別 \\"{leftType}\\" 和 \\"{rightType}\\" 不支援運算子 \\"{operator}\\"","typeNotSupportUnaryOperator":"型別 \\"{type}\\" 不支援運算子 \\"{operator}\\"","typeNotSupportUnaryOperatorBidirectional":"預期的類型為 \\"{expectedType}\\" 時，類型 \\"{type}\\" 不支援運算子 \\"{operator}\\"","typeNotUsableWith":"類型 \\"{type}\\" 的物件不能與 \\"with\\" 搭配使用，因為它未實作 {method}","typeParameterBoundNotAllowed":"界限或條件約束不能與 variadic 型別參數或 ParamSpec 一起使用","typeParameterConstraintTuple":"類型參數限制式必須是兩個或兩個以上類型的 Tuple","typeParameterExistingTypeParameter":"類型參數 \\"{name}\\" 已在使用中","typeParameterNotDeclared":"類型參數 \\"{name}\\" 未包含在 \\"{container}\\" 的類型參數清單中","typeParametersMissing":"至少必須指定一個類型參數","typePartiallyUnknown":"\\"{name}\\" 的類型部分未知","typeUnknown":"\\"{name}\\" 的類型未知","typeVarAssignedName":"TypeVar 必須指派至名為 \\"{name}\\" 的變數","typeVarAssignmentMismatch":"無法將型別 \\"{type}\\" 指派給型別變數 \\"{name}\\"","typeVarBoundAndConstrained":"TypeVar 不能同時繫結和限制","typeVarBoundGeneric":"TypeVar 繫結類型不能是一般","typeVarConstraintGeneric":"TypeVar 限制式類型不能是一般","typeVarDefaultBoundMismatch":"TypeVar 預設型別必須是繫結型別的子型別","typeVarDefaultConstraintMismatch":"TypeVar 預設型別必須是其中一個限制型別","typeVarDefaultIllegal":"型別變數預設型別需要 Python 3.13 或較新的版本","typeVarDefaultInvalidTypeVar":"類型參數 \\"{name}\\" 的預設類型參考不在範圍的一或多個類型變數","typeVarFirstArg":"預期為 TypeVar 的名稱作為第一個引數","typeVarNoMember":"TypeVar \\"{type}\\" 沒有成員 \\"{name}\\"","typeVarNotSubscriptable":"TypeVar \\"{type}\\" 不能下標","typeVarNotUsedByOuterScope":"類型變數 \\"{name}\\" 在此內容中沒有意義","typeVarPossiblyUnsolvable":"如果呼叫者未提供參數 \\"{param}\\" 的引數，則型別變數 \\"{name}\\" 可能無法解析","typeVarScopedToReturnType":"型別變數 \\"{name}\\" 的範圍為傳回型別內的可呼叫項目，無法在函式主體中參考","typeVarSingleConstraint":"TypeVar 至少必須有兩個限制類型","typeVarTupleConstraints":"TypeVarTuple 不能有值條件約束","typeVarTupleContext":"此內容中不允許 TypeVarTuple","typeVarTupleDefaultNotUnpacked":"TypeVarTuple 預設型別必須是未封裝的元組或 TypeVarTuple","typeVarTupleMustBeUnpacked":"TypeVarTuple 值需要解除封裝運算子","typeVarTupleUnknownParam":"\\"{name}\\" 是 TypeVarTuple 的未知參數","typeVarUnknownParam":"\\"{name}\\" 對 TypeVar 是未知的參數","typeVarUsedByOuterScope":"外部領域已在使用 TypeVar \\"{name}\\"","typeVarUsedOnlyOnce":"TypeVar \\"{name}\\" 只會在一般函式簽章中出現一次","typeVarVariance":"TypeVar 不能同時為共變數和逆變數","typeVarWithDefaultFollowsVariadic":"TypeVar \\"{typeVarName}\\" 具有預設值，無法遵循 TypeVarTuple \\"{variadicName}\\"","typeVarWithoutDefault":"\\"{name}\\" 無法出現在型別參數清單中的 \\"{other}\\" 後面，因為它沒有預設型別","typeVarsNotInGenericOrProtocol":"Generic[] 或 Protocol[] 必須包含所有類型變數","typedDictAccess":"無法存取 TypedDict 中的項目","typedDictAssignedName":"TypedDict 必須指派至名為 \\"{name}\\" 的變數","typedDictBadVar":"TypedDict 類別只能包含型別註釋","typedDictBaseClass":"TypedDict 類別的所有基底類別也必須是 TypedDict 類別","typedDictBoolParam":"預期 \\"{name}\\" 參數的值為 True 或 False","typedDictClosedExtras":"基底類別 \\"{name}\\" 是已關閉的 TypedDict; 額外項目必須為型別 \\"{type}\\"","typedDictClosedNoExtras":"基底類別 \\"{name}\\" 是已關閉的 TypedDict; 不允許額外項目","typedDictDelete":"無法刪除 TypedDict 中的項目","typedDictEmptyName":"TypedDict 內的名稱不可為空白","typedDictEntryName":"字典項目名稱預期為字串常值","typedDictEntryUnique":"字典內的名稱必須是唯一的","typedDictExtraArgs":"不支援額外的 TypedDict 引數","typedDictFieldNotRequiredRedefinition":"TypedDict 項目 \\"{name}\\" 不能重新定義為 NotRequired","typedDictFieldReadOnlyRedefinition":"TypedDict 項目 \\"{name}\\" 不能重新定義為 ReadOnly","typedDictFieldRequiredRedefinition":"TypedDict 項目 \\"{name}\\" 不能重新定義為 Required","typedDictFirstArg":"預期 TypedDict 類別名稱作為第一個引數","typedDictInitsubclassParameter":"TypedDict 不支援__init_subclass__參數 \\"{name}\\"","typedDictNotAllowed":"\\"TypedDict\\" 不能用在此內容中","typedDictSecondArgDict":"預期為字典或關鍵字參數作為第二個參數","typedDictSecondArgDictEntry":"應為簡單字典輸入項目","typedDictSet":"無法在 TypedDict 中指派項目","unaccessedClass":"未存取類別 \\"{name}\\"","unaccessedFunction":"未存取函式 \\"{name}\\"","unaccessedImport":"未存取匯入 \\"{name}\\"","unaccessedSymbol":"未存取 \\"{name}\\"","unaccessedVariable":"未存取變數 \\"{name}\\"","unannotatedFunctionSkipped":"因為未標註函式 \\"{name}\\"，所以略過其分析","unaryOperationNotAllowed":"類型註釋中不允許一元運算子","unexpectedAsyncToken":"預期為 \\"def\\"、\\"with\\" 或 \\"for\\" 來追蹤 \\"async\\"","unexpectedExprToken":"運算式結尾未預期的權杖","unexpectedIndent":"未預期的縮排","unexpectedUnindent":"取消縮排未預期","unhashableDictKey":"字典索引鍵必須是可雜湊的","unhashableSetEntry":"設定項目必須是可雜湊","uninitializedAbstractVariables":"抽象基底類別中定義的變數未在 Final 類別 \\"{classType}\\" 中初始化","uninitializedInstanceVariable":"執行個體變數 \\"{name}\\" 未在類別本文或 __init__ 方法上初始化","unionForwardReferenceNotAllowed":"聯集語法不能與字串運算元搭配使用; 使用引號括住整個運算式","unionSyntaxIllegal":"聯集的替代語法需要 Python 3.10 或更新版本","unionTypeArgCount":"聯集需要兩個或多個類型引數","unionUnpackedTuple":"集合聯集不能包含未封裝的 Tuple","unionUnpackedTypeVarTuple":"集合聯集不能包含未封裝的 TypeVarTuple","unnecessaryCast":"不必要的 \\"cast\\" 呼叫; 型別已是 \\"{type}\\"","unnecessaryIsInstanceAlways":"不必要的 isinstance 呼叫; \\"{testType}\\" 一律是 \\"{classType}\\" 的執行個體","unnecessaryIsSubclassAlways":"不必要的 issubclass 呼叫; \\"{testType}\\"永遠是 \\"{classType}\\" 的子類別","unnecessaryPyrightIgnore":"不必要的 \\"# pyright: ignore\\" 註解","unnecessaryPyrightIgnoreRule":"不必要的 \\"# pyright: ignore\\" 規則: \\"{name}\\"","unnecessaryTypeIgnore":"不必要的 \\"# type: ignore\\" 註解","unpackArgCount":"\\"Unpack\\" 後面應為單一型別引數","unpackExpectedTypeVarTuple":"預期 TypeVarTuple 或 tuple 作為 Unpack 的類型引數","unpackExpectedTypedDict":"應為解除封裝的 TypedDict 型別引數","unpackIllegalInComprehension":"理解中不允許解壓縮作業","unpackInAnnotation":"類型註釋中不允許解壓縮運算子","unpackInDict":"字典中不允許解壓縮作業","unpackInSet":"集合內不允許將運算子解除封裝","unpackNotAllowed":"此內容中不允許解壓縮","unpackOperatorNotAllowed":"此內容中不允許解壓縮作業","unpackTuplesIllegal":"Python 3.8 之前的 Tuple 中不允許解壓縮作業","unpackedArgInTypeArgument":"解壓縮的引數不能用於類型引數清單","unpackedArgWithVariadicParam":"未封裝的引數無法用於 TypeVarTuple 參數","unpackedDictArgumentNotMapping":"** 後的引數運算式必須是具有 \\"str\\" 金鑰類型的對應","unpackedDictSubscriptIllegal":"字典解壓縮運算子在下標中不被允許","unpackedSubscriptIllegal":"下標中的解壓縮運算子需要 Python 3.11 或更新版本","unpackedTypeVarTupleExpected":"預期為解壓縮的 TypeVarTuple; 使用 Unpack[{name1}] 或 *{name2}","unpackedTypedDictArgument":"無法比對解壓縮的 TypedDict 引數與參數","unreachableCode":"無法連線到程式碼","unreachableExcept":"無法連接 Except 子句，因為例外已處理","unsupportedDunderAllOperation":"不支援 \\"__all__\\" 上的作業，因此匯出的符號清單可能不正確","unusedCallResult":"呼叫運算式的結果是 \\"{type}\\" 型別，而且未使用; 如果這是刻意的，則指派給變數 \\"_\\"","unusedCoroutine":"未使用非同步函式呼叫的結果; 使用 \\"await\\" 或指派結果至變數","unusedExpression":"未使用運算式值","varAnnotationIllegal":"變數的類型註釋需要 Python 3.6 或更新版本; 使用類型註解以獲得與先前版本的相容性","variableFinalOverride":"變數 \\"{name}\\" 標示為 Final，且會覆寫類別 \\"{className}\\" 中相同名稱的非 Final 變數","variadicTypeArgsTooMany":"類型引數清單最多只能有一個解壓縮的 TypeVarTuple 或 tuple","variadicTypeParamTooManyAlias":"類型別名最多只能有一個 TypeVarTuple 類型參數，但收到多個 ({names})","variadicTypeParamTooManyClass":"一般類別最多只能有一個 TypeVarTuple 類型參數，但收到多個 ({names})","walrusIllegal":"運算子 \\":=\\" 需要 Python 3.8 或更新版本","walrusNotAllowed":"此內容中不允許未使用括弧括住的運算子 \\":=\\"","wildcardInFunction":"類別或函式內不允許萬用字元匯入","wildcardLibraryImport":"不允許從程式庫匯入萬用字元","wildcardPatternTypePartiallyUnknown":"萬用字元模式擷取的類型部分未知","wildcardPatternTypeUnknown":"萬用字元模式擷取的型別不明","yieldFromIllegal":"使用 \\"yield from\\" 需要 Python 3.3 或更新版本","yieldFromOutsideAsync":"非同步函式中不允許 \\"yield from\\"","yieldOutsideFunction":"在函式或 lambda 外部不允許 \\"yield\\"","yieldWithinListCompr":"清單理解內不允許 \\"yield\\"","zeroCaseStatementsFound":"Match 陳述式必須至少包含一個 case 陳述式","zeroLengthTupleNotAllowed":"此內容中不允許零長度 Tuple"},"DiagnosticAddendum":{"annotatedNotAllowed":"[已標註] 特殊表單不可與執行個體和類別檢查一起使用","argParam":"引數對應至參數 \\"{paramName}\\"","argParamFunction":"引數對應至函式 \\"{functionName}\\" 中的參數 \\"{paramName}\\"","argsParamMissing":"參數 \\"*{paramName}\\" 沒有對應的參數","argsPositionOnly":"僅限位置的參數不符; 應為 {expected}，但收到 {received}","argumentType":"引數類型為 \\"{type}\\"","argumentTypes":"引數型別: ({types})","assignToNone":"類型不能指派至類型 \\"None\\"","asyncHelp":"您是指 \\"async with\\" 嗎?","baseClassIncompatible":"基底類別 \\"{baseClass}\\" 與類型 \\"{type}\\" 不相容","baseClassIncompatibleSubclass":"基底類別 \\"{baseClass}\\" 衍生自與類型 \\"{type}\\" 不相容的 \\"{subclass}\\"","baseClassOverriddenType":"基底類別 \\"{baseClass}\\" 提供類型 \\"{type}\\"，其已覆寫","baseClassOverridesType":"基底類別 \\"{baseClass}\\" 以型別 \\"{type}\\" 來覆寫","bytesTypePromotions":"將 disableBytesTypePromotions 設定為 false，以啟用「bytearray」和「memoryview」的類型升級行為","conditionalRequiresBool":"類型 \\"{operandType}\\" 的方法 __bool__ 傳回類型 \\"{boolReturnType}\\" 而非 \\"bool\\"","dataClassFieldLocation":"欄位宣告","dataClassFrozen":"\\"{name}\\" 已凍結","dataProtocolUnsupported":"\\"{name}\\" 是個資料通訊協定","descriptorAccessBindingFailed":"無法為描述項類別 \\"{className}\\" 繫結方法 \\"{name}\\"","descriptorAccessCallFailed":"無法呼叫描述項類別 \\"{className}\\" 的方法 \\"{name}\\"","finalMethod":"最終方法","functionParamDefaultMissing":"參數 \\"{name}\\" 遺漏了預設引數","functionParamName":"參數名稱不符: \\"{destName}\\" 與 \\"{srcName}\\"","functionParamPositionOnly":"僅位置參數不符；參數 \\"{name}\\" 不是僅限位置","functionReturnTypeMismatch":"函式傳回型別 \\"{sourceType}\\" 與型別 \\"{destType}\\" 不相容","functionTooFewParams":"函式接受太少位置參數; 預期 {expected}，但收到 {received}","functionTooManyParams":"函式接受太多位置參數; 預期 {expected}，但收到 {received}","genericClassNotAllowed":"執行個體或類別檢查不允許具有類型引數的泛型類型","incompatibleDeleter":"屬性 deleter 方法不相容","incompatibleGetter":"屬性 getter 方法不相容","incompatibleSetter":"屬性 setter 方法不相容","initMethodLocation":"__init__ 方法於類別 \\"{type}\\" 中定義","initMethodSignature":"__init__ 的簽章為 \\"{type}\\"","initSubclassLocation":"__init_subclass__ 方法已於類別 \\"{name}\\" 中定義","invariantSuggestionDict":"請考慮從「dict」切換到實值型別中共變數的「Mapping」","invariantSuggestionList":"請考慮從共變數的「list」切換到「Sequence」","invariantSuggestionSet":"考慮從 “set”切換到共同變數 “Container”","keyNotRequired":"\\"{name}\\" 在 \\"{type}\\" 中不是必要的索引鍵，因此存取可能會導致執行階段例外狀況","keyReadOnly":"\\"{name}\\" 是 \\"{type}\\" 中的唯讀金鑰","keyRequiredDeleted":"\\"{name}\\" 是必要的金鑰，因此不能刪除","keyUndefined":"\\"{name}\\" 不是 \\"{type}\\" 中定義的金鑰","kwargsParamMissing":"參數 \\"**{paramName}\\" 沒有對應的參數","listAssignmentMismatch":"類型 \\"{type}\\" 與目標清單不相容","literalAssignmentMismatch":"\\"{sourceType}\\" 不能指派至類型 \\"{destType}\\"","matchIsNotExhaustiveHint":"如果不需要徹底處理，請新增 \\"case _: pass\\"","matchIsNotExhaustiveType":"未處理的類型: \\"{type}\\"","memberAssignment":"無法將型別 \\"{type}\\" 的運算式指派給類別 \\"{classType}\\" 的成員 \\"{name}\\"","memberIsAbstract":"\\"{type}.{name}\\" 未實作","memberIsAbstractMore":"和其他 {count} 人...","memberIsClassVarInProtocol":"\\"{name}\\" 定義為通訊協定中的 ClassVar","memberIsFinalInProtocol":"\\"{name}\\" 在通訊協定中標示為 Final","memberIsInitVar":"成員 \\"{name}\\" 是僅限初始化的欄位","memberIsInvariant":"\\"{name}\\" 為不變數，因為它可變動","memberIsNotClassVarInClass":"\\"{name}\\" 必須定義為 ClassVar，才能與通訊協定相容","memberIsNotClassVarInProtocol":"\\"{name}\\" 未定義為通訊協定中的 ClassVar","memberIsNotFinalInProtocol":"\\"{name}\\" 未在通訊協定中標示為 Final","memberIsWritableInProtocol":"\\"{name}\\" 在通訊協定中是可寫入的","memberSetClassVar":"無法透過類別執行個體指派成員 \\"{name}\\"，因為它是 ClassVar","memberTypeMismatch":"\\"{name}\\" 是不相容的類型","memberUnknown":"成員 \\"{name}\\" 未知","metaclassConflict":"Metaclass「{metaclass1}」與「{metaclass2}」衝突","missingDeleter":"屬性 deleter 方法遺失","missingGetter":"屬性 getter 方法遺失","missingSetter":"遺漏了屬性 setter 方法","namedParamMissingInDest":"目的地中遺失關鍵字參數 \\"{name}\\"","namedParamMissingInSource":"來源中遺漏了關鍵字參數 \\"{name}\\"","namedParamTypeMismatch":"類型 \\"{sourceType}\\" 的關鍵字參數 \\"{name}\\" 不能指派至類型 \\"{destType}\\"","namedTupleNotAllowed":"執行個體或類別檢查無法使用 NamedTuple","newMethodLocation":"__new__ 方法於類別 \\"{type}\\" 中定義","newMethodSignature":"__new__ 的簽章為 \\"{type}\\"","newTypeClassNotAllowed":"使用 NewType 建立的類別不能與執行個體和類別檢查一起使用","noOverloadAssignable":"沒有任何多載函式符合類型 \\"{type}\\"","noneNotAllowed":"無法對執行個體或類別檢查使用 None","orPatternMissingName":"遺失名稱: {name}","overloadIndex":"多載 {index} 是最接近的相符項目","overloadNotAssignable":"\\"{name}\\" 的一或多個多載無法指派","overloadSignature":"多載簽章在這裡定義","overriddenMethod":"覆寫方法","overriddenSymbol":"覆寫的符號","overrideInvariantMismatch":"覆寫類型 \\"{overrideType}\\" 與基底類型 \\"{baseType}\\" 不同","overrideIsInvariant":"變數是可變動的，所以其類型是不變的","overrideNoOverloadMatches":"覆寫中沒有任何多載簽章與基底方法相容","overrideNotClassMethod":"基底方法宣告為 classmethod，但無法覆寫","overrideNotInstanceMethod":"基底方法已宣告為執行個體方法，但無法覆寫","overrideNotStaticMethod":"基底方法宣告為 staticmethod，但無法覆寫","overrideOverloadNoMatch":"覆寫未處理基底方法的所有多載","overrideOverloadOrder":"覆寫方法的多載必須與基底方法的順序相同","overrideParamKeywordNoDefault":"關鍵字參數 \\"{name}\\" 不相符: 基底參數有預設引數值，覆寫參數則否","overrideParamKeywordType":"關鍵字參數 \\"{name}\\" 型別不符: 基底參數為型別 \\"{baseType}\\"，覆寫參數為型別 \\"{overrideType}\\"","overrideParamName":"參數 {index} 名稱不符: 基底參數名為 \\"{baseName}\\"，覆寫參數名為 \\"{overrideName}\\"","overrideParamNameExtra":"基底中遺失參數 \\"{name}\\"","overrideParamNameMissing":"覆寫中遺漏了參數 \\"{name}\\"","overrideParamNamePositionOnly":"參數 {index} 不符: 基底參數 \\"{baseName}\\" 為關鍵字參數，覆寫參數為 \\"position-only\\"","overrideParamNoDefault":"參數 {index} 不相符: 基底參數有預設引數值，覆寫參數則否","overrideParamType":"參數 \\"{index}\\" 型別不符: 基底參數為型別 \\"{baseType}\\"，覆寫參數為型別 \\"{overrideType}\\"","overridePositionalParamCount":"位置參數計數不相符; 基底方法有 {baseCount} 個，但覆寫有 {overrideCount} 個","overrideReturnType":"傳回類型不符: 基底方法會傳回類型 \\"{baseType}\\"，覆寫會傳回類型 \\"{overrideType}\\"","overrideType":"基底類別會將類型定義為 \\"{type}\\"","paramAssignment":"參數 {index}: 類型 \\"{sourceType}\\" 不能指派至類型 \\"{destType}\\"","paramSpecMissingInOverride":"覆寫方法中遺漏了 ParamSpec 參數","paramType":"參數類型為 \\"{paramType}\\"","privateImportFromPyTypedSource":"改為從 \\"{module}\\" 匯入","propertyAccessFromProtocolClass":"通訊協定類別中定義的屬性無法存取為類別變數","propertyMethodIncompatible":"屬性方法 \\"{name}\\" 不相容","propertyMethodMissing":"覆寫中遺漏了屬性方法 \\"{name}\\"","propertyMissingDeleter":"屬性 \\"{name}\\" 沒有定義的 deleter","propertyMissingSetter":"屬性 \\"{name}\\" 沒有定義的 setter","protocolIncompatible":"\\"{sourceType}\\" 與通訊協定 \\"{destType}\\" 不相容","protocolMemberMissing":"\\"{name}\\" 不存在","protocolRequiresRuntimeCheckable":"通訊協定類別必須為 @runtime_checkable，才能搭配執行個體和類別檢查使用","protocolSourceIsNotConcrete":"\\"{sourceType}\\" 不是實體類別型別，因此無法指派給型別 \\"{destType}\\"","protocolUnsafeOverlap":"\\"{name}\\" 的屬性與通訊協定的名稱相同","pyrightCommentIgnoreTip":"使用 \\"# pyright: ignore[<diagnostic rules>]\\" 來隱藏單行的診斷","readOnlyAttribute":"屬性 \\"{name}\\" 為唯讀","seeClassDeclaration":"請參閱類別宣告","seeDeclaration":"請參閱宣告","seeFunctionDeclaration":"請參閱函式宣告","seeMethodDeclaration":"請參閱方法宣告","seeParameterDeclaration":"請參閱參數宣告","seeTypeAliasDeclaration":"請參閱類型別名宣告","seeVariableDeclaration":"請參閱變數宣告","tupleAssignmentMismatch":"型別 \\"{type}\\" 與目標元組不相容","tupleEntryTypeMismatch":"Tuple 項目 {entry} 的類型不正確","tupleSizeIndeterminateSrc":"元組大小不符; 預期為 {expected}，但收到不確定的大小","tupleSizeIndeterminateSrcDest":"元組大小不符; 預期為 {expected} 或其他，但收到不確定的大小","tupleSizeMismatch":"元組大小不符; 預期為 {expected}，但收到 {received}","tupleSizeMismatchIndeterminateDest":"元組大小不符; 預期為 {expected} 或其他，但收到 {received}","typeAliasInstanceCheck":"使用 \\"type\\" 陳述式建立的類型別名不能搭配執行個體和類別檢查使用","typeAssignmentMismatch":"類型 \\"{sourceType}\\" 不能指派至類型 \\"{destType}\\"","typeBound":"類型 \\"{sourceType}\\" 與類型變數 \\"{name}\\" 的繫結類型 \\"{destType}\\" 不相容","typeConstrainedTypeVar":"類型 \\"{type}\\" 與限制類型變數 \\"{name}\\" 不相容","typeIncompatible":"\\"{sourceType}\\" 與 \\"{destType}\\" 不相容","typeNotClass":"\\"{type}\\" 不是類別","typeNotStringLiteral":"\\"{type}\\" 不是字串常值","typeOfSymbol":"\\"{name}\\" 的型別為 \\"{type}\\"","typeParamSpec":"類型 \\"{type}\\" 與 ParamSpec \\"{name}\\" 不相容","typeUnsupported":"類型 \\"{type}\\" 不受支援","typeVarDefaultOutOfScope":"類型變數 \\"{name}\\" 不在範圍內","typeVarIsContravariant":"型別參數 \\"{name}\\" 具有反變性，但 \\"{sourceType}\\" 不是 \\"{destType}\\" 的超型別","typeVarIsCovariant":"型別參數 \\"{name}\\" 具有共變性，但 \\"{sourceType}\\" 不是 \\"{destType}\\" 的子型別","typeVarIsInvariant":"型別參數 \\"{name}\\" 具有不變性，但 \\"{sourceType}\\" 與 \\"{destType}\\" 不同","typeVarNotAllowed":"執行個體或類別檢查不允許 TypeVar","typeVarTupleRequiresKnownLength":"TypeVarTuple 無法繫結至長度不明的元組","typeVarUnnecessarySuggestion":"改用 {type}","typeVarUnsolvableRemedy":"提供多載，其指定未提供引數時的傳回類型","typeVarsMissing":"遺失類型變數: {names}","typedDictBaseClass":"類別 \\"{type}\\" 不是 TypedDict","typedDictClassNotAllowed":"執行個體或類別檢查不允許 TypedDict 類別","typedDictClosedExtraNotAllowed":"無法新增項目 \\"{name}\\"","typedDictClosedExtraTypeMismatch":"無法新增型別為 \\"{type}\\" 的項目 \\"{name}\\"","typedDictClosedFieldNotRequired":"無法新增項目 \\"{name}\\"，因為它必須是 NotRequired","typedDictExtraFieldNotAllowed":"\\"{name}\\" 不存在於 \\"{type}\\"","typedDictExtraFieldTypeMismatch":"\\"{name}\\" 型別與 \\"{type}\\" 中的 \\"__extra_items__\\" 型別不相容","typedDictFieldMissing":"\\"{type}\\" 遺失 \\"{name}\\"","typedDictFieldNotReadOnly":"\\"{name}\\" 在 \\"{type}\\" 中不是唯讀","typedDictFieldNotRequired":"\\"{type}\\" 中不需要 \\"{name}\\"","typedDictFieldRequired":"\\"{type}\\" 中需要 \\"{name}\\"","typedDictFieldTypeMismatch":"型別 \\"{type}\\" 無法指派給項目 \\"{name}\\"","typedDictFieldUndefined":"\\"{name}\\" 是型別 \\"{type}\\" 中未定義的項目","typedDictFinalMismatch":"\\"{sourceType}\\" 與 \\"{destType}\\" 不相容，因為@final 不符","typedDictKeyAccess":"使用 [\\"{name}\\"] 參考 TypedDict 中的項目","typedDictNotAllowed":"執行個體或類別檢查無法使用 TypedDict","unhashableType":"型別 \\"{type}\\" 無法雜湊","uninitializedAbstractVariable":"執行個體變數 \\"{name}\\" 在抽象基底類別 \\"{classType}\\" 中定義，但未初始化","unreachableExcept":"\\"{exceptionType}\\" 是 \\"{parentType}\\" 的子類別","useDictInstead":"使用 Dict[T1，T2] 來表示字典型別","useListInstead":"使用 List[T] 來表示清單型別，或使用 Union [T1, T2] 來表示等位型別","useTupleInstead":"使用 tuple[T1, ..., Tn] 來指出 Tuple 類型或 Union[T1, T2] 來指出聯集類型","useTypeInstead":"改為使用 Type[T]","varianceMismatchForClass":"型別引數 \\"{typeVarName}\\" 的變異數與基底類別 \\"{className}\\" 不相容","varianceMismatchForTypeAlias":"型別引數 \\"{typeVarName}\\" 的變異數與 \\"{typeAliasParam}\\" 不相容"}}');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
var exports = __webpack_exports__;
/*!***************************!*\
  !*** ./src/langserver.ts ***!
  \***************************/

Object.defineProperty(exports, "__esModule", ({ value: true }));
const nodeMain_1 = __webpack_require__(/*! pyright-internal/nodeMain */ "../pyright-internal/src/nodeMain.ts");
// Command line version doesn't use any worker threads.
(0, nodeMain_1.main)(/* maxWorkers */ 0);

})();

/******/ })()
;
//# sourceMappingURL=pyright-langserver.js.map