Lexer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import { SyntaxReferenceError, SyntaxMatchError } from './error.js';
  2. import * as names from '../utils/names.js';
  3. import { cssWideKeywords } from './generic-const.js';
  4. import { createGenericTypes } from './generic.js';
  5. import * as units from './units.js';
  6. import { parse, generate, walk } from '../definition-syntax/index.js';
  7. import prepareTokens from './prepare-tokens.js';
  8. import { buildMatchGraph } from './match-graph.js';
  9. import { matchAsTree } from './match.js';
  10. import * as trace from './trace.js';
  11. import { matchFragments } from './search.js';
  12. import { getStructureFromConfig } from './structure.js';
  13. function dumpMapSyntax(map, compact, syntaxAsAst) {
  14. const result = {};
  15. for (const name in map) {
  16. if (map[name].syntax) {
  17. result[name] = syntaxAsAst
  18. ? map[name].syntax
  19. : generate(map[name].syntax, { compact });
  20. }
  21. }
  22. return result;
  23. }
  24. function dumpAtruleMapSyntax(map, compact, syntaxAsAst) {
  25. const result = {};
  26. for (const [name, atrule] of Object.entries(map)) {
  27. result[name] = {
  28. prelude: atrule.prelude && (
  29. syntaxAsAst
  30. ? atrule.prelude.syntax
  31. : generate(atrule.prelude.syntax, { compact })
  32. ),
  33. descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst)
  34. };
  35. }
  36. return result;
  37. }
  38. function valueHasVar(tokens) {
  39. for (let i = 0; i < tokens.length; i++) {
  40. if (tokens[i].value.toLowerCase() === 'var(') {
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. function syntaxHasTopLevelCommaMultiplier(syntax) {
  47. const singleTerm = syntax.terms[0];
  48. return (
  49. syntax.explicit === false &&
  50. syntax.terms.length === 1 &&
  51. singleTerm.type === 'Multiplier' &&
  52. singleTerm.comma === true
  53. );
  54. }
  55. function buildMatchResult(matched, error, iterations) {
  56. return {
  57. matched,
  58. iterations,
  59. error,
  60. ...trace
  61. };
  62. }
  63. function matchSyntax(lexer, syntax, value, useCssWideKeywords) {
  64. const tokens = prepareTokens(value, lexer.syntax);
  65. let result;
  66. if (valueHasVar(tokens)) {
  67. return buildMatchResult(null, new Error('Matching for a tree with var() is not supported'));
  68. }
  69. if (useCssWideKeywords) {
  70. result = matchAsTree(tokens, lexer.cssWideKeywordsSyntax, lexer);
  71. }
  72. if (!useCssWideKeywords || !result.match) {
  73. result = matchAsTree(tokens, syntax.match, lexer);
  74. if (!result.match) {
  75. return buildMatchResult(
  76. null,
  77. new SyntaxMatchError(result.reason, syntax.syntax, value, result),
  78. result.iterations
  79. );
  80. }
  81. }
  82. return buildMatchResult(result.match, null, result.iterations);
  83. }
  84. export class Lexer {
  85. constructor(config, syntax, structure) {
  86. this.cssWideKeywords = cssWideKeywords;
  87. this.syntax = syntax;
  88. this.generic = false;
  89. this.units = { ...units };
  90. this.atrules = Object.create(null);
  91. this.properties = Object.create(null);
  92. this.types = Object.create(null);
  93. this.structure = structure || getStructureFromConfig(config);
  94. if (config) {
  95. if (config.cssWideKeywords) {
  96. this.cssWideKeywords = config.cssWideKeywords;
  97. }
  98. if (config.units) {
  99. for (const group of Object.keys(units)) {
  100. if (Array.isArray(config.units[group])) {
  101. this.units[group] = config.units[group];
  102. }
  103. }
  104. }
  105. if (config.types) {
  106. for (const [name, type] of Object.entries(config.types)) {
  107. this.addType_(name, type);
  108. }
  109. }
  110. if (config.generic) {
  111. this.generic = true;
  112. for (const [name, value] of Object.entries(createGenericTypes(this.units))) {
  113. this.addType_(name, value);
  114. }
  115. }
  116. if (config.atrules) {
  117. for (const [name, atrule] of Object.entries(config.atrules)) {
  118. this.addAtrule_(name, atrule);
  119. }
  120. }
  121. if (config.properties) {
  122. for (const [name, property] of Object.entries(config.properties)) {
  123. this.addProperty_(name, property);
  124. }
  125. }
  126. }
  127. this.cssWideKeywordsSyntax = buildMatchGraph(this.cssWideKeywords.join(' | '));
  128. }
  129. checkStructure(ast) {
  130. function collectWarning(node, message) {
  131. warns.push({ node, message });
  132. }
  133. const structure = this.structure;
  134. const warns = [];
  135. this.syntax.walk(ast, function(node) {
  136. if (structure.hasOwnProperty(node.type)) {
  137. structure[node.type].check(node, collectWarning);
  138. } else {
  139. collectWarning(node, 'Unknown node type `' + node.type + '`');
  140. }
  141. });
  142. return warns.length ? warns : false;
  143. }
  144. createDescriptor(syntax, type, name, parent = null) {
  145. const ref = {
  146. type,
  147. name
  148. };
  149. const descriptor = {
  150. type,
  151. name,
  152. parent,
  153. serializable: typeof syntax === 'string' || (syntax && typeof syntax.type === 'string'),
  154. syntax: null,
  155. match: null,
  156. matchRef: null // used for properties when a syntax referenced as <'property'> in other syntax definitions
  157. };
  158. if (typeof syntax === 'function') {
  159. descriptor.match = buildMatchGraph(syntax, ref);
  160. } else {
  161. if (typeof syntax === 'string') {
  162. // lazy parsing on first access
  163. Object.defineProperty(descriptor, 'syntax', {
  164. get() {
  165. Object.defineProperty(descriptor, 'syntax', {
  166. value: parse(syntax)
  167. });
  168. return descriptor.syntax;
  169. }
  170. });
  171. } else {
  172. descriptor.syntax = syntax;
  173. }
  174. // lazy graph build on first access
  175. Object.defineProperty(descriptor, 'match', {
  176. get() {
  177. Object.defineProperty(descriptor, 'match', {
  178. value: buildMatchGraph(descriptor.syntax, ref)
  179. });
  180. return descriptor.match;
  181. }
  182. });
  183. if (type === 'Property') {
  184. Object.defineProperty(descriptor, 'matchRef', {
  185. get() {
  186. const syntax = descriptor.syntax;
  187. const value = syntaxHasTopLevelCommaMultiplier(syntax)
  188. ? buildMatchGraph({
  189. ...syntax,
  190. terms: [syntax.terms[0].term]
  191. }, ref)
  192. : null;
  193. Object.defineProperty(descriptor, 'matchRef', {
  194. value
  195. });
  196. return value;
  197. }
  198. });
  199. }
  200. }
  201. return descriptor;
  202. }
  203. addAtrule_(name, syntax) {
  204. if (!syntax) {
  205. return;
  206. }
  207. this.atrules[name] = {
  208. type: 'Atrule',
  209. name: name,
  210. prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, 'AtrulePrelude', name) : null,
  211. descriptors: syntax.descriptors
  212. ? Object.keys(syntax.descriptors).reduce(
  213. (map, descName) => {
  214. map[descName] = this.createDescriptor(syntax.descriptors[descName], 'AtruleDescriptor', descName, name);
  215. return map;
  216. },
  217. Object.create(null)
  218. )
  219. : null
  220. };
  221. }
  222. addProperty_(name, syntax) {
  223. if (!syntax) {
  224. return;
  225. }
  226. this.properties[name] = this.createDescriptor(syntax, 'Property', name);
  227. }
  228. addType_(name, syntax) {
  229. if (!syntax) {
  230. return;
  231. }
  232. this.types[name] = this.createDescriptor(syntax, 'Type', name);
  233. }
  234. checkAtruleName(atruleName) {
  235. if (!this.getAtrule(atruleName)) {
  236. return new SyntaxReferenceError('Unknown at-rule', '@' + atruleName);
  237. }
  238. }
  239. checkAtrulePrelude(atruleName, prelude) {
  240. const error = this.checkAtruleName(atruleName);
  241. if (error) {
  242. return error;
  243. }
  244. const atrule = this.getAtrule(atruleName);
  245. if (!atrule.prelude && prelude) {
  246. return new SyntaxError('At-rule `@' + atruleName + '` should not contain a prelude');
  247. }
  248. if (atrule.prelude && !prelude) {
  249. if (!matchSyntax(this, atrule.prelude, '', false).matched) {
  250. return new SyntaxError('At-rule `@' + atruleName + '` should contain a prelude');
  251. }
  252. }
  253. }
  254. checkAtruleDescriptorName(atruleName, descriptorName) {
  255. const error = this.checkAtruleName(atruleName);
  256. if (error) {
  257. return error;
  258. }
  259. const atrule = this.getAtrule(atruleName);
  260. const descriptor = names.keyword(descriptorName);
  261. if (!atrule.descriptors) {
  262. return new SyntaxError('At-rule `@' + atruleName + '` has no known descriptors');
  263. }
  264. if (!atrule.descriptors[descriptor.name] &&
  265. !atrule.descriptors[descriptor.basename]) {
  266. return new SyntaxReferenceError('Unknown at-rule descriptor', descriptorName);
  267. }
  268. }
  269. checkPropertyName(propertyName) {
  270. if (!this.getProperty(propertyName)) {
  271. return new SyntaxReferenceError('Unknown property', propertyName);
  272. }
  273. }
  274. matchAtrulePrelude(atruleName, prelude) {
  275. const error = this.checkAtrulePrelude(atruleName, prelude);
  276. if (error) {
  277. return buildMatchResult(null, error);
  278. }
  279. const atrule = this.getAtrule(atruleName);
  280. if (!atrule.prelude) {
  281. return buildMatchResult(null, null);
  282. }
  283. return matchSyntax(this, atrule.prelude, prelude || '', false);
  284. }
  285. matchAtruleDescriptor(atruleName, descriptorName, value) {
  286. const error = this.checkAtruleDescriptorName(atruleName, descriptorName);
  287. if (error) {
  288. return buildMatchResult(null, error);
  289. }
  290. const atrule = this.getAtrule(atruleName);
  291. const descriptor = names.keyword(descriptorName);
  292. return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false);
  293. }
  294. matchDeclaration(node) {
  295. if (node.type !== 'Declaration') {
  296. return buildMatchResult(null, new Error('Not a Declaration node'));
  297. }
  298. return this.matchProperty(node.property, node.value);
  299. }
  300. matchProperty(propertyName, value) {
  301. // don't match syntax for a custom property at the moment
  302. if (names.property(propertyName).custom) {
  303. return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties'));
  304. }
  305. const error = this.checkPropertyName(propertyName);
  306. if (error) {
  307. return buildMatchResult(null, error);
  308. }
  309. return matchSyntax(this, this.getProperty(propertyName), value, true);
  310. }
  311. matchType(typeName, value) {
  312. const typeSyntax = this.getType(typeName);
  313. if (!typeSyntax) {
  314. return buildMatchResult(null, new SyntaxReferenceError('Unknown type', typeName));
  315. }
  316. return matchSyntax(this, typeSyntax, value, false);
  317. }
  318. match(syntax, value) {
  319. if (typeof syntax !== 'string' && (!syntax || !syntax.type)) {
  320. return buildMatchResult(null, new SyntaxReferenceError('Bad syntax'));
  321. }
  322. if (typeof syntax === 'string' || !syntax.match) {
  323. syntax = this.createDescriptor(syntax, 'Type', 'anonymous');
  324. }
  325. return matchSyntax(this, syntax, value, false);
  326. }
  327. findValueFragments(propertyName, value, type, name) {
  328. return matchFragments(this, value, this.matchProperty(propertyName, value), type, name);
  329. }
  330. findDeclarationValueFragments(declaration, type, name) {
  331. return matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name);
  332. }
  333. findAllFragments(ast, type, name) {
  334. const result = [];
  335. this.syntax.walk(ast, {
  336. visit: 'Declaration',
  337. enter: (declaration) => {
  338. result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name));
  339. }
  340. });
  341. return result;
  342. }
  343. getAtrule(atruleName, fallbackBasename = true) {
  344. const atrule = names.keyword(atruleName);
  345. const atruleEntry = atrule.vendor && fallbackBasename
  346. ? this.atrules[atrule.name] || this.atrules[atrule.basename]
  347. : this.atrules[atrule.name];
  348. return atruleEntry || null;
  349. }
  350. getAtrulePrelude(atruleName, fallbackBasename = true) {
  351. const atrule = this.getAtrule(atruleName, fallbackBasename);
  352. return atrule && atrule.prelude || null;
  353. }
  354. getAtruleDescriptor(atruleName, name) {
  355. return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators
  356. ? this.atrules[atruleName].declarators[name] || null
  357. : null;
  358. }
  359. getProperty(propertyName, fallbackBasename = true) {
  360. const property = names.property(propertyName);
  361. const propertyEntry = property.vendor && fallbackBasename
  362. ? this.properties[property.name] || this.properties[property.basename]
  363. : this.properties[property.name];
  364. return propertyEntry || null;
  365. }
  366. getType(name) {
  367. return hasOwnProperty.call(this.types, name) ? this.types[name] : null;
  368. }
  369. validate() {
  370. function syntaxRef(name, isType) {
  371. return isType ? `<${name}>` : `<'${name}'>`;
  372. }
  373. function validate(syntax, name, broken, descriptor) {
  374. if (broken.has(name)) {
  375. return broken.get(name);
  376. }
  377. broken.set(name, false);
  378. if (descriptor.syntax !== null) {
  379. walk(descriptor.syntax, function(node) {
  380. if (node.type !== 'Type' && node.type !== 'Property') {
  381. return;
  382. }
  383. const map = node.type === 'Type' ? syntax.types : syntax.properties;
  384. const brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties;
  385. if (!hasOwnProperty.call(map, node.name)) {
  386. errors.push(`${syntaxRef(name, broken === brokenTypes)} used missed syntax definition ${syntaxRef(node.name, node.type === 'Type')}`);
  387. broken.set(name, true);
  388. } else if (validate(syntax, node.name, brokenMap, map[node.name])) {
  389. errors.push(`${syntaxRef(name, broken === brokenTypes)} used broken syntax definition ${syntaxRef(node.name, node.type === 'Type')}`);
  390. broken.set(name, true);
  391. }
  392. }, this);
  393. }
  394. }
  395. const errors = [];
  396. let brokenTypes = new Map();
  397. let brokenProperties = new Map();
  398. for (const key in this.types) {
  399. validate(this, key, brokenTypes, this.types[key]);
  400. }
  401. for (const key in this.properties) {
  402. validate(this, key, brokenProperties, this.properties[key]);
  403. }
  404. const brokenTypesArray = [...brokenTypes.keys()].filter(name => brokenTypes.get(name));
  405. const brokenPropertiesArray = [...brokenProperties.keys()].filter(name => brokenProperties.get(name));
  406. if (brokenTypesArray.length || brokenPropertiesArray.length) {
  407. return {
  408. errors,
  409. types: brokenTypesArray,
  410. properties: brokenPropertiesArray
  411. };
  412. }
  413. return null;
  414. }
  415. dump(syntaxAsAst, pretty) {
  416. return {
  417. generic: this.generic,
  418. cssWideKeywords: this.cssWideKeywords,
  419. units: this.units,
  420. types: dumpMapSyntax(this.types, !pretty, syntaxAsAst),
  421. properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst),
  422. atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst)
  423. };
  424. }
  425. toString() {
  426. return JSON.stringify(this.dump());
  427. }
  428. };