Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | 21x 21x 782x 492x 38x 405x 141x 59x 82x 1x 81x 1x 80x 19x 19x 19x 2x 17x 14x 14x 14x 14x 14x 366x 366x 2x 364x 364x 364x 311x 53x 46x 7x 5x 2x 362x 362x 2x 360x 12x 549x 549x 520x 520x 11x 11x 11x 509x 509x 4x 505x 468x 37x 33x 4x 1135x 1135x 939x 196x 196x 196x 13x 183x 183x 5x 178x 178x 5x 173x 173x 11x 162x 162x 8x 154x 983x 983x 982x 982x 828x 983x 238x 238x 162x 76x 666x 238x 121x 117x 117x 121x 17x 104x 3x 3x 101x 101x 77x 24x 20x 20x 6x 14x 117x 117x 67x 50x 42x 8x 4x 4x 988x 988x 367x 367x 367x 367x 275x 92x 621x 17x 604x 5x 599x 599x 530x 530x 69x 69x 8x 8x 61x 61x 1x 60x 6x 6x 19x 19x 17x 2x 2x 1x 1x 233x 46x 17x 7x 10x 4x 4x 6x 2x 2x 105x 105x 26x | /**
* TypeResolver - Handles type inference, classification, and validation
* Static class that reads from CodeGenState directly.
*/
import * as Parser from "../../logic/parser/grammar/CNextParser";
import CodeGenState from "../../state/CodeGenState";
import INTEGER_TYPES from "./types/INTEGER_TYPES";
import FLOAT_TYPES from "./types/FLOAT_TYPES";
import SIGNED_TYPES from "./types/SIGNED_TYPES";
import UNSIGNED_TYPES from "./types/UNSIGNED_TYPES";
import TYPE_WIDTH from "./types/TYPE_WIDTH";
import TYPE_RANGES from "./types/TYPE_RANGES";
import ExpressionUnwrapper from "../../../utils/ExpressionUnwrapper";
/**
* Internal type info tracked through postfix suffix chains.
* Preserves isArray so indexing can distinguish array access from bit indexing.
*/
type InternalTypeInfo = { baseType: string; isArray: boolean };
/**
* Discriminated union for postfix suffix processing results.
* stop=true: return type immediately (terminal suffix like bit indexing).
* stop=false: continue chain with updated InternalTypeInfo.
*/
type SuffixResult =
| { stop: true; type: string | null }
| { stop: false; info: InternalTypeInfo };
class TypeResolver {
/** Sentinel value for `global` keyword in postfix expression type resolution */
private static readonly GLOBAL_SENTINEL = "__global__";
/** Sentinel value for `this` keyword in postfix expression type resolution */
private static readonly THIS_SENTINEL = "__this__";
/**
* ADR-024: Check if a type is any integer (signed or unsigned)
*/
static isIntegerType(typeName: string): boolean {
return (INTEGER_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is a floating point type
*/
static isFloatType(typeName: string): boolean {
return (FLOAT_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is a signed integer
*/
static isSignedType(typeName: string): boolean {
return (SIGNED_TYPES as readonly string[]).includes(typeName);
}
/**
* ADR-024: Check if a type is an unsigned integer
*/
static isUnsignedType(typeName: string): boolean {
return (UNSIGNED_TYPES as readonly string[]).includes(typeName);
}
/**
* Check if a type is a user-defined struct (C-Next or C header).
* Issue #103: Now checks both knownStructs AND SymbolTable.
*/
static isStructType(typeName: string): boolean {
if (CodeGenState.symbols?.knownStructs.has(typeName)) {
return true;
}
// Issue #551: Bitmaps are struct-like (use pass-by-reference with -> access)
if (CodeGenState.symbols?.knownBitmaps.has(typeName)) {
return true;
}
if (CodeGenState.symbolTable.getStructFields(typeName)) {
return true;
}
return false;
}
/**
* ADR-024: Check if conversion from sourceType to targetType is narrowing
*/
static isNarrowingConversion(
sourceType: string,
targetType: string,
): boolean {
const sourceWidth = TYPE_WIDTH[sourceType] || 0;
const targetWidth = TYPE_WIDTH[targetType] || 0;
if (sourceWidth === 0 || targetWidth === 0) {
return false;
}
return targetWidth < sourceWidth;
}
/**
* ADR-024: Check if conversion involves a sign change
*/
static isSignConversion(sourceType: string, targetType: string): boolean {
const sourceIsSigned = TypeResolver.isSignedType(sourceType);
const sourceIsUnsigned = TypeResolver.isUnsignedType(sourceType);
const targetIsSigned = TypeResolver.isSignedType(targetType);
const targetIsUnsigned = TypeResolver.isUnsignedType(targetType);
return (
(sourceIsSigned && targetIsUnsigned) ||
(sourceIsUnsigned && targetIsSigned)
);
}
/**
* ADR-024: Validate that a literal value fits within the target type's range.
* Throws an error if the value doesn't fit.
*/
static validateLiteralFitsType(
literalText: string,
targetType: string,
): void {
const range = TYPE_RANGES[targetType];
if (!range) {
return;
}
let value: bigint;
try {
const cleanText = literalText.trim();
if (/^-?\d+$/.exec(cleanText)) {
value = BigInt(cleanText);
} else if (/^0[xX][0-9a-fA-F]+$/.exec(cleanText)) {
value = BigInt(cleanText);
} else if (/^0[bB][01]+$/.exec(cleanText)) {
value = BigInt(cleanText);
} else {
return;
}
} catch {
return;
}
const [min, max] = range;
if (TypeResolver.isUnsignedType(targetType) && value < 0n) {
throw new Error(
`Error: Negative value ${literalText} cannot be assigned to unsigned type ${targetType}`,
);
}
if (value < min || value > max) {
throw new Error(
`Error: Value ${literalText} exceeds ${targetType} range (${min} to ${max})`,
);
}
}
/**
* ADR-024: Get the type from a literal (suffixed or unsuffixed).
*/
static getLiteralType(ctx: Parser.LiteralContext): string | null {
const text = ctx.getText();
if (text === "true" || text === "false") return "bool";
const suffixMatch = /([uUiI])(8|16|32|64)$/.exec(text);
if (suffixMatch) {
const signChar = suffixMatch[1].toLowerCase();
const width = suffixMatch[2];
return (signChar === "u" ? "u" : "i") + width;
}
const floatMatch = /[fF](32|64)$/.exec(text);
if (floatMatch) {
return "f" + floatMatch[1];
}
// Plain integer literals (no suffix) have type int in C
// Check for integer: starts with digit, no decimal point
if (/^\d+$/.test(text) || /^0[xXbBoO][\da-fA-F]+$/.test(text)) {
return "int";
}
// Plain float literals (no suffix) have type double in C
if (
/^\d*\.\d+([eE][+-]?\d+)?$/.test(text) ||
/^\d+[eE][+-]?\d+$/.test(text)
) {
return "f64";
}
return null;
}
/**
* ADR-024: Get the type of an expression for type checking.
*/
static getExpressionType(ctx: Parser.ExpressionContext): string | null {
const postfix = ExpressionUnwrapper.getPostfixExpression(ctx);
if (postfix) {
return TypeResolver.getPostfixExpressionType(postfix);
}
const ternary = ctx.ternaryExpression();
const orExprs = ternary.orExpression();
if (orExprs.length > 1) {
return null;
}
const or = orExprs[0];
if (or.andExpression().length > 1) {
return "bool";
}
const and = or.andExpression()[0];
if (and.equalityExpression().length > 1) {
return "bool";
}
const eq = and.equalityExpression()[0];
if (eq.relationalExpression().length > 1) {
return "bool";
}
const rel = eq.relationalExpression()[0];
if (rel.bitwiseOrExpression().length > 1) {
return "bool";
}
return null;
}
/**
* ADR-024: Get the type of a postfix expression.
* Tracks InternalTypeInfo (baseType + isArray) through the suffix chain
* so that array indexing is correctly distinguished from bit indexing.
*/
static getPostfixExpressionType(
ctx: Parser.PostfixExpressionContext,
): string | null {
const primary = ctx.primaryExpression();
if (!primary) return null;
let current = TypeResolver.getPrimaryExpressionTypeInfo(primary);
if (!current) return null;
const suffixes = ctx.children?.slice(1) || [];
for (const suffix of suffixes) {
const result = TypeResolver.processPostfixSuffix(
suffix.getText(),
current,
);
if (result.stop) {
return result.type;
}
current = result.info;
}
return current.baseType;
}
/**
* Process a single postfix suffix and determine the resulting type.
* Returns { type, stop, info } where stop=true means return type immediately.
*/
private static processPostfixSuffix(
text: string,
current: InternalTypeInfo,
): SuffixResult {
if (text.startsWith(".")) {
return TypeResolver.processMemberSuffix(text.slice(1), current);
}
Eif (text.startsWith("[") && text.endsWith("]")) {
return TypeResolver.processIndexingSuffix(text, current);
}
return { stop: false, info: current };
}
/**
* Process a member access suffix (.name) and resolve the resulting type.
* Handles global/this sentinel values and regular struct member lookups.
*/
private static processMemberSuffix(
memberName: string,
current: InternalTypeInfo,
): SuffixResult {
// Handle global.X — resolve X as a global variable name
if (current.baseType === TypeResolver.GLOBAL_SENTINEL) {
return TypeResolver.resolveRegistryLookup(memberName);
}
// Handle this.X — resolve X as a scope member variable
if (
current.baseType === TypeResolver.THIS_SENTINEL &&
CodeGenState.currentScope
) {
const scopedName = `${CodeGenState.currentScope}_${memberName}`;
return TypeResolver.resolveRegistryLookup(scopedName);
}
const memberInfo = TypeResolver.getMemberTypeInfo(
current.baseType,
memberName,
);
if (!memberInfo) {
return { stop: true, type: null };
}
return {
stop: false,
info: { baseType: memberInfo.baseType, isArray: memberInfo.isArray },
};
}
/**
* Look up a variable name in the type registry and return a SuffixResult.
*/
private static resolveRegistryLookup(name: string): SuffixResult {
const typeInfo = CodeGenState.getVariableTypeInfo(name);
if (typeInfo) {
return {
stop: false,
info: { baseType: typeInfo.baseType, isArray: typeInfo.isArray },
};
}
return { stop: true, type: null };
}
/**
* Process array or bit indexing suffix.
* Checks isArray BEFORE isIntegerType to correctly distinguish
* array element access from bit indexing.
*/
private static processIndexingSuffix(
text: string,
current: InternalTypeInfo,
): SuffixResult {
const inner = text.slice(1, -1);
// Range indexing: [start, width] - always bit extraction
if (inner.includes(",")) {
return { stop: true, type: null };
}
// Array access: if current type is known to be an array, index yields element
if (current.isArray) {
return {
stop: false,
info: { baseType: current.baseType, isArray: false },
};
}
// Bit indexing on integer: single bit returns bool
if (TypeResolver.isIntegerType(current.baseType)) {
return { stop: true, type: "bool" };
}
// Unknown indexing - preserve current state
return { stop: false, info: current };
}
/**
* Get full InternalTypeInfo from a primary expression (preserves isArray).
*/
private static getPrimaryExpressionTypeInfo(
ctx: Parser.PrimaryExpressionContext,
): InternalTypeInfo | null {
const id = ctx.IDENTIFIER();
if (id) {
const name = id.getText();
const scopedName = CodeGenState.resolveIdentifier(name);
const typeInfo = CodeGenState.getVariableTypeInfo(scopedName);
if (typeInfo) {
return { baseType: typeInfo.baseType, isArray: typeInfo.isArray };
}
return null;
}
// Handle global.X and this.X — these are scope qualifiers, not types.
// The actual variable name is the first .suffix after the keyword.
// Return a sentinel so getPostfixExpressionType knows to consume one suffix.
if (ctx.GLOBAL()) {
return { baseType: TypeResolver.GLOBAL_SENTINEL, isArray: false };
}
if (ctx.THIS()) {
return { baseType: TypeResolver.THIS_SENTINEL, isArray: false };
}
const literal = ctx.literal();
if (literal) {
const litType = TypeResolver.getLiteralType(literal);
return litType ? { baseType: litType, isArray: false } : null;
}
const expr = ctx.expression();
if (expr) {
const exprType = TypeResolver.getExpressionType(expr);
return exprType ? { baseType: exprType, isArray: false } : null;
}
const cast = ctx.castExpression();
if (cast) {
return { baseType: cast.type().getText(), isArray: false };
}
return null;
}
/**
* ADR-024: Get the type of a primary expression (public API, returns baseType only).
*/
static getPrimaryExpressionType(
ctx: Parser.PrimaryExpressionContext,
): string | null {
const info = TypeResolver.getPrimaryExpressionTypeInfo(ctx);
return info?.baseType ?? null;
}
/**
* ADR-024: Get the type of a unary expression (for cast validation).
*/
static getUnaryExpressionType(
ctx: Parser.UnaryExpressionContext,
): string | null {
const postfix = ctx.postfixExpression();
if (postfix) {
return TypeResolver.getPostfixExpressionType(postfix);
}
const unary = ctx.unaryExpression();
if (unary) {
return TypeResolver.getUnaryExpressionType(unary);
}
return null;
}
/**
* ADR-024: Validate that a type conversion is allowed.
*/
static validateTypeConversion(
targetType: string,
sourceType: string | null,
): void {
if (!sourceType) return;
if (sourceType === targetType) return;
if (
!TypeResolver.isIntegerType(sourceType) ||
!TypeResolver.isIntegerType(targetType)
)
return;
if (TypeResolver.isNarrowingConversion(sourceType, targetType)) {
const targetWidth = TYPE_WIDTH[targetType] || 0;
throw new Error(
`Error: Cannot assign ${sourceType} to ${targetType} (narrowing). ` +
`Use bit indexing: value[0, ${targetWidth}]`,
);
}
if (TypeResolver.isSignConversion(sourceType, targetType)) {
const targetWidth = TYPE_WIDTH[targetType] || 0;
throw new Error(
`Error: Cannot assign ${sourceType} to ${targetType} (sign change). ` +
`Use bit indexing: value[0, ${targetWidth}]`,
);
}
}
/**
* Get type info for a struct member field.
* Issue #831: SymbolTable is the single source of truth for struct fields.
*/
static getMemberTypeInfo(
structType: string,
memberName: string,
): { isArray: boolean; baseType: string } | undefined {
const fieldInfo = CodeGenState.symbolTable?.getStructFieldInfo(
structType,
memberName,
);
if (!fieldInfo) return undefined;
return {
isArray:
fieldInfo.arrayDimensions !== undefined &&
fieldInfo.arrayDimensions.length > 0,
baseType: fieldInfo.type,
};
}
}
export default TypeResolver;
|