How to copy token found by lex (yytext) to another string? - lex

Whenever I get a token being recognized by a lex program for e.g.
"while" { printf("%s is a loop\n",yytext);}
I want to collect that token name (i.e while) in another string, that is declared earlier, for e.g.
"while" { printf("%s is a loop\n",yytext); str = yytext;}
but it doesn't produce the required output when str is being printed in main. It prints whole input from where the token has been recognized to the end of the input. How to copy just the token we have found to another string?

In C the memory for strings has to be allocated explicitly. The following would work:
"while" {
printf("%s is a loop\n",yytext);
str = malloc(strlen(yytext)+1);
if (str == NULL) abort();
strcpy(str,yytext);
}
Beware that the above code will leak memory if the while keyword occurs more than once in the input.

Related

No exact matches in call to subscript , If I use forEach, does not work

Please check the attached code below.
Why Pattern raise Error? , "No exact matches in call to subscript"
What is the difference between A and B?
This is the text import from the console.
3
Everest 8849
K2 8611
Kangchenjunga 8586
This is code
struct Mountain {
let name: String
let height: Int
}
func highestmountain() {
var mtList = [Mountain]()
let N = Int(readLine()!)!
(0..<N)
.forEach { _ in
/* Pattern A */
readLine()!
.split(separator: " ")
.forEach {
mtList.append(Mountain(name: "\($0[0])", height: Int("\($0[1])")!)) // Error: No exact matches in call to subscript
}
/* Pattern B */
let reads = readLine()!
.split(separator: " ")
mtList.append(Mountain(name: "\(reads[0])", height: Int("\(reads[1])")!)) // works!
}
}
In Pattern A, you're using split(" ") which creates an array of Strings (or, more specifically, String.SubSequence), and then you call forEach on that array.
forEach calls the attached closure for each item in the array. So, with your second input line, for example, on the first forEach, $0 will be "Everest" and on the second call, it'll be 8849. However, in your code, you're attempting to get $0[0], but $0 is not an array -- it's a single String.SubSequence. Thus the error about the subscript.
Your second approach (Pattern B) works because reads is an Array of String.SubSequence, so using a subscript (ie the [0]) works.
Unrelated to your question, but it's worth noting that using subscripts like [1] will fail and crash the app if you haven't first checked to make sure that the array has enough items in it. Force unwrapping with a ! (like you do with Int(...)!) can also cause crashes.

Getting DDMathParser tokens and group tokens

I already found a solution to my problem on stackoverflow but it is in Objective-C. See this link
DDMathParser - Getting tokens
I translated this into Swift as shown below. So what is the latest way to get tokens from a string and to get grouped tokens?
For example: 1 + ($a - (3 / 4))
Here is my try:
do{
let token = try Tokenizer(string: "1 + ($a - (3 /4))").tokenize()
for element in token {
print(element)
}
} catch {
print(error)
}
But I get the following messages:
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.VariableToken
MathParser.OperatorToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.DecimalNumberToken
MathParser.OperatorToken
MathParser.OperatorToken
How do I get the specific tokens from my string?
You're getting all of the tokens.
OperatorToken, DecimalNumberToken, etc all inherit from a RawToken superclass. RawToken defines a .string and a .range property.
The .string is the actual String, as extracted or inferred from the source. The .range is where in the original string the token is located.
It's important to note, however, that there may be tokens produced by the tokenizer that are not present in the original string. For example, tokens get injected by the Tokenizer when resolving implicit multiplication (3x turns in to 3 * x).
Added later:
If you want the final tree of how it all gets parsed, then you want the Expression:
let expression = try Expression(string: "1 + ($a - (3 / 4))")
At this point, you switch on expression.kind. It'll either be a number, a variable, or a function. function expressions have child expressions, representing the arguments to the function.

Argument labels do not match any availble overloads

I'm trying to create an anagram tester, and I'm pretty sure the code I have should work, but I'm getting an error 'Argument labels '(_:)' do not match any available overloads' I've looked at the other posts regarding the same error, but I'm still not sure what this means or how to fix it.
var anagram1 : String!
var anagram2 : String!
var failure : Bool = false
var counter : Int = 0
print("Please enter first word: ")
anagram1 = readLine()
print("Please enter Second word: ")
anagram2 = readLine()
if anagram1.count == anagram2.count {
for i in anagram1.characters{
if (!failure){
failure = true
for y in anagram2.characters {
counter += 1
if i == y {
failure = false
anagram2.remove(at: String.Index(counter)) // error here
}
}
}
else {
print("these words are not anagrams")
break;
}
}
if (!failure) {
print("these words ARE anagrams")
}
}
else{
print ("these words aren't even the same length you fucking nonce")
}
To answer your first question: the error message Argument labels '(_:)' do not match any available overloads means that you've given a function parameter names or types that don't match anything Swift knows about.
The compiler is also trying to tell you what parameters to look at. '(_:)' says that you're calling a function with an unlabeled parameter. (That means a value without any parameter name. A common example of a function that would look like this is print("something"). In Swift documentation, this would look like print(_:).
Finally, overloads are ways to call a function with different information. Again using the print function as an example, you can call it multiple ways. A couple of the most common overloads would be:
// print something, followed by a newline character
print("something")
// print something, but stay on the same line
// (end with an empty string instead of the default newline character)
print("something", terminator: "")
Documented, these might look like print(_:) and print(_:, terminator:).
Note: these are broken down for explanation. The actual Swift documentation shows func print(_: Any..., separator: String, terminator: String) which covers a number of different overloads!
Looking at the line where the error occurs, you see a function call and an initializer (which is essentially a function). Documented, the way you've entered the parameters, the functions would look like: remove(at:) and String.Index(_:).
String.Index(_:) matches the parameters of the error message, so that's where your error is. There is no overload of the String.Index initializer that takes an unnamed parameter.
To fix this error, you need to find the correct way to create a String.Index parameter for the remove(at:) function. One way might be to try something like this:
for y in anagram2.characters.enumerated() {
// `y` now represents a `tuple`: (offset: Int, element: Character)
// so, you don't need `counter` anymore; use `offset` instead
if i == y.element { //`i` is a Character, so it can compare to `element`
...
let yIndex: String.Index = anagram2.index(anagram2.startIndex, offsetBy: y.offset)
anagram2.remove(at: yIndex)
...
}
}
However, there are other issues with your code that will cause further errors.
For one, you're looping through a string (anagram2) and trying to change it at the same time - not a good thing to do.
Good luck to you in solving the anagram problem!
Thanks for the help Leo but I found a way of doing it :)
if anagram1.count == anagram2.count {
for i in anagram1.characters{
if (!failure){
counter = -1
failure = true
for y in anagram2.characters {
counter += 1
if i == y {
failure = false
if counter < anagram2.count {
anagram2.remove(at: (anagram2.index(anagram2.startIndex, offsetBy: counter)))
break;
}
}
}
}

Converting C char array (unsafe pointer) to String

I have an UnsafeMutablePointer<Character> filled by a CoreFoundation method.
If I NSLog it with %s placeholder, it outputs just fine.
But if I try with Swift's print it just writes the memory address.
Tried nearly everything... also I don't understand why if I try to access the underlying memory property I get a EXC_BAD_ACCESS.
let deviceName = UnsafeMutablePointer<Character>.alloc(64)
/* other statements in which deviceName is filled */
NSLog("device %s by %s", deviceName, manufacturerName)
// Outputs correctly the string
print(String(deviceName[0]))
// Get an EXC_BAD_ACCESS error at runtime
print(String(deviceName.memory))
// Get an EXC_BAD_ACCESS error at runtime
let str = withUnsafePointer(&deviceName) { String.fromCString(UnsafePointer($0)) }
print(str)
// Outputs an empty string
print("\(deviceName) by \(manufacturerName)")
// Outputs just memory addresses
You seem unwilling to show your code, so I can't really help. But this looks just wrong:
let deviceName = UnsafeMutablePointer<Character>.alloc(64)
/* other statements in which deviceName is filled */
That is not how to get hold of a C string in Swift, and if you believe that it is a C string in Swift, you're wrong; it would need to be an array of Int8 (C characters), not Swift Character (a struct!), to be a C string.
In other words, C char (your question's title) is not Swift Character - they are nothing like one another. A C char is a small number, a Swift Character is an object in an object-oriented language that C knows nothing about!

What is Optional({}) at Alamofire mean when i create output of JSON

When I create output of JSON using Alamofire, I saw this in my console
What does Optional({}) mean?
Optional({
0 = (
All,
""
);
C2001 = (
"ARAI Bay Side"
);
C2002 = (
"ARAI Fukuoka"
);
})
I am newbie to swift and this, so any ideas?
What Alamofire gives you is an optional variable, because it can't predict in advance whether the request will succeed and have output or fail and have none.
Similarly, it also gives you an error? variable (note the ?, which means it's also an optional) that will be nil if the request succeeded or will be something (most likely an NSError) if an error occurred.
You can check with if yourVariable != nil to see whether the optional variable is set (contains something), in which case you'll be able to unwrap it with yourVariable!.
You can also use the following :
if let yourUnwrappedVariable = yourVariable!
to unwrap the variable into a new (non-optional) yourUnwrappedVariable variable and execute the code in that if block if the variable was set (contained something, wasn't nil), this time without needing to unwrap the variable again like the previous example (here you already have the yourUnwrappedVariable variable and can use it right away in that if block).
Finally, if you're sure the variable will always be set, you can unwrap it by passing it followed by a ! sign to whatever method call you want like so :
myMethod(initWithData: yourVariable!, anotherArgument: anotherValue)
If the variable ever happens to not contain anything, an exception will be thrown.
What you are seeing is the output from global functions like print() or println(), which enclose optional descriptions inside Optional( ), unless the value of the optional is nil, in which case just nil is printed.
If you have this:
var foo: Int?
foo = 7
println(foo)
The output is Optional(7)
whereas
println(foo!)
just prints 7