safe-parser.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. let Comment = require('postcss/lib/comment')
  2. let Parser = require('postcss/lib/parser')
  3. let tokenizer = require('postcss/lib/tokenize')
  4. class SafeParser extends Parser {
  5. checkMissedSemicolon() {}
  6. comment(token) {
  7. let node = new Comment()
  8. this.init(node, token[2])
  9. let pos =
  10. this.input.fromOffset(token[3]) ||
  11. this.input.fromOffset(this.input.css.length - 1)
  12. node.source.end = {
  13. column: pos.col,
  14. line: pos.line,
  15. offset: token[3] + 1
  16. }
  17. let text = token[1].slice(2)
  18. if (text.slice(-2) === '*/') text = text.slice(0, -2)
  19. if (/^\s*$/.test(text)) {
  20. node.text = ''
  21. node.raws.left = text
  22. node.raws.right = ''
  23. } else {
  24. let match = text.match(/^(\s*)([^]*\S)(\s*)$/)
  25. node.text = match[2]
  26. node.raws.left = match[1]
  27. node.raws.right = match[3]
  28. }
  29. }
  30. createTokenizer() {
  31. this.tokenizer = tokenizer(this.input, { ignoreErrors: true })
  32. }
  33. decl(tokens) {
  34. if (tokens.length > 1 && tokens.some(i => i[0] === 'word')) {
  35. super.decl(tokens)
  36. }
  37. }
  38. doubleColon() {}
  39. endFile() {
  40. if (this.current.nodes && this.current.nodes.length) {
  41. this.current.raws.semicolon = this.semicolon
  42. }
  43. this.current.raws.after = (this.current.raws.after || '') + this.spaces
  44. while (this.current.parent) {
  45. this.current = this.current.parent
  46. this.current.raws.after = ''
  47. }
  48. this.root.source.end = this.getPosition(this.tokenizer.position())
  49. }
  50. precheckMissedSemicolon(tokens) {
  51. let colon = this.colon(tokens)
  52. if (colon === false) return
  53. let nextStart, prevEnd
  54. for (nextStart = colon - 1; nextStart >= 0; nextStart--) {
  55. if (tokens[nextStart][0] === 'word') break
  56. }
  57. if (nextStart === 0 || nextStart < 0) return
  58. for (prevEnd = nextStart - 1; prevEnd >= 0; prevEnd--) {
  59. if (tokens[prevEnd][0] !== 'space') {
  60. prevEnd += 1
  61. break
  62. }
  63. }
  64. let other = tokens.slice(nextStart)
  65. let spaces = tokens.slice(prevEnd, nextStart)
  66. tokens.splice(prevEnd, tokens.length - prevEnd)
  67. this.spaces = spaces.map(i => i[1]).join('')
  68. this.decl(other)
  69. }
  70. unclosedBracket() {}
  71. unexpectedClose() {
  72. this.current.raws.after += '}'
  73. }
  74. unknownWord(tokens) {
  75. this.spaces += tokens.map(i => i[1]).join('')
  76. }
  77. unnamedAtrule(node) {
  78. node.name = ''
  79. }
  80. }
  81. module.exports = SafeParser