Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/highlight.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * A small Python tokenizer for the code view. No dependency: the agent's code is Python, and a block is only47 * tokenized when it is opened. Returns flat tokens; the component maps each kind to a design-token class.48 */49export type TokenKind = "plain" | "keyword" | "builtin" | "string" | "number" | "comment" | "decorator" | "def";50export interface Token { kind: TokenKind; text: string }5152const KEYWORDS = new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case".split(" "));53const BUILTINS = new Set("print len range enumerate zip map filter sorted sum min max abs round int float str bool list dict set tuple open isinstance type super getattr setattr hasattr any all iter next repr format input id".split(" "));5455export function tokenizePython(code: string): Token[] {56 const tokens: Token[] = [];57 const push = (kind: TokenKind, text: string) => {58 if (!text) return;59 const last = tokens[tokens.length - 1];60 if (last && last.kind === kind && kind === "plain") last.text += text; else tokens.push({ kind, text });61 };62 const n = code.length;63 let i = 0;64 let afterDef = false;65 while (i < n) {66 const ch = code[i];67 if (ch === "#") {68 let j = code.indexOf("\n", i);69 if (j < 0) j = n;70 push("comment", code.slice(i, j));71 i = j;72 continue;73 }74 // strings, with optional prefix (r, b, f, u and pairs) and triple quotes75 const sm = /^(?:[rbfuRBFU]{0,2})("""|'''|"|')/.exec(code.slice(i, i + 5));76 if (sm && (i === 0 || !/[A-Za-z0-9_]/.test(code[i - 1]))) {77 const quote = sm[1];78 const start = i;79 i += sm[0].length;80 const raw = /r/i.test(sm[0].slice(0, sm[0].length - quote.length));81 while (i < n) {82 if (!raw && code[i] === "\\") { i += 2; continue; }83 if (raw && code[i] === "\\" && code[i + 1] === quote[0]) { i += 2; continue; }84 if (code.startsWith(quote, i)) { i += quote.length; break; }85 if (quote.length === 1 && code[i] === "\n") break;86 i++;87 }88 push("string", code.slice(start, Math.min(i, n)));89 continue;90 }91 if (/[0-9]/.test(ch) || (ch === "." && /[0-9]/.test(code[i + 1] ?? ""))) {92 const m = /^(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*)?\.?\d[\d_]*(?:[eE][+-]?\d+)?[jJ]?)/.exec(code.slice(i, i + 40));93 if (m && m[0]) { push("number", m[0]); i += m[0].length; continue; }94 }95 if (/[A-Za-z_]/.test(ch)) {96 let j = i + 1;97 while (j < n && /[A-Za-z0-9_]/.test(code[j])) j++;98 const word = code.slice(i, j);99 if (afterDef) { push("def", word); afterDef = false; }100 else if (KEYWORDS.has(word)) { push("keyword", word); afterDef = word === "def" || word === "class"; }101 else if (BUILTINS.has(word) && code[j] === "(" && code[i - 1] !== ".") push("builtin", word);102 else push("plain", word);103 i = j;104 continue;105 }106 if (ch === "@" && (i === 0 || /\n\s*$/.test(code.slice(Math.max(0, i - 40), i)))) {107 let j = i + 1;108 while (j < n && /[A-Za-z0-9_.]/.test(code[j])) j++;109 push("decorator", code.slice(i, j));110 i = j;111 continue;112 }113 push("plain", ch);114 i++;115 }116 return tokens;117}118