forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

lang.rs321 lines, 15.1 KiBHistoryRawDownload
1//! Code block languages: the registry the editor offers, and a cheap heuristic that guesses
2//! the language of an untagged block. Pure string work, so it builds for wasm32 too.
3
4/// A language a code block can be tagged with.
5#[derive(Debug, PartialEq, Eq)]
6pub struct Lang {
7 pub id: &'static str,
8 pub name: &'static str,
9 pub aliases: &'static [&'static str],
10 pub formattable: bool,
11}
12
13/// Every language, in display order.
14pub static LANGS: &[Lang] = &[
15 Lang { id: "rust", name: "Rust", aliases: &["rs"], formattable: true },
16 Lang { id: "python", name: "Python", aliases: &["py", "python3"], formattable: false },
17 Lang { id: "javascript", name: "JavaScript", aliases: &["js", "jsx", "mjs", "cjs", "node"], formattable: true },
18 Lang { id: "typescript", name: "TypeScript", aliases: &["ts", "tsx"], formattable: true },
19 Lang { id: "go", name: "Go", aliases: &["golang"], formattable: false },
20 Lang { id: "java", name: "Java", aliases: &[], formattable: false },
21 Lang { id: "kotlin", name: "Kotlin", aliases: &["kt", "kts"], formattable: false },
22 Lang { id: "c", name: "C", aliases: &["h"], formattable: false },
23 Lang { id: "cpp", name: "C++", aliases: &["c++", "cc", "cxx", "hpp"], formattable: false },
24 Lang { id: "csharp", name: "C#", aliases: &["cs", "c#"], formattable: false },
25 Lang { id: "swift", name: "Swift", aliases: &[], formattable: false },
26 Lang { id: "ruby", name: "Ruby", aliases: &["rb"], formattable: false },
27 Lang { id: "php", name: "PHP", aliases: &[], formattable: false },
28 Lang { id: "html", name: "HTML", aliases: &["htm", "xml", "svg", "xhtml"], formattable: true },
29 Lang { id: "css", name: "CSS", aliases: &["scss", "less"], formattable: true },
30 Lang { id: "json", name: "JSON", aliases: &["jsonc", "json5"], formattable: true },
31 Lang { id: "yaml", name: "YAML", aliases: &["yml"], formattable: true },
32 Lang { id: "toml", name: "TOML", aliases: &[], formattable: true },
33 Lang { id: "sql", name: "SQL", aliases: &["postgres", "postgresql", "mysql", "sqlite"], formattable: true },
34 Lang { id: "bash", name: "Shell", aliases: &["sh", "shell", "zsh", "console", "shellscript"], formattable: false },
35 Lang { id: "markdown", name: "Markdown", aliases: &["md"], formattable: true },
36 Lang { id: "text", name: "Plain text", aliases: &["plaintext", "txt", "plain"], formattable: false },
37];
38
39/// The language whose id or alias matches `s` (trimmed, ASCII case-insensitive).
40pub fn find(s: &str) -> Option<&'static Lang> {
41 let s = s.trim();
42 LANGS.iter().find(|l| l.id.eq_ignore_ascii_case(s) || l.aliases.iter().any(|a| a.eq_ignore_ascii_case(s)))
43}
44
45const SCAN_LIMIT: usize = 20_000;
46const MIN_SCORE: i32 = 3;
47const MARGIN: i32 = 1;
48
49/// Substring signals `(language id, weight, pattern)`. A line containing the pattern adds
50/// the weight once.
51const SIGNALS: &[(&str, i32, &str)] = &[
52 ("rust", 3, "fn "), ("rust", 2, "let mut "), ("rust", 1, "mut "), ("rust", 3, "impl "),
53 ("rust", 1, "pub "), ("rust", 3, "&self"), ("rust", 3, ".await"), ("rust", 2, "?;"),
54 ("rust", 2, "match "), ("rust", 2, "Some("), ("rust", 2, "Ok("), ("rust", 2, "Err("),
55 ("rust", 2, "#["), ("rust", 3, "println!"), ("rust", 3, "format!"), ("rust", 3, "vec!"),
56 ("rust", 2, ".unwrap()"), ("rust", 1, ".clone()"), ("rust", 1, "::"), ("rust", 1, "->"),
57 ("rust", 1, "=>"), ("rust", 1, "let "), ("rust", 4, "use std::"), ("rust", 3, "crate::"),
58 ("rust", 2, "&mut "), ("rust", 2, "Vec<"), ("rust", 2, "Option<"), ("rust", 2, "Result<"),
59 ("rust", 2, "String::"), ("rust", 2, ".collect"),
60 ("python", 3, "elif "), ("python", 3, "__init__"), ("python", 3, "lambda "),
61 ("python", 2, "print("), ("python", 2, "True"), ("python", 2, "False"), ("python", 1, "None"),
62 ("python", 1, "self."),
63 ("javascript", 2, "const "), ("javascript", 2, "let "), ("javascript", 2, "=>"),
64 ("javascript", 2, "function"), ("javascript", 3, "console.log"), ("javascript", 2, "==="),
65 ("javascript", 2, "!=="), ("javascript", 3, "require("), ("javascript", 3, "module.exports"),
66 ("javascript", 3, "export default"), ("javascript", 1, "export "), ("javascript", 2, "document."),
67 ("javascript", 2, "window."), ("javascript", 2, "undefined"),
68 ("typescript", 4, ": string"), ("typescript", 4, ": number"), ("typescript", 4, ": boolean"),
69 ("typescript", 2, ": void"), ("typescript", 3, "interface "), ("typescript", 2, "readonly "),
70 ("typescript", 3, "as const"), ("typescript", 2, "implements "), ("typescript", 3, "Promise<"),
71 ("typescript", 3, "keyof "), ("typescript", 3, "import type"), ("typescript", 3, "export type"),
72 ("go", 3, "package "), ("go", 2, "func "), ("go", 3, ":="), ("go", 3, "fmt."),
73 ("go", 3, "err != nil"), ("go", 2, "import ("), ("go", 2, "chan "), ("go", 2, "defer "),
74 ("go", 2, "interface{}"), ("go", 2, "map["), ("go", 2, "[]byte"), ("go", 2, "go func"),
75 ("go", 1, "make("),
76 ("java", 3, "public class"), ("java", 3, "System.out"), ("java", 3, "public static void"),
77 ("java", 3, "@Override"), ("java", 2, "String[]"), ("java", 1, "public "), ("java", 1, "private "),
78 ("java", 1, "protected "),
79 ("kotlin", 3, "fun "), ("kotlin", 2, "val "), ("kotlin", 1, "println("), ("kotlin", 3, "data class"),
80 ("kotlin", 3, "companion object"), ("kotlin", 3, "lateinit"), ("kotlin", 3, "?.let"),
81 ("c", 2, "#include"), ("c", 2, ".h>"), ("c", 3, "int main"), ("c", 2, "printf("), ("c", 2, "malloc("),
82 ("c", 2, "NULL"), ("c", 2, "#define"), ("c", 1, "struct "), ("c", 1, "sizeof("), ("c", 1, "char "),
83 ("cpp", 1, "#include"), ("cpp", 3, "<iostream>"), ("cpp", 3, "<vector>"), ("cpp", 2, "std::"),
84 ("cpp", 3, "template<"), ("cpp", 3, "template <"), ("cpp", 2, "cout"), ("cpp", 2, "cin >>"),
85 ("cpp", 2, "nullptr"), ("cpp", 3, "using namespace"),
86 ("csharp", 3, "using System"), ("csharp", 2, "namespace "), ("csharp", 3, "Console.Write"),
87 ("csharp", 1, "public void"), ("csharp", 2, "async Task"), ("csharp", 3, "[HttpGet"),
88 ("csharp", 3, "get; set;"), ("csharp", 1, "var "),
89 ("swift", 3, "guard "), ("swift", 2, "var "), ("swift", 3, "import UIKit"),
90 ("swift", 3, "import SwiftUI"), ("swift", 3, "import Foundation"), ("swift", 2, "func "),
91 ("swift", 1, "let "), ("swift", 3, "@State"), ("swift", 1, "print("), ("swift", 2, "?? "),
92 ("swift", 2, "-> Void"),
93 ("ruby", 3, "puts "), ("ruby", 2, "require '"), ("ruby", 3, "attr_accessor"), ("ruby", 3, "elsif "),
94 ("ruby", 3, "unless "), ("ruby", 3, "do |"),
95 ("php", 5, "<?php"), ("php", 3, "$this->"), ("php", 2, "$_"),
96 ("html", 2, "</"), ("html", 3, "<html"), ("html", 2, "<div"), ("html", 2, "<body"),
97 ("html", 2, "<head"), ("html", 2, "<script"), ("html", 2, "<img"), ("html", 2, "<a href"),
98 ("html", 2, "<span"),
99 ("css", 3, "@media"), ("css", 3, "@keyframes"), ("css", 2, "@import"), ("css", 3, "!important"),
100 ("css", 2, "px;"), ("css", 2, "rem;"), ("css", 3, "var(--"), ("css", 2, "rgba("),
101 ("bash", 1, "&&"), ("bash", 3, "; then"), ("bash", 2, "; do"), ("bash", 2, "$("),
102 ("bash", 1, "${"), ("bash", 2, "| grep"), ("bash", 2, "export "), ("bash", 2, "set -"),
103 ("markdown", 2, "]("),
104];
105
106/// SQL keywords, matched against the lowercased line.
107const SQL: &[(&str, i32)] = &[
108 ("select ", 3), ("insert into", 3), ("create table", 3), ("alter table", 3),
109 ("delete from", 3), ("where ", 2), ("order by", 2), ("group by", 2), ("join ", 2),
110 ("values (", 2), ("from ", 1),
111];
112
113/// Shell commands, matched at the start of a line.
114const SHELL_CMDS: &[&str] = &[
115 "sudo ", "apt ", "cargo ", "npm ", "bun ", "git ", "cd ", "mkdir ", "chmod ", "echo ", "ls ",
116 "curl ", "pip ", "docker ", "make ", "rm ", "cp ", "mv ",
117];
118
119/// CSS properties, matched at the start of a `prop: value;` line.
120const CSS_PROPS: &[&str] = &[
121 "color", "margin", "padding", "display", "background", "font", "border", "width", "height",
122 "position", "flex", "grid", "line-height", "text-", "box-",
123];
124
125/// Guesses the language of an untagged code block from weighted line signals. Only the
126/// first 20 KB are scanned. Returns `None` when no language clearly wins; never `text`.
127pub fn detect(code: &str) -> Option<&'static str> {
128 let mut end = code.len().min(SCAN_LIMIT);
129 while !code.is_char_boundary(end) {
130 end -= 1;
131 }
132 let text = &code[..end];
133
134 let mut score = vec![0i32; LANGS.len()];
135 let mut add = |id: &str, w: i32| {
136 if let Some(i) = LANGS.iter().position(|l| l.id == id) {
137 score[i] += w;
138 }
139 };
140
141 let whole = text.trim();
142 if whole.starts_with(['{', '[']) && whole.ends_with(['}', ']']) && whole.contains("\": ") && !whole.contains(';') {
143 add("json", 6);
144 }
145
146 for raw in text.lines() {
147 let t = raw.trim();
148 if t.is_empty() {
149 continue;
150 }
151 for &(id, w, pat) in SIGNALS {
152 if t.contains(pat) {
153 add(id, w);
154 }
155 }
156 let lower = t.to_ascii_lowercase();
157 for &(pat, w) in SQL {
158 if lower.contains(pat) {
159 add("sql", w);
160 }
161 }
162
163 // Shapes that need the whole line, not a substring.
164 if t.starts_with("def ") {
165 if t.ends_with(':') { add("python", 3) } else { add("ruby", 2) }
166 }
167 if t.starts_with("class ") && t.ends_with(':') {
168 add("python", 3);
169 }
170 if t.starts_with("from ") && t.contains(" import ") {
171 add("python", 3);
172 }
173 if let Some(rest) = t.strip_prefix("import ") {
174 if rest.contains(" from ") {
175 add("javascript", 3);
176 } else if rest.starts_with(|c: char| c.is_ascii_lowercase()) && !rest.contains([';', '"', '\'', '{', '(']) {
177 add("python", 2);
178 }
179 }
180 if t.starts_with("type ") && t.contains(" = ") && !t.ends_with(';') {
181 add("typescript", 3);
182 }
183 if has_closure(t) {
184 add("rust", 3);
185 }
186 // A one-line rule: `a { color: red; }`.
187 if t.contains('{') && t.ends_with('}') && t.contains(": ") && t.contains(';') && !t.contains('(') && !t.contains('"') {
188 add("css", 3);
189 }
190 if t == "end" {
191 add("ruby", 2);
192 }
193 if matches!(t, "fi" | "done" | "esac") {
194 add("bash", 2);
195 }
196 if t.starts_with("---") {
197 add("yaml", 3);
198 }
199 if t.starts_with("- ") {
200 add("yaml", 1);
201 }
202 if yaml_key(t) {
203 add("yaml", 2);
204 }
205 if t.strip_prefix('[').and_then(|s| s.strip_suffix(']')).is_some_and(ident) {
206 add("toml", 3);
207 }
208 if t.split_once(" = ").is_some_and(|(key, _)| ident(key)) {
209 add("toml", 1);
210 }
211 if t.starts_with('"') && t.contains("\": ") {
212 add("json", 1);
213 }
214 if t.starts_with('$') && t.ends_with(';') {
215 add("php", 2);
216 }
217 if t.ends_with('{')
218 && !t.contains('(')
219 && ((t.starts_with(['.', '#', '*']) && !t.starts_with("#[")) || t.starts_with("body") || t.starts_with("html"))
220 {
221 add("css", 2);
222 }
223 if let Some((prop, _)) = t.strip_suffix(';').and_then(|s| s.split_once(':'))
224 && !prop.contains(' ') && CSS_PROPS.iter().any(|p| prop.starts_with(p)) {
225 add("css", 2);
226 }
227 if lower.starts_with("<!doctype") {
228 add("html", 4);
229 }
230 if lower.starts_with("<?xml") {
231 add("html", 3);
232 }
233 if t.starts_with('<') && t.ends_with('>') {
234 add("html", 2);
235 }
236 if t.starts_with("#!") && t.contains("sh") {
237 add("bash", 5);
238 }
239 if t.starts_with("$ ") || SHELL_CMDS.iter().any(|c| t.starts_with(c)) {
240 add("bash", 3);
241 }
242 if t.starts_with("# ") || t.starts_with("## ") {
243 add("markdown", 1);
244 }
245 if t.starts_with("```") {
246 add("markdown", 3);
247 }
248 if t.starts_with("- [ ]") || t.starts_with("- [x]") {
249 add("markdown", 3);
250 }
251 if t.matches("**").count() >= 2 {
252 add("markdown", 2);
253 }
254 }
255
256 let (mut top, mut best) = (0i32, usize::MAX);
257 let mut second = 0i32;
258 for (i, &s) in score.iter().enumerate() {
259 if s > top {
260 second = top;
261 (top, best) = (s, i);
262 } else if s > second {
263 second = s;
264 }
265 }
266 (top >= MIN_SCORE && top - second >= MARGIN).then(|| LANGS[best].id)
267}
268
269/// A simple identifier: letters, digits, `_`, `-` or `.`.
270fn ident(s: &str) -> bool {
271 !s.is_empty() && s.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
272}
273
274/// A YAML `key: value` or `key:` line.
275fn yaml_key(t: &str) -> bool {
276 t.split_once(':').is_some_and(|(key, rest)| ident(key) && (rest.is_empty() || rest.starts_with(' ')))
277 && !t.ends_with([',', ';', '{', '(', '['])
278}
279
280/// A `|args|` closure head opened after `(`, `,`, `=` or `.`, as in `.map(|s| ...)`.
281fn has_closure(t: &str) -> bool {
282 let b = t.as_bytes();
283 (1..b.len()).any(|i| {
284 b[i] == b'|'
285 && matches!(b[i - 1], b'(' | b',' | b'=' | b'.')
286 && t[i + 1..].split_once('|').is_some_and(|(args, _)| {
287 !args.is_empty()
288 && args.len() <= 20
289 && args.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b' ' | b','))
290 })
291 })
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 #[test]
299 fn detects_snippets_and_finds_langs() {
300 let cases = [
301 ("let rows = load_job_rows(state, &viewer.0.id, 50).await?;\nlet skipped = query_params::<JobsQuery>(cx)?\n .skipped\n .clone()\n .filter(|s| !s.is_empty() && s.len() < 2000)\n .map(|s| g::bulk_skipped(lang, &s));", "rust"),
302 ("import os\n\ndef load(path):\n if not path:\n return None\n return open(path).read()", "python"),
303 ("const add = (a, b) => a + b;\nconsole.log(add(1, 2));", "javascript"),
304 ("interface User { id: number; name: string }\nconst greet = (u: User): string => `hi ${u.name}`;", "typescript"),
305 ("package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hi\")\n}", "go"),
306 ("{\n \"name\": \"note\",\n \"version\": \"1.0.0\",\n \"private\": true\n}", "json"),
307 ("<!DOCTYPE html>\n<html>\n <body>\n <p class=\"x\">Hi</p>\n </body>\n</html>", "html"),
308 (".card {\n display: flex;\n padding: 1rem;\n color: #333;\n}", "css"),
309 ("SELECT id, name\nFROM users\nWHERE active = 1\nORDER BY name;", "sql"),
310 ("#!/bin/bash\nset -e\nexport PATH=$HOME/bin:$PATH\ncargo build && sudo cp target/release/app /usr/local/bin/\necho \"done\"", "bash"),
311 ("name: build\non: push\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4", "yaml"),
312 ("[package]\nname = \"note-model\"\nversion = \"0.1.0\"\nedition = \"2024\"", "toml"),
313 ];
314 for (code, id) in cases {
315 assert_eq!(detect(code), Some(id), "{code}");
316 }
317 assert_eq!(detect("hello world"), None);
318 assert_eq!(find("RS").map(|l| l.id), Some("rust"));
319 assert_eq!(find("c++").map(|l| l.id), Some("cpp"));
320 }
321}