Browse Source

JavaScript Highlighter: Handle ternary expressions

master
Shadowfacts 3 months ago
parent
commit
a976cf894f
Signed by: Shadowfacts <me@shadowfacts.net> GPG Key ID: 94A5AB95422746E5
2 changed files with 21 additions and 2 deletions
  1. 20
    1
      MongoView/Synax Highlighting/JavaScriptHighlighter.swift
  2. 1
    1
      jstest/main.swift

+ 20
- 1
MongoView/Synax Highlighting/JavaScriptHighlighter.swift View File

@@ -19,6 +19,7 @@ fileprivate let identifierStarts: CharacterSet = {
19 19
     return set
20 20
 }()
21 21
 fileprivate let operators = CharacterSet(charactersIn: "+-*/<>=")
22
+fileprivate let expressionEnds = CharacterSet(charactersIn: ",]});")
22 23
 
23 24
 class JavaScriptHighlighter {
24 25
     private let text: String
@@ -71,7 +72,7 @@ class JavaScriptHighlighter {
71 72
         ], range: fullRange)
72 73
 
73 74
         currentIndex = text.startIndex
74
-        while currentIndex < text.endIndex {
75
+        while let char = peek(), !expressionEnds.contains(char) {
75 76
             consumeExpression()
76 77
         }
77 78
 
@@ -116,6 +117,8 @@ class JavaScriptHighlighter {
116 117
             consumeArray()
117 118
         } else if char == "." {
118 119
             consumeDotLookup()
120
+        } else if char == "?" {
121
+            consumeTernaryExpression()
119 122
         } else {
120 123
             consume()
121 124
         }
@@ -310,6 +313,22 @@ class JavaScriptHighlighter {
310 313
         }
311 314
     }
312 315
     
316
+    func consumeTernaryExpression() {
317
+        consume() // ?
318
+        print("Ternary expression")
319
+        indent += "  "
320
+        print("Ternary true result")
321
+        while let char = peek(), char != ":" {
322
+            consumeExpression() // true result
323
+        }
324
+        consume() // :
325
+        print("Ternary false result")
326
+        while let char = peek(), !expressionEnds.contains(char) {
327
+            consumeExpression()
328
+        }
329
+        indent = String(indent.dropLast(2))
330
+    }
331
+    
313 332
 }
314 333
 
315 334
 extension JavaScriptHighlighter {

+ 1
- 1
jstest/main.swift View File

@@ -8,6 +8,6 @@
8 8
 
9 9
 import Foundation
10 10
 
11
-let source = "{a: 1234 , 'b': 'blah', foo}"
11
+let source = "a ? 'foo' : b ? 'bar' : 'baz'"
12 12
 _ = JavaScriptHighlighter(text: source).highlight()
13 13
 

Loading…
Cancel
Save